半成品
import socket import struct from zlib import crc32 def data_processing(data): # 解析数据 head = struct.unpack(">4s", data[0:4])[0] # 固定包头 protocol_version = struct.unpack('>B', data[4:5])[0] # 协议版本 private_id = struct.unpack('>B', data[5:6])[0] # 私有版本 package_length = struct.unpack('>H', data[6:8])[0] # 包长度 print("固定包头: ", head, "协议版本: ", protocol_version, "私有版本: ", private_id, "私有数据包长度: ", package_length, "校验: ", struct.unpack(">L", data[-4:])[0]) analyzing_data(data[8:-4]) return data[8:-4], private_id def analyzing_data(self, data): id_counter = struct.unpack(">H", data[0:1])[0] auto_or_manual = struct.unpack(">B", data[1:2])[0] def send_data(self, private_id, version = 1): """ ["执行结果码", ">B", 1], ["已收到指令ID", ">H", 2], ["已完成指令ID", ">H", 2], ["X坐标", ">I", 4], ["Y坐标", ">H", 2], ["摄像头X坐标", ">H", 2], ["摄像头Y坐标", ">H", 2], ["摄像头Z坐标", ">H", 2], ["电池电量", ">B", 1], ["是否在充电", ">B", 1], ["避障传感器", ">H", 2], ["故障码", ">H", 2], """ head = struct.pack('>4s', 'HXTX'.encode("utf-8")) # 固定包头 ver = struct.pack('>B', 1) # 协议版本 private = struct.pack('>B', private_id) # 私有命令ID # 私有参数 cmd_bytes = struct.pack(">B", 0) cmd_bytes += struct.pack(">H", ) cmd_bytes += struct.pack(">H", ) cmd_bytes += struct.pack(">I", 100) cmd_bytes += struct.pack(">H", 50) cmd_bytes += struct.pack(">H", 30) cmd_bytes += struct.pack(">H", 30) cmd_bytes += struct.pack(">H", 30) cmd_bytes += struct.pack(">B", 20) cmd_bytes += struct.pack(">B", 0) cmd_bytes += struct.pack(">H", 0) cmd_bytes += struct.pack(">H", 0) data_len = struct.pack(">H", len(cmd_bytes) + 4) # 包长度 package_data = head + ver + private + data_len + cmd_bytes """校验32bit""" check_crc32 = crc32(package_data) _crc32 = struct.pack('>L', check_crc32) return package_data + _crc32 ip_port=('127.0.0.1',8081) udp_server_sock=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) udp_server_sock.bind(ip_port) while True: try: msg, addr=udp_server_sock.recvfrom(1024) print(msg) data_processing(msg) udp_server_sock.sendto(msg,addr) except Exception: pass