An example program using NucleoL476RG with X-Nucleo-IDW01M1 wifi shield to sends analog data to Ubidots IoT Provider

Dependencies:   NetworkSocketAPI X_NUCLEO_IDW01M1v2 mbed

Fork of TLS_HelloWorld_IDW01M1 by ST

Complete tutorial at https://www.hackster.io/rreicher/nucleol476rg-to-ubidots-00d173

Revision:
13:12401835892c
Parent:
12:7b6b23225fd0
--- a/main.cpp	Mon Jan 16 13:20:06 2017 +0000
+++ b/main.cpp	Fri Oct 06 13:03:51 2017 +0000
@@ -1,138 +1,161 @@
-/* SpwfInterface NetworkSocketAPI Example Program
- * Copyright (c) 2015 ARM Limited
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
+/*
+    Copyright (C) 2017 romain reicher
 
-#include "mbed.h"
-#include "SpwfInterface.h"
-#include "TCPSocket.h"
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
 
-//www.mbed.com CA certificate in PEM format
-char  CA_cert []="-----BEGIN CERTIFICATE-----\r\n"
-"MIIDVDCCAjygAwIBAgIDAjRWMA0GCSqGSIb3DQEBBQUAMEIxCzAJBgNVBAYTAlVT\r\n"
-"MRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMRswGQYDVQQDExJHZW9UcnVzdCBHbG9i\r\n"
-"YWwgQ0EwHhcNMDIwNTIxMDQwMDAwWhcNMjIwNTIxMDQwMDAwWjBC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BWaAocvmMw==\r\n"
-"-----END CERTIFICATE-----\r\n";
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+    
+    About 
+    ---------------------------------------------------------------------
+
+    Send sensors value to Ubidots.
+    This example sends 3 variables to Ubidots.
+        - STM32L476 VBAT/3 internal channel in mV
+        - STM32L476 Internal Temperature Sensor in C
+        - The status of onboard User Button (blue) on NucleoL476RG 
+    Use NucleoL476RG with X-Nucleo-IDW01M1v2 wifi shield
+ 
+    Important note: Some IDW01M1 wifi shield had resistor R21 mounted
+                    which interfere with STLink/SWD programmer.
+                    Please unmount R21 to fix it.
+ 
+    romain reicher
+    Date     :  20/09/2017
+    Revision :  v0.1  
+*/
 
 
-//------------------------------------
-// Hyperterminal configuration
-// 9600 bauds, 8-bit data, no parity
-//------------------------------------
+#include "mbed.h"
+#include "SpwfInterface.h"  
+#include "TCPSocket.h"
 
-Serial pc(USBTX, USBRX);
-DigitalOut myled(LED1);
+/* Wifi Acces Point Settings */ 
+#define AP_SSID         "YOUR_WIFI_SSID"            
+#define AP_PASSWORD     "YOUR_WIFI_PASSWORD"
+#define UBIDOTS_SERVER  "things.ubidots.com"
+#define UBIDOTS_PORT    80
+#define UBIDOTS_TOKEN   "YOUR_UBIDOTS_TOKEN"
+#define UBIDOTS_DEVICE  "YOUR_UBIDOTS_LABEL_DEVICE"
 
-/*************************************
-//FRDM-K64: D9->UART1_TX, D7->UART1_RX
-Pin connections:
-    FRDM      IDW01M1
-   ------    ---------
-    +3v3 <--> +3v3
-    GND  <--> GND
-    D9   <--> D8
-    D7   <--> D2
+/* Communication ressources */
+SpwfSAInterface spwf(D8, D2, false);    
+Serial pc(USBTX, USBRX);
+
+/* Digital ressources */
+DigitalOut myLed(LED1);
+DigitalIn myButton(USER_BUTTON);
+
+/* Analog ressources */
+AnalogIn adc_vbat(ADC_VBAT);    // VBAT / 3 internal to ADC channel
+AnalogIn adc_temp(ADC_TEMP);    // Internal Temp Sensor to ADC Channel
+
+/* Global variables */
+float temp = adc_temp.read() * 100;     // Converted in C
+float batt = adc_vbat.read() * 30000;   // Converted in mV  
+bool level = false;
 
-SpwfSAInterface spwf(D9, D7, false);
-*************************************/
-/*************************************
-//LPCXpresso11U68: D9->UART1_TX, D7->UART1_RX
-Pin connections:
-    LPC      IDW01M1
-   ------    ---------
-    +3v3 <--> +3v3
-    GND  <--> GND
-    A1   <--> D8
-    A2   <--> D2
-
-SpwfSAInterface spwf(A1, A2, false);
-*************************************/
+/**
+  * @brief  Main program
+  * @param  None
+  * @retval None
+  */
+int main() 
+{
+    /* Configure Serial baud rate */
+    pc.baud(115200);
+    
+    /* Update level variable state depending USER_BUTTON state */
+    if (myButton == 0)
+        level = true;
+    else
+        level = false;
+    
+    TCPSocket socket(&spwf);
+    char sendBuffer[256];
+    char message[64];
+    int err;
+    
+    /* ######################## WIFI CONNECTION ######################## */
 
-//NUCLEO: D8->UART1_TX (PA_9), D2->UART1_RX (PA_10)
-SpwfSAInterface spwf(D8, D2, false);
-
-int main() {
-    int err;    
-    char * ssid = "STM";
-    char * seckey = "STMDemo";  
-      
-    pc.printf("\r\nTLS_HelloWorld mbed Application\r\n");     
-    pc.printf("\r\nconnecting to AP\r\n");
-            
-    if(spwf.connect(ssid, seckey, NSAPI_SECURITY_WPA2)) {      
-        pc.printf("\r\nnow connected\r\n");
-    } else {
-        pc.printf("\r\nerror connecting to AP.\r\n");
+    pc.printf("IDW01M1 NetworkSocketAPI TCP Client Ubidots\r\n");
+    pc.printf("Connecting to AP\r\n");
+    
+    //* Connect to wifi acces point */    
+    if(spwf.connect(AP_SSID, AP_PASSWORD, NSAPI_SECURITY_WPA2)) 
+    {      
+        pc.printf("Now connected\r\n");
+    } 
+    else
+    {
+        pc.printf("Error connecting to AP.\r\n");
         return -1;
     }   
+    
+    /* #################### GET CONNECTION INFOS ######################## */
+    
+    /* Get and print network connection parameters ip and mac adress */   
+    const char *ip = spwf.get_ip_address();
+    const char *mac = spwf.get_mac_address();    
 
-// Start Secure Socket connection test (one way server autentication only)   
-    TCPSocket socket(&spwf);
-    time_t ctTime;
-    ctTime = time(NULL);             
-    printf ("Start Secure Socket connection with one way server autentication test\n\r");                
-    printf("Initial System Time is: %s\r\n", ctime(&ctTime));   
-    printf("Need to adjust time? if yes enter time in seconds elapsed since Epoch (cmd: date +'%%s'), otherwise enter 0 ");                
-    int t=0;
-    scanf("%d",&t);
-    printf ("entered time is: %d \n\r", t);
-    if (t != 0) { time_t txTm = t; set_time(txTm); }  // set Nucleo system time
-    ctTime = time(NULL);    
-    printf ("The current system time is: %s", ctime (&ctTime));  // set WiFi module systm time
-    if (!spwf.set_time(ctTime)) printf ("ERROR set_time\n\r");       
-    if (!spwf.clean_TLS_certificate(ALL)) printf ("ERROR clean_TLS_certificate\n\r");
-    if (!spwf.set_TLS_certificate(CA_cert, sizeof(CA_cert), FLASH_CA_ROOT_CERT)) printf ("ERROR set_TLS_certificate\n\r");
-    if (!spwf.set_TLS_SRV_domain("*.mbed.com",FLASH_DOMAIN)) printf ("ERROR set_TLS_CA_domain\n\r");
-// NOTE:  the Wifi API set_secure_mode() and set_unsecure_mode() refers to the whole interface so the socket must be created / opened after 
-// having set the desidered mode (deft unsecure).
-//#define SEC_MODE1 // two possible ways to secure connect a socket are shown 
-    SocketAddress addr(&spwf, "");
-    spwf.gethostbyname(&addr,"www.mbed.com");  // ask DNS to resolve URL/IP 
-    addr.set_port(443);     
-    spwf.set_secure_mode();           
-    socket.open(&spwf);
-    spwf.set_unsecure_mode();    
-    printf ("Connecting to www.mbed.com IP: %s ...\n\r", addr.get_ip_address());
-#ifdef SEC_MODE1    
-    err = socket.connect(addr);
-#else
-    err = socket.connect("www.mbed.com", 443);
-#endif    
-    if (err != 0 )printf ("ERROR secure socket connection failed: %d\n\r", err);
-    else printf ("--->>> Secure socket CONNECTED to: %s\n\r", addr.get_ip_address());
-    socket.close();      
-    printf ("Socket closed\n\r");
+    pc.printf("IP address is: %s\r\n", ip ? ip : "No IP");
+    pc.printf("MAC address is: %s\r\n", mac ? mac : "No MAC");
+    
+    /* ##################### UBIDOATS SEND DATA ######################### */
+
+    printf("Sending HTTP Data to Ubidots...\r\n");
+ 
+    /* Open a socket , create a TCP connection to Ubidots */
+    err = socket.connect(UBIDOTS_SERVER, UBIDOTS_PORT); 
+    if (err!=0) 
+    {
+      pc.printf("\r\nCould not connect to Socket, err = %d!!\r\n", err); 
+      return -1;
+    } 
+    else 
+        pc.printf("\r\nconnected to host server\r\n"); 
+    
+    /* Construct content of HTTP command */
+    sprintf(message, "{\"temperature\": %0.2f, \"battery\": %0.2f, \"level\": %d}", temp, batt, (int)level);
+    printf("Content Length = %d\r\n", (int)strlen(message));
+    
+    /* Construct HTTP command to send */
+    sprintf(sendBuffer, "POST /api/v1.6/devices/%s/?token=%s HTTP/1.1\r\nHost: things.ubidots.com\r\nContent-Type: application/json\r\nContent-Length: %d\r\n\r\n%s", UBIDOTS_DEVICE, UBIDOTS_TOKEN, (int)strlen(message),message); 
+    pc.printf("HTTP command %s\r\n", sendBuffer);
+    wait(2.0);
+     
+    /* Send http request to Ubidots */ 
+    int scount = socket.send(sendBuffer, (int)strlen(sendBuffer));
+    printf("sent %d [%.*s]\r\n", scount, strstr(sendBuffer, "\r\n") - sendBuffer, sendBuffer);
+
+    /* Receive a simple http response and print out the response line */
+    char respBuffer[64];
+    int rcount = socket.recv(respBuffer, sizeof respBuffer);
+    printf("recv %d [%.*s]\r\n", rcount, strstr(respBuffer, "\r\n") - respBuffer, respBuffer);
+
+    /* Close the socket to return its memory and bring down the network interface */
+    pc.printf("Close Socket\r\n");
+    socket.close();
+    
+    /* Disconnect */
+    pc.printf("Disconnect Wifi\r\n");
     spwf.disconnect();
-    printf ("WIFI disconnected, exiting ...\n\r");
+    wait(1.0);
+    pc.printf("Done\r\n");
 
-    while(1) { 
-      wait(1);
-      myled = !myled;
+    myLed = 0;
+        
+    while(1) 
+    {
+        myLed = !myLed;
+        wait(1.0);
     }
 }