Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. Serial communication
Forum Updated to NodeBB v4.3 + New Features

Serial communication

Scheduled Pinned Locked Moved Solved General and Desktop
39 Posts 6 Posters 4.6k Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • D Offline
    D Offline
    Damian7546
    wrote on last edited by
    #1

    Hi,

    I would like to write serial communication to my device but I don't know how start. I would be really grateful if anyone can get me code skeleton to realising below timing diagram:
    TimmingDiagram.jpg

    I was thinking about using an example: "Blocking Master Example", and use three signals:

    void response(const QString &s);
    void error(const QString &s);
    void timeout(const QString &s);
    

    And inside the response slot I should use state machine based about switch instruction ?

    Please for any tips.

    J.HilkJ 1 Reply Last reply
    0
    • D Damian7546

      @J-Hilk It still doesn't work:
      m_responseStatus = static_cast<Response::Status>(m_request.at(2));

      Result:
      ASSERT: "uint(i) < uint(size())" in file C:/Qt/5.15.2/mingw81_32/include/QtCore/qbytearray.h, line 500

      J.HilkJ Online
      J.HilkJ Online
      J.Hilk
      Moderators
      wrote on last edited by
      #37

      @Damian7546 yes, but not the cast or assignment fails, but the access of your QByteArray, it doesn't have 3 Bytes in it and you try to access it outside of the range


      Be aware of the Qt Code of Conduct, when posting : https://forum.qt.io/topic/113070/qt-code-of-conduct


      Q: What's that?
      A: It's blue light.
      Q: What does it do?
      A: It turns blue.

      D 1 Reply Last reply
      2
      • D Damian7546

        Hi,

        I would like to write serial communication to my device but I don't know how start. I would be really grateful if anyone can get me code skeleton to realising below timing diagram:
        TimmingDiagram.jpg

        I was thinking about using an example: "Blocking Master Example", and use three signals:

        void response(const QString &s);
        void error(const QString &s);
        void timeout(const QString &s);
        

        And inside the response slot I should use state machine based about switch instruction ?

        Please for any tips.

        J.HilkJ Online
        J.HilkJ Online
        J.Hilk
        Moderators
        wrote on last edited by J.Hilk
        #2

        @Damian7546 said in Serial communication:

        I was thinking about using an example: "Blocking Master Example"

        No, please use the async and not the blocking functions. The blocking ones are only meant to be used on systems without an event loop.

        You can either do your "State machine" yourself, or you use the convenient https://doc.qt.io/qt-6/qstatemachine.html class :D


        +1 for ai generated code examples:

        #include <QCoreApplication>
        #include <QStateMachine>
        #include <QSerialPort>
        #include <QTimer>
        #include <QDebug>
        
        class SerialComm : public QObject
        {
            Q_OBJECT
            QStateMachine machine;
            QState *s1;
            QState *s2;
            QSerialPort serial;
            QTimer timer;
        
        public:
            SerialComm() {
                s1 = new QState();
                s2 = new QState();
        
                s1->addTransition(this, SIGNAL(requestSent()), s2);
                s2->addTransition(this, SIGNAL(doneReading()), s1);
                s2->addTransition(&timer, SIGNAL(timeout()), s1);
        
                machine.addState(s1);
                machine.addState(s2);
        
                machine.setInitialState(s1);
                machine.start();
        
                connect(&serial, SIGNAL(readyRead()), this, SLOT(readData()));
                connect(this, SIGNAL(doneReading()), &serial, SLOT(clear()));
        
                serial.setPortName("COM1");
                serial.setBaudRate(QSerialPort::Baud9600);
                serial.open(QIODevice::ReadWrite);
        
                timer.setInterval(3000); // 3 seconds timeout
                timer.setSingleShot(true);
            }
        
        public slots:
            void sendRequest() {
                QByteArray request = "Your request data";
                serial.write(request);
                emit requestSent();
                timer.start();
            }
        
            void readData() {
                QByteArray data = serial.readAll();
                qDebug() << "Received: " << data;
                emit doneReading();
                timer.stop();
            }
        
        signals:
            void doneReading();
            void requestSent();
        };
        
        int main(int argc, char *argv[])
        {
            QCoreApplication a(argc, argv);
            SerialComm comm;
            QTimer::singleShot(0, &comm, SLOT(sendRequest()));
            return a.exec();
        }
        
        

        Be aware of the Qt Code of Conduct, when posting : https://forum.qt.io/topic/113070/qt-code-of-conduct


        Q: What's that?
        A: It's blue light.
        Q: What does it do?
        A: It turns blue.

        D JonBJ 2 Replies Last reply
        1
        • J.HilkJ J.Hilk

          @Damian7546 said in Serial communication:

          I was thinking about using an example: "Blocking Master Example"

          No, please use the async and not the blocking functions. The blocking ones are only meant to be used on systems without an event loop.

          You can either do your "State machine" yourself, or you use the convenient https://doc.qt.io/qt-6/qstatemachine.html class :D


          +1 for ai generated code examples:

          #include <QCoreApplication>
          #include <QStateMachine>
          #include <QSerialPort>
          #include <QTimer>
          #include <QDebug>
          
          class SerialComm : public QObject
          {
              Q_OBJECT
              QStateMachine machine;
              QState *s1;
              QState *s2;
              QSerialPort serial;
              QTimer timer;
          
          public:
              SerialComm() {
                  s1 = new QState();
                  s2 = new QState();
          
                  s1->addTransition(this, SIGNAL(requestSent()), s2);
                  s2->addTransition(this, SIGNAL(doneReading()), s1);
                  s2->addTransition(&timer, SIGNAL(timeout()), s1);
          
                  machine.addState(s1);
                  machine.addState(s2);
          
                  machine.setInitialState(s1);
                  machine.start();
          
                  connect(&serial, SIGNAL(readyRead()), this, SLOT(readData()));
                  connect(this, SIGNAL(doneReading()), &serial, SLOT(clear()));
          
                  serial.setPortName("COM1");
                  serial.setBaudRate(QSerialPort::Baud9600);
                  serial.open(QIODevice::ReadWrite);
          
                  timer.setInterval(3000); // 3 seconds timeout
                  timer.setSingleShot(true);
              }
          
          public slots:
              void sendRequest() {
                  QByteArray request = "Your request data";
                  serial.write(request);
                  emit requestSent();
                  timer.start();
              }
          
              void readData() {
                  QByteArray data = serial.readAll();
                  qDebug() << "Received: " << data;
                  emit doneReading();
                  timer.stop();
              }
          
          signals:
              void doneReading();
              void requestSent();
          };
          
          int main(int argc, char *argv[])
          {
              QCoreApplication a(argc, argv);
              SerialComm comm;
              QTimer::singleShot(0, &comm, SLOT(sendRequest()));
              return a.exec();
          }
          
          
          D Offline
          D Offline
          Damian7546
          wrote on last edited by Damian7546
          #3

          @J-Hilk Would you put in my timing chart to your code? only by using mnemonic

          1 Reply Last reply
          0
          • J.HilkJ J.Hilk

            @Damian7546 said in Serial communication:

            I was thinking about using an example: "Blocking Master Example"

            No, please use the async and not the blocking functions. The blocking ones are only meant to be used on systems without an event loop.

            You can either do your "State machine" yourself, or you use the convenient https://doc.qt.io/qt-6/qstatemachine.html class :D


            +1 for ai generated code examples:

            #include <QCoreApplication>
            #include <QStateMachine>
            #include <QSerialPort>
            #include <QTimer>
            #include <QDebug>
            
            class SerialComm : public QObject
            {
                Q_OBJECT
                QStateMachine machine;
                QState *s1;
                QState *s2;
                QSerialPort serial;
                QTimer timer;
            
            public:
                SerialComm() {
                    s1 = new QState();
                    s2 = new QState();
            
                    s1->addTransition(this, SIGNAL(requestSent()), s2);
                    s2->addTransition(this, SIGNAL(doneReading()), s1);
                    s2->addTransition(&timer, SIGNAL(timeout()), s1);
            
                    machine.addState(s1);
                    machine.addState(s2);
            
                    machine.setInitialState(s1);
                    machine.start();
            
                    connect(&serial, SIGNAL(readyRead()), this, SLOT(readData()));
                    connect(this, SIGNAL(doneReading()), &serial, SLOT(clear()));
            
                    serial.setPortName("COM1");
                    serial.setBaudRate(QSerialPort::Baud9600);
                    serial.open(QIODevice::ReadWrite);
            
                    timer.setInterval(3000); // 3 seconds timeout
                    timer.setSingleShot(true);
                }
            
            public slots:
                void sendRequest() {
                    QByteArray request = "Your request data";
                    serial.write(request);
                    emit requestSent();
                    timer.start();
                }
            
                void readData() {
                    QByteArray data = serial.readAll();
                    qDebug() << "Received: " << data;
                    emit doneReading();
                    timer.stop();
                }
            
            signals:
                void doneReading();
                void requestSent();
            };
            
            int main(int argc, char *argv[])
            {
                QCoreApplication a(argc, argv);
                SerialComm comm;
                QTimer::singleShot(0, &comm, SLOT(sendRequest()));
                return a.exec();
            }
            
            
            JonBJ Offline
            JonBJ Offline
            JonB
            wrote on last edited by JonB
            #4

            @J-Hilk said in Serial communication:

            +1 for ai generated code examples:

            Just a shame that it uses SIGNAL()/SLOT() when a far better replacement was introduced before ChatGPT was even born. I guess now these will never, ever be removed from example code if ChatGPT recommends it now....

            Pl45m4P 1 Reply Last reply
            1
            • JonBJ JonB

              @J-Hilk said in Serial communication:

              +1 for ai generated code examples:

              Just a shame that it uses SIGNAL()/SLOT() when a far better replacement was introduced before ChatGPT was even born. I guess now these will never, ever be removed from example code if ChatGPT recommends it now....

              Pl45m4P Offline
              Pl45m4P Offline
              Pl45m4
              wrote on last edited by
              #5

              @JonB

              Haha, you are on a misson to personally ban the old syntax from the Internet, aren't you? 🤣

              But serious, it's kinda interesting that even beginners who start with Qt6, use the good old Qt4 string based connections :D


              If debugging is the process of removing software bugs, then programming must be the process of putting them in.

              ~E. W. Dijkstra

              1 Reply Last reply
              0
              • D Offline
                D Offline
                Damian7546
                wrote on last edited by Damian7546
                #6

                Back to the topic of discussion, I have a little problem:
                I defined class like below:

                class Response
                {
                public:
                    enum class Status : quint8{
                        ENABLE = 0x11,
                    };
                    Response();
                };
                

                In other class I have defined vriables:

                Response::Status m_responseStatus;
                QByteArray m_data;
                

                How I can assign below variables ?

                m_responseStatus = m_data[2];
                if (m_responseStatus == Response::Status::ENABLE)
                
                jsulmJ 1 Reply Last reply
                0
                • D Damian7546

                  Back to the topic of discussion, I have a little problem:
                  I defined class like below:

                  class Response
                  {
                  public:
                      enum class Status : quint8{
                          ENABLE = 0x11,
                      };
                      Response();
                  };
                  

                  In other class I have defined vriables:

                  Response::Status m_responseStatus;
                  QByteArray m_data;
                  

                  How I can assign below variables ?

                  m_responseStatus = m_data[2];
                  if (m_responseStatus == Response::Status::ENABLE)
                  
                  jsulmJ Online
                  jsulmJ Online
                  jsulm
                  Lifetime Qt Champion
                  wrote on last edited by
                  #7

                  @Damian7546 said in Serial communication:

                  How I can assign below variables ?

                  You need to extract the part of the byte array containing the status and cast it to Response::Status. You can for example use https://doc.qt.io/qt-6/qbytearray.html#mid to get the part of the byte array containing status, convert it to int using https://doc.qt.io/qt-6/qbytearray.html#toInt and then cast.

                  https://forum.qt.io/topic/113070/qt-code-of-conduct

                  D 1 Reply Last reply
                  0
                  • jsulmJ jsulm

                    @Damian7546 said in Serial communication:

                    How I can assign below variables ?

                    You need to extract the part of the byte array containing the status and cast it to Response::Status. You can for example use https://doc.qt.io/qt-6/qbytearray.html#mid to get the part of the byte array containing status, convert it to int using https://doc.qt.io/qt-6/qbytearray.html#toInt and then cast.

                    D Offline
                    D Offline
                    Damian7546
                    wrote on last edited by Damian7546
                    #8

                    @jsulm Do you mean about this notation:
                    m_responseStatus = (Response::Status)m_request.mid(2,1).toInt(nullptr, 16);

                    ?

                    jsulmJ 1 Reply Last reply
                    0
                    • D Damian7546

                      @jsulm Do you mean about this notation:
                      m_responseStatus = (Response::Status)m_request.mid(2,1).toInt(nullptr, 16);

                      ?

                      jsulmJ Online
                      jsulmJ Online
                      jsulm
                      Lifetime Qt Champion
                      wrote on last edited by
                      #9

                      @Damian7546 Something like this. But better don't use c-style casts:

                      m_responseStatus = static_cast<Response::Status>(m_request.mid(2,1).toInt(nullptr, 16));
                      

                      https://forum.qt.io/topic/113070/qt-code-of-conduct

                      D 2 Replies Last reply
                      2
                      • jsulmJ jsulm

                        @Damian7546 Something like this. But better don't use c-style casts:

                        m_responseStatus = static_cast<Response::Status>(m_request.mid(2,1).toInt(nullptr, 16));
                        
                        D Offline
                        D Offline
                        Damian7546
                        wrote on last edited by Damian7546
                        #10

                        @jsulm Thank you.

                        On base above proposition, I prepared conception synchronous serial communication (without blocking) with my device using state machine.

                        • Firstly I changed old Qt4 string based connections,
                        • Secondly I prefer use switch instruction instead QStateMachine

                        This is only skeleton, without any tests . I would like to know yours opinion, What do you think about below solution:

                        #include "mydevice.h"
                        
                        
                        MyDevice::MyDevice(QObject *parent)
                            : QObject{parent}
                        {
                            serial = new QSerialPort();
                            serial->setPortName("COM9");
                            serial->setBaudRate(QSerialPort::Baud9600);
                            serial->setDataBits(QSerialPort::Data8);
                            serial->setParity(QSerialPort::EvenParity);
                            serial->open(QIODevice::ReadWrite);
                        
                            connect(serial, &QSerialPort::readyRead, this, &MyDevice::serialRecive);
                        
                            connect(&timerResponse, &QTimer::timeout, this, [&](){  m_timeoutResponse = true;
                                timerResponse.stop();
                                qDebug()<<"Timeout response";}
                        
                            );
                            connect(&timerState, &QTimer::timeout, this, &MyDevice::stateMachine);
                        
                        
                        
                            if(!serial->isOpen()){
                                qInfo() << "Serial port status: " << serial->isOpen();
                            }else{
                                //run state machine!
                         	m_state = State::state::STATUS_REQUEST;
                                timerState.start(100);
                            }
                        
                           
                        
                        }
                        
                        void MyDevice::serialRecive()
                        {
                        
                            m_request.append(serial->readAll());
                        
                            while(!messageComplete(m_request) && !m_timeoutResponse) {
                                if(!serial->waitForReadyRead(20)){
                                    qDebug()<<"Incomplete response";
                                    m_state = State::state::STATUS_REQUEST;
                                    return;
                                }
                                m_request.append(serial->readAll());
                            }
                        
                            bool crcValid=validateResponse(m_request);
                            if(!crcValid){
                                qDebug()<<"Crc error";
                                m_state = State::state::STATUS_REQUEST;
                                return;
                            }
                        
                            if(m_timeoutResponse)
                            {
                                qDebug()<<"Timeout response";
                                m_state = State::state::STATUS_REQUEST;
                                return;
                            }
                        
                            timerResponse.stop();
                            qDebug()<<"Correct response: " << m_request;
                        }
                        
                        
                        
                        void MyDevice::stateMachine()
                        {
                        
                            m_responseStatus = static_cast<Response::Status>(m_request.mid(2,1).toInt(nullptr, 16));
                        
                        
                            switch (m_state)
                            {
                            case State::state::STATUS_REQUEST:
                                timerResponse.start(m_timeout);
                                clearBuffers();
                                serial->write(createMessage(Commands::deviceCommand::POLL,m_data));
                                m_state = State::state::STATUS_RESPONSE;
                                break;
                            case State::state::STATUS_RESPONSE:
                                if(m_responseStatus == Response::Status::POWER_UP)  m_state = State::state::VERSION_REQUEST;
                                if(m_responseStatus == Response::Status::POWER_UP_WITH_BILL_IN_ACCEPTOR) m_state = State::state::RESET_REQUEST;
                                if(m_responseStatus == Response::Status::POWER_UP_WITH_BILL_IN_STACKER) m_state = State::state::RESET_REQUEST;
                                if(m_responseStatus == Response::Status::INITIALIZE) m_state = State::state::EN_DIS_REQUEST;
                                if(m_responseStatus == Response::Status::ENABLE) m_state = State::state::STATUS_REQUEST;
                                if(m_responseStatus == Response::Status::ACCEPTING) m_state = State::state::STATUS_REQUEST;
                                if(m_responseStatus == Response::Status::ESCROW) m_state = State::state::STACK1_REQUEST;
                                if(m_responseStatus == Response::Status::STACKING) m_state = State::state::STATUS_REQUEST;
                                if(m_responseStatus == Response::Status::STACKED) m_state = State::state::STATUS_REQUEST;
                                if(m_responseStatus == Response::Status::VALID) m_state = State::state::ACK_REQUEST;
                                if(m_responseStatus == Response::Status::REJECTING) m_state = State::state::STATUS_REQUEST;
                                if(m_responseStatus == Response::Status::JAM_IN_ACCEPTOR) m_state = State::state::STATUS_REQUEST;
                                if(m_timeoutResponse) {
                                    m_timeoutResponse = false;
                                    m_state = State::state::STATUS_REQUEST;
                                }
                                break;
                        
                        
                            case State::state::VERSION_REQUEST:
                                timerResponse.start(m_timeout);
                                clearBuffers();
                                serial->write(createMessage(Commands::deviceCommand::GET_VERSION,m_data));
                                m_state = State::state::VERSION_RESPONSE;
                                break;
                            case State::state::VERSION_RESPONSE:
                                if(m_responseStatus == Response::Status::STAT_VERSION) m_state = State::state::RESET_REQUEST;
                                if(m_timeoutResponse) {
                                    m_timeoutResponse = false;
                                    m_state = State::state::STATUS_REQUEST;
                                }
                                break;
                        
                        
                        
                            case State::state::RESET_REQUEST:
                                timerResponse.start(m_timeout);
                                clearBuffers();
                                serial->write(createMessage(Commands::deviceCommand::RESET,m_data));
                                m_state = State::state::RESET_RESPONSE;
                                break;
                            case State::state::RESET_RESPONSE:
                                if(m_responseStatus == Response::Status::ACK) m_state = State::state::STATUS_REQUEST;
                                if(m_timeoutResponse) {
                                    m_timeoutResponse = false;
                                    m_state = State::state::STATUS_REQUEST;
                                }
                                break;
                        
                        
                        
                        
                        
                            case State::state::EN_DIS_REQUEST:
                                timerResponse.start(m_timeout);
                                clearBuffers();
                                m_data = QByteArray("\xff\xff",2);
                                serial->write(createMessage(Commands::deviceCommand::ENABLE,m_data));
                                m_state = State::state::EN_DIS_RESPONSE;
                                break;
                            case State::state::EN_DIS_RESPONSE:
                                if(m_responseStatus == Response::Status::STAT_EN_DIS) m_state = State::state::SECURITY_REQUEST;
                                if(m_timeoutResponse) {
                                    m_timeoutResponse = false;
                                    m_state = State::state::STATUS_REQUEST;
                                }
                                break;
                        
                        
                        
                        
                        
                            case State::state::SECURITY_REQUEST:
                                timerResponse.start(m_timeout);
                                clearBuffers();
                                m_data = QByteArray("\xff\xff",2);
                                serial->write(createMessage(Commands::deviceCommand::SECURITY,m_data));
                                m_state = State::state::SECURITY_REQUEST;
                                break;
                            case State::state::SECURITY_RESPONSE:
                                if(m_responseStatus == Response::Status::CMD_ENABLE_SECURITY) m_state = State::state::OPTIONAL_FUN_REQUEST;
                                if(m_timeoutResponse) {
                                    m_timeoutResponse = false;
                                    m_state = State::state::STATUS_REQUEST;
                                }
                                break;
                        
                        
                        
                        
                        
                        
                            case State::state::OPTIONAL_FUN_REQUEST:
                                timerResponse.start(m_timeout);
                                clearBuffers();
                                serial->write(createMessage(Commands::deviceCommand::OPTIONAL,m_data));
                                m_state = State::state::OPTIONAL_FUN_RESPONSE;
                                break;
                            case State::state::OPTIONAL_FUN_RESPONSE:
                                if(m_responseStatus == Response::Status::CMD_OPTIONAL) m_state = State::state::INHIBIT_REQUEST;
                                if(m_timeoutResponse) {
                                    m_timeoutResponse = false;
                                    m_state = State::state::STATUS_REQUEST;
                                }
                                break;
                        
                        
                        
                        
                            case State::state::INHIBIT_REQUEST:
                                timerResponse.start(m_timeout);
                                clearBuffers();
                                serial->write(createMessage(Commands::deviceCommand::INHIBIT,m_data));
                                m_state = State::state::INHIBIT_RESPONSE;
                                break;
                            case State::state::INHIBIT_RESPONSE:
                                if(m_responseStatus == Response::Status::CMD_INHIBIT)  m_state = State::state::STATUS_REQUEST;
                                if(m_timeoutResponse) {
                                    m_timeoutResponse = false;
                                    m_state = State::state::STATUS_REQUEST;
                                }
                                break;
                        
                        
                        
                        
                        
                            case State::state::STACK1_REQUEST:
                                timerResponse.start(m_timeout);
                                clearBuffers();
                                serial->write(createMessage(Commands::deviceCommand::STACK1,m_data));
                                m_state = State::state::STACK1_RESPONSE;
                                break;
                        
                            case State::state::STACK1_RESPONSE:
                                if(m_responseStatus == Response::Status::ACK) m_state = State::state::STATUS_REQUEST;
                                if(m_timeoutResponse) {
                                    m_timeoutResponse = false;
                                    m_state = State::state::STATUS_REQUEST;
                                }
                                break;
                        
                        
                        
                        
                        
                        
                            case State::state::STACK2_REQUEST:
                                timerResponse.start(m_timeout);
                                clearBuffers();
                                serial->write(createMessage(Commands::deviceCommand::STACK2,m_data));
                                m_state = State::state::STACK2_RESPONSE;
                                break;
                        
                            case State::state::STACK2_RESPONSE:
                                if(m_responseStatus == Response::Status::ACK) m_state = State::state::STATUS_REQUEST;
                                if(m_timeoutResponse) {
                                    m_timeoutResponse = false;
                                    m_state = State::state::STATUS_REQUEST;
                                }
                                break;
                        
                        
                        
                        
                        
                            case State::state::ACK_REQUEST:
                                timerResponse.start(m_timeout);
                                clearBuffers();
                                serial->write(createMessage(Commands::deviceCommand::ACK,m_data));
                                m_state = State::state::STATUS_REQUEST;
                                break;
                        
                        
                        
                        
                        
                        
                            case State::state::RETURN_REQUEST:
                                timerResponse.start(m_timeout);
                                clearBuffers();
                                serial->write(createMessage(Commands::deviceCommand::RETURN,m_data));
                                m_state = State::state::RETURN_RESPONSE;
                                break;
                        
                            case State::state::RETURN_RESPONSE:
                                if(m_responseStatus == Response::Status::ACK) m_state = State::state::STATUS_REQUEST;
                                if(m_timeoutResponse) {
                                    m_timeoutResponse = false;
                                    m_state = State::state::STATUS_REQUEST;
                                }
                                break;
                            default:
                                break;
                            }
                        
                        
                        }
                        
                        void MyDevice::clearBuffers()
                        {
                            m_request.clear();
                            m_data.clear();
                        }
                        
                        bool MyDevice::messageComplete(const QByteArray &data) const
                        {
                            if(data.size()>=3){
                                quint8 length=(unsigned char)data[1];
                                if(length==data.length())
                                    return true;
                            }
                            return false;
                        }
                        
                        bool MyDevice::validateResponse(QByteArray data)
                        {
                            if(data.size()<3)
                                return false;
                        
                            QByteArray crc=data.right(2);
                            std::reverse(crc.begin(),crc.end());
                            bool ok=false;
                        
                            quint16 messageCRC=crc.toHex().toUInt(&ok,16);
                            if(!ok)
                                return false;
                        
                            data.chop(2);
                        
                            return (messageCRC==crc16(data));
                        }
                        QByteArray MyDevice::createMessage(const Commands::deviceCommand &cmd, const QByteArray &data)
                        {
                            QByteArray message;
                            message.append(0xFC);
                        
                            if(data.count() > 0) {
                                message.append(0x05+data.count());
                            }
                            else{
                                message.append(0x05);
                            }
                            message.append((char)cmd);
                        
                            if(data.count() > 0) {
                                for (int i= 0 ; i< data.count() ; i++)
                                    message.append(data[i]);
                            }
                        
                        
                            quint16 crc=crc16(message);
                            QByteArray crcData=QByteArray((char *)&crc,2);
                        
                            message.append(crcData);
                        
                            return message;
                        
                        
                        }
                        
                        quint16 MyDevice::crc16(const QByteArray &data)
                        {
                            unsigned int CRC;
                            unsigned char j;
                            CRC = 0;
                            for(int i=0; i < data.size(); i++)
                            {
                                CRC ^= (unsigned char)data[i];
                                for(j=0; j < 8; j++)
                                {
                                    if(CRC & 0x0001) {CRC >>= 1; CRC ^= POLYNOMIAL;}
                                    else CRC >>= 1;
                                }
                            }
                            return CRC;
                        }
                        
                        
                        
                        JonBJ 1 Reply Last reply
                        0
                        • D Damian7546

                          @jsulm Thank you.

                          On base above proposition, I prepared conception synchronous serial communication (without blocking) with my device using state machine.

                          • Firstly I changed old Qt4 string based connections,
                          • Secondly I prefer use switch instruction instead QStateMachine

                          This is only skeleton, without any tests . I would like to know yours opinion, What do you think about below solution:

                          #include "mydevice.h"
                          
                          
                          MyDevice::MyDevice(QObject *parent)
                              : QObject{parent}
                          {
                              serial = new QSerialPort();
                              serial->setPortName("COM9");
                              serial->setBaudRate(QSerialPort::Baud9600);
                              serial->setDataBits(QSerialPort::Data8);
                              serial->setParity(QSerialPort::EvenParity);
                              serial->open(QIODevice::ReadWrite);
                          
                              connect(serial, &QSerialPort::readyRead, this, &MyDevice::serialRecive);
                          
                              connect(&timerResponse, &QTimer::timeout, this, [&](){  m_timeoutResponse = true;
                                  timerResponse.stop();
                                  qDebug()<<"Timeout response";}
                          
                              );
                              connect(&timerState, &QTimer::timeout, this, &MyDevice::stateMachine);
                          
                          
                          
                              if(!serial->isOpen()){
                                  qInfo() << "Serial port status: " << serial->isOpen();
                              }else{
                                  //run state machine!
                           	m_state = State::state::STATUS_REQUEST;
                                  timerState.start(100);
                              }
                          
                             
                          
                          }
                          
                          void MyDevice::serialRecive()
                          {
                          
                              m_request.append(serial->readAll());
                          
                              while(!messageComplete(m_request) && !m_timeoutResponse) {
                                  if(!serial->waitForReadyRead(20)){
                                      qDebug()<<"Incomplete response";
                                      m_state = State::state::STATUS_REQUEST;
                                      return;
                                  }
                                  m_request.append(serial->readAll());
                              }
                          
                              bool crcValid=validateResponse(m_request);
                              if(!crcValid){
                                  qDebug()<<"Crc error";
                                  m_state = State::state::STATUS_REQUEST;
                                  return;
                              }
                          
                              if(m_timeoutResponse)
                              {
                                  qDebug()<<"Timeout response";
                                  m_state = State::state::STATUS_REQUEST;
                                  return;
                              }
                          
                              timerResponse.stop();
                              qDebug()<<"Correct response: " << m_request;
                          }
                          
                          
                          
                          void MyDevice::stateMachine()
                          {
                          
                              m_responseStatus = static_cast<Response::Status>(m_request.mid(2,1).toInt(nullptr, 16));
                          
                          
                              switch (m_state)
                              {
                              case State::state::STATUS_REQUEST:
                                  timerResponse.start(m_timeout);
                                  clearBuffers();
                                  serial->write(createMessage(Commands::deviceCommand::POLL,m_data));
                                  m_state = State::state::STATUS_RESPONSE;
                                  break;
                              case State::state::STATUS_RESPONSE:
                                  if(m_responseStatus == Response::Status::POWER_UP)  m_state = State::state::VERSION_REQUEST;
                                  if(m_responseStatus == Response::Status::POWER_UP_WITH_BILL_IN_ACCEPTOR) m_state = State::state::RESET_REQUEST;
                                  if(m_responseStatus == Response::Status::POWER_UP_WITH_BILL_IN_STACKER) m_state = State::state::RESET_REQUEST;
                                  if(m_responseStatus == Response::Status::INITIALIZE) m_state = State::state::EN_DIS_REQUEST;
                                  if(m_responseStatus == Response::Status::ENABLE) m_state = State::state::STATUS_REQUEST;
                                  if(m_responseStatus == Response::Status::ACCEPTING) m_state = State::state::STATUS_REQUEST;
                                  if(m_responseStatus == Response::Status::ESCROW) m_state = State::state::STACK1_REQUEST;
                                  if(m_responseStatus == Response::Status::STACKING) m_state = State::state::STATUS_REQUEST;
                                  if(m_responseStatus == Response::Status::STACKED) m_state = State::state::STATUS_REQUEST;
                                  if(m_responseStatus == Response::Status::VALID) m_state = State::state::ACK_REQUEST;
                                  if(m_responseStatus == Response::Status::REJECTING) m_state = State::state::STATUS_REQUEST;
                                  if(m_responseStatus == Response::Status::JAM_IN_ACCEPTOR) m_state = State::state::STATUS_REQUEST;
                                  if(m_timeoutResponse) {
                                      m_timeoutResponse = false;
                                      m_state = State::state::STATUS_REQUEST;
                                  }
                                  break;
                          
                          
                              case State::state::VERSION_REQUEST:
                                  timerResponse.start(m_timeout);
                                  clearBuffers();
                                  serial->write(createMessage(Commands::deviceCommand::GET_VERSION,m_data));
                                  m_state = State::state::VERSION_RESPONSE;
                                  break;
                              case State::state::VERSION_RESPONSE:
                                  if(m_responseStatus == Response::Status::STAT_VERSION) m_state = State::state::RESET_REQUEST;
                                  if(m_timeoutResponse) {
                                      m_timeoutResponse = false;
                                      m_state = State::state::STATUS_REQUEST;
                                  }
                                  break;
                          
                          
                          
                              case State::state::RESET_REQUEST:
                                  timerResponse.start(m_timeout);
                                  clearBuffers();
                                  serial->write(createMessage(Commands::deviceCommand::RESET,m_data));
                                  m_state = State::state::RESET_RESPONSE;
                                  break;
                              case State::state::RESET_RESPONSE:
                                  if(m_responseStatus == Response::Status::ACK) m_state = State::state::STATUS_REQUEST;
                                  if(m_timeoutResponse) {
                                      m_timeoutResponse = false;
                                      m_state = State::state::STATUS_REQUEST;
                                  }
                                  break;
                          
                          
                          
                          
                          
                              case State::state::EN_DIS_REQUEST:
                                  timerResponse.start(m_timeout);
                                  clearBuffers();
                                  m_data = QByteArray("\xff\xff",2);
                                  serial->write(createMessage(Commands::deviceCommand::ENABLE,m_data));
                                  m_state = State::state::EN_DIS_RESPONSE;
                                  break;
                              case State::state::EN_DIS_RESPONSE:
                                  if(m_responseStatus == Response::Status::STAT_EN_DIS) m_state = State::state::SECURITY_REQUEST;
                                  if(m_timeoutResponse) {
                                      m_timeoutResponse = false;
                                      m_state = State::state::STATUS_REQUEST;
                                  }
                                  break;
                          
                          
                          
                          
                          
                              case State::state::SECURITY_REQUEST:
                                  timerResponse.start(m_timeout);
                                  clearBuffers();
                                  m_data = QByteArray("\xff\xff",2);
                                  serial->write(createMessage(Commands::deviceCommand::SECURITY,m_data));
                                  m_state = State::state::SECURITY_REQUEST;
                                  break;
                              case State::state::SECURITY_RESPONSE:
                                  if(m_responseStatus == Response::Status::CMD_ENABLE_SECURITY) m_state = State::state::OPTIONAL_FUN_REQUEST;
                                  if(m_timeoutResponse) {
                                      m_timeoutResponse = false;
                                      m_state = State::state::STATUS_REQUEST;
                                  }
                                  break;
                          
                          
                          
                          
                          
                          
                              case State::state::OPTIONAL_FUN_REQUEST:
                                  timerResponse.start(m_timeout);
                                  clearBuffers();
                                  serial->write(createMessage(Commands::deviceCommand::OPTIONAL,m_data));
                                  m_state = State::state::OPTIONAL_FUN_RESPONSE;
                                  break;
                              case State::state::OPTIONAL_FUN_RESPONSE:
                                  if(m_responseStatus == Response::Status::CMD_OPTIONAL) m_state = State::state::INHIBIT_REQUEST;
                                  if(m_timeoutResponse) {
                                      m_timeoutResponse = false;
                                      m_state = State::state::STATUS_REQUEST;
                                  }
                                  break;
                          
                          
                          
                          
                              case State::state::INHIBIT_REQUEST:
                                  timerResponse.start(m_timeout);
                                  clearBuffers();
                                  serial->write(createMessage(Commands::deviceCommand::INHIBIT,m_data));
                                  m_state = State::state::INHIBIT_RESPONSE;
                                  break;
                              case State::state::INHIBIT_RESPONSE:
                                  if(m_responseStatus == Response::Status::CMD_INHIBIT)  m_state = State::state::STATUS_REQUEST;
                                  if(m_timeoutResponse) {
                                      m_timeoutResponse = false;
                                      m_state = State::state::STATUS_REQUEST;
                                  }
                                  break;
                          
                          
                          
                          
                          
                              case State::state::STACK1_REQUEST:
                                  timerResponse.start(m_timeout);
                                  clearBuffers();
                                  serial->write(createMessage(Commands::deviceCommand::STACK1,m_data));
                                  m_state = State::state::STACK1_RESPONSE;
                                  break;
                          
                              case State::state::STACK1_RESPONSE:
                                  if(m_responseStatus == Response::Status::ACK) m_state = State::state::STATUS_REQUEST;
                                  if(m_timeoutResponse) {
                                      m_timeoutResponse = false;
                                      m_state = State::state::STATUS_REQUEST;
                                  }
                                  break;
                          
                          
                          
                          
                          
                          
                              case State::state::STACK2_REQUEST:
                                  timerResponse.start(m_timeout);
                                  clearBuffers();
                                  serial->write(createMessage(Commands::deviceCommand::STACK2,m_data));
                                  m_state = State::state::STACK2_RESPONSE;
                                  break;
                          
                              case State::state::STACK2_RESPONSE:
                                  if(m_responseStatus == Response::Status::ACK) m_state = State::state::STATUS_REQUEST;
                                  if(m_timeoutResponse) {
                                      m_timeoutResponse = false;
                                      m_state = State::state::STATUS_REQUEST;
                                  }
                                  break;
                          
                          
                          
                          
                          
                              case State::state::ACK_REQUEST:
                                  timerResponse.start(m_timeout);
                                  clearBuffers();
                                  serial->write(createMessage(Commands::deviceCommand::ACK,m_data));
                                  m_state = State::state::STATUS_REQUEST;
                                  break;
                          
                          
                          
                          
                          
                          
                              case State::state::RETURN_REQUEST:
                                  timerResponse.start(m_timeout);
                                  clearBuffers();
                                  serial->write(createMessage(Commands::deviceCommand::RETURN,m_data));
                                  m_state = State::state::RETURN_RESPONSE;
                                  break;
                          
                              case State::state::RETURN_RESPONSE:
                                  if(m_responseStatus == Response::Status::ACK) m_state = State::state::STATUS_REQUEST;
                                  if(m_timeoutResponse) {
                                      m_timeoutResponse = false;
                                      m_state = State::state::STATUS_REQUEST;
                                  }
                                  break;
                              default:
                                  break;
                              }
                          
                          
                          }
                          
                          void MyDevice::clearBuffers()
                          {
                              m_request.clear();
                              m_data.clear();
                          }
                          
                          bool MyDevice::messageComplete(const QByteArray &data) const
                          {
                              if(data.size()>=3){
                                  quint8 length=(unsigned char)data[1];
                                  if(length==data.length())
                                      return true;
                              }
                              return false;
                          }
                          
                          bool MyDevice::validateResponse(QByteArray data)
                          {
                              if(data.size()<3)
                                  return false;
                          
                              QByteArray crc=data.right(2);
                              std::reverse(crc.begin(),crc.end());
                              bool ok=false;
                          
                              quint16 messageCRC=crc.toHex().toUInt(&ok,16);
                              if(!ok)
                                  return false;
                          
                              data.chop(2);
                          
                              return (messageCRC==crc16(data));
                          }
                          QByteArray MyDevice::createMessage(const Commands::deviceCommand &cmd, const QByteArray &data)
                          {
                              QByteArray message;
                              message.append(0xFC);
                          
                              if(data.count() > 0) {
                                  message.append(0x05+data.count());
                              }
                              else{
                                  message.append(0x05);
                              }
                              message.append((char)cmd);
                          
                              if(data.count() > 0) {
                                  for (int i= 0 ; i< data.count() ; i++)
                                      message.append(data[i]);
                              }
                          
                          
                              quint16 crc=crc16(message);
                              QByteArray crcData=QByteArray((char *)&crc,2);
                          
                              message.append(crcData);
                          
                              return message;
                          
                          
                          }
                          
                          quint16 MyDevice::crc16(const QByteArray &data)
                          {
                              unsigned int CRC;
                              unsigned char j;
                              CRC = 0;
                              for(int i=0; i < data.size(); i++)
                              {
                                  CRC ^= (unsigned char)data[i];
                                  for(j=0; j < 8; j++)
                                  {
                                      if(CRC & 0x0001) {CRC >>= 1; CRC ^= POLYNOMIAL;}
                                      else CRC >>= 1;
                                  }
                              }
                              return CRC;
                          }
                          
                          
                          
                          JonBJ Offline
                          JonBJ Offline
                          JonB
                          wrote on last edited by JonB
                          #11

                          @Damian7546
                          I have an observation. Perhaps it is me/only a matter of approach or preference, but why do you choose to introduce waitForReadyRead() calls (in a loop) inside the slot handler for readyRead signal? It may work, but mixes asynchronous and synchronous approach.

                          I would make serialRecive() do nothing if messageComplete(m_request) is false. Just buffer the bytes into m_request and exit the slot (set m_state if appropriate). Then next time readyRead emitted and slot called append the new bytes and see whether now message completed again. When so, process the bytes received in the buffer, either directly in serialRecive(), or probably better emit a messageCompleted() signal of your own from there, and do your processing in a slot on that. Seems cleaner to me, but maybe up to you.

                          Christian EhrlicherC 1 Reply Last reply
                          1
                          • JonBJ JonB

                            @Damian7546
                            I have an observation. Perhaps it is me/only a matter of approach or preference, but why do you choose to introduce waitForReadyRead() calls (in a loop) inside the slot handler for readyRead signal? It may work, but mixes asynchronous and synchronous approach.

                            I would make serialRecive() do nothing if messageComplete(m_request) is false. Just buffer the bytes into m_request and exit the slot (set m_state if appropriate). Then next time readyRead emitted and slot called append the new bytes and see whether now message completed again. When so, process the bytes received in the buffer, either directly in serialRecive(), or probably better emit a messageCompleted() signal of your own from there, and do your processing in a slot on that. Seems cleaner to me, but maybe up to you.

                            Christian EhrlicherC Offline
                            Christian EhrlicherC Offline
                            Christian Ehrlicher
                            Lifetime Qt Champion
                            wrote on last edited by
                            #12

                            @JonB said in Serial communication:

                            It may work, but mixes asynchronous and synchronous approach.

                            But is also may eat kitten...
                            Don't do that. Buffer the data read in a member variable and wait for the next readyRead()

                            Qt Online Installer direct download: https://download.qt.io/official_releases/online_installers/
                            Visit the Qt Academy at https://academy.qt.io/catalog

                            D 1 Reply Last reply
                            0
                            • Christian EhrlicherC Christian Ehrlicher

                              @JonB said in Serial communication:

                              It may work, but mixes asynchronous and synchronous approach.

                              But is also may eat kitten...
                              Don't do that. Buffer the data read in a member variable and wait for the next readyRead()

                              D Offline
                              D Offline
                              Damian7546
                              wrote on last edited by Damian7546
                              #13

                              @Christian-Ehrlicher @JonB Thank you for yours suggestions.

                              I have implemented your comments,suggestions, and now code look like:

                              #include "mydevice.h"
                              
                              
                              MyDevice::MyDevice(QObject *parent)
                                  : QObject{parent}
                              {
                                  serial = new QSerialPort();
                                  serial->setPortName("COM9");
                                  serial->setBaudRate(QSerialPort::Baud9600);
                                  serial->setDataBits(QSerialPort::Data8);
                                  serial->setParity(QSerialPort::EvenParity);
                                  serial->open(QIODevice::ReadWrite);
                              
                                  connect(serial, &QSerialPort::readyRead, this, &MyDevice::serialRecive);
                              
                                  connect(&timerResponse, &QTimer::timeout, this, [&](){  m_timeoutResponse = true;
                                                                                          timerResponse.stop();
                                                                                          qDebug()<<"Timeout response";}
                              
                                  );
                                  connect(&timerState, &QTimer::timeout, this, &MyDevice::stateMachine);
                              
                              
                              
                                  if(!serial->isOpen()){
                                      qInfo() << "Serial port status: " << serial->isOpen();
                                  }else{
                                      //run state machine!
                                      m_state = State::state::STATUS_REQUEST;
                                      timerState.start(100);
                                  }
                              
                              
                              
                              }
                              
                              void MyDevice::serialRecive()
                              {
                                  m_request_part.append(serial->readAll());
                                  qDebug() << "Partially received: " << m_request_part;
                              
                                  while(!messageComplete(m_request_part)) {
                                      return;
                                  }
                              
                                  bool crcValid=validateResponse(m_request_part);
                                  if(!crcValid){
                                      qDebug()<<"Crc error";
                                      m_state = State::state::STATUS_REQUEST;
                                      return;
                                  }
                              
                                  timerResponse.stop();
                                  m_request = m_request_part;
                                  qDebug()<<"Correct response: " << m_request;
                              }
                              
                              
                              
                              void MyDevice::stateMachine()
                              {
                                  if (m_request.count() > 3)
                                      m_responseStatus = static_cast<Response::Status>(m_request.mid(2,1).toInt(nullptr, 16));
                                  else
                                      m_responseStatus = Response::Status::UNKNOWN;
                              
                              
                                  switch (m_state)
                                  {
                                  case State::state::STATUS_REQUEST:
                                      timerResponse.start(m_timeout);
                                      clearBuffers();
                                      serial->write(createMessage(Commands::deviceCommand::POLL,m_data));
                                      m_state = State::state::STATUS_RESPONSE;
                                      break;
                                  case State::state::STATUS_RESPONSE:
                                      if(m_responseStatus == Response::Status::POWER_UP)  m_state = State::state::VERSION_REQUEST;
                                      if(m_responseStatus == Response::Status::POWER_UP_WITH_BILL_IN_ACCEPTOR) m_state = State::state::RESET_REQUEST;
                                      if(m_responseStatus == Response::Status::POWER_UP_WITH_BILL_IN_STACKER) m_state = State::state::RESET_REQUEST;
                                      if(m_responseStatus == Response::Status::INITIALIZE) m_state = State::state::EN_DIS_REQUEST;
                                      if(m_responseStatus == Response::Status::ENABLE) m_state = State::state::STATUS_REQUEST;
                                      if(m_responseStatus == Response::Status::ACCEPTING) m_state = State::state::STATUS_REQUEST;
                                      if(m_responseStatus == Response::Status::ESCROW) m_state = State::state::STACK1_REQUEST;
                                      if(m_responseStatus == Response::Status::STACKING) m_state = State::state::STATUS_REQUEST;
                                      if(m_responseStatus == Response::Status::STACKED) m_state = State::state::STATUS_REQUEST;
                                      if(m_responseStatus == Response::Status::VALID) m_state = State::state::ACK_REQUEST;
                                      if(m_responseStatus == Response::Status::REJECTING) m_state = State::state::STATUS_REQUEST;
                                      if(m_responseStatus == Response::Status::JAM_IN_ACCEPTOR) m_state = State::state::STATUS_REQUEST;
                                      if(m_timeoutResponse) {
                                          m_timeoutResponse = false;
                                          m_state = State::state::STATUS_REQUEST;
                                      }
                                      break;
                              
                              
                                  case State::state::VERSION_REQUEST:
                                      timerResponse.start(m_timeout);
                                      clearBuffers();
                                      serial->write(createMessage(Commands::deviceCommand::GET_VERSION,m_data));
                                      m_state = State::state::VERSION_RESPONSE;
                                      break;
                                  case State::state::VERSION_RESPONSE:
                                      if(m_responseStatus == Response::Status::STAT_VERSION) m_state = State::state::RESET_REQUEST;
                                      if(m_timeoutResponse) {
                                          m_timeoutResponse = false;
                                          m_state = State::state::STATUS_REQUEST;
                                      }
                                      break;
                              
                              
                              
                                  case State::state::RESET_REQUEST:
                                      timerResponse.start(m_timeout);
                                      clearBuffers();
                                      serial->write(createMessage(Commands::deviceCommand::RESET,m_data));
                                      m_state = State::state::RESET_RESPONSE;
                                      break;
                                  case State::state::RESET_RESPONSE:
                                      if(m_responseStatus == Response::Status::ACK) m_state = State::state::STATUS_REQUEST;
                                      if(m_timeoutResponse) {
                                          m_timeoutResponse = false;
                                          m_state = State::state::STATUS_REQUEST;
                                      }
                                      break;
                              
                              
                              
                              
                              
                                  case State::state::EN_DIS_REQUEST:
                                      timerResponse.start(m_timeout);
                                      clearBuffers();
                                      m_data = QByteArray("\xff\xff",2);
                                      serial->write(createMessage(Commands::deviceCommand::ENABLE,m_data));
                                      m_state = State::state::EN_DIS_RESPONSE;
                                      break;
                                  case State::state::EN_DIS_RESPONSE:
                                      if(m_responseStatus == Response::Status::STAT_EN_DIS) m_state = State::state::SECURITY_REQUEST;
                                      if(m_timeoutResponse) {
                                          m_timeoutResponse = false;
                                          m_state = State::state::STATUS_REQUEST;
                                      }
                                      break;
                              
                              
                              
                              
                              
                                  case State::state::SECURITY_REQUEST:
                                      timerResponse.start(m_timeout);
                                      clearBuffers();
                                      m_data = QByteArray("\xff\xff",2);
                                      serial->write(createMessage(Commands::deviceCommand::SECURITY,m_data));
                                      m_state = State::state::SECURITY_REQUEST;
                                      break;
                                  case State::state::SECURITY_RESPONSE:
                                      if(m_responseStatus == Response::Status::CMD_ENABLE_SECURITY) m_state = State::state::OPTIONAL_FUN_REQUEST;
                                      if(m_timeoutResponse) {
                                          m_timeoutResponse = false;
                                          m_state = State::state::STATUS_REQUEST;
                                      }
                                      break;
                              
                              
                              
                              
                              
                              
                                  case State::state::OPTIONAL_FUN_REQUEST:
                                      timerResponse.start(m_timeout);
                                      clearBuffers();
                                      serial->write(createMessage(Commands::deviceCommand::OPTIONAL,m_data));
                                      m_state = State::state::OPTIONAL_FUN_RESPONSE;
                                      break;
                                  case State::state::OPTIONAL_FUN_RESPONSE:
                                      if(m_responseStatus == Response::Status::CMD_OPTIONAL) m_state = State::state::INHIBIT_REQUEST;
                                      if(m_timeoutResponse) {
                                          m_timeoutResponse = false;
                                          m_state = State::state::STATUS_REQUEST;
                                      }
                                      break;
                              
                              
                              
                              
                                  case State::state::INHIBIT_REQUEST:
                                      timerResponse.start(m_timeout);
                                      clearBuffers();
                                      serial->write(createMessage(Commands::deviceCommand::INHIBIT,m_data));
                                      m_state = State::state::INHIBIT_RESPONSE;
                                      break;
                                  case State::state::INHIBIT_RESPONSE:
                                      if(m_responseStatus == Response::Status::CMD_INHIBIT)  m_state = State::state::STATUS_REQUEST;
                                      if(m_timeoutResponse) {
                                          m_timeoutResponse = false;
                                          m_state = State::state::STATUS_REQUEST;
                                      }
                                      break;
                              
                              
                              
                              
                              
                                  case State::state::STACK1_REQUEST:
                                      timerResponse.start(m_timeout);
                                      clearBuffers();
                                      serial->write(createMessage(Commands::deviceCommand::STACK1,m_data));
                                      m_state = State::state::STACK1_RESPONSE;
                                      break;
                              
                                  case State::state::STACK1_RESPONSE:
                                      if(m_responseStatus == Response::Status::ACK) m_state = State::state::STATUS_REQUEST;
                                      if(m_timeoutResponse) {
                                          m_timeoutResponse = false;
                                          m_state = State::state::STATUS_REQUEST;
                                      }
                                      break;
                              
                              
                              
                              
                              
                              
                                  case State::state::STACK2_REQUEST:
                                      timerResponse.start(m_timeout);
                                      clearBuffers();
                                      serial->write(createMessage(Commands::deviceCommand::STACK2,m_data));
                                      m_state = State::state::STACK2_RESPONSE;
                                      break;
                              
                                  case State::state::STACK2_RESPONSE:
                                      if(m_responseStatus == Response::Status::ACK) m_state = State::state::STATUS_REQUEST;
                                      if(m_timeoutResponse) {
                                          m_timeoutResponse = false;
                                          m_state = State::state::STATUS_REQUEST;
                                      }
                                      break;
                              
                              
                              
                              
                              
                                  case State::state::ACK_REQUEST:
                                      timerResponse.start(m_timeout);
                                      clearBuffers();
                                      serial->write(createMessage(Commands::deviceCommand::ACK,m_data));
                                      m_state = State::state::STATUS_REQUEST;
                                      break;
                              
                              
                              
                              
                              
                              
                                  case State::state::RETURN_REQUEST:
                                      timerResponse.start(m_timeout);
                                      clearBuffers();
                                      serial->write(createMessage(Commands::deviceCommand::RETURN,m_data));
                                      m_state = State::state::RETURN_RESPONSE;
                                      break;
                              
                                  case State::state::RETURN_RESPONSE:
                                      if(m_responseStatus == Response::Status::ACK) m_state = State::state::STATUS_REQUEST;
                                      if(m_timeoutResponse) {
                                          m_timeoutResponse = false;
                                          m_state = State::state::STATUS_REQUEST;
                                      }
                                      break;
                                  default:
                                      break;
                                  }
                              
                              
                              }
                              
                              void MyDevice::clearBuffers()
                              {
                                  m_request.clear();
                                  m_data.clear();
                                  m_request_part.clear();
                              }
                              
                              bool MyDevice::messageComplete(const QByteArray &data) const
                              {
                                  if(data.size()>=3){
                                      quint8 length=(unsigned char)data[1];
                                      if(length==data.length())
                                          return true;
                                  }
                                  return false;
                              }
                              
                              bool MyDevice::validateResponse(QByteArray data)
                              {
                                  if(data.size()<3)
                                      return false;
                              
                                  QByteArray crc=data.right(2);
                                  std::reverse(crc.begin(),crc.end());
                                  bool ok=false;
                              
                                  quint16 messageCRC=crc.toHex().toUInt(&ok,16);
                                  if(!ok)
                                      return false;
                              
                                  data.chop(2);
                              
                                  return (messageCRC==crc16(data));
                              }
                              QByteArray MyDevice::createMessage(const Commands::deviceCommand &cmd, const QByteArray &data)
                              {
                                  QByteArray message;
                                  message.append(0xFC);
                              
                                  if(data.count() > 0) {
                                      message.append(0x05+data.count());
                                  }
                                  else{
                                      message.append(0x05);
                                  }
                                  message.append((char)cmd);
                              
                                  if(data.count() > 0) {
                                      for (int i= 0 ; i< data.count() ; i++)
                                          message.append(data[i]);
                                  }
                              
                              
                                  quint16 crc=crc16(message);
                                  QByteArray crcData=QByteArray((char *)&crc,2);
                              
                                  message.append(crcData);
                              
                                  return message;
                              
                              
                              }
                              
                              quint16 MyDevice::crc16(const QByteArray &data)
                              {
                                  unsigned int CRC;
                                  unsigned char j;
                                  CRC = 0;
                                  for(int i=0; i < data.size(); i++)
                                  {
                                      CRC ^= (unsigned char)data[i];
                                      for(j=0; j < 8; j++)
                                      {
                                          if(CRC & 0x0001) {CRC >>= 1; CRC ^= POLYNOMIAL;}
                                          else CRC >>= 1;
                                      }
                                  }
                                  return CRC;
                              }
                              
                              
                              

                              I would be rally gratefull for more suggestions.

                              jsulmJ 1 Reply Last reply
                              0
                              • D Damian7546

                                @Christian-Ehrlicher @JonB Thank you for yours suggestions.

                                I have implemented your comments,suggestions, and now code look like:

                                #include "mydevice.h"
                                
                                
                                MyDevice::MyDevice(QObject *parent)
                                    : QObject{parent}
                                {
                                    serial = new QSerialPort();
                                    serial->setPortName("COM9");
                                    serial->setBaudRate(QSerialPort::Baud9600);
                                    serial->setDataBits(QSerialPort::Data8);
                                    serial->setParity(QSerialPort::EvenParity);
                                    serial->open(QIODevice::ReadWrite);
                                
                                    connect(serial, &QSerialPort::readyRead, this, &MyDevice::serialRecive);
                                
                                    connect(&timerResponse, &QTimer::timeout, this, [&](){  m_timeoutResponse = true;
                                                                                            timerResponse.stop();
                                                                                            qDebug()<<"Timeout response";}
                                
                                    );
                                    connect(&timerState, &QTimer::timeout, this, &MyDevice::stateMachine);
                                
                                
                                
                                    if(!serial->isOpen()){
                                        qInfo() << "Serial port status: " << serial->isOpen();
                                    }else{
                                        //run state machine!
                                        m_state = State::state::STATUS_REQUEST;
                                        timerState.start(100);
                                    }
                                
                                
                                
                                }
                                
                                void MyDevice::serialRecive()
                                {
                                    m_request_part.append(serial->readAll());
                                    qDebug() << "Partially received: " << m_request_part;
                                
                                    while(!messageComplete(m_request_part)) {
                                        return;
                                    }
                                
                                    bool crcValid=validateResponse(m_request_part);
                                    if(!crcValid){
                                        qDebug()<<"Crc error";
                                        m_state = State::state::STATUS_REQUEST;
                                        return;
                                    }
                                
                                    timerResponse.stop();
                                    m_request = m_request_part;
                                    qDebug()<<"Correct response: " << m_request;
                                }
                                
                                
                                
                                void MyDevice::stateMachine()
                                {
                                    if (m_request.count() > 3)
                                        m_responseStatus = static_cast<Response::Status>(m_request.mid(2,1).toInt(nullptr, 16));
                                    else
                                        m_responseStatus = Response::Status::UNKNOWN;
                                
                                
                                    switch (m_state)
                                    {
                                    case State::state::STATUS_REQUEST:
                                        timerResponse.start(m_timeout);
                                        clearBuffers();
                                        serial->write(createMessage(Commands::deviceCommand::POLL,m_data));
                                        m_state = State::state::STATUS_RESPONSE;
                                        break;
                                    case State::state::STATUS_RESPONSE:
                                        if(m_responseStatus == Response::Status::POWER_UP)  m_state = State::state::VERSION_REQUEST;
                                        if(m_responseStatus == Response::Status::POWER_UP_WITH_BILL_IN_ACCEPTOR) m_state = State::state::RESET_REQUEST;
                                        if(m_responseStatus == Response::Status::POWER_UP_WITH_BILL_IN_STACKER) m_state = State::state::RESET_REQUEST;
                                        if(m_responseStatus == Response::Status::INITIALIZE) m_state = State::state::EN_DIS_REQUEST;
                                        if(m_responseStatus == Response::Status::ENABLE) m_state = State::state::STATUS_REQUEST;
                                        if(m_responseStatus == Response::Status::ACCEPTING) m_state = State::state::STATUS_REQUEST;
                                        if(m_responseStatus == Response::Status::ESCROW) m_state = State::state::STACK1_REQUEST;
                                        if(m_responseStatus == Response::Status::STACKING) m_state = State::state::STATUS_REQUEST;
                                        if(m_responseStatus == Response::Status::STACKED) m_state = State::state::STATUS_REQUEST;
                                        if(m_responseStatus == Response::Status::VALID) m_state = State::state::ACK_REQUEST;
                                        if(m_responseStatus == Response::Status::REJECTING) m_state = State::state::STATUS_REQUEST;
                                        if(m_responseStatus == Response::Status::JAM_IN_ACCEPTOR) m_state = State::state::STATUS_REQUEST;
                                        if(m_timeoutResponse) {
                                            m_timeoutResponse = false;
                                            m_state = State::state::STATUS_REQUEST;
                                        }
                                        break;
                                
                                
                                    case State::state::VERSION_REQUEST:
                                        timerResponse.start(m_timeout);
                                        clearBuffers();
                                        serial->write(createMessage(Commands::deviceCommand::GET_VERSION,m_data));
                                        m_state = State::state::VERSION_RESPONSE;
                                        break;
                                    case State::state::VERSION_RESPONSE:
                                        if(m_responseStatus == Response::Status::STAT_VERSION) m_state = State::state::RESET_REQUEST;
                                        if(m_timeoutResponse) {
                                            m_timeoutResponse = false;
                                            m_state = State::state::STATUS_REQUEST;
                                        }
                                        break;
                                
                                
                                
                                    case State::state::RESET_REQUEST:
                                        timerResponse.start(m_timeout);
                                        clearBuffers();
                                        serial->write(createMessage(Commands::deviceCommand::RESET,m_data));
                                        m_state = State::state::RESET_RESPONSE;
                                        break;
                                    case State::state::RESET_RESPONSE:
                                        if(m_responseStatus == Response::Status::ACK) m_state = State::state::STATUS_REQUEST;
                                        if(m_timeoutResponse) {
                                            m_timeoutResponse = false;
                                            m_state = State::state::STATUS_REQUEST;
                                        }
                                        break;
                                
                                
                                
                                
                                
                                    case State::state::EN_DIS_REQUEST:
                                        timerResponse.start(m_timeout);
                                        clearBuffers();
                                        m_data = QByteArray("\xff\xff",2);
                                        serial->write(createMessage(Commands::deviceCommand::ENABLE,m_data));
                                        m_state = State::state::EN_DIS_RESPONSE;
                                        break;
                                    case State::state::EN_DIS_RESPONSE:
                                        if(m_responseStatus == Response::Status::STAT_EN_DIS) m_state = State::state::SECURITY_REQUEST;
                                        if(m_timeoutResponse) {
                                            m_timeoutResponse = false;
                                            m_state = State::state::STATUS_REQUEST;
                                        }
                                        break;
                                
                                
                                
                                
                                
                                    case State::state::SECURITY_REQUEST:
                                        timerResponse.start(m_timeout);
                                        clearBuffers();
                                        m_data = QByteArray("\xff\xff",2);
                                        serial->write(createMessage(Commands::deviceCommand::SECURITY,m_data));
                                        m_state = State::state::SECURITY_REQUEST;
                                        break;
                                    case State::state::SECURITY_RESPONSE:
                                        if(m_responseStatus == Response::Status::CMD_ENABLE_SECURITY) m_state = State::state::OPTIONAL_FUN_REQUEST;
                                        if(m_timeoutResponse) {
                                            m_timeoutResponse = false;
                                            m_state = State::state::STATUS_REQUEST;
                                        }
                                        break;
                                
                                
                                
                                
                                
                                
                                    case State::state::OPTIONAL_FUN_REQUEST:
                                        timerResponse.start(m_timeout);
                                        clearBuffers();
                                        serial->write(createMessage(Commands::deviceCommand::OPTIONAL,m_data));
                                        m_state = State::state::OPTIONAL_FUN_RESPONSE;
                                        break;
                                    case State::state::OPTIONAL_FUN_RESPONSE:
                                        if(m_responseStatus == Response::Status::CMD_OPTIONAL) m_state = State::state::INHIBIT_REQUEST;
                                        if(m_timeoutResponse) {
                                            m_timeoutResponse = false;
                                            m_state = State::state::STATUS_REQUEST;
                                        }
                                        break;
                                
                                
                                
                                
                                    case State::state::INHIBIT_REQUEST:
                                        timerResponse.start(m_timeout);
                                        clearBuffers();
                                        serial->write(createMessage(Commands::deviceCommand::INHIBIT,m_data));
                                        m_state = State::state::INHIBIT_RESPONSE;
                                        break;
                                    case State::state::INHIBIT_RESPONSE:
                                        if(m_responseStatus == Response::Status::CMD_INHIBIT)  m_state = State::state::STATUS_REQUEST;
                                        if(m_timeoutResponse) {
                                            m_timeoutResponse = false;
                                            m_state = State::state::STATUS_REQUEST;
                                        }
                                        break;
                                
                                
                                
                                
                                
                                    case State::state::STACK1_REQUEST:
                                        timerResponse.start(m_timeout);
                                        clearBuffers();
                                        serial->write(createMessage(Commands::deviceCommand::STACK1,m_data));
                                        m_state = State::state::STACK1_RESPONSE;
                                        break;
                                
                                    case State::state::STACK1_RESPONSE:
                                        if(m_responseStatus == Response::Status::ACK) m_state = State::state::STATUS_REQUEST;
                                        if(m_timeoutResponse) {
                                            m_timeoutResponse = false;
                                            m_state = State::state::STATUS_REQUEST;
                                        }
                                        break;
                                
                                
                                
                                
                                
                                
                                    case State::state::STACK2_REQUEST:
                                        timerResponse.start(m_timeout);
                                        clearBuffers();
                                        serial->write(createMessage(Commands::deviceCommand::STACK2,m_data));
                                        m_state = State::state::STACK2_RESPONSE;
                                        break;
                                
                                    case State::state::STACK2_RESPONSE:
                                        if(m_responseStatus == Response::Status::ACK) m_state = State::state::STATUS_REQUEST;
                                        if(m_timeoutResponse) {
                                            m_timeoutResponse = false;
                                            m_state = State::state::STATUS_REQUEST;
                                        }
                                        break;
                                
                                
                                
                                
                                
                                    case State::state::ACK_REQUEST:
                                        timerResponse.start(m_timeout);
                                        clearBuffers();
                                        serial->write(createMessage(Commands::deviceCommand::ACK,m_data));
                                        m_state = State::state::STATUS_REQUEST;
                                        break;
                                
                                
                                
                                
                                
                                
                                    case State::state::RETURN_REQUEST:
                                        timerResponse.start(m_timeout);
                                        clearBuffers();
                                        serial->write(createMessage(Commands::deviceCommand::RETURN,m_data));
                                        m_state = State::state::RETURN_RESPONSE;
                                        break;
                                
                                    case State::state::RETURN_RESPONSE:
                                        if(m_responseStatus == Response::Status::ACK) m_state = State::state::STATUS_REQUEST;
                                        if(m_timeoutResponse) {
                                            m_timeoutResponse = false;
                                            m_state = State::state::STATUS_REQUEST;
                                        }
                                        break;
                                    default:
                                        break;
                                    }
                                
                                
                                }
                                
                                void MyDevice::clearBuffers()
                                {
                                    m_request.clear();
                                    m_data.clear();
                                    m_request_part.clear();
                                }
                                
                                bool MyDevice::messageComplete(const QByteArray &data) const
                                {
                                    if(data.size()>=3){
                                        quint8 length=(unsigned char)data[1];
                                        if(length==data.length())
                                            return true;
                                    }
                                    return false;
                                }
                                
                                bool MyDevice::validateResponse(QByteArray data)
                                {
                                    if(data.size()<3)
                                        return false;
                                
                                    QByteArray crc=data.right(2);
                                    std::reverse(crc.begin(),crc.end());
                                    bool ok=false;
                                
                                    quint16 messageCRC=crc.toHex().toUInt(&ok,16);
                                    if(!ok)
                                        return false;
                                
                                    data.chop(2);
                                
                                    return (messageCRC==crc16(data));
                                }
                                QByteArray MyDevice::createMessage(const Commands::deviceCommand &cmd, const QByteArray &data)
                                {
                                    QByteArray message;
                                    message.append(0xFC);
                                
                                    if(data.count() > 0) {
                                        message.append(0x05+data.count());
                                    }
                                    else{
                                        message.append(0x05);
                                    }
                                    message.append((char)cmd);
                                
                                    if(data.count() > 0) {
                                        for (int i= 0 ; i< data.count() ; i++)
                                            message.append(data[i]);
                                    }
                                
                                
                                    quint16 crc=crc16(message);
                                    QByteArray crcData=QByteArray((char *)&crc,2);
                                
                                    message.append(crcData);
                                
                                    return message;
                                
                                
                                }
                                
                                quint16 MyDevice::crc16(const QByteArray &data)
                                {
                                    unsigned int CRC;
                                    unsigned char j;
                                    CRC = 0;
                                    for(int i=0; i < data.size(); i++)
                                    {
                                        CRC ^= (unsigned char)data[i];
                                        for(j=0; j < 8; j++)
                                        {
                                            if(CRC & 0x0001) {CRC >>= 1; CRC ^= POLYNOMIAL;}
                                            else CRC >>= 1;
                                        }
                                    }
                                    return CRC;
                                }
                                
                                
                                

                                I would be rally gratefull for more suggestions.

                                jsulmJ Online
                                jsulmJ Online
                                jsulm
                                Lifetime Qt Champion
                                wrote on last edited by jsulm
                                #14

                                @Damian7546 said in Serial communication:

                                while(!messageComplete(m_request_part)) {
                                return;
                                }

                                Why do you have a loop here if you anyway do a return?

                                https://forum.qt.io/topic/113070/qt-code-of-conduct

                                D 1 Reply Last reply
                                1
                                • jsulmJ jsulm

                                  @Damian7546 said in Serial communication:

                                  while(!messageComplete(m_request_part)) {
                                  return;
                                  }

                                  Why do you have a loop here if you anyway do a return?

                                  D Offline
                                  D Offline
                                  Damian7546
                                  wrote on last edited by
                                  #15

                                  @jsulm Better?

                                  if(!messageComplete(m_request_part)) {
                                  return;
                                  }
                                  
                                  JonBJ 1 Reply Last reply
                                  1
                                  • D Damian7546

                                    @jsulm Better?

                                    if(!messageComplete(m_request_part)) {
                                    return;
                                    }
                                    
                                    JonBJ Offline
                                    JonBJ Offline
                                    JonB
                                    wrote on last edited by
                                    #16

                                    @Damian7546 More readable/clear :)

                                    Christian EhrlicherC 1 Reply Last reply
                                    0
                                    • JonBJ JonB

                                      @Damian7546 More readable/clear :)

                                      Christian EhrlicherC Offline
                                      Christian EhrlicherC Offline
                                      Christian Ehrlicher
                                      Lifetime Qt Champion
                                      wrote on last edited by
                                      #17

                                      From my pov the parsing is incorrect as there may be more than one message in the buffer so the second (or even the first part of the second) is thrown away.

                                      Qt Online Installer direct download: https://download.qt.io/official_releases/online_installers/
                                      Visit the Qt Academy at https://academy.qt.io/catalog

                                      D 1 Reply Last reply
                                      1
                                      • Christian EhrlicherC Christian Ehrlicher

                                        From my pov the parsing is incorrect as there may be more than one message in the buffer so the second (or even the first part of the second) is thrown away.

                                        D Offline
                                        D Offline
                                        Damian7546
                                        wrote on last edited by
                                        #18

                                        @Christian-Ehrlicher so how to fix it?

                                        JonBJ 1 Reply Last reply
                                        0
                                        • D Damian7546

                                          @Christian-Ehrlicher so how to fix it?

                                          JonBJ Offline
                                          JonBJ Offline
                                          JonB
                                          wrote on last edited by
                                          #19

                                          @Damian7546
                                          Remove only what is used for a message from the buffer, leaving any further unused bytes there might be for appending to create next "message".

                                          1 Reply Last reply
                                          0
                                          • jsulmJ jsulm

                                            @Damian7546 Something like this. But better don't use c-style casts:

                                            m_responseStatus = static_cast<Response::Status>(m_request.mid(2,1).toInt(nullptr, 16));
                                            
                                            D Offline
                                            D Offline
                                            Damian7546
                                            wrote on last edited by Damian7546
                                            #20

                                            @jsulm
                                            This conversion doesn't work.

                                            class Response
                                            {
                                            public:
                                                enum class Status : quint8{
                                                     DISABLE = 0x1A,
                                                };
                                                Response();
                                            };
                                            
                                            

                                            In m_responseStatus variable I have 0x1A value, but below statement is not equal:

                                            m_responseStatus = static_cast<Response::Status>(m_request.mid(2,1).toInt(nullptr, 16));
                                                qDebug() << "m_responseStatus: " << m_request.mid(2,1);
                                            
                                                if(Response::Status::DISABLE == m_responseStatus)
                                                    qDebug() << "ok convert";
                                                else
                                                    qDebug() << "bad convert";
                                            
                                            

                                            Problem is in toInt conversion:

                                            qDebug() << "m_responseStatus: " << m_request.mid(2,1);
                                            qDebug() << "m_responseStatus: " << m_request.mid(2,1).toInt(nullptr, 16);
                                            

                                            result:
                                            m_responseStatus: "\x1A"
                                            m_responseStatus: 0

                                            JonBJ 1 Reply Last reply
                                            0

                                            • Login

                                            • Login or register to search.
                                            • First post
                                              Last post
                                            0
                                            • Categories
                                            • Recent
                                            • Tags
                                            • Popular
                                            • Users
                                            • Groups
                                            • Search
                                            • Get Qt Extensions
                                            • Unsolved