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: MQTT NDefLib NetworkSocketAPI Servo Light_Sensor_Nucleo X_NUCLEO_IDW01M1v2 mbed
Fork of IDW01M1_Cloud_IBM by
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 00019 00020 #include "SpwfInterface.h" 00021 #include "XNucleo6180XA1.h" 00022 #include "TCPSocket.h" 00023 #include "MQTTClient.h" 00024 #include "MQTTWiFi.h" 00025 #include "Servo/Servo.h" 00026 00027 #include <ctype.h> 00028 //#include "x_nucleo_iks01a1.h" 00029 //#include "X_NUCLEO_NFC01A1.h" 00030 //#include "NDefLib/NDefNfcTag.h" 00031 #include "NDefLib/RecordType/RecordURI.h" 00032 00033 /* Definitions ---------------------------------------------------------------*/ 00034 00035 #define VL6180X_I2C_SDA D14 00036 #define VL6180X_I2C_SCL D15 00037 00038 00039 /* Variables -----------------------------------------------------------------*/ 00040 00041 static XNucleo6180XA1 *board = NULL; 00042 int status; 00043 00044 00045 //------------------------------------ 00046 // Hyperterminal configuration 00047 // 9600 bauds, 8-bit data, no parity 00048 //------------------------------------ 00049 //Serial pc(SERIAL_TX, SERIAL_RX); 00050 DigitalOut myled(LED1); 00051 bool quickstartMode = true; 00052 00053 Servo myservo(D11); 00054 00055 00056 00057 00058 00059 //float Moisture = 0 ; 00060 00061 #define ORG_QUICKSTART // comment to connect to play.internetofthings.ibmcloud.co 00062 //#define SUBSCRIBE // uncomment to subscribe to broker msgs (not to be used with IBM broker) 00063 #define X_NUCLEO_NFC01A1_PRESENT // uncomment to add NFC support 00064 00065 #define MQTT_MAX_PACKET_SIZE 250 00066 #define MQTT_MAX_PAYLOAD_SIZE 300 00067 00068 // Configuration values needed to connect to IBM IoT Cloud 00069 #define BROKER_URL ".messaging.internetofthings.ibmcloud.com"; 00070 #ifdef ORG_QUICKSTART 00071 #define ORG "quickstart" // connect to quickstart.internetofthings.ibmcloud.com/ For a registered connection, replace with your org 00072 #define ID "" 00073 #define AUTH_TOKEN "" 00074 #define DEFAULT_TYPE_NAME "iotsample-mbed-Nucleo" 00075 #else // not def ORG_QUICKSTART 00076 #define ORG "" // connect to play.internetofthings.ibmcloud.com/ For a registered connection, replace with your org 00077 #define ID "" // For a registered connection, replace with your id 0080E1B8D765 00078 #define AUTH_TOKEN ""// For a registered connection, replace with your auth-token 00079 #define DEFAULT_TYPE_NAME "" 00080 #endif 00081 #define TOPIC "iot-2/evt/status/fmt/json" 00082 00083 #define TYPE DEFAULT_TYPE_NAME // For a registered connection, replace with your type 00084 #define MQTT_PORT 1883 00085 #define MQTT_TLS_PORT 8883 00086 #define IBM_IOT_PORT MQTT_PORT 00087 // WiFi network credential 00088 #define SSID "STM" // Network must be visible otherwise it can't connect 00089 #define PASSW "STMdemoPWD" 00090 #warning "Wifi SSID & password empty" 00091 00092 char id[30] = ID; // mac without colons 00093 char org[12] = ORG; 00094 int connack_rc = 0; // MQTT connack return code 00095 const char* ip_addr = ""; 00096 char* host_addr = ""; 00097 char type[30] = TYPE; 00098 char auth_token[30] = AUTH_TOKEN; // Auth_token is only used in non-quickstart mode 00099 bool netConnecting = false; 00100 int connectTimeout = 1000; 00101 bool mqttConnecting = false; 00102 bool netConnected = false; 00103 bool connected = false; 00104 int retryAttempt = 0; 00105 char subscription_url[MQTT_MAX_PAYLOAD_SIZE]; 00106 00107 00108 int32_t axes[3]; 00109 00110 00111 MQTT::Message message; 00112 MQTTString TopicName={TOPIC}; 00113 MQTT::MessageData MsgData(TopicName, message); 00114 00115 void subscribe_cb(MQTT::MessageData & msgMQTT) { 00116 char msg[MQTT_MAX_PAYLOAD_SIZE]; 00117 msg[0]='\0'; 00118 strncat (msg, (char*)msgMQTT.message.payload, msgMQTT.message.payloadlen); 00119 printf ("--->>> subscribe_cb msg: %s\n\r", msg); 00120 } 00121 00122 int subscribe(MQTT::Client<MQTTWiFi, Countdown, MQTT_MAX_PACKET_SIZE>* client, MQTTWiFi* ipstack) 00123 { 00124 char* pubTopic = TOPIC; 00125 return client->subscribe(pubTopic, MQTT::QOS1, subscribe_cb); 00126 } 00127 00128 int connect(MQTT::Client<MQTTWiFi, Countdown, MQTT_MAX_PACKET_SIZE>* client, MQTTWiFi* ipstack) 00129 { 00130 const char* iot_ibm = BROKER_URL; 00131 00132 00133 char hostname[strlen(org) + strlen(iot_ibm) + 1]; 00134 sprintf(hostname, "%s%s", org, iot_ibm); 00135 SpwfSAInterface& WiFi = ipstack->getWiFi(); 00136 // ip_addr = WiFi.get_ip_address(); 00137 // Construct clientId - d:org:type:id 00138 char clientId[strlen(org) + strlen(type) + strlen(id) + 5]; 00139 sprintf(clientId, "d:%s:%s:%s", org, type, id); 00140 sprintf(subscription_url, "%s.%s/#/device/%s/light/", org, "internetofthings.ibmcloud.com",id); 00141 00142 // Network debug statements 00143 LOG("=====================================\n\r"); 00144 LOG("Connecting WiFi.\n\r"); 00145 LOG("Nucleo IP ADDRESS: %s\n\r", WiFi.get_ip_address()); 00146 LOG("Nucleo MAC ADDRESS: %s\n\r", WiFi.get_mac_address()); 00147 LOG("Server Hostname: %s port: %d\n\r", hostname, IBM_IOT_PORT); 00148 // for(int i = 0; clientId[i]; i++){ // set lowercase mac 00149 // clientId[i] = tolower(clientId[i]); 00150 // } 00151 LOG("Client ID: %s\n\r", clientId); 00152 LOG("Topic: %s\n\r",TOPIC); 00153 LOG("Subscription URL: %s\n\r", subscription_url); 00154 LOG("=====================================\n\r"); 00155 00156 netConnecting = true; 00157 ipstack->open(&ipstack->getWiFi()); 00158 int rc = ipstack->connect(hostname, IBM_IOT_PORT, connectTimeout); 00159 if (rc != 0) 00160 { 00161 WARN("IP Stack connect returned: %d\n", rc); 00162 return rc; 00163 } 00164 printf ("--->TCP Connected\n\r"); 00165 netConnected = true; 00166 netConnecting = false; 00167 00168 // MQTT Connect 00169 mqttConnecting = true; 00170 MQTTPacket_connectData data = MQTTPacket_connectData_initializer; 00171 data.MQTTVersion = 4; 00172 data.struct_version=0; 00173 data.clientID.cstring = clientId; 00174 00175 if (!quickstartMode) 00176 { 00177 data.username.cstring = "use-token-auth"; 00178 data.password.cstring = auth_token; 00179 } 00180 if ((rc = client->connect(data)) == 0) 00181 { 00182 connected = true; 00183 printf ("--->MQTT Connected\n\r"); 00184 #ifdef SUBSCRIBE 00185 if (!subscribe(client, ipstack)) printf ("--->>>MQTT subscribed to: %s\n\r",TOPIC); 00186 #endif 00187 } 00188 else { 00189 WARN("MQTT connect returned %d\n", rc); 00190 } 00191 if (rc >= 0) 00192 connack_rc = rc; 00193 mqttConnecting = false; 00194 return rc; 00195 } 00196 00197 int getConnTimeout(int attemptNumber) 00198 { // First 10 attempts try within 3 seconds, next 10 attempts retry after every 1 minute 00199 // after 20 attempts, retry every 10 minutes 00200 return (attemptNumber < 10) ? 3 : (attemptNumber < 20) ? 60 : 600; 00201 } 00202 00203 void attemptConnect(MQTT::Client<MQTTWiFi, Countdown, MQTT_MAX_PACKET_SIZE>* client, MQTTWiFi* ipstack) 00204 { 00205 connected = false; 00206 00207 while (connect(client, ipstack) != MQTT_CONNECTION_ACCEPTED) 00208 { 00209 if (connack_rc == MQTT_NOT_AUTHORIZED || connack_rc == MQTT_BAD_USERNAME_OR_PASSWORD) { 00210 printf ("File: %s, Line: %d Error: %d\n\r",__FILE__,__LINE__, connack_rc); 00211 return; // don't reattempt to connect if credentials are wrong 00212 } 00213 int timeout = getConnTimeout(++retryAttempt); 00214 WARN("Retry attempt number %d waiting %d\n", retryAttempt, timeout); 00215 00216 // if ipstack and client were on the heap we could deconstruct and goto a label where they are constructed 00217 // or maybe just add the proper members to do this disconnect and call attemptConnect(...) 00218 // this works - reset the system when the retry count gets to a threshold 00219 if (retryAttempt == 5) 00220 NVIC_SystemReset(); 00221 else 00222 wait(timeout); 00223 } 00224 } 00225 00226 00227 00228 int publish(MQTT::Client<MQTTWiFi, Countdown, MQTT_MAX_PACKET_SIZE>* client, MQTTWiFi* ipstack) 00229 { 00230 MQTT::Message message; 00231 char* pubTopic = TOPIC; 00232 /* Creates the 6180XA1 expansion board singleton obj. */ 00233 00234 00235 00236 00237 /* Initializes the 6180XA1 expansion board with default values. */ 00238 status = board->init_board(); 00239 00240 char buf[MQTT_MAX_PAYLOAD_SIZE]; 00241 00242 uint32_t lux, dist; 00243 00244 board->sensor_top->get_distance(&dist); 00245 board->sensor_top->get_lux(&lux); 00246 00247 00248 if ((lux<40)&&(lux>10)) 00249 { for(int i=5; i<160; i++) { 00250 myservo = i/160.0; 00251 wait(0.01); 00252 } 00253 } 00254 else 00255 if ((lux<180)&&(lux>150)) 00256 { for(int i=5; i<170; i++) { 00257 myservo = i/170.0; 00258 wait(0.01); 00259 } 00260 } 00261 00262 // 00263 sprintf(buf, 00264 "{\"d\":{\"ST\":\"Nucleo-IoT-mbed\",\"Distance\": %1.0d, \"Lux\": %1.0d}}", 00265 dist,lux); 00266 message.qos = MQTT::QOS0; 00267 message.retained = false; 00268 message.dup = false; 00269 message.payload = (void*)buf; 00270 message.payloadlen = strlen(buf); 00271 00272 // LOG("Publishing %s\n\r", buf); 00273 printf("Publishing %s\n\r", buf); 00274 return client->publish(pubTopic, message); 00275 } 00276 00277 int main() 00278 { 00279 const char * ssid = SSID; // Network must be visible otherwise it can't connect 00280 const char * seckey = PASSW; 00281 SpwfSAInterface spwf(D8, D2, false); 00282 00283 DevI2C *device_i2c = new DevI2C(VL6180X_I2C_SDA, VL6180X_I2C_SCL); 00284 board = XNucleo6180XA1::instance(device_i2c, A3, A0, D13, D0); 00285 00286 00287 00288 00289 // Timer tyeld; 00290 myled=0; 00291 00292 00293 printf("\r\nX-NUCLEO-IDW01M1 mbed Application\r\n"); 00294 printf("\r\nconnecting to AP\r\n"); 00295 00296 quickstartMode=false; 00297 if (strcmp(org, "quickstart") == 0){quickstartMode = true;} 00298 MQTTWiFi ipstack(spwf, ssid, seckey, NSAPI_SECURITY_WPA2); 00299 MQTT::Client<MQTTWiFi, Countdown, MQTT_MAX_PACKET_SIZE> client(ipstack); 00300 if (quickstartMode){ 00301 char mac[50]; // remove all : from mac 00302 char *digit=NULL; 00303 sprintf (id,"%s", ""); 00304 sprintf (mac,"%s",ipstack.getWiFi().get_mac_address()); 00305 digit = strtok (mac,":"); 00306 while (digit != NULL) 00307 { 00308 strcat (id, digit); 00309 digit = strtok (NULL, ":"); 00310 } 00311 } 00312 attemptConnect(&client, &ipstack); 00313 if (connack_rc == MQTT_NOT_AUTHORIZED || connack_rc == MQTT_BAD_USERNAME_OR_PASSWORD) 00314 { 00315 while (true) 00316 wait(1.0); // Permanent failures - don't retry 00317 } 00318 00319 myled=1; 00320 int count = 0; 00321 // tyeld.start(); 00322 while (true) 00323 { 00324 if (++count == 100) 00325 { // Publish a message every second 00326 if (publish(&client, &ipstack) != 0) { 00327 myled=0; 00328 attemptConnect(&client, &ipstack); // if we have lost the connection 00329 } else myled=1; 00330 count = 0; 00331 } 00332 // int start = tyeld.read_ms(); 00333 client.yield(10); // allow the MQTT client to receive messages 00334 // printf ("tyeld: %d\n\r",tyeld.read_ms()-start); 00335 } 00336 }
Generated on Fri Jul 15 2022 17:40:17 by
1.7.2
