myDevicesIoT / Mbed 2 deprecated Cayenne-ESP8266Interface

Dependencies:   Cayenne-MQTT-mbed ESP8266Interface mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 /**
00002 * Example app for using the Cayenne MQTT C++ library to send and receive example data. This example uses
00003 * the ESP8266Interface library to connect via WiFi.
00004 */
00005 
00006 #include "MQTTTimer.h"
00007 #include "CayenneMQTTClient.h"
00008 #include "MQTTNetwork.h"
00009 #include "ESP8266Interface.h"
00010 
00011 // WiFi network info.
00012 char* ssid = "ssid";
00013 char* wifiPassword = "wifiPassword";
00014 
00015 // Cayenne authentication info. This should be obtained from the Cayenne Dashboard.
00016 char* username = "MQTT_USERNAME";
00017 char* password = "MQTT_PASSWORD";
00018 char* clientID = "CLIENT_ID";
00019 
00020 // Use Cayenne IP instead of "mqtt.mydevices.com" since the ESP8266Interface doesn't support looking up the domain name.
00021 #define CAYENNE_IP "57.7.250.10"
00022 
00023 ESP8266Interface interface(D8, D2, D3, ssid, wifiPassword, 115200); // TX, RX, Reset, SSID, Password, Baud
00024 MQTTNetwork<ESP8266Interface> network(interface);
00025 CayenneMQTT::MQTTClient<MQTTNetwork<ESP8266Interface>, MQTTTimer> mqttClient(network, username, password, clientID);
00026 
00027 /**
00028 * Print the message info.
00029 * @param[in] message The message received from the Cayenne server.
00030 */
00031 void outputMessage(CayenneMQTT::MessageData& message)
00032 {
00033     switch (message.topic)  {
00034     case COMMAND_TOPIC:
00035         printf("topic=Command");
00036         break;
00037     case CONFIG_TOPIC:
00038         printf("topic=Config");
00039         break;
00040     default:
00041         printf("topic=%d", message.topic);
00042         break;
00043     }
00044     printf(" channel=%d", message.channel);
00045     if (message.clientID) {
00046         printf(" clientID=%s", message.clientID);
00047     }
00048     if (message.type) {
00049         printf(" type=%s", message.type);
00050     }
00051     for (size_t i = 0; i < message.valueCount; ++i) {
00052         if (message.getValue(i)) {
00053             printf(" value=%s", message.getValue(i));
00054         }
00055         if (message.getUnit(i)) {
00056             printf(" unit=%s", message.getUnit(i));
00057         }
00058     }
00059     if (message.id) {
00060         printf(" id=%s", message.id);
00061     }
00062     printf("\n");
00063 }
00064 
00065 /**
00066 * Handle messages received from the Cayenne server.
00067 * @param[in] message The message received from the Cayenne server.
00068 */
00069 void messageArrived(CayenneMQTT::MessageData& message)
00070 {
00071     int error = 0;
00072     // Add code to process the message. Here we just ouput the message data.
00073     outputMessage(message);
00074 
00075     if (message.topic == COMMAND_TOPIC) {
00076         // If this is a command message we publish a response to show we recieved it. Here we are just sending a default 'OK' response.
00077         // An error response should be sent if there are issues processing the message.
00078         if ((error = mqttClient.publishResponse(message.id, NULL, message.clientID)) != CAYENNE_SUCCESS) {
00079             printf("Response failure, error: %d\n", error);
00080         }
00081             
00082         // Send the updated state for the channel so it is reflected in the Cayenne dashboard. If a command is successfully processed
00083         // the updated state will usually just be the value received in the command message.
00084         if ((error = mqttClient.publishData(DATA_TOPIC, message.channel, NULL, NULL, message.getValue())) != CAYENNE_SUCCESS) {
00085             printf("Publish state failure, error: %d\n", error);
00086         }
00087     }
00088 }
00089 
00090 /**
00091 * Connect to the Cayenne server.
00092 * @return Returns CAYENNE_SUCCESS if the connection succeeds, or an error code otherwise.
00093 */
00094 int connectClient(void)
00095 {
00096     int error = 0;
00097     // Connect to the server.
00098     printf("Connecting to %s:%d\n", CAYENNE_IP, CAYENNE_PORT);
00099     while ((error = network.connect(CAYENNE_IP, CAYENNE_PORT)) != 0) {
00100         printf("TCP connect failed, error: %d\n", error);
00101         wait(2);
00102     }
00103 
00104     if ((error = mqttClient.connect()) != MQTT::SUCCESS) {
00105         printf("MQTT connect failed, error: %d\n", error);
00106         return error;
00107     }
00108     printf("Connected\n");
00109 
00110     // Subscribe to required topics.
00111     if ((error = mqttClient.subscribe(COMMAND_TOPIC, CAYENNE_ALL_CHANNELS)) != CAYENNE_SUCCESS) {
00112         printf("Subscription to Command topic failed, error: %d\n", error);
00113     }
00114     if ((error = mqttClient.subscribe(CONFIG_TOPIC, CAYENNE_ALL_CHANNELS)) != CAYENNE_SUCCESS) {
00115         printf("Subscription to Config topic failed, error:%d\n", error);
00116     }
00117 
00118     // Send device info. Here we just send some example values for the system info. These should be changed to use actual system data, or removed if not needed.
00119     mqttClient.publishData(SYS_VERSION_TOPIC, CAYENNE_NO_CHANNEL, NULL, NULL, CAYENNE_VERSION);
00120     mqttClient.publishData(SYS_MODEL_TOPIC, CAYENNE_NO_CHANNEL, NULL, NULL, "mbedDevice");
00121     //mqttClient.publishData(SYS_CPU_MODEL_TOPIC, CAYENNE_NO_CHANNEL, NULL, NULL, "CPU Model");
00122     //mqttClient.publishData(SYS_CPU_SPEED_TOPIC, CAYENNE_NO_CHANNEL, NULL, NULL, "1000000000");
00123 
00124     return CAYENNE_SUCCESS;
00125 }
00126 
00127 /**
00128 * Main loop where MQTT code is run.
00129 */
00130 void loop(void)
00131 {
00132     // Start the countdown timer for publishing data every 5 seconds. Change the timeout parameter to publish at a different interval.
00133     MQTTTimer timer(5000);
00134 
00135     while (true) {
00136         // Yield to allow MQTT message processing.
00137         mqttClient.yield(1000);
00138 
00139         // Check that we are still connected, if not, reconnect.
00140         if (!network.connected() || !mqttClient.connected()) {
00141             network.disconnect();
00142             mqttClient.disconnect();
00143             printf("Reconnecting\n");
00144             while (connectClient() != CAYENNE_SUCCESS) {
00145                 wait(2);
00146                 printf("Reconnect failed, retrying\n");
00147             }
00148         }
00149 
00150         // Publish some example data every few seconds. This should be changed to send your actual data to Cayenne.
00151         if (timer.expired()) {
00152             int error = 0;
00153             if ((error = mqttClient.publishData(DATA_TOPIC, 0, TYPE_TEMPERATURE, UNIT_CELSIUS, 30.5)) != CAYENNE_SUCCESS) {
00154                 printf("Publish temperature failed, error: %d\n", error);
00155             }
00156             if ((error = mqttClient.publishData(DATA_TOPIC, 1, TYPE_LUMINOSITY, UNIT_LUX, 1000)) != CAYENNE_SUCCESS) {
00157                 printf("Publish luminosity failed, error: %d\n", error);
00158             }
00159             if ((error = mqttClient.publishData(DATA_TOPIC, 2, TYPE_BAROMETRIC_PRESSURE, UNIT_HECTOPASCAL, 800)) != CAYENNE_SUCCESS) {
00160                 printf("Publish barometric pressure failed, error: %d\n", error);
00161             }
00162             // Restart the countdown timer for publishing data every 5 seconds. Change the timeout parameter to publish at a different interval.
00163             timer.countdown_ms(5000);
00164         }
00165     }
00166 }
00167 
00168 /**
00169 * Main function.
00170 */
00171 int main()
00172 {
00173     printf("Initialiizing interface\n");
00174     interface.init();    
00175 
00176     // Set the default function that receives Cayenne messages.
00177     mqttClient.setDefaultMessageHandler(messageArrived);
00178 
00179     // Connect to Cayenne.
00180     if (connectClient() == CAYENNE_SUCCESS) {
00181         // Run main loop.
00182         loop();
00183     }
00184     else {
00185         printf("Connection failed, exiting\n");
00186     }
00187 
00188     if (mqttClient.connected())
00189         mqttClient.disconnect();
00190     if (network.connected())
00191         network.disconnect();
00192 
00193     return 0;
00194 }
00195