Important: Please read the Qt Code of Conduct -

How to make a message dispatcher ?

  • My QtApp needs to talk to a device connected via RS232 .
    This device sending byte messages to establish communication and expects properly formed responses.

    This messages starts with 0xAA followed by 2bytes holding the length of this message. e.g.: (i inserted spaces for better reading only )
    AA 0D 00 FF 11 22 33 44 FF FF FF FF 00 00

    • 0xAA = starter
    • 0×000d = dec 13 (length of message without startbyte)
    • 0xFF = command type
    • 0×11223344 = source address []
    • 0xFFFFFFFF = destination address, in this case ‘to all’
    • trailing 2 null bytes, not used or reserve

    Theseveral different messages may vary in length but the structure
    of the first 14 bytes is always the same.
    My primarly designed code to read this messages is shown below.
    void MainWindow::readyReadSlot() {

        if (port->bytesAvailable() > 2) {
            QByteArray part(port->peek(3));
            int pos = part.indexOf(0xAA, 0);
            if (pos > -1) {
                m_len = * 0xFF;
                m_len +=;
        if (port->bytesAvailable() > m_len+1) {
            m_data = port->read(m_len+1);
            ui->TE1->append(m_data.toHex().toUpper() );


    line 13 is just to see results, but this result should be send to a “dispatcher”
    which has to be created in near future.

    If the receive-buffer contains at least the starter byte and the length information, i wait until this number of bytes is received, then i read the entire message with
    given length.

    I’m pretty sure the above code can be done much smarter and more efficient.
    Most interesting now is a dispatcher for the diffrent types of messages coming in.
    How to design such dispatcher ?

    Actually i think about a custom class inherits QSerialport and emits signals depending on
    what response is required by particulary message coming from device.
    Maybe "QAbstractEventDispatcher " is an possibility (?)

    Dispatcher concepts and simple examples highly welcome.

Log in to reply