PLC
作者:互联网
PLC(Programmable Logic Controller)即可编程逻辑控制器,可以理解为一个微型计算机,广泛应用于工业控制领域中,包括楼宇智控、精密机床、汽车电子等等。
当前市场上主流的PLC通信方式为网络通信和串行通信。网络通信这块主要协议有profinet,modbus-tcp等,串行通信主要是基于RS232/485的modbus。
连接PLC,python解析
1 import snap7 2 import struct 3 4 # 创建通讯客户端实例 5 plcObj = snap7.client.Client() 6 7 # 连接至PLC 8 plcObj.connect('192.168.10.230', 0, 1) 9 10 # 读取数据 11 data = plcObj.db_read(10, 0, 776) 12 13 # 关闭连接 14 plcObj.disconnect() 15 16 # python解析 17 selfBool = bool.from_bytes(data[0:1], byteorder='big') 18 selfInt = int.from_bytes(data[2:4], byteorder='big') 19 selfReal = struct.unpack('>f', data[4:8])[0] 20 selfString = data[10:264].decode(encoding="ascii") 21 selfWString = data[268:].decode(encoding="utf-16be") 22 print("python自身函数解析:") 23 print( 24 f"bool:{selfBool}; int:{selfInt}; real:{selfReal}; string:{selfString}; wstring:{selfWString}" 25 )
写入数据
1 import snap7 2 import struct 3 4 # 创建通讯客户端实例 5 plcObj = snap7.client.Client() 6 7 # 连接至PLC 8 plcObj.connect('192.168.10.230', 0, 1) 9 10 11 # 写入DB10.0 —— bool值 12 plcObj.write_area(snap7.client.Areas.DB, 10, 0, bool.to_bytes(False, 1, 'big')) 13 14 # 写入DB10.2 15 plcObj.write_area(snap7.client.Areas.DB, 10, 2, int.to_bytes(200, 2, 'big')) 16 # plcObj.write_area(snap7.client.Areas.DB, 10, 2, struct.pack(">h", 112)) 17 18 # 写入DB10.4 —— real值 19 plcObj.write_area(snap7.client.Areas.DB, 10, 4, struct.pack(">f", 10.1)) 20 21 # 写入DB10.8 —— string值 22 str = 'hello python' 23 data = int.to_bytes(254, 1, 'big') + int.to_bytes(len(str), 1, 'big') + str.encode(encoding='ascii') 24 plcObj.write_area(snap7.client.Areas.DB, 10, 8, data) 25 26 # 写入DB10.264 —— wstring值 27 str = '中国北京市' 28 data = int.to_bytes(508, 2, 'big') + int.to_bytes(len(str), 2, 'big') + str.encode(encoding='utf-16be') 29 plcObj.write_area(snap7.client.Areas.DB, 10, 264, data) 30 31 # 关闭连接 32 plcObj.disconnect()
人生短短三万天。
标签:10,snap7,big,bytes,PLC,plcObj,data 来源: https://www.cnblogs.com/lzcnblogs/p/16547090.html