Adding States to Improve Code in MQTT

Last modified by Microchip on 2023/11/09 09:07

New states can be added so the device goes in circles through different states instead of staying in APP_STATE_TLS_CONNECTED. This is unnecessary, and the program doesn’t perform better, but the code will be clearer.

In this example, the APP_STATE_TLS_CONNECTED state has been deleted, and three new states have been added:

  • SUBSCRIBING
  • PUBLISHING
  • PROCESS_PACKET

Declare New States

At the top of mqtt_example.c, the names of the states are declared. You can delete the APP_STATE_TLS_CONNECTED state and add new ones.

Code View showing Subscribing, Publishing, and PROCESS_LAST_PACKET
Keep in mind that if you delete a state, APP_STATE_TLS_CONNECTED for example, you can’t use it anymore. Instead, you can write the name of one of your new states; PUBLISHING for example, where  APP_STATE_TLS_CONNECTED was written.

Back to Top

Socket Handler

When the device is fully connected to MQTT, the SocketHandler function sets the next state. Originally, it was APP_STATE_TLS_CONNECTED, but you can change it to any state that you want where changeState() is mentioned in the declaration SocketHandler().

Code View Highlighting changeState(SUBSCRIBING)

Back to Top

Write New States

Now you can add code for the new states. If you don’t know how “switch” and “case” work, consider learning about them in C before continuing. See the "C Programming Switch Statements" page to familiarize yourself with them.

At some point in the code, inside of your new states (preferably at the end), write “changeState(next_state);”, unless you want the program to stay in that state forever. See the accompanying example.

Code View Highlighting case SUBSRIBING

case SUBSCRIBING:
{
          changeState(PUBLISHING);
         break;
  }

       case PUBLISHING:
        {
           if(appMQTTPublishTimeoutOccured == true)
            {
                appMQTTPublishTimeoutOccured = false;
                app_buildPublishPacket();                //build the packet for the first message
           }

            MQTT_ReceptionHandler(mqttConnnectionInfo);
            MQTT_TransmissionHandler(mqttConnnectionInfo);
            changeState(PROCESS_LAST_PACKET);
           break;
        }
      
       case PROCESS_LAST_PACKET:
        {
            changeState(SUBSCRIBING);
           break;
        }

Back to Top