import snap7from snap7.util import get_int,get_boolfrom snap7.util import set_int,set_boolclient=snap7.client.Client()# 创建PLC客户端client.connect('192.168.0.198',0,1)# 连接PLC(IP地址、机架号、槽号)# 读取DB块中的整数数据db_number = 1 # 数据块编号byte_offset = 2 # 字节偏移量data = client.db_read(db_number, byte_offset, 2) # 读取2字节数据value=get_int(data,0)# 解析为整数print(f"读取的整数值: {value}")# 读取I区的布尔值area = snap7.types.areas.pe # 输入区byte_offset = 0 # 字节偏移量bit_offset = 0 # 位偏移量data = client.read_area(area, db_number, byte_offset, 1)bool_value = get_bool(data, byte_offset, bit_offset)print(f"读取的布尔值: {bool_value}")# 写入DB块中的整数数据db_number = 1byte_offset = 0value = 1234 # 要写入的整数值data = bytearray(2)set_int(data, 0, value)client.db_write(db_number, byte_offset, data)# 写入Q区的布尔值area = snap7.types.areas.pa # 输出区byte_offset = 0bit_offset = 0value = True # 要写入的布尔值set_bool(data, byte_offset, bit_offset, value)client.write_area(area, db_number, byte_offset, data)client.disconnect()