Here is an exciting framework for fully utilizing the huge capabilities of the ESP8266.

This is an original.

Something that I have not seen anywhere before. You see, using this structure opens up many more possibilities and applications for this amazing device…

Most folks in the ESP8266 world seem to fall into one of two camps. The first group, typically diehard Arduino developers, want to use the ESP8266 as a serial to WIFI shield. A couple bucks to add WIFI to the very popular Arduino platform is most cost effective method of bringing it on-line. Much cheaper than alternative WiFi shields.

Others see the ESP8266 as a complete solution. It is often referred to as a System On a Chip (SoC). They not only use the ESP8266 for WIFI internet access, but also use the platform to read sensors, control “things”, process data and provide web server functionality.

Among The Examples

The majority of those that have delved into the ESP8266 world started by loading the serial to WIFI firmware often referred to as the AT command set. This is available as a binary file downloaded to the ESP8266 via it’s serial interface. That’s where I began my ESP8266 journey.

It was not long after my start that I searched for the AT firmware source code. Fortunately, it is available within earlier versions of the EspressIf SDK. You see, prior to version 1.0, many example applications were included in the development package. And yes, the AT command set was among these examples.

The other most useful example application is the IoT_Demo. This software has survived every release of the SDK, including the current version. This example provides a framework for a web server to make your “things” Internet accessible.

After studying the software structure of these examples I got to thinking…

Wouldn’t it be great to merge these two applications? So you benefit from both features?

It indeed did look feasible.

The combined application would not only service AT commands through the serial port, but also service http GET or POST commands via the Internet.

And that’s not all…

This single ESP8266 firmware application could also be used to read sensors and control devices.

I am stoked to say I have successfully merged these examples. This broadens the capabilities and applications of a single ESP8266 based system.

It works!

Here’s how…

ESP8266 Dual Server Architecture

The ESP8266 is used to perform 3 primary functions. First, it provides basic serial to Wifi capability using the standard AT command set that many first-time users tinker with. Note that since the design presented here includes the AT firmware source code, the command set can be expanded to also provide access to the Esp8266 Daq and Control features. This is depicted in the following diagram as two-way arrows from the AT Server.

The ESP8266 also provides Web Server functionality. This feature operates completely independently from the serial AT Server. The web server responds to http GET commands received form the Internet via the built-in Wifi capability. Just like the AT Server, the Web Server has access to the Daq and Control functions.

And finally, the data acquisition (DAQ) and control function, also running independently from the other two features, controls all the Esp8266 outputs and receives all the sensor inputs. Because of the many possible sensors connected to the system, the DAQ function must be managed so that it does not monopolize the Esp8266 processor. This is accomplished by limiting it’s execution to the reading of one sensor each time the function is called.

Task Distribution

Separate callbacks are registered for each of the three ESP8266 primary functions. Both the AT and Web Server callbacks are event driven. They are only executed upon user request. The AT callback is executed anytime data is received on the serial port, while the Web Server callback is run upon receipt of an http GET request.

The callback for the Daq/Control features are different. This feature is set up to execute periodically (once every second) from a Timer callback. This keeps the sensor data fresh, available for consumption by the AT or Web Server, upon request.

AT Callback – The AT serial port server callback is installed in the uset_init() function when at_init() is executed. The AT server responds to any of the requests defined in at_cmd.h.

