We will write a simple code that will publish IoTaaP state every 300ms and listen for incoming commands through API. This example is based on the MQTTS example.
First we will define constants:
#define DEVICE_ID "fi3v849t4973v"
#define CONTROL_TOPIC "light_device"
DEVICE_ID will be used for publishing the device state and CONTROL_TOPIC will be used for “receiving” commands.
Next, in the MQTT(S) callback function we must add our callbackInnerFunction from the IoTaaP library. This function will handle everything connected with the IoTaaP API.
void callback(char *topic, byte *message, unsigned int length)
iotaap.mqtt.callbackInnerFunction(CONTROL_TOPIC,topic, message, length);
In the setup() we must connect our module to the cloud and set DEVICE_ID as MQTT client ID:
iotaap.mqtt.connect(DEVICE_ID, "iotaap.cloud", 8883, callback, true, "<username>", "<password>", CA_cert);
Also, as you can see, we must call enableApi() function that will basically subscribe our module to the “api/#” topics. Function will also initialize serial port with the specified or default baud rate (115200).
Finally, if we want to publish device state to the cloud, we must call apiLoop() function in the loop(). If you only want to use IoTaaP incomming API, you have to call keepAlive() function in the loop().
apiLoop() by default has 10ms interval, but this interval can be changed by passing the parameter in the function. apiLoop() implements the keepAlive() function, so it is not needed if you are using apiLoop().