1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
| from loguru import logger import serial
class SelfSerial(): def __init__(self, device): self.uart = serial.Serial(port=device, bytesize=8, baudrate=115200, stopbits=1, timeout=0) self.msg_mode = 0 self.uart_buf = [] self.state = 0
def uart_read_mode(self, lastmode): if self.uart.in_waiting > 0: data = self.uart.read().hex() mode = self.data_processing(data) if mode: if lastmode != mode: logger.info('Get Command. Run Model:{}'.format(mode)) return mode else: return lastmode else: return lastmode
def uart_send_msg(self, mode, msg): data_list = [0x0f, 0xf0, mode, len(msg)] data_list.extend(msg) data_list.append(self.sum_check(data_list)) data = bytearray(data_list) self.uart.write(data)
def data_processing(self, data): if(self.state == 0): self.uart_buf = [] if(data == "0f"): self.state = 1 self.uart_buf.append(data) else: self.state = 0
elif(self.state == 1): if(data == "f0"): self.state = 2 self.uart_buf.append(data) else: self.state = 0
elif(self.state == 2): if(data == "20"): self.state = 3 self.uart_buf.append(data) else: self.state = 0
elif(self.state == 3): if(data == "01"): self.state = 4 self.uart_buf.append(data) else: self.state = 0
elif(self.state == 4): self.state = 5 self.uart_buf.append(data)
elif(self.state == 5): sum = 0 for i in range(5): sum = sum + int(self.uart_buf[i],16) sum = sum % 256 data_16 = int(data, 16) if(data_16 == sum): mode = self.uart_buf[4] self.uart_buf = [] self.state = 0 return int(mode, 16) else: self.state = 0
def sum_check(self, data_list): data_sum = 0 for temp in data_list: data_sum = temp+data_sum return data_sum % 256
''' #定义发送数据包 返回list def pack_data_17(self, data1, data2, data3): datalist = [0x0f, 0xf0, 0x17, 0x03, data1, data2, data3] datalist.append(self.sum_check(datalist)) data = bytearray(datalist) return data def pack_data_18(self, data1, data2, data3): datalist = [0x0f, 0xf0, 0x18, 0x03, data1, data2, data3] datalist.append(self.sum_check(datalist)) data = bytearray(datalist) return data
def pack_data_19(self, data1, data2, data3): datalist = [0x0f, 0xf0, 0x19, 0x03, data1, data2, data3] datalist.append(self.sum_check(datalist)) data = bytearray(datalist) return data
def pack_data_20(self, data1, data2, data3): datalist = [0x0f, 0xf0, 0x20, 0x03, data1, data2, data3] datalist.append(self.sum_check(datalist)) data = bytearray(datalist) return data '''
|