Waiting for a variable that changes in another slot



  • In my dialog window I have a slot connected to the 'clicked' signal of a push button. In this slot I send a packet using the SerialPort object emitting a signal connected to it. My serial protocol expects an aknoledge (or not acknoledge) response for every packed sent via serial. Now, for one single packet I can manage the response creating a new slot in my dialog window, ReceivePacket(), connected to the signal coming from the SerialPort object. But if I need to manage multiple packets at once (then multiple responses) inside the same slot (button clicked), what's the best approce? How can I know in the button clicked slot if I received the response (acknowledge or not acknowledge) for every packet sent?

    Following my code. The WriteRegister() is the slot connected to the push button.

    class CodecSettingsDialog : public QDialog
    {
        Q_OBJECT
    
    public:
        explicit CodecSettingsDialog( QWidget *parent = nullptr );
        ~CodecSettingsDialog();
    
    signals:
        void SendPacket( QByteArray packet );
    
    public slots:
        void ReceivePacket( QByteArray packet );
        void WriteRegisters();
        void ReadRegisters();
    
    private:
        Ui::CodecSettingsDialog *ui;
        bool ackReceived;
    };
    
    void CodecSettingsDialog::ReceivePacket( QByteArray packet )
    {
        ackReceived = true;  // Can I set this flag meanwhile the WriteRegister runs?
    }
    
    void CodecSettingsDialog::WriteRegister()
    {
        QString regAddress = ui->writeReadRegisterComboBox->currentData().toString();
        QString regValue = ui->writeRegisterLineEdit->text();
        QByteArray cmd;
    
        cmd.append( ( char ) 0x02 );
    
        cmd.append( ( char ) 0x0F );
        cmd.append( ( char ) 0x00 );
    
        cmd.append( ( char ) 0x01 );
    
        cmd.append( "DBCW" );
        cmd.append( regAddress.toLatin1() );
        cmd.append( regValue.toLatin1() );
    
        cmd.append( ( char ) 0x03 );
        cmd.append( ( char ) 0x04 );
        
        emit SendPacket( cmd );
        
        while (ackReceived == false)
            ;
        
        // ...from here I'd like to continue to send packets and wait responses
    }
    

  • Lifetime Qt Champion

    Hi and welcome to devnet,

    Since you have a protocol to follow you should rather have a controller class that does the command sending and answer analysis. You can then queue the commands and in your controller send them one after the other after receiving the port answer. No need to block anything, you should use Qt's asynchronous nature.



  • @SGaist I got your point and makes sense for me. Does Qt have a class to manage or create the queues? Thanks.



  • @Andrew23
    Just in general for queues Qt offers QQueue Class.


Log in to reply