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: Moisture_Quickstart_IBM_Cloud NetworkSocketAPI X_NUCLEO_IDW01M1v2 mbed
main.cpp
00001 /* SpwfInterface NetworkSocketAPI Example Program 00002 * Copyright (c) 2015 ARM Limited 00003 * 00004 * Licensed under the Apache License, Version 2.0 (the "License"); 00005 * you may not use this file except in compliance with the License. 00006 * You may obtain a copy of the License at 00007 * 00008 * http://www.apache.org/licenses/LICENSE-2.0 00009 * 00010 * Unless required by applicable law or agreed to in writing, software 00011 * distributed under the License is distributed on an "AS IS" BASIS, 00012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 00013 * See the License for the specific language governing permissions and 00014 * limitations under the License. 00015 */ 00016 00017 #include "mbed.h" 00018 #include "SpwfInterface.h" 00019 #include "TCPSocket.h" 00020 #include "MQTTClient.h" 00021 #include "MQTTWiFi.h" 00022 #include <ctype.h> 00023 00024 00025 //------------------------------------ 00026 // Hyperterminal configuration 00027 // 9600 bauds, 8-bit data, no parity 00028 //------------------------------------ 00029 Serial pc(SERIAL_TX, SERIAL_RX); 00030 DigitalOut myled(LED1); 00031 bool quickstartMode = true; 00032 00033 //DigitalOut heater(D12); 00034 AnalogIn sensorG(D13); 00035 00036 00037 00038 //DigitalIn sensor(D13); 00039 float value = 0; 00040 00041 #define ORG_QUICKSTART // comment to connect to play.internetofthings.ibmcloud.co 00042 //#define SUBSCRIBE // uncomment to subscribe to broker msgs (not to be used with IBM broker) 00043 #define X_NUCLEO_NFC01A1_PRESENT // uncomment to add NFC support 00044 00045 #define MQTT_MAX_PACKET_SIZE 250 00046 #define MQTT_MAX_PAYLOAD_SIZE 300 00047 00048 // Configuration values needed to connect to IBM IoT Cloud 00049 #define BROKER_URL ".messaging.internetofthings.ibmcloud.com"; 00050 #ifdef ORG_QUICKSTART 00051 #define ORG "quickstart" // connect to quickstart.internetofthings.ibmcloud.com/ For a registered connection, replace with your org 00052 #define ID "" 00053 #define AUTH_TOKEN "" 00054 #define DEFAULT_TYPE_NAME "iotsample-mbed-Nucleo" 00055 #else // not def ORG_QUICKSTART 00056 #define ORG "" // connect to play.internetofthings.ibmcloud.com/ For a registered connection, replace with your org 00057 #define ID "" // For a registered connection, replace with your id 0080E1B8D765 00058 #define AUTH_TOKEN ""// For a registered connection, replace with your auth-token 00059 #define DEFAULT_TYPE_NAME "" 00060 #endif 00061 #define TOPIC "iot-2/evt/status/fmt/json" 00062 00063 #define TYPE DEFAULT_TYPE_NAME // For a registered connection, replace with your type 00064 #define MQTT_PORT 1883 00065 #define MQTT_TLS_PORT 8883 00066 #define IBM_IOT_PORT MQTT_PORT 00067 // WiFi network credential 00068 #define SSID "STM" // Network must be visible otherwise it can't connect 00069 #define PASSW "STMdemoPWD" 00070 #warning "Wifi SSID & password empty" 00071 00072 char id[30] = ID; // mac without colons 00073 char org[12] = ORG; 00074 int connack_rc = 0; // MQTT connack return code 00075 const char* ip_addr = ""; 00076 char* host_addr = ""; 00077 char type[30] = TYPE; 00078 char auth_token[30] = AUTH_TOKEN; // Auth_token is only used in non-quickstart mode 00079 bool netConnecting = false; 00080 int connectTimeout = 1000; 00081 bool mqttConnecting = false; 00082 bool netConnected = false; 00083 bool connected = false; 00084 int retryAttempt = 0; 00085 char subscription_url[MQTT_MAX_PAYLOAD_SIZE]; 00086 00087 00088 00089 MQTT::Message message; 00090 MQTTString TopicName={TOPIC}; 00091 MQTT::MessageData MsgData(TopicName, message); 00092 00093 void subscribe_cb(MQTT::MessageData & msgMQTT) { 00094 char msg[MQTT_MAX_PAYLOAD_SIZE]; 00095 msg[0]='\0'; 00096 strncat (msg, (char*)msgMQTT.message.payload, msgMQTT.message.payloadlen); 00097 printf ("--->>> subscribe_cb msg: %s\n\r", msg); 00098 } 00099 00100 int subscribe(MQTT::Client<MQTTWiFi, Countdown, MQTT_MAX_PACKET_SIZE>* client, MQTTWiFi* ipstack) 00101 { 00102 char* pubTopic = TOPIC; 00103 return client->subscribe(pubTopic, MQTT::QOS1, subscribe_cb); 00104 } 00105 00106 int connect(MQTT::Client<MQTTWiFi, Countdown, MQTT_MAX_PACKET_SIZE>* client, MQTTWiFi* ipstack) 00107 { 00108 const char* iot_ibm = BROKER_URL; 00109 00110 00111 char hostname[strlen(org) + strlen(iot_ibm) + 1]; 00112 sprintf(hostname, "%s%s", org, iot_ibm); 00113 SpwfSAInterface& WiFi = ipstack->getWiFi(); 00114 // ip_addr = WiFi.get_ip_address(); 00115 // Construct clientId - d:org:type:id 00116 char clientId[strlen(org) + strlen(type) + strlen(id) + 5]; 00117 sprintf(clientId, "d:%s:%s:%s", org, type, id); 00118 sprintf(subscription_url, "%s.%s/#/device/%s/iotsample-Insat2/", org, "internetofthings.ibmcloud.com",id); 00119 00120 // Network debug statements 00121 LOG("=====================================\n\r"); 00122 LOG("Connecting WiFi.\n\r"); 00123 LOG("Nucleo IP ADDRESS: %s\n\r", WiFi.get_ip_address()); 00124 LOG("Nucleo MAC ADDRESS: %s\n\r", WiFi.get_mac_address()); 00125 LOG("Server Hostname: %s port: %d\n\r", hostname, IBM_IOT_PORT); 00126 // for(int i = 0; clientId[i]; i++){ // set lowercase mac 00127 // clientId[i] = tolower(clientId[i]); 00128 // } 00129 LOG("Client ID: %s\n\r", clientId); 00130 LOG("Topic: %s\n\r",TOPIC); 00131 LOG("Subscription URL: %s\n\r", subscription_url); 00132 LOG("=====================================\n\r"); 00133 00134 netConnecting = true; 00135 ipstack->open(&ipstack->getWiFi()); 00136 int rc = ipstack->connect(hostname, IBM_IOT_PORT, connectTimeout); 00137 if (rc != 0) 00138 { 00139 WARN("IP Stack connect returned: %d\n", rc); 00140 return rc; 00141 } 00142 printf ("--->TCP Connected\n\r"); 00143 netConnected = true; 00144 netConnecting = false; 00145 00146 // MQTT Connect 00147 mqttConnecting = true; 00148 MQTTPacket_connectData data = MQTTPacket_connectData_initializer; 00149 data.MQTTVersion = 4; 00150 data.struct_version=0; 00151 data.clientID.cstring = clientId; 00152 00153 if (!quickstartMode) 00154 { 00155 data.username.cstring = "use-token-auth"; 00156 data.password.cstring = auth_token; 00157 } 00158 if ((rc = client->connect(data)) == 0) 00159 { 00160 connected = true; 00161 printf ("--->MQTT Connected\n\r"); 00162 #ifdef SUBSCRIBE 00163 if (!subscribe(client, ipstack)) printf ("--->>>MQTT subscribed to: %s\n\r",TOPIC); 00164 #endif 00165 } 00166 else { 00167 WARN("MQTT connect returned %d\n", rc); 00168 } 00169 if (rc >= 0) 00170 connack_rc = rc; 00171 mqttConnecting = false; 00172 return rc; 00173 } 00174 00175 int getConnTimeout(int attemptNumber) 00176 { // First 10 attempts try within 3 seconds, next 10 attempts retry after every 1 minute 00177 // after 20 attempts, retry every 10 minutes 00178 return (attemptNumber < 10) ? 3 : (attemptNumber < 20) ? 60 : 600; 00179 } 00180 00181 void attemptConnect(MQTT::Client<MQTTWiFi, Countdown, MQTT_MAX_PACKET_SIZE>* client, MQTTWiFi* ipstack) 00182 { 00183 connected = false; 00184 00185 while (connect(client, ipstack) != MQTT_CONNECTION_ACCEPTED) 00186 { 00187 if (connack_rc == MQTT_NOT_AUTHORIZED || connack_rc == MQTT_BAD_USERNAME_OR_PASSWORD) { 00188 printf ("File: %s, Line: %d Error: %d\n\r",__FILE__,__LINE__, connack_rc); 00189 return; // don't reattempt to connect if credentials are wrong 00190 } 00191 int timeout = getConnTimeout(++retryAttempt); 00192 WARN("Retry attempt number %d waiting %d\n", retryAttempt, timeout); 00193 00194 // if ipstack and client were on the heap we could deconstruct and goto a label where they are constructed 00195 // or maybe just add the proper members to do this disconnect and call attemptConnect(...) 00196 // this works - reset the system when the retry count gets to a threshold 00197 if (retryAttempt == 5) 00198 NVIC_SystemReset(); 00199 else 00200 wait(timeout); 00201 } 00202 } 00203 00204 int publish(MQTT::Client<MQTTWiFi, Countdown, MQTT_MAX_PACKET_SIZE>* client, MQTTWiFi* ipstack) 00205 { 00206 MQTT::Message message; 00207 char* pubTopic = TOPIC; 00208 00209 char buf[MQTT_MAX_PAYLOAD_SIZE]; 00210 00211 // To Do 00212 00213 value = sensorG; 00214 00215 sprintf(buf, 00216 "{\"d\":{\"ST\":\"Nucleo-IoT-mbed\",\"Sensor\":%1.0f}}", 00217 value); 00218 message.qos = MQTT::QOS0; 00219 message.retained = false; 00220 message.dup = false; 00221 message.payload = (void*)buf; 00222 message.payloadlen = strlen(buf); 00223 00224 // LOG("Publishing %s\n\r", buf); 00225 printf("Publishing %s\n\r", buf); 00226 return client->publish(pubTopic, message); 00227 } 00228 00229 int main() 00230 { 00231 const char * ssid = SSID; // Network must be visible otherwise it can't connect 00232 const char * seckey = PASSW; 00233 SpwfSAInterface spwf(D8, D2, false); 00234 00235 00236 pc.printf("\r\nX-NUCLEO-IDW01M1 mbed Application\r\n"); 00237 pc.printf("\r\nconnecting to AP\r\n"); 00238 00239 quickstartMode=false; 00240 if (strcmp(org, "quickstart") == 0){quickstartMode = true;} 00241 MQTTWiFi ipstack(spwf, ssid, seckey, NSAPI_SECURITY_WPA2); 00242 MQTT::Client<MQTTWiFi, Countdown, MQTT_MAX_PACKET_SIZE> client(ipstack); 00243 if (quickstartMode){ 00244 char mac[50]; // remove all : from mac 00245 char *digit=NULL; 00246 sprintf (id,"%s", ""); 00247 sprintf (mac,"%s",ipstack.getWiFi().get_mac_address()); 00248 digit = strtok (mac,":"); 00249 while (digit != NULL) 00250 { 00251 strcat (id, digit); 00252 digit = strtok (NULL, ":"); 00253 } 00254 } 00255 attemptConnect(&client, &ipstack); 00256 if (connack_rc == MQTT_NOT_AUTHORIZED || connack_rc == MQTT_BAD_USERNAME_OR_PASSWORD) 00257 { 00258 while (true) 00259 wait(1.0); // Permanent failures - don't retry 00260 } 00261 00262 myled=1; 00263 int count = 0; 00264 // tyeld.start(); 00265 while (true) 00266 { 00267 if (++count == 100) 00268 { // Publish a message every second 00269 if (publish(&client, &ipstack) != 0) { 00270 myled=0; 00271 attemptConnect(&client, &ipstack); // if we have lost the connection 00272 } else myled=1; 00273 count = 0; 00274 } 00275 // int start = tyeld.read_ms(); 00276 client.yield(10); // allow the MQTT client to receive messages 00277 // printf ("tyeld: %d\n\r",tyeld.read_ms()-start); 00278 } 00279 }
Generated on Thu Jul 14 2022 03:54:39 by
1.7.2