vb0 = 66
vb1 = -90
vw2 = 32767
vw4 = -3000
vd6 = 99999
vd10 = -9888888
vd14 = 7887.999
vd18 = -0.9999
#Bytes類型,是由8個二進制位組成的正整數(shù),范圍0-255共256個數(shù)
# for i in range(256):
# print(f'{i:08b}-->{i}')
#
#
# #1 利用自身的方法進行解析
# vb0_byte = vb0.to_bytes(1)
# vb1_byte = vb1.to_bytes(1,signed=True)
# vw2_bytes = int.to_bytes(vw2,2)
# vw4_bytes = int.to_bytes(vw4,2,signed=True)
# vd6_bytes = int.to_bytes(vd6,4)
# vd10_bytes = int.to_bytes(vd10,4,signed=True)
#
#2 使用struct 模塊
"""
大小端 > 大端 <小端
格式符:
整數(shù)類型:
有符合字節(jié) ’b' 無符號字節(jié) ‘B’ 1byte
有符號短整數(shù) 'h' 無符號短整數(shù) 'H' 2bytes
有符號整數(shù) 'i' 無符號整數(shù) 'I' 4bytes
有符號長長整數(shù) 'q' 無符號長長整數(shù) 'Q' 8bytes
浮點數(shù)
單精度 'f' 4bytes
雙精度 'd' 8bytes
"""
import struct
my_data = struct.pack(">BbHhIiff",vb0,vb1,vw2,vw4,vd6,vd10,vd14,vd18)
print(my_data,len(my_data))
if __name__ == '__main__':
from snap7 import client
def connect_plc() -> client.Client:
plc = client.Client()
plc.set_connection_type(3)
plc.connect("192.168.5.20", 0, 1)
return plc
def write_to_plc(start_addr, byte: bytes):
plc = connect_plc()
plc.db_write(1, start_addr, byte)
plc.disconnect()
def read_plc(start_addr, num) -> bytearray:
plc = connect_plc()
data = plc.db_read(1, start_addr, num)
plc.disconnect()
return data
# data_bytes = vb0_byte + vb1_byte + vw2_bytes + vw4_bytes + vd6_bytes + vd10_bytes
# print(data_bytes, len(data_bytes))
# write_to_plc(0,my_data)
data = read_plc(0,22)
struct_data = struct.unpack(">BbHhIiff",data)
print(struct_data)
承擔因您的行為而導致的法律責任,
本站有權(quán)保留或刪除有爭議評論。
參與本評論即表明您已經(jīng)閱讀并接受
上述條款。