# C:\Users\chx_s\AppData\Local\Programs\Python\Python310\Scripts\pip.exe # C:\Users\chx_s\AppData\Local\Programs\Python\Python310\python.exe import sys import struct from binascii import * # 临时注释掉crcmod导入,用于测试弹窗功能 from crcmod import * import random import re # bytes解包 def my_unpack(s, data, i): global info_msg global error_msg temp_msg = "" if type(s) == str: np = struct.calcsize(s) try: val = struct.unpack(s, data[i:(i + np)]) return i + np, val[0] except: temp_msg = "fun:" + sys._getframe().f_code.co_name + \ ",line:" + f"{sys._getframe().f_lineno}." + \ f"\n出错了!!!,s={s},i={i},data={data}" error_msg = error_msg + temp_msg info_msg = info_msg + temp_msg return i + np, 0 elif type(s) == int: val = data[i:(i + s)] return i + s, val def convert_to_24byte_bytes(s): """将字符串转换为24字节的bytes,不足补0x00""" bytes_data = s.encode('utf-8')[:24] # 取前24字节 return bytes_data.ljust(24, b'\x00') # 不足24字节用0x00填充 def get_msg_restart(device, data): print(f"this is get_msg_restart:") # body pub_body = bytearray(struct.pack("H", 0x2006)) # 注意 2006 是指十六进制 0x2006 pub_body = pub_body + bytearray(bytes(struct.pack("I", int(device['dev_sn'])))) # 注意 103 是指十进制 103 # add something # pub_header = bytearray.fromhex("FEFE01390100000363206A00") # header pub_header = bytearray(struct.pack("H", 0xFEFE)) # 协议头 pub_header = pub_header + bytearray(struct.pack("B", 0x01)) # 协议版本 pub_header = pub_header + bytearray(struct.pack("I", random.randint(0, 1000000000))) # 消息ID pub_header = pub_header + bytearray(struct.pack("B", 0x01)) # 一级类型 pub_header = pub_header + bytearray(struct.pack("H", 0x1021)) # 二级类型 pub_header = pub_header + bytearray(struct.pack("H", (len(pub_body) + 2))) # 消息长度 # 重新结算长度 # pub_header[10:12] = bytearray(struct.pack("H", (len(pub_body)))) # 添加crc16 pub_frame = pub_header + pub_body crc16mod = crcmod.mkCrcFun(0x18005, rev=True, initCrc=0x0000, xorOut=0000) crc16 = crc16mod(pub_frame) # 完整消息 pub_frame = pub_frame + bytearray(struct.pack("