Avnet / Mbed 2 deprecated WNCInterface_MQTT_hivemq

Dependencies:   WNCInterface mbed-rtos mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 //#define MQTT_DEBUG
00002 
00003 #include "mbed.h"
00004 #include "MQTTClient.h"
00005 #include "MQTTFormat.h"
00006 
00007 //#include "MQTTEthernet.h"
00008 #include "MQTTWNCInterface.h"
00009 #include "rtos.h"
00010 #include "k64f.h"
00011 
00012 
00013 // connect options for MQTT broker
00014 #define BROKER "broker.hivemq.com"   // MQTT broker URL
00015 #define PORT 1883                           // MQTT broker port number
00016 #define CLIENTID "96430312d8f7"                         // use K64F MAC address without colons
00017 #define USERNAME ""                         // not required for MQTT Dashboard public broker 
00018 #define PASSWORD ""                         // not required for MQTT Dashboard public broker
00019 #define TOPIC "jmf/Test1"                            // MQTT topic
00020 
00021 Queue<uint32_t, 6> messageQ;
00022 MODSERIAL pc(USBTX,USBRX,256,256);
00023     
00024 struct rcvd_errs{
00025     int err;
00026     char *er;
00027     };
00028     
00029 rcvd_errs response[] = {
00030     200, "200 OK - Request has succeeded.",
00031     201, "201 Created - Request has been fulfilled and a new resource created.",
00032     202, "202 Accepted - The request has been accepted for processing, but the processing will be completed asynchronously",
00033     204, "204 No Content - The server has fulfilled the request but does not need to return an entity-body.",
00034     400, "400 Bad Request - Bad request (e.g. sending an array when the API is expecting a hash.)",
00035     401, "401 Unauthorized - No valid API key provided.",
00036     403, "403 Forbidden - You tried to access a disabled device, or your API key is not allowed to access that resource, etc.",
00037     404, "404 Not Found - The requested item could not be found.",
00038     405, "405 Method Not Allowed - The HTTP method specified is not allowed.",
00039     415, "415 Unsupported Media Type - The requested media type is currently not supported.",
00040     422, "422 Unprocessable Entity - Can result from sending invalid fields.",
00041     429, "429 Too Many Requests - The user has sent too many requests in a given period of time.",
00042     500, "500 Server errors - Something went wrong in the M2X server",
00043     502, "502 Server errors - Something went wrong in the M2X server",
00044     503, "503 Server errors - Something went wrong in the M2X server",
00045     504, "504 Server errors - Something went wrong in the M2X server",
00046     };
00047 #define RCMAX   sizeof(response)/sizeof(rcvd_errs)
00048 
00049 char * response_str(int rc) {
00050     static char *unkown = "Unknown error code...";
00051     int i=0;
00052     while( response[i].err != rc && i < RCMAX)
00053         i++;
00054     return (i<RCMAX? response[i].er : unkown);
00055 }
00056 
00057 // LED color control function
00058 void controlLED(color_t led_color) {
00059     switch(led_color) {
00060         case red :
00061             greenLED = blueLED = 1;          
00062             redLED = 0.7;
00063             break;
00064         case green :
00065             redLED = blueLED = 1;
00066             greenLED = 0.7;
00067             break;
00068         case blue :
00069             redLED = greenLED = 1;
00070             blueLED = 0.7;
00071             break;
00072         case off :
00073             redLED = greenLED = blueLED = 1;
00074             break;
00075     }
00076 }
00077     
00078 // Switch 2 interrupt handler
00079 void sw2_ISR(void) {
00080     messageQ.put((uint32_t*)22);
00081 }
00082 
00083 // Switch3 interrupt handler
00084 void sw3_ISR(void) {
00085     messageQ.put((uint32_t*)33);
00086 }
00087  
00088 // MQTT message arrived callback function
00089 void messageArrived(MQTT::MessageData& md) {
00090     MQTT::Message &message = md.message;
00091     pc.printf("Receiving MQTT message:  %.*s\r\n", message.payloadlen, (char*)message.payload);
00092     
00093     if (message.payloadlen == 3) {
00094         if (strncmp((char*)message.payload, "red", 3) == 0)
00095             controlLED(red);
00096         
00097         else if(strncmp((char*)message.payload, "grn", 3) == 0)
00098             controlLED(green);
00099         
00100         else if(strncmp((char*)message.payload, "blu", 3) == 0)
00101             controlLED(blue);
00102         
00103         else if(strncmp((char*)message.payload, "off", 3) == 0)
00104             controlLED(off);
00105     }        
00106 }
00107 
00108 int main() {
00109     int rc, good = 0;
00110     Timer tmr;
00111     char* topic = TOPIC;
00112     // turn off LED  
00113     controlLED(blue);
00114 
00115     pc.baud(115200);
00116     pc.printf("\r\n\r\nWelcome to the K64F MQTT Demo!\r\n");
00117         
00118     // set SW2 and SW3 to generate interrupt on falling edge 
00119     switch2.fall(&sw2_ISR);
00120     switch3.fall(&sw3_ISR);
00121 
00122     // initialize ethernet interface
00123     MQTTwnc ipstack = MQTTwnc();
00124     
00125     // get and display client network info
00126     WNCInterface& eth = ipstack.getEth();
00127     
00128     // construct the MQTT client
00129     MQTT::Client<MQTTwnc, Countdown> client = MQTT::Client<MQTTwnc, Countdown>(ipstack);
00130     
00131     char* hostname = BROKER;
00132     int port = PORT;
00133 
00134     pc.printf("\r\nConnected to local network...\r\n");    
00135     pc.printf("IP address is %s\r\n", eth.getIPAddress());
00136     pc.printf("MAC address is %s\r\n", eth.getMACAddress());
00137     pc.printf("Gateway address is %s\r\n", eth.getGateway());
00138 
00139     MQTTPacket_connectData data = MQTTPacket_connectData_initializer;       
00140     int tries;
00141     
00142     while( !good ) {    
00143         tries=0;
00144         // connect to TCP socket and check return code
00145         tmr.start();
00146         rc = 1;
00147         while( rc && tries < 3) {
00148             pc.printf("\r\n\r\nAttempting TCP connect to %s:%d:  ", hostname, port);
00149             rc = ipstack.connect(hostname, port);
00150             if( rc ) {
00151                 pc.printf("Failed!!\r\n");
00152                 while( tmr.read_ms() < 5000 ) ;
00153                 tries++;
00154                 tmr.reset();
00155             }
00156             else {
00157                 pc.printf("Success!\r\n");
00158                 rc = 0;
00159             }
00160         }
00161     
00162         data.MQTTVersion = 3;
00163         data.clientID.cstring = eth.getMACAddress();
00164     //    data.username.cstring = USERNAME;
00165     //    data.password.cstring = PASSWORD;
00166         
00167         // send MQTT connect packet and check return code
00168         rc = 1;
00169         tmr.reset(); 
00170         while( !client.isConnected() && rc && tries < 3) {
00171             pc.printf("Attempting (%d) MQTT connect to %s:%d: ", tries, hostname, port);
00172             rc = client.connect(data);
00173             if( rc ) {
00174                 pc.printf("Connection Failed!\r\n");
00175                 while( tmr.read_ms() < 5000 );
00176                 tmr.reset();
00177                 tries++;
00178             }
00179             else
00180                 pc.printf("Connected!\r\n");
00181         }
00182 
00183         // subscribe to MQTT topic
00184         tmr.reset();
00185         rc = 1;
00186         while( rc && client.isConnected() && tries < 3) {
00187             pc.printf("We are %s, Subscribing to MQTT topic %s (%d): ", client.isConnected()?"connected":"NOT CONNECTED",topic,tries);
00188             rc = client.subscribe(topic, MQTT::QOS0, messageArrived);
00189             if( rc ) {
00190                 pc.printf("Subscribe request failed!\r\n");
00191                 while( tmr.read_ms() < 5000 );
00192                 tries++;
00193                 tmr.reset();
00194             }
00195             else {
00196                 good=1;
00197                 pc.printf("Subscribe successful!\r\n");
00198             }
00199         }
00200     }        
00201     
00202     MQTT::Message message;
00203     char buf[100];
00204     message.qos = MQTT::QOS0;
00205     message.retained = false;
00206     message.dup = false;
00207     message.payload = (void*)buf;
00208     message.payloadlen = strlen(buf)+1;
00209     
00210     while(true) {
00211         osEvent switchEvent = messageQ.get(100);
00212         
00213         if (switchEvent.value.v == 22 || switchEvent.value.v == 33) {
00214             switch(switchEvent.value.v) {
00215                 case 22 :
00216                     sprintf(buf, "sw2");
00217                     break;
00218                 case 33 :
00219                     sprintf(buf, "sw3");
00220                     break;
00221             }
00222             pc.printf("Publishing MQTT message: %s (%d)\r\n", (char*)message.payload,
00223                        message.payloadlen);
00224             rc = client.publish(topic, message);
00225             if( rc ) {
00226                 pc.printf("Publish request failed! (%d)\r\n",rc);
00227             }
00228             else {
00229                 pc.printf("Publish successful!\r\n");            
00230             client.yield(100);
00231             }
00232         }
00233         else {
00234             client.yield(100);
00235         }           
00236     }
00237 }
00238