Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
Dependencies: WNCInterface mbed-rtos mbed
main.cpp
00001 //#define MQTT_DEBUG 00002 00003 //org=9k09br 00004 //type=cc 00005 //id=Mz-1107199-7010 00006 //auth-method=token 00007 //auth-token=SecurityToekn99 00008 // 00009 00010 #include "mbed.h" 00011 #include "MQTTClient.h" 00012 #include "MQTTFormat.h" 00013 00014 //#include "MQTTEthernet.h" 00015 #include "MQTTWNCInterface.h" 00016 #include "rtos.h" 00017 #include "k64f.h" 00018 #include "HTS221.h" 00019 00020 I2C i2c(PTC11, PTC10); //SDA, SCL -- define the I2C pins being used 00021 MODSERIAL pc(USBTX,USBRX,256,256); 00022 00023 #include "hardware.h" 00024 00025 00026 // connect options for MQTT broker 00027 #define CLIENT "quickstart" 00028 #define URL CLIENT ".messaging.internetofthings.ibmcloud.com" 00029 #define CONFIGTYPE "d:" CLIENT ":MicroZed:%s" 00030 00031 #define PORT 1883 // MQTT broker port number 00032 #define CLIENTID "96430312d8f7" // use MAC address without colons 00033 #define USERNAME "" // not required for demo app 00034 #define PASSWORD "" // not required for demo app 00035 #define PUBLISH_TOPIC "iot-2/evt/status/fmt/json" // MQTT topic 00036 #define SUBSCRIBTOPIC "iot-2/cmd/+/fmt/+" 00037 00038 #define HTS221_STR " Temp is: %0.2f F \n\r Humid is: %02d %%\n\r" 00039 00040 Queue<uint32_t, 6> messageQ; 00041 00042 struct rcvd_errs{ 00043 int err; 00044 char *er; 00045 }; 00046 00047 rcvd_errs response[] = { 00048 200, "200 OK - Request has succeeded.", 00049 201, "201 Created - Request has been fulfilled and a new resource created.", 00050 202, "202 Accepted - The request has been accepted for processing, but the processing will be completed asynchronously", 00051 204, "204 No Content - The server has fulfilled the request but does not need to return an entity-body.", 00052 400, "400 Bad Request - Bad request (e.g. sending an array when the API is expecting a hash.)", 00053 401, "401 Unauthorized - No valid API key provided.", 00054 403, "403 Forbidden - You tried to access a disabled device, or your API key is not allowed to access that resource, etc.", 00055 404, "404 Not Found - The requested item could not be found.", 00056 405, "405 Method Not Allowed - The HTTP method specified is not allowed.", 00057 415, "415 Unsupported Media Type - The requested media type is currently not supported.", 00058 422, "422 Unprocessable Entity - Can result from sending invalid fields.", 00059 429, "429 Too Many Requests - The user has sent too many requests in a given period of time.", 00060 500, "500 Server errors - Something went wrong in the M2X server", 00061 502, "502 Server errors - Something went wrong in the M2X server", 00062 503, "503 Server errors - Something went wrong in the M2X server", 00063 504, "504 Server errors - Something went wrong in the M2X server", 00064 }; 00065 #define RCMAX sizeof(response)/sizeof(rcvd_errs) 00066 00067 char * response_str(int rc) { 00068 static char *unkown = "Unknown error code..."; 00069 int i=0; 00070 while( response[i].err != rc && i < RCMAX) 00071 i++; 00072 return (i<RCMAX? response[i].er : unkown); 00073 } 00074 00075 // LED color control function 00076 void controlLED(color_t led_color) { 00077 switch(led_color) { 00078 case red : 00079 greenLED = blueLED = 1; 00080 redLED = 0.7; 00081 break; 00082 case green : 00083 redLED = blueLED = 1; 00084 greenLED = 0.7; 00085 break; 00086 case blue : 00087 redLED = greenLED = 1; 00088 blueLED = 0.7; 00089 break; 00090 case off : 00091 redLED = greenLED = blueLED = 1; 00092 break; 00093 } 00094 } 00095 00096 // Switch 2 interrupt handler 00097 void sw2_ISR(void) { 00098 messageQ.put((uint32_t*)22); 00099 } 00100 00101 // Switch3 interrupt handler 00102 void sw3_ISR(void) { 00103 messageQ.put((uint32_t*)33); 00104 } 00105 00106 // MQTT message arrived callback function 00107 void messageArrived(MQTT::MessageData& md) { 00108 MQTT::Message &message = md.message; 00109 printf("Receiving MQTT message: %.*s\r\n", message.payloadlen, (char*)message.payload); 00110 00111 if (message.payloadlen == 3) { 00112 if (strncmp((char*)message.payload, "red", 3) == 0) 00113 controlLED(red); 00114 00115 else if(strncmp((char*)message.payload, "grn", 3) == 0) 00116 controlLED(green); 00117 00118 else if(strncmp((char*)message.payload, "blu", 3) == 0) 00119 controlLED(blue); 00120 00121 else if(strncmp((char*)message.payload, "off", 3) == 0) 00122 controlLED(off); 00123 } 00124 } 00125 00126 int main() { 00127 int rc, qStart=0, txSel=0, good = 0; 00128 Timer tmr; 00129 char* topic = PUBLISH_TOPIC; 00130 char clientID[100], buf[100]; 00131 string st, uniqueID; 00132 00133 HTS221 hts221; 00134 00135 pc.baud(115200); 00136 rc = hts221.init(); 00137 if ( rc ) { 00138 pc.printf(BLU "HTS221 Detected (0x%02X)\n\r",rc); 00139 pc.printf(HTS221_STR, CTOF(hts221.readTemperature()), hts221.readHumidity()/10); 00140 } 00141 else { 00142 pc.printf(RED "HTS221 NOT DETECTED!\n\r"); 00143 } 00144 00145 00146 // turn off LED 00147 controlLED(blue); 00148 00149 // set SW2 and SW3 to generate interrupt on falling edge 00150 switch2.fall(&sw2_ISR); 00151 switch3.fall(&sw3_ISR); 00152 00153 // initialize ethernet interface 00154 MQTTwnc ipstack = MQTTwnc(); 00155 00156 // get and display client network info 00157 WNCInterface& eth = ipstack.getEth(); 00158 00159 // construct the MQTT client 00160 MQTT::Client<MQTTwnc, Countdown> client = MQTT::Client<MQTTwnc, Countdown>(ipstack); 00161 00162 char* hostname = URL; 00163 int port = PORT; 00164 st = eth.getMACAddress(); 00165 uniqueID="IoT-"; 00166 uniqueID += st[0]; 00167 uniqueID += st[1]; 00168 uniqueID += st[3]; 00169 uniqueID += st[4]; 00170 uniqueID += st[6]; 00171 uniqueID += st[7]; 00172 uniqueID += st[9]; 00173 uniqueID += st[10]; 00174 uniqueID += "-2016"; 00175 00176 sprintf(clientID, CONFIGTYPE, uniqueID.c_str()); 00177 00178 printf(" _____\r\n"); 00179 printf(" * *\r\n"); 00180 printf(" *____ *____ Bluemix Quick Start example\r\n"); 00181 printf(" * *===* *==* using the AT&T IoT Starter Kit\r\n"); 00182 printf(" *___*===*___** AVNET\r\n"); 00183 printf(" *======*\r\n"); 00184 printf(" *====*\r\n"); 00185 printf("\r\n"); 00186 printf("This demonstration program operates the same as the original \r\n"); 00187 printf("MicroZed IIoT Starter Kit except it only reads from the HTS221 \r\n"); 00188 printf("temp sensor (no 31855 currently present and no generated data).\r\n"); 00189 printf("\r\n"); 00190 printf("Local network info...\r\n"); 00191 printf("IP address is %s\r\n", eth.getIPAddress()); 00192 printf("MAC address is %s\r\n", eth.getMACAddress()); 00193 printf("Gateway address is %s\r\n", eth.getGateway()); 00194 printf("Your <uniqueID> is: %s\r\n", uniqueID.c_str()); 00195 printf("\r\nTo run the demo, go to 'https://quickstart.internetofthings.ibmcloud.com/#/'\r\n"); 00196 printf("and enter '%s' as your device ID. The temprature data will then be displayed\r\n",uniqueID.c_str()); 00197 printf("as it is received. You can switch between temprature and humidity by depressing SW2.\r\n"); 00198 printf("---------------------------------------------------------------\r\n"); 00199 00200 MQTTPacket_connectData data = MQTTPacket_connectData_initializer; 00201 00202 int tries; 00203 00204 while( !good ) { 00205 tries=0; 00206 // connect to TCP socket and check return code 00207 tmr.start(); 00208 rc = 1; 00209 while( rc && tries < 3) { 00210 printf("\r\n\r\n(%d) Attempting TCP connect to %s:%d: ", tries++, hostname, port); 00211 rc = ipstack.connect(hostname, port); 00212 if( rc ) { 00213 printf("Failed (%d)!\r\n",rc); 00214 while( tmr.read_ms() < 5000 ) ; 00215 tmr.reset(); 00216 } 00217 else { 00218 printf("Success!\r\n"); 00219 rc = 0; 00220 } 00221 } 00222 if( tries < 3 ) 00223 tries = 0; 00224 else 00225 continue; 00226 00227 data.willFlag = 0; 00228 data.MQTTVersion = 3; 00229 00230 data.clientID.cstring = clientID; 00231 // data.username.cstring = USERNAME; 00232 // data.password.cstring = PASSWORD; 00233 data.keepAliveInterval = 10; 00234 data.cleansession = 1; 00235 00236 rc = 1; 00237 tmr.reset(); 00238 while( !client.isConnected() && rc && tries < 3) { 00239 printf("(%d) Attempting MQTT connect to %s:%d: ", tries++, hostname, port); 00240 rc = client.connect(data); 00241 if( rc ) { 00242 printf("Failed (%d)!\r\n",rc); 00243 while( tmr.read_ms() < 5000 ); 00244 tmr.reset(); 00245 } 00246 else 00247 printf("Success!\r\n"); 00248 } 00249 00250 if( tries < 3 ) 00251 tries = 0; 00252 else 00253 continue; 00254 00255 #if 0 00256 //Only need to subscribe if we are not running quickstart 00257 // subscribe to MQTT topic 00258 tmr.reset(); 00259 rc = 1; 00260 while( rc && client.isConnected() && tries < 3) { 00261 printf("(%d) Attempting to subscribing to MQTT topic %s: ", tries, SUBSCRIBTOPIC); 00262 rc = client.subscribe(SUBSCRIBTOPIC, MQTT::QOS0, messageArrived); 00263 if( rc ) { 00264 printf("Failed (%d)!\r\n", rc); 00265 while( tmr.read_ms() < 5000 ); 00266 tries++; 00267 tmr.reset(); 00268 } 00269 else { 00270 good=1; 00271 printf("Subscribe successful!\r\n"); 00272 } 00273 } 00274 #else 00275 good = 1; 00276 #endif 00277 while (!good); 00278 } 00279 00280 MQTT::Message message; 00281 message.qos = MQTT::QOS0; 00282 message.retained = false; 00283 message.dup = false; 00284 message.payload = (void*)buf; 00285 00286 while(true) { 00287 osEvent switchEvent = messageQ.get(100); 00288 00289 if( switchEvent.value.v == 22 ) //switch between sending humidity & temp 00290 txSel = !txSel; 00291 00292 if( switchEvent.value.v == 33) //user wants to run in Quickstart of Demo mode 00293 qStart = !qStart; 00294 00295 memset(buf,0x00,sizeof(buf)); 00296 if( txSel ) { 00297 rc = hts221.readHumidity(); 00298 sprintf(buf, "{\"d\" : {\"humd\" : \"%2d.%d\" }}", rc/10, rc-((rc/10)*10)); 00299 printf("Publishing MQTT message '%s' ", (char*)message.payload); 00300 } 00301 else { 00302 sprintf(buf, "{\"d\" : {\"temp\" : \"%5.1f\" }}", CTOF(hts221.readTemperature())); 00303 printf("Publishing MQTT message '%s' ", (char*)message.payload); 00304 } 00305 message.payloadlen = strlen(buf); 00306 printf("(%d)\r\n",message.payloadlen); 00307 rc = client.publish(topic, message); 00308 if( rc ) { 00309 printf("Publish request failed! (%d)\r\n",rc); 00310 FATAL_WNC_ERROR(resume); 00311 } 00312 00313 client.yield(6000); 00314 } 00315 }
Generated on Thu Jul 14 2022 04:13:06 by
1.7.2