1024AirConditioner

发布时间 2023-10-12 15:25:45作者: suphgcm
import serial
import crcmod

def getCrc16(veritydata):
if not veritydata:
return
crc16 = crcmod.mkCrcFun(0x18005, 0xFFFF, True, 0x0000)
return crc16(veritydata)

def getModbus04(addr, startRegAddr, regNum, funCode=4):
if addr < 0 or addr > 0xFF or startRegAddr < 0 or startRegAddr > 0xFFFF or regNum < 1 or regNum > 0x70:
return
sendBytes = addr.to_bytes(1, byteorder="big", signed=False) +\
funCode.to_bytes(1, byteorder="big", signed=False) +\
startRegAddr.to_bytes(2, byteorder="big", signed=False) +\
regNum.to_bytes(2, byteorder="big", signed=False)
crcCode = getCrc16(sendBytes)
sendBytes += crcCode.to_bytes(2, byteorder="little", signed=False)
return sendBytes

if __name__ == '__main__':
last_state = 0
com = serial.Serial("com1", 38400, timeout=0.2)
while True:
sendBytes = getModbus04(1, 0, 1)
com.write(sendBytes)
readBytes = com.read(1*2+5)
if readBytes[4] == 1:
if last_state == 0:
print("1\n")
file = open(r"D:\PycharmProjects\temp\new_file.txt", "w")
file.close()
last_state = 1
else:
last_state = 0