class ComPortClass(QObject): def __init__(self): self.SerialPort = QtSerialPort.QSerialPort() self.SerialPort.setBaudRate(115200) self.SerialPort.setPortName("COM8") self.SerialPort.readyRead.connect(self.ReadData) self.DATA_WAIT_SIZE = 0 self.DATA_BUFFER = QByteArray() self.DATA_MESSAGE = QByteArray() self.FLAG_WAIT_DATA = False def OpenPort(self): result = self.SerialPort.open(QtSerialPort.QSerialPort.ReadWrite) print(" PORT - ",self.SerialPort.portName()," OPENED") #self.Window.ui.ButtonOpenPort.clicked.connect(self.OpenPort) #self.Window.ui.ButtonSendData.clicked.connect(self.TestCOMConnection) #self.Window.ui.ButStepMotorRight.clicked.connect(lambda: self.MotorControl.MoveStepMotor(NumberMotor=0,Direction=1)) #self.Window.ui.ButStepMotorLeft.clicked.connect(lambda: self.MotorControl.MoveStepMotor(NumberMotor=1,Direction=-1)) def TestCOMConnection(self): self.HEADER_DATA = bytearray.fromhex("A1 F1 00") COMMAND_HEADER = bytearray.fromhex("01") self.DATA = COMMAND_HEADER + bytearray("TEST MESSAGE","utf-8") self.HEADER_DATA[2] = len(self.DATA) result = self.SerialPort.write(self.HEADER_DATA) result = self.SerialPort.write(self.DATA) print("SEND MESSAGE - ",self.DATA) def ClosePort(self): result = self.SerialPort.close() def ReadData(self): New_Data = self.SerialPort.readAll() self.DATA_BUFFER.append(New_Data) #print("BUFFER - " ,self.DATA_BUFFER.toHex(),"SIZE - ",self.DATA_BUFFER.length(),"WAIT - ",self.DATA_WAIT_SIZE) while(self.DATA_BUFFER.length() >= 3): if(self.DATA_BUFFER[0] == b'\xF1' and self.DATA_BUFFER[1] == b'\xA1'): self.DATA_WAIT_SIZE = self.DATA_BUFFER[2][0] self.DATA_BUFFER.remove(0,3) if(self.DATA_BUFFER.length() >= self.DATA_WAIT_SIZE): self.DATA_MESSAGE.clear() self.DATA_MESSAGE.append(self.DATA_BUFFER) self.DATA_BUFFER.remove(0,self.DATA_WAIT_SIZE) self.DATA_MESSAGE.truncate(self.DATA_WAIT_SIZE) print(self.DATA_BUFFER.toHex()) self.Window.AddText(" " + self.DATA_MESSAGE.data().decode(encoding="utf-8"),0) else: break;
class BufferQueueIO(QIODevice): def __init__(self, bufQ, parent): super(BufferQueueIO, self).__init__(parent) self.buffer = QByteArray() self.bufQ = bufQ def start(self): self.open(QIODevice.ReadOnly) def stop(self): self.m_pos = 0 self.close() def readData(self, maxlen): if self.bufQ.qsize() >= 2: self.buffer.append(self.bufQ.get()) if self.buffer.length() < maxlen: # FIXME, return correct length QByteArray of zeros return QByteArray(bytearray((0, ) * 10)).data() else: outp = self.buffer.mid(0, maxlen).data() self.buffer.remove(0, maxlen) return outp def writeData(self, data): return 0 def bytesAvailable(self): return self.m_buffer.size() + super(BufferQueueIO, self).bytesAvailable()
def post_data_to_array(self, post_data): post_params = QByteArray() for (key, value) in post_data.items(): if isinstance(value, list): for val in value: post_params.append(key + "=" + val + "&") else: post_params.append(key + "=" + value + "&") post_params.remove(post_params.length() - 1, 1) return post_params
class Door(): templet = b'\x3a\x00\x00\x00\x00\x0d\x0a' # int is id of door degaussSuccess = pyqtSignal(int) # 消磁成功 inOpenDoorSuccess = pyqtSignal(int) # 进门开门成功 outOpenDooSuccess = pyqtSignal(int) # 出门开门成功 outOpenDooSuccessByUser = pyqtSignal(int) # 用户手动开门出门 getDataSingal = pyqtSignal(str) def __init__(self, port_name=None, baud_rate=None, data_bits=None, stop_bits=None): # Reading config config = read_config()[port_name] # Logging module self.mylogging = MyLogging(logger_name='user') self.mylogger = self.mylogging.logger # Configurate door_controller. self.door_controller = QSerialPort() self.door_controller.setPortName(config['port_name']) self.door_controller.setBaudRate(int(config['baud_rate'])) self.door_controller.setDataBits(int(config['data_bits'])) self.door_controller.setStopBits(int(config['stop_bits'])) # Check self. self.check() # Start to work. self.data = QByteArray() self.setDataTerminalReady(True) self.readyRead.connect(self.acceptData) def check(self): info = QSerialPortInfo.availablePorts() # Checking SerialPort is deeply used. if len(info) == 0: self.mylogger.error('SerialPort has no availablePorts.') self.mylogger.warning('Please check your [weigher] and [' 'door_controller].') if self.port_name == None: self.mylogger.error('The port_name of [door_controller] is None.') # Checking whether the door serial port can open. if not self.door_controller.open(QIODevice.ReadWrite): self.mylogger.error('Open %s device failed.' % self.door_controller) return None def byteToInt(strbyte): if type(strbyte) == str: strbyte = strbyte.encode('UTF-8') t = strbyte + b'\x00' i = struct.unpack("<h", t)[0] return i def get_char_bit(char, n): return (char >> (8 - n)) & 1 # get the LRC def getLRC(self, cmd): tmp = cmd[1] + cmd[2] + cmd[3] if (self.get_char_bit(tmp, 1) == 1): tmp = ~tmp tmp = struct.pack('<h', tmp)[0] + 1 return tmp # add LRC to Cmd def addLRC(self, cmd): cmd[4] = self.getLRC(cmd) return cmd def checkLRC(self, cmd): if type(cmd) == QByteArray: cmd = cmd.data() if type(cmd) != bytearray: cmd = bytearray(cmd) return cmd[4] == self.getLRC(cmd) # send data @pyqtSlot(int) def sendOpenDoorIn(self, doorNumber): cmd = bytearray(self.templet) cmd[1] = struct.pack('<h', doorNumber)[0] cmd[2] = self.byteToInt(b'\xCC') self.mylogger.warning([hex(x) for x in bytes(cmd)]) if self.door_controller.write(self.addLRC(cmd)) == 7: return True else: return False @pyqtSlot(int) def sendOpenDoorOut(self, doorNumber): cmd = bytearray(self.templet) cmd[1] = struct.pack('<h', doorNumber)[0] cmd[2] = self.byteToInt(b'\xBB') self.mylogger.warning([hex(x) for x in bytes(cmd)]) if self.door_controller.write(self.addLRC(cmd)) == 7: return True else: return False @pyqtSlot(int) def sendDegauss(self, doorNumber=1): cmd = bytearray(self.templet) cmd[1] = struct.pack('<h', doorNumber)[0] cmd[2] = self.byteToInt(b'\xAA') end = self.addLRC(cmd) self.mylogger.warning([hex(x) for x in bytes(end)]) if self.door_controller.write(end) == 7: return True else: return False @pyqtSlot() def sendZeroWeight(self): cmd = b"\x3A\x01\xAB\x00\x54\x0D\x0A" if self.door_controller.write(cmd) == 7: return True else: return False @pyqtSlot() def acceptData(self): # print("acceptData",self.data) self.data.append(self.door_controller.readAll()) # read all data while self.data.length() > 0: if self.data.length() >= 7: # if get a complete data for i in range(self.data.length()): if self.data[i] == '\x3a': # find the SOI tmp = self.data[i:7] # get a cmd # print("get cmd :",str(tmp.data())) self.mylogger.debug("Get [cmd]: %s" % str(tmp.data())) tmp = self.bytearray(tmp.data()) self.data = self.data[i + 7:] # cut data doorNumber = tmp[1] if self.checkLRC(tmp): # check LRC if tmp[2] == self.byteToInt(b'\xaa'): # self.degaussTime = time.time() # print("接收消磁指令反馈 %s" % self.degaussTime) self.mylogger.debug( "Get degauss Feedback %s" % tmp) self.degaussSuccess.emit(doorNumber) elif tmp[2] == self.byteToInt(b'\xbb'): if tmp[3] == self.byteToInt(b'\x01'): self.outOpenDooSuccess.emit(doorNumber) elif tmp[3] == self.byteToInt(b'\x02'): self.outOpenDooSuccessByUser.emit( doorNumber) elif tmp[2] == self.byteToInt(b'\xcc'): self.inOpenDoorSuccess.emit(doorNumber) stlist = [hex(c) for c in tmp] st = " ".join(stlist) self.getDataSingal.emit(st) else: self.mylogger.error('LRC check fail.') break self.data.append(self.readAll()) break print("accept Data finish.") self.mylogger.info("Accept door_controller Data finish.")
class SerialWidget(QWidget): def __init__(self, parent=None): super().__init__(parent) self.__data = QByteArray() self.__serial = QSerialPort() self.__timer = QTimer(self) for info in QSerialPortInfo.availablePorts(): if info.description() == "USB-SERIAL CH340": self.__serial = QSerialPort(info) print(self.__serial.portName()) break self.__serial.readyRead.connect(self.__read_data) self.__timer.timeout.connect(self.__timer_update_com) self.__temperature = 0 self.__humidity = 0 self.__co2 = 0 self.__tvoc = 0 self.__pm25 = 0 self.__pm10 = 0 self.__o2 = 0 if self.__serial.open(QIODevice.ReadWrite): print("open success") else: print("open fail") self.__auto_save_thread = AutoSave(self) self.__auto_save_thread.start() def closeEvent(self, QCloseEvent): self.__auto_save_thread.kill() super().closeEvent(QCloseEvent) def __read_data(self): self.__timer.start(40) self.__data.append(self.__serial.readAll()) def __timer_update_com(self): self.__timer.stop() length = self.__data.length() i = 0 while i < length: num = ord(self.__data[i]) if num == 116: num = ord(self.__data[i + 1]) self.__temperature = num i += 1 print("temperature:" + str(self.__temperature)) elif num == 116 - ord('t') + ord('h'): num = ord(self.__data[i + 1]) self.__humidity = num i += 1 print("humidity:" + str(self.__humidity)) elif num == 116 - ord('t') + ord('c'): num = ord(self.__data[i + 1]) * 258 + ord(self.__data[i + 2]) self.__co2 = num i += 2 print("CO2:" + str(self.__co2)) num = ord(self.__data[i + 1]) * 258 + ord(self.__data[i + 2]) self.__tvoc = num i += 2 print("TVOC:" + str(self.__tvoc)) elif num == 116 - ord('t') + ord('o'): num = ord(self.__data[i + 1]) * 258 + ord(self.__data[i + 2]) num = num * (3300 / 4096) / 100 num = round(num, 3) self.__o2 = num i += 2 print("O2:" + str(self.__o2) + "%") elif num == 116 - ord('t') + ord('p'): num = ord(self.__data[i + 1]) * 258 + ord(self.__data[i + 2]) num /= 10 self.__pm25 = num i += 2 print("PM2.5:" + str(self.__pm25)) num = ord(self.__data[i + 1]) * 258 + ord(self.__data[i + 2]) num /= 10 self.__pm10 = num i += 2 print("PM10:" + str(self.__pm10)) i += 1 self.__data.clear() def get_temperature(self): return self.__temperature def get_humidity(self): return self.__humidity def get_co2(self): return self.__co2 def get_tvoc(self): return self.__tvoc def get_pm25(self): return self.__pm25 def get_pm10(self): return self.__pm10 def get_o2(self): return self.__o2