Example program to create IoT devices for a local network, which connect to a local server.
Dependencies: WebSocketClient WiflyInterface mbed messages
This code is used in the second part of my Internet of Things (IoT) blog post available here. The code is fairly simple, but its real value is in its reliability. I have worked hard to try to make the wireless connection as reliable, and as fast, as possible. There are a few lines of code that must be modified before it will work correctly, and those are described in the following Wiki pages.
It is designed to work with a Python WebSocket Server running on a PC, the source code of which is available here.
Once operating with the server, each microcontroller, or IoT device, will broadcast a counter and its internal temperature to your WebSocket Server.
Diff: source/globals.cpp
- Revision:
- 2:7abdaa5a9209
- Parent:
- 1:4403f2ed1c1f
- Child:
- 3:f20e114eb2ee
--- a/source/globals.cpp Tue Oct 04 13:19:19 2016 +0000 +++ b/source/globals.cpp Tue Oct 04 13:59:13 2016 +0000 @@ -21,6 +21,7 @@ Serial pc(USBTX, USBRX); InterruptIn UIBut1(USER_BUTTON); Timer DisplayTimer; +DigitalOut Led(LED1); WiflyInterface eth(D8, D2, D6, LED1, wifissid, wifipassword, WPA2); @@ -131,22 +132,29 @@ void ReceiveNetworkData(unsigned int * wifi_cmd, unsigned int * var, float * value){ char msg_buffer[CHARMSGBUFF]; char msg_buffer2[CHARMSGBUFF]; - // Check for data on the websocket: - if(ws.readmsg(msg_buffer)){ - INFO("Received: %s", msg_buffer); - sscanf(msg_buffer, "%d,%s", wifi_cmd, msg_buffer2); - if(*wifi_cmd == CHANGEVAR_WIFI_CMD){ - // Get two more values: - sscanf(msg_buffer2, "%d,%f", var, value); + int resp; + if(IotStatus.CheckFlag(SF_SERVERCONNECTED)){ + // Check for data on the websocket: + resp = ws.readmsg(msg_buffer); + if(resp == 1){ + INFO("Received: %s", msg_buffer); + sscanf(msg_buffer, "%d,%s", wifi_cmd, msg_buffer2); + if(*wifi_cmd == CHANGEVAR_WIFI_CMD){ + // Get two more values: + sscanf(msg_buffer2, "%d,%f", var, value); + }else{ + // Get one: + sscanf(msg_buffer2, "%f", value); + } + }else if(resp == -1){ + // Connection to the server is lost: + IotStatus.ClearFlag(SF_SERVERCONNECTED); }else{ - // Get one: - sscanf(msg_buffer2, "%f", value); + //DBG("Did not receive anything :(\n\r"); + *wifi_cmd = NO_WIFI_CMD; + *var = 0; + *value = 0.0f; } - }else{ - //DBG("Did not receive anything :(\n\r"); - *wifi_cmd = NO_WIFI_CMD; - *var = 0; - *value = 0.0f; } return; }