serial-portchecksumprefix

PyQT5 QtSerialPort checksum prefix question


The follow configuration: Raspberry Rpi4B / Python 3.11.2 / PyQt5 5.15.9

The follow configuration: Raspberry Rpi4B / Python 3.11.2 / PyQt5 5.15.9 I have a question about how to adjust prefix checksum byte, in my code I am missing the sign \x, the rest seems to work fine, also changing the last data bytes. See attached code and shell result

from PyQt5 import QtCore, QtWidgets, QtSerialPort

class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)
        
        self.send1_btn = QtWidgets.QPushButton(
            text="Send1",
            clicked=self.send1
        )
        lay = QtWidgets.QVBoxLayout(self)
        hlay = QtWidgets.QHBoxLayout()
        hlay.addWidget(self.send1_btn)
        lay.addLayout(hlay)
        
        self.serial = QtSerialPort.QSerialPort('/dev/ttyUSB0',
        baudRate=QtSerialPort.QSerialPort.Baud57600,
        parity=QtSerialPort.QSerialPort.NoParity,
        dataBits=QtSerialPort.QSerialPort.Data8,
        stopBits=QtSerialPort.QSerialPort.OneStop)
        self.serial.open(QtCore.QIODevice.ReadWrite)
        self.serial.setDataTerminalReady(True) 
        #self.serial.readyRead.connect(self.handle_ready_Read)
               
    def send1(self):
        intiger_val = 1468                       # value 1468 that I always want to adjust
        bytes_val = intiger_val.to_bytes(2,'big')
        print("bytes_val=",bytes_val)
        result = bytearray(b'\xCC\x04\x3C\x34')  # fixed previous bytes
        result.extend(bytes_val)
        print("result=",result)                  # correct bytes up to here
        def rs232_checksum(the_bytes):
            return b'%02X' % (sum(the_bytes) & 0xFF)
        checksum_bytes = rs232_checksum(result)
        print("checksum=",checksum_bytes)        # checksum byte correct but missing prefix \x
        result.extend(checksum_bytes)
        send_value=bytes(result)
        print("send_value=",send_value)          # Bytes correct but missing prefix \x 01
        self.serial.write(send_value)            #bytes must be '\xCC\x04\x3C\x34\x05\xbc\x01'

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())

Shell result

# bytes_val= b'\x05\xbc'
# result= bytearray(b'\xcc\x04<4\x05\xbc')
# checksum= b'01
# send_value= b'\xcc\x04<4\x05\xbc01'

Solution

  • It took me hours of searching, but I found a solution. There is maybe a shorter way, please give me then a comment. following inserted into the code

    import codecs

    checksum_convert=codecs.getdecoder('hex')(checksum_bytes)[0]