sending data to DeviceHub.net

Dependencies:   EthernetInterface MQTT mbed-rtos mbed

Files at this revision

API Documentation at this revision

Comitter:
alexandrug
Date:
Thu Oct 01 18:55:33 2015 +0000
Commit message:
sample

Changed in this revision

EthernetInterface.lib Show annotated file Show diff for this revision Revisions of this file
K64F.h Show annotated file Show diff for this revision Revisions of this file
MQTT.lib Show annotated file Show diff for this revision Revisions of this file
main.cpp Show annotated file Show diff for this revision Revisions of this file
mbed-rtos.lib Show annotated file Show diff for this revision Revisions of this file
mbed.bld Show annotated file Show diff for this revision Revisions of this file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/EthernetInterface.lib	Thu Oct 01 18:55:33 2015 +0000
@@ -0,0 +1,1 @@
+http://mbed.org/users/mbed_official/code/EthernetInterface/#2fc406e2553f
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/K64F.h	Thu Oct 01 18:55:33 2015 +0000
@@ -0,0 +1,19 @@
+#if !defined(K64F_H)
+#define K64F_H
+
+BusOut led2 (LED_BLUE);
+BusOut r (D5);
+BusOut g (D9);
+BusOut b (D8);
+DigitalIn Up(A2); DigitalIn Down(A3); DigitalIn Right(A4); DigitalIn Left(A5); DigitalIn Click(D4);
+AnalogIn ain1(A0); AnalogIn ain2(A1);
+
+#define LED2_OFF 1
+#define LED2_ON 0
+
+static uint32_t linkStatus(void)
+{
+    return (1);
+}
+
+#endif
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/MQTT.lib	Thu Oct 01 18:55:33 2015 +0000
@@ -0,0 +1,1 @@
+http://mbed.org/teams/mqtt/code/MQTT/#37f007d2a8ae
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main.cpp	Thu Oct 01 18:55:33 2015 +0000
@@ -0,0 +1,188 @@
+#include "MQTTClient.h"
+#include "MQTTEthernet.h"
+#include "rtos.h"
+#include <stdlib.h>
+
+#define __APP_SW_REVISION__ "1"
+
+#define MQTT_PORT 1883
+
+#define MQTT_MAX_PACKET_SIZE 250
+
+#include "K64F.h"
+
+bool quickstartMode = true;
+
+bool connected = false;
+bool mqttConnecting = false;
+bool netConnected = false;
+bool netConnecting = false;
+bool ethernetInitialising = true;
+int connack_rc = 0; // MQTT connack return code
+int retryAttempt = 0;
+
+int blink_interval = 0;
+
+char* ip_addr = "";
+char* gateway_addr = "";
+char* host_addr = "";
+int connectTimeout = 1000;
+
+#define API_KEY         "ba8b7a2d-b690-4351-8521-100b45c09dd8"
+#define PROJECT_ID      "4505"
+#define AN_SENSOR_NAME  "test"
+#define DEVICE_UUID     "1deffe91-f938-48c5-aaea-3aef29af7869"
+#define ID              "aaa"                        
+
+char* pubTopic = "/a/"API_KEY"/p/"PROJECT_ID"/d/"DEVICE_UUID"/sensor/"AN_SENSOR_NAME"/data";
+char id[30] = ID;                 
+
+int connect(MQTT::Client<MQTTEthernet, Countdown, MQTT_MAX_PACKET_SIZE>* client, MQTTEthernet* ipstack)
+{   
+    const char* host = "mqtt.devicehub.net";
+    
+    char hostname[strlen(host) + 1];
+    sprintf(hostname, "%s", host);
+    EthernetInterface& eth = ipstack->getEth();
+    ip_addr = eth.getIPAddress();
+    gateway_addr = eth.getGateway();
+    
+    char clientId[strlen(id)];
+    sprintf(clientId, "%s",id);
+    
+    // Network debug statements 
+    LOG("=====================================\n");
+    LOG("Connecting Ethernet.\n");
+    LOG("IP ADDRESS: %s\n", eth.getIPAddress());
+    LOG("MAC ADDRESS: %s\n", eth.getMACAddress());
+    LOG("Gateway: %s\n", eth.getGateway());
+    LOG("Network Mask: %s\n", eth.getNetworkMask());
+    LOG("Server Hostname: %s\n", hostname);
+    LOG("Client ID: %s\n", clientId);
+    LOG("=====================================\n");
+    
+    netConnecting = true;
+    int rc = ipstack->connect(hostname, MQTT_PORT, connectTimeout);
+    if (rc != 0)
+    {
+        WARN("IP Stack connect returned: %d\n", rc);    
+        return rc;
+    }
+    netConnected = true;
+    netConnecting = false;
+
+    // MQTT Connect
+    mqttConnecting = true;
+    MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
+    data.MQTTVersion = 3;
+    data.clientID.cstring = clientId;
+
+    
+    if ((rc = client->connect(data)) == 0) 
+    {       
+        connected = true;
+    }
+    else
+        WARN("MQTT connect returned %d\n", rc);
+    if (rc >= 0)
+        connack_rc = rc;
+    mqttConnecting = false;
+    return rc;
+}
+
+
+int getConnTimeout(int attemptNumber)
+{  // First 10 attempts try within 3 seconds, next 10 attempts retry after every 1 minute
+   // after 20 attempts, retry every 10 minutes
+    return (attemptNumber < 10) ? 3 : (attemptNumber < 20) ? 60 : 600;
+}
+
+
+void attemptConnect(MQTT::Client<MQTTEthernet, Countdown, MQTT_MAX_PACKET_SIZE>* client, MQTTEthernet* ipstack)
+{
+    connected = false;
+   
+    while (!linkStatus()) 
+    {
+        wait(1.0f);
+        WARN("Ethernet link not present. Check cable connection\n");
+    }
+        
+    while (connect(client, ipstack) != MQTT_CONNECTION_ACCEPTED) 
+    {    
+          
+        int timeout = getConnTimeout(++retryAttempt);
+        WARN("Retry attempt number %d waiting %d\n", retryAttempt, timeout);
+        
+        // this works - reset the system when the retry count gets to a threshold
+        if (retryAttempt == 5)
+            NVIC_SystemReset();
+        else
+            wait(timeout);
+    }
+}
+
+
+int publish(MQTT::Client<MQTTEthernet, Countdown, MQTT_MAX_PACKET_SIZE>* client, MQTTEthernet* ipstack)
+{
+    MQTT::Message message;
+    
+    int analog_sensor = rand() % 100;        
+    char buf[250];
+    sprintf(buf,"{\"value\": %d }", analog_sensor);
+    message.qos = MQTT::QOS0;
+    message.retained = false;
+    message.dup = false;
+    message.payload = (void*)buf;
+    message.payloadlen = strlen(buf);
+    
+    LOG("Publishing %s\n", buf);
+    return client->publish(pubTopic, message);
+}
+
+
+char* getMac(EthernetInterface& eth, char* buf, int buflen)    // Obtain MAC address
+{   
+    strncpy(buf, eth.getMACAddress(), buflen);
+
+    char* pos;                                                 // Remove colons from mac address
+    while ((pos = strchr(buf, ':')) != NULL)
+        memmove(pos, pos + 1, strlen(pos) + 1);
+    return buf;
+}
+
+int main()
+{    
+    
+    led2 = LED2_OFF; // K64F: turn off the main board LED 
+        
+    LOG("***** DeviceHub.net example *****\n");
+    MQTTEthernet ipstack;
+    ethernetInitialising = false;
+    MQTT::Client<MQTTEthernet, Countdown, MQTT_MAX_PACKET_SIZE> client(ipstack);
+    LOG("Ethernet Initialized\n"); 
+    
+    if (quickstartMode)
+        getMac(ipstack.getEth(), id, sizeof(id));
+        
+    attemptConnect(&client, &ipstack);
+
+    
+    blink_interval = 0;
+    int count = 0;
+    while (true)
+    {
+        if (++count == 100)
+        {               // Publish a message every second
+            if (publish(&client, &ipstack) != 0) 
+                attemptConnect(&client, &ipstack);   // if we have lost the connection
+            count = 0;
+        }
+        
+        if (blink_interval == 0)
+            led2 = LED2_OFF;
+        else if (count % blink_interval == 0)
+            led2 = !led2;
+        client.yield(10);  // allow the MQTT client to receive messages
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mbed-rtos.lib	Thu Oct 01 18:55:33 2015 +0000
@@ -0,0 +1,1 @@
+http://mbed.org/users/mbed_official/code/mbed-rtos/#a21475017ae2
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mbed.bld	Thu Oct 01 18:55:33 2015 +0000
@@ -0,0 +1,1 @@
+http://mbed.org/users/mbed_official/code/mbed/builds/8ed44a420e5c
\ No newline at end of file