Asavie IoT Connect cloud service connector example

Dependencies:   MQTT

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 /*
00002  * @author  Asavie - Mark Lambe
00003  * @version V1.0.0
00004  * @date    25 March 2019
00005  * @brief   Demonstration of Asavie IoT Connect cloud service connector and proxy
00006  * @overview Securely connect MQTT data to IoT cloud services via Asavie proxy, 
00007  * further information on setup available at https://developer.asavie.com
00008  *
00009  ******************************************************************************
00010  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
00011  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
00012  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
00013  * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
00014  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
00015  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
00016  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
00017  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
00018  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
00019  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
00020  *
00021  ******************************************************************************
00022  */
00023 
00024 #include "mbed.h"
00025 #include "common_functions.h"
00026 #include "UDPSocket.h"
00027 #include "CellularLog.h"
00028 #include "MQTTNetwork.h"
00029 #include "MQTTmbed.h"
00030 #include "MQTTClient.h"
00031 
00032 
00033 // MQTT host details
00034 static const char mqtt_host[] = "mqtt.asavie.network";
00035 static int mqtt_port = 1883;
00036 
00037 // Define MQTT details
00038 char mqtt_client[] = "Asavie";
00039 char mqtt_topic[] = "Asavie";
00040 char mqtt_pub_msg[] = "{\"message\": \"MQTT sent via Asavie IoT Connect\"}";
00041 
00042 // Incoming MQTT message
00043 int arrivedcount = 0;
00044 
00045 
00046 //TCP test
00047 #define UDP 0
00048 #define TCP 1
00049 
00050 // Number of retries /
00051 #define RETRY_COUNT 3
00052 
00053 NetworkInterface *iface;
00054 
00055 // Echo server hostname
00056 const char *host_name = MBED_CONF_APP_ECHO_SERVER_HOSTNAME;
00057 
00058 // Echo server port (same for TCP and UDP)
00059 const int port = MBED_CONF_APP_ECHO_SERVER_PORT;
00060 
00061 static rtos::Mutex trace_mutex;
00062 
00063 #if MBED_CONF_MBED_TRACE_ENABLE
00064 static void trace_wait()
00065 {
00066     trace_mutex.lock();
00067 }
00068 
00069 static void trace_release()
00070 {
00071     trace_mutex.unlock();
00072 }
00073 
00074 static char time_st[50];
00075 
00076 static char* trace_time(size_t ss)
00077 {
00078     snprintf(time_st, 49, "[%08llums]", Kernel::get_ms_count());
00079     return time_st;
00080 }
00081 
00082 static void trace_open()
00083 {
00084     mbed_trace_init();
00085     mbed_trace_prefix_function_set( &trace_time );
00086 
00087     mbed_trace_mutex_wait_function_set(trace_wait);
00088     mbed_trace_mutex_release_function_set(trace_release);
00089 
00090     mbed_cellular_trace::mutex_wait_function_set(trace_wait);
00091     mbed_cellular_trace::mutex_release_function_set(trace_release);
00092 }
00093 
00094 static void trace_close()
00095 {
00096     mbed_cellular_trace::mutex_wait_function_set(NULL);
00097     mbed_cellular_trace::mutex_release_function_set(NULL);
00098 
00099     mbed_trace_free();
00100 }
00101 #endif // #if MBED_CONF_MBED_TRACE_ENABLE
00102 
00103 Thread dot_thread(osPriorityNormal, 512);
00104 
00105 void print_function(const char *format, ...)
00106 {
00107     trace_mutex.lock();
00108     va_list arglist;
00109     va_start( arglist, format );
00110     vprintf(format, arglist);
00111     va_end( arglist );
00112     trace_mutex.unlock();
00113 }
00114 
00115 void dot_event()
00116 {
00117     while (true) {
00118         ThisThread::sleep_for(4000);
00119         if (iface && iface->get_connection_status() == NSAPI_STATUS_GLOBAL_UP) {
00120             break;
00121         } else {
00122             trace_mutex.lock();
00123             printf(".");
00124             fflush(stdout);
00125             trace_mutex.unlock();
00126         }
00127     }
00128 }
00129 
00130 /**
00131  * Connects to the Cellular Network
00132  */
00133 nsapi_error_t do_connect()
00134 {
00135     nsapi_error_t retcode = NSAPI_ERROR_OK;
00136     uint8_t retry_counter = 0;
00137 
00138     while (iface->get_connection_status() != NSAPI_STATUS_GLOBAL_UP) {
00139         retcode = iface->connect();
00140         if (retcode == NSAPI_ERROR_AUTH_FAILURE) {
00141             print_function("\n\nAuthentication Failure. Exiting application\n");
00142         } else if (retcode == NSAPI_ERROR_OK) {
00143             print_function("\n\nConnection Established.\n");
00144         } else if (retry_counter > RETRY_COUNT) {
00145             print_function("\n\nFatal connection failure: %d\n", retcode);
00146         } else {
00147             print_function("\n\nCouldn't connect: %d, will retry\n", retcode);
00148             retry_counter++;
00149             continue;
00150         }
00151         break;
00152     }
00153     return retcode;
00154 }
00155 
00156 /**
00157  * MQTT message receiver
00158  */
00159 
00160 void messageArrived(MQTT::MessageData& md)
00161 {
00162     MQTT::Message &message = md.message;
00163     print_function("Message arrived: qos %d, retained %d, dup %d, packetid %d\r\n", message.qos, message.retained, message.dup, message.id);
00164     print_function("Payload %.*s\r\n", message.payloadlen, (char*)message.payload);
00165     ++arrivedcount;
00166 }
00167 
00168 
00169 int mqtt_send_receive() {
00170     
00171     MQTTNetwork mqttNetwork(iface);
00172 
00173     MQTT::Client<MQTTNetwork, Countdown> client(mqttNetwork);
00174 
00175     print_function("Connecting to %s:%d\r\n", mqtt_host, mqtt_port);
00176     int rc = mqttNetwork.connect(mqtt_host, mqtt_port);
00177     if (rc != 0)
00178         print_function("rc from TCP connect is %d\r\n", rc);
00179 
00180     MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
00181     data.MQTTVersion = 3;
00182     data.clientID.cstring = mqtt_client;
00183 
00184     if ((rc = client.connect(data)) != 0)
00185         print_function("rc from MQTT connect is %d\r\n", rc);
00186 
00187     if ((rc = client.subscribe(mqtt_topic, MQTT::QOS0, messageArrived)) != 0)
00188         print_function("rc from MQTT subscribe is %d\r\n", rc);
00189 
00190     MQTT::Message message;
00191 
00192     // QoS 0
00193     char buf[100];
00194     sprintf(buf, "Hello World!  QoS 0 message from Asavie \r\n");
00195     message.qos = MQTT::QOS0;
00196     message.retained = false;
00197     message.dup = false;
00198     message.payload = (void*)buf;
00199     message.payloadlen = strlen(buf)+1;
00200     rc = client.publish(mqtt_topic, message);
00201     while (arrivedcount < 1)
00202         client.yield(100);
00203 
00204     // QoS 1
00205     sprintf(buf, "Hello World!  QoS 1 message from Asavie \r\n");
00206     message.qos = MQTT::QOS1;
00207     message.payloadlen = strlen(buf)+1;
00208     rc = client.publish(mqtt_topic, message);
00209     while (arrivedcount < 2)
00210         client.yield(100);
00211 
00212     // QoS 2
00213     sprintf(buf, "Hello World!  QoS 2 message from Asavie \r\n");
00214     message.qos = MQTT::QOS2;
00215     message.payloadlen = strlen(buf)+1;
00216     rc = client.publish(mqtt_topic, message);
00217     while (arrivedcount < 3)
00218         client.yield(100);
00219 
00220     if ((rc = client.unsubscribe(mqtt_topic)) != 0)
00221         print_function("rc from unsubscribe was %d\r\n", rc);
00222 
00223     if ((rc = client.disconnect()) != 0)
00224         print_function("rc from disconnect was %d\r\n", rc);
00225 
00226     mqttNetwork.disconnect();
00227 
00228     print_function("MQTT finished, received %d msgs\r\n", arrivedcount);
00229 
00230     return 0;
00231 }
00232 
00233 
00234 
00235 /**
00236  * Opens a UDP or a TCP socket with the given echo server and performs an echo
00237  * transaction retrieving current.
00238  */
00239 nsapi_error_t test_send_recv()
00240 {
00241     nsapi_size_or_error_t retcode;
00242 #if MBED_CONF_APP_SOCK_TYPE == TCP
00243     TCPSocket sock;
00244 #else
00245     UDPSocket sock;
00246 #endif
00247 
00248     retcode = sock.open(iface);
00249     if (retcode != NSAPI_ERROR_OK) {
00250 #if MBED_CONF_APP_SOCK_TYPE == TCP
00251         print_function("TCPSocket.open() fails, code: %d\n", retcode);
00252 #else
00253         print_function("UDPSocket.open() fails, code: %d\n", retcode);
00254 #endif
00255         return -1;
00256     }
00257 
00258     SocketAddress sock_addr;
00259     retcode = iface->gethostbyname(host_name, &sock_addr);
00260     if (retcode != NSAPI_ERROR_OK) {
00261         print_function("Couldn't resolve remote host: %s, code: %d\n", host_name, retcode);
00262         return -1;
00263     }
00264 
00265     sock_addr.set_port(port);
00266 
00267     sock.set_timeout(15000);
00268     int n = 0;
00269     const char *echo_string = "TEST";
00270     char recv_buf[4];
00271 #if MBED_CONF_APP_SOCK_TYPE == TCP
00272     retcode = sock.connect(sock_addr);
00273     if (retcode < 0) {
00274         print_function("TCPSocket.connect() fails, code: %d\n", retcode);
00275         return -1;
00276     } else {
00277         print_function("TCP: connected with %s server\n", host_name);
00278     }
00279     retcode = sock.send((void*) echo_string, sizeof(echo_string));
00280     if (retcode < 0) {
00281         print_function("TCPSocket.send() fails, code: %d\n", retcode);
00282         return -1;
00283     } else {
00284         print_function("TCP: Sent %d Bytes to %s\n", retcode, host_name);
00285     }
00286 
00287     n = sock.recv((void*) recv_buf, sizeof(recv_buf));
00288 #else
00289 
00290     retcode = sock.sendto(sock_addr, (void*) echo_string, sizeof(echo_string));
00291     if (retcode < 0) {
00292         print_function("UDPSocket.sendto() fails, code: %d\n", retcode);
00293         return -1;
00294     } else {
00295         print_function("UDP: Sent %d Bytes to %s\n", retcode, host_name);
00296     }
00297 
00298     n = sock.recvfrom(&sock_addr, (void*) recv_buf, sizeof(recv_buf));
00299 #endif
00300 
00301     sock.close();
00302 
00303     if (n > 0) {
00304         print_function("Received from echo server %d Bytes\n", n);
00305         return 0;
00306     }
00307 
00308     return -1;
00309 }
00310 
00311 int main()
00312 {
00313      
00314     print_function("\n\nAsavie IoT Connect cloud service connector example\n");
00315     print_function("\n\nBuilt: %s, %s\n", __DATE__, __TIME__);
00316 #ifdef MBED_CONF_NSAPI_DEFAULT_CELLULAR_PLMN
00317     print_function("\n\n[MAIN], plmn: %s\n", MBED_CONF_NSAPI_DEFAULT_CELLULAR_PLMN);
00318 #endif
00319 
00320     print_function("Establishing connection\n");
00321 #if MBED_CONF_MBED_TRACE_ENABLE
00322     trace_open();
00323 #else
00324     dot_thread.start(dot_event);
00325 #endif // #if MBED_CONF_MBED_TRACE_ENABLE
00326 
00327     // sim pin, apn, credentials and possible plmn are taken atuomtically from json when using get_default_instance()
00328     iface = NetworkInterface::get_default_instance();
00329     MBED_ASSERT(iface);
00330 
00331     nsapi_error_t retcode = NSAPI_ERROR_NO_CONNECTION;
00332 
00333     /* Attempt to connect to a cellular network */
00334     while (do_connect() == NSAPI_ERROR_OK) {
00335         // Validate TCP session rules in Asavie IoT Connect
00336         retcode = test_send_recv();
00337         // Validate Asavie IoT Connect cloud service connector
00338         retcode = mqtt_send_receive();
00339         
00340     }
00341     
00342     
00343     if (iface->disconnect() != NSAPI_ERROR_OK) {
00344         print_function("\n\n disconnect failed.\n\n");
00345     }
00346 
00347     if (retcode == NSAPI_ERROR_OK) {
00348         print_function("\n\nSuccess. Exiting \n\n");
00349     } else {
00350         print_function("\n\nFailure. Exiting \n\n");
00351     }
00352 
00353     while(do_connect() == NSAPI_ERROR_OK);
00354 #if MBED_CONF_MBED_TRACE_ENABLE
00355     trace_close();
00356 #else
00357     dot_thread.terminate();
00358 #endif // #if MBED_CONF_MBED_TRACE_ENABLE
00359 
00360     return 0;
00361 }