at_funcationType at_fun[at_cmdNum]={ {NULL, 0, NULL, NULL, NULL, at_exeCmdNull}, . . {"+CIPSERVER", 10, NULL, NULL,at_setupCmdCipserver, NULL}, {"+CIPMODE", 8, NULL, at_queryCmdCipmode, at_setupCmdCipmode, NULL}, {"+CIPSTO", 7, NULL, at_queryCmdCipsto, at_setupCmdCipsto, NULL}, {"+CIUPDATE", 9, NULL, NULL, NULL, at_exeCmdCiupdate}, {"+CIPING", 7, NULL, NULL, NULL, at_exeCmdCiping}, {"+CIPAPPUP", 9, NULL, NULL, NULL, at_exeCmdCipappup}, {"+GETSENSOR", 10, NULL, NULL, at_exeGetSensorVal, NULL},

The new request, “+GETSENSOR”, has been added to provide a method for the serial port server to get the sensor readings. Upon receiving this request, the function at_exeGetSensorVal() is called. This function returns the current sensor reading over the ESP8266 serial port.

void ICACHE_FLASH_ATTR at_exeGetSensorVal(uint8_t id, char *pPara) { int isensno = atoi(++pPara); switch(isensno) { case 1: uart0_sendStr(tInside); break; case 2: uart0_sendStr(tOutside); break; case 3: uart0_sendStr(tAttic); break; case 4: uart0_sendStr(tDht11); break; case 5: uart0_sendStr(hDht11); break; case 6: uart0_sendStr(pBmp085); break; case 7: uart0_sendStr(tBmp085); break; case 8: uart0_sendStr(aBmp085); break; default: uart0_sendStr("out of range"); break; } uart0_sendStr("\r

"); }

The requests are made by sending the following string over the serial port:

AT+GETSENSOR=n

“n” is the sensor number and corresponds to the case number in the code above.

As you can see, it is not difficult to add your own custom commands to the standard ESP8266 AT command set.

Web Server Callback – This application uses the Web Server code provided in the IoT_Demo example. The user_init() function sets up and connects to the local Wifi before launching the Web Server. The callback webserver_recv() is registered during the initialization sequence. That function is executed any time an http GET request is received.

For this demo application, the Web Server only responds to “request-GetSensors”. More requests can be added as noted in the code that follows. When received, the server replies by sending a JSON string containing all the sensor readings.

LOCAL void ICACHE_FLASH_ATTR webserver_recv(void *arg, char *pusrdata, unsigned short length) { URL_Param *pURL_Param = NULL; char *pParseBuffer = NULL; bool parse_flag = false; struct espconn *ptrespconn = arg; int i; espconn_set_opt(ptrespconn, ESPCONN_REUSEADDR); if(upgrade_lock == 0){ parse_flag = save_data(pusrdata, length); if (parse_flag == false) { response_send(ptrespconn, false); } pURL_Param = (URL_Param *)os_zalloc(sizeof(URL_Param)); parse_url_params(precvbuffer, pURL_Param); switch (pURL_Param->Type) { case GET: if(os_strcmp(pURL_Param->pParam[0], "request")==0) { <strong>// GetSensors is the only request the server currently supports</strong> <strong> if(os_strcmp(pURL_Param->pParVal[0], "GetSensors")==0) {</strong> <strong> json_send(ptrespconn, GET_SENSORS);</strong> <strong> }</strong> // Add additional requests here } json_send(ptrespconn, CONNECT_STATUS); break; case POST: ets_uart_printf("We have a POST request.

"); break; } if (precvbuffer != NULL){ os_free(precvbuffer); precvbuffer = NULL; } os_free(pURL_Param); pURL_Param = NULL; } else if(upgrade_lock == 1){ local_upgrade_download(ptrespconn,pusrdata, length); if (precvbuffer != NULL){ os_free(precvbuffer); precvbuffer = NULL; } os_free(pURL_Param); pURL_Param = NULL; } }

Acquisition/Control Timer Callback – This callback serves as the application’s periodic loop() function. It is called once every second. The functions is mechanized as a state machine. In this example, 5 states are implemented, one for each sensor in the system. Exactly one state is executed each time the function is called. Upon completion of the sensor read, the code is set to execute the next state the next time the function is called. The code can be modified as needed to add or delete states and sensor hardware.

LOCAL void ICACHE_FLASH_ATTR loop_cb(void *arg) { char szT[32]; DHT_Sensor DHsensor; DHT_Sensor_Data data; DHsensor.pin = 5; //GPIO14 DHsensor.type = DHT11; int32_t temperature; int32_t pressure; //--------------------------------------------------- //This state machine reads 1 sensor each iteration //--------------------------------------------------- switch(nTcnt%5) { case 0: //Read first DS18B20 Temperature Sensor get_temp_ds18b20(1,1,tInside); break; case 1: //Read second DS18B20 Temperature Sensor get_temp_ds18b20(2,1,tOutside); break; case 2: //Read third DS18B20 Temperature Sensor get_temp_ds18b20(3,1,tAttic); break; case 3: //Read DHT11 temperature and humidity Sensor DHTRead(&DHsensor, &data); DHTFloat2String(tDht11, ((9/5) * data.temperature)+32); DHTFloat2String(hDht11, data.humidity); break; case 4: //Read BMP085 Temperature and pressure Sensor temperature = BMP180_GetTemperature(); pressure = BMP180_GetPressure(OSS_0); os_sprintf(pBmp085,"%ld.%01d", pressure/3386,(pressure%3386)/1000); os_sprintf(tBmp085,"%ld.%01d", ((temperature*18)/100) + 32,(temperature*18)%100); os_sprintf(aBmp085,"%03d", 328 * (BMP180_CalcAltitude(pressure)/100000)); break; default: break; } }

Want the code for this framework? Please feel free to use and modify it for your own custom requirements. It is available on Github here.

Testing the Code

Let’s test the dual server by sending a command over the serial port and via http GET. The command will retrieve sensors values read by the ESP8266. For this test case, the 1 second loop() function has been modified as follows to populate the sensor variables without actually reading any sensors.

LOCAL void ICACHE_FLASH_ATTR loop_cb(void *arg) { //----------------------------------------------------- //This test code populates the variables associated //with the sensor values in lieu of actually reading //sensors. This code is used to test the functionality //of the dual server application. All variables are //set with fixed values except iTinside, which is // incremented by 1.5 degrees each time this function //is called. //----------------------------------------------------- if(tI<800) { tI += 15; } else { tI = 600; } os_sprintf(tInside,"%d.%d",tI/10,tI%10); //Sensor 1 os_sprintf(tOutside,"%s","79.2"); //Sensor 2 os_sprintf(tAttic,"%s","88.5"); //Sensor 3 os_sprintf(tDht11,"%s","69.1"); //Sensor 4 os_sprintf(hDht11,"%s","34.7"); //Sensor 5 os_sprintf(pBmp085,"%s","29.7"); //Sensor 6 os_sprintf(tBmp085,"%s","71.1"); //Sensor 7 os_sprintf(aBmp085,"%s","555.0"); //Sensor 8 }

AT Serial Server Test

The added function in this demo application to the AT command set is “AT+GETSENSOR=n”. “n” is filled in with an integer value representing the sensor number. Enter the following to test this new command:

Sensor Serial Port Command Expected Reply Inside Temperature AT+GETSENSOR=1 increasing value in range 60-80 F Outside Temperature AT+GETSENSOR=2 79.2 Attic Temperature AT+GETSENSOR=3 88.5 DHT11 Temperature AT+GETSENSOR=4 69.1 DHT11 Humidity AT+GETSENSOR=5 34.7 BMP085 Pressure AT+GETSENSOR=6 29.7 BMP085 Temperature AT+GETSENSOR=7 71.1 BMP085 Altitude AT+GETSENSOR=8 550.0

Web Server Test

The web server can easily be tested by entering a single URL in any web browser. In this demo application, the IP is hard-coded to “192.168.0.106” and the server responds to port 9703 requests. Thus, the test URL is:

http://192.168.0.106:9703/?request=GetSensors

And the expected reply will be the following JSON string:

{ "B_Pressure":"29.7", "B_Temperature":"71.1", "B_Altitude":"555.0", "DS_TempInside":"79.5", <--NOTE: This value will range from 60-80 F in 1.5 degree increments "DS_TempOutside":"79.2", "DS_TempAttic":"88.5", "DH_Humidity":"34.7", "DH_Temperature":"69.1" }

Your demo application is working properly if the expected responses are observed.

In Closing

This opens up new possibilities. With this structure, you use the ESP8266 as an Arduino serial to WIFI shield. Yet at the same time use this same ESP8266 as a web server. And a sensor acquisition engine. And to control “things”. All you need to do is add meat to the bones provided here. What will you come up with?

I hope you find this information useful…