W5500-Ethernet-Interface Makers / Mbed 2 deprecated IBMIoTClientEthernetExample_W5500

Dependencies:   MQTT W5500Interface mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 #include "mbed.h"
00002 #include "MQTTClient.h"
00003 #include "MQTTEthernet.h"
00004 
00005 // Configuration values needed to connect to IBM IoT Cloud
00006 #define QUICKSTARTMODE 0
00007 #if (QUICKSTARTMODE)
00008 #define ORG "uasfg"
00009 #define ID ""
00010 #define AUTH_TOKEN "mhhWy4Qg)C*w3jL@(O"
00011 #define TYPE "W5500"
00012 #else
00013 #define ORG "uasfg"
00014 #define ID ""
00015 #define AUTH_TOKEN "mhhWy4Qg)C*w3jL@(O"
00016 #define TYPE "W5500"
00017 #endif
00018 
00019 #define MQTT_PORT 1883
00020 #define MQTT_TLS_PORT 8883
00021 #define IBM_IOT_PORT MQTT_PORT
00022 
00023 #define MQTT_MAX_PACKET_SIZE 250
00024 
00025 
00026 #define USING_HW_STACK_W5500
00027 
00028 bool quickstartMode = (QUICKSTARTMODE) ? true : false;
00029 char org[11] = ORG;  
00030 char type[30] = TYPE;
00031 char id[30] = ID;                 // mac without colons
00032 char auth_token[30] = AUTH_TOKEN; // Auth_token is only used in non-quickstart mode
00033 
00034 bool connected = false;
00035 
00036 
00037 char* getMac(EthernetInterface& eth, char* buf, int buflen)    // Obtain MAC address
00038 {   
00039     strncpy(buf, eth.getMACAddress(), buflen);
00040 
00041     char* pos;                                                 // Remove colons from mac address
00042     while ((pos = strchr(buf, ':')) != NULL)
00043         memmove(pos, pos + 1, strlen(pos) + 1);
00044     return buf;
00045 }
00046 
00047 
00048 int connect(MQTT::Client<MQTTEthernet, Countdown, MQTT_MAX_PACKET_SIZE>* client, MQTTEthernet* ipstack)
00049 {
00050     const char* iot_ibm = ".messaging.internetofthings.ibmcloud.com";
00051 
00052     char hostname[strlen(org) + strlen(iot_ibm) + 1];
00053     sprintf(hostname, "%s%s", org, iot_ibm);
00054     int rc = ipstack->connect(hostname, IBM_IOT_PORT);
00055 
00056     if (rc != 0)
00057         return rc;
00058 
00059     // Construct clientId - d:org:type:id
00060     char clientId[strlen(org) + strlen(type) + strlen(id) + 5];
00061     sprintf(clientId, "d:%s:%s:%s", org, type, id);
00062     DEBUG("clientid is %s\r\n", clientId);
00063 
00064     // MQTT Connect
00065     MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
00066     data.MQTTVersion = 3;
00067     data.clientID.cstring = clientId;
00068 
00069     if (!quickstartMode)
00070     {
00071         data.username.cstring = "use-token-auth";
00072         data.password.cstring = auth_token;
00073     }
00074 
00075     if ((rc = client->connect(&data)) == 0)
00076     {
00077         connected = true;
00078     }
00079 
00080     return rc;
00081 }
00082 
00083 
00084 int getConnTimeout(int attemptNumber)
00085 {  // First 10 attempts try within 3 seconds, next 10 attempts retry after every 1 minute
00086    // after 20 attempts, retry every 10 minutes
00087     return (attemptNumber < 10) ? 3 : (attemptNumber < 20) ? 60 : 600;
00088 }
00089 
00090 
00091 void attemptConnect(MQTT::Client<MQTTEthernet, Countdown, MQTT_MAX_PACKET_SIZE>* client, MQTTEthernet* ipstack)
00092 {
00093     int retryAttempt = 0;
00094     connected = false;
00095 
00096     // make sure a cable is connected before starting to connect
00097     while ( !ipstack->getEth().linkstatus() ) {
00098         wait(1.0f);
00099         WARN("Ethernet link not present. Check cable connection\r\n");
00100     }
00101 
00102     while (connect(client, ipstack) != 0)
00103     {
00104         int timeout = getConnTimeout(++retryAttempt);
00105         WARN("Retry attempt number %d waiting %d\r\n", retryAttempt, timeout);
00106         wait(timeout);
00107     }
00108 }
00109 
00110 int publish(MQTT::Client<MQTTEthernet, Countdown, MQTT_MAX_PACKET_SIZE>* client, MQTTEthernet* ipstack)
00111 {
00112     MQTT::Message message;
00113     char* pubTopic = "iot-2/evt/status/fmt/json";
00114 
00115     char buf[250];
00116     sprintf(buf,
00117      "{\"d\":{\"myName\":\"IoT mbed\",\"cputemp\":%0.4f,\"testvalue\":%s}}",
00118             12.4,"W5500");
00119 
00120     message.qos = MQTT::QOS0;
00121     message.retained = false;
00122     message.dup = false;
00123     message.payload = (void*)buf;
00124     message.payloadlen = strlen(buf);
00125 
00126     LOG("Publishing %s\r\n", buf);
00127     return client->publish(pubTopic, &message);
00128 }
00129 
00130 
00131 void messageArrived(MQTT::MessageData& md)
00132 {
00133     MQTT::Message &message = md.message;
00134     char topic[md.topicName.lenstring.len + 1];
00135 
00136     sprintf(topic, "%.*s", md.topicName.lenstring.len, md.topicName.lenstring.data);
00137 
00138     LOG("Message arrived on topic %s: %.*s\r\n",  topic, message.payloadlen, message.payload);
00139 
00140     // Command topic: iot-2/cmd/blink/fmt/json - cmd is the string between cmd/ and /fmt/
00141     char* start = strstr(topic, "/cmd/") + 5;
00142     int len = strstr(topic, "/fmt/") - start;
00143 
00144     if (memcmp(start, "blink", len) == 0)
00145     {
00146         char payload[message.payloadlen + 1];
00147         sprintf(payload, "%.*s", message.payloadlen, (char*)message.payload);
00148 
00149         char* pos = strchr(payload, '}');
00150         if (pos != NULL)
00151         {
00152             *pos = '\0';
00153             if ((pos = strchr(payload, ':')) != NULL)
00154             {
00155             }
00156         }
00157     }
00158     else
00159         WARN("Unsupported command: %.*s\r\n", len, start);
00160 }
00161 
00162 int main()
00163 {    
00164 #if defined(TARGET_KL25Z)
00165     Serial pc(USBTX, USBRX);
00166     pc.baud(115200);
00167 
00168     SPI spi(D11, D12, D13); // mosi, miso, sclk
00169     wait(1);
00170     
00171     MQTTEthernet ipstack(&spi, D10, D9); //scs(D10), nRESET(PTA20)
00172     MQTT::Client<MQTTEthernet, Countdown, MQTT_MAX_PACKET_SIZE> client(ipstack);
00173 #endif    
00174 
00175     getMac(ipstack.getEth(), id, sizeof(id));
00176     attemptConnect(&client, &ipstack);
00177 
00178     int count = 0;
00179     while (true)
00180     {
00181         if (!ipstack.getEth().linkstatus()) {
00182             NVIC_SystemReset();
00183             // if ipstack and client were on the heap we could deconstruct and goto a label where they are constructed
00184             //  or maybe just add the proper members to do this disconnect and call attemptConnect(...)
00185         }
00186 
00187         if (++count == 100)
00188         {               // Publish a message every second
00189             if (publish(&client, &ipstack) != 0)
00190                 attemptConnect(&client, &ipstack);   // if we have lost the connection
00191             count = 0;
00192         }
00193 
00194         client.yield(10);  // allow the MQTT client to receive messages
00195     }
00196 }