📜 ⬆️ ⬇️

IoT for a penny: make a device with a web interface


Author: Nikolai Khabarov, Senior Embedded Developer, DataArt

In this article we will explain how to create your own device with a web interface on your home network, using the latest 0.5 DeviceHive firmware version for the ESP8266 chip. But for a start, let's look at what's new in the firmware itself: the main innovations are related to the ability to work autonomously in a local network.


')
Previous articles of the cycle:

IoT for pennies, or What can DeviceHive.
IoT for a penny: a practical guide. Part 1, hardware.
Wireless configuration ESP8266 in firmware DeviceHive v 0.3.
IoT for a penny: a practical guide. Part 2, soft.

Great news - we updated DeviceHive firmware for ESP8266 to version 0.5. For those who have forgotten or did not know at all, I remind you, this firmware is an implementation of connecting to the DeviceHive server inside the ESP8266 chip. New features of the firmware allow the chip to work in the local network as a terminal device with its own web interface. In this case, you do not need to use the server even to host the web page, although all the functionality of connecting to a remote server is saved and can be used in conjunction with a local solution.

You can download the latest firmware version, as always, on GitHub . You can also see the source code of the firmware .

So, what's new with us.

1. Local RESTful API


Now on each chip on port 80 there is a simple HTTP server with a RESTful API. Commands completely repeat cloud commands except for the ability to use interrupts. A complete list of commands can be found in this document . For example, if you want to know the status of all the outputs of the chip, then you need to use the command 'gpio / read'. In the case of Klaud, we just sent this command to the server, and now we can simply access the local RESTful API at the address 'http: //device-id.local/api/gpio/read' and in response we will get a JSON containing the state of all the conclusions . If the access key (AccessKey) is not set on the chip, this can be done even from the browser:



Or using the curl utility.

curl -i -X POST \ -H "Authorization: Bearer YourAccessKeyHere=" \ http://esp-demo.local/api/gpio/read 

If you have an access key, it must be passed in the HTTP header. The key is used both for authorization on the cloud server and for local work. For local use, the key should be treated as a simple string, that is, a password. The method can be either GET or POST - this does not affect the functionality of the commands. The command is transmitted in the address of the request, and the parameters, if any, in the body of the request in the form of JSON.

2. mDNS


You probably noticed that in the example above, the domain name esp-demo.local is used. Multicast Domain Name System is now implemented on the chip, and all devices that support mDNS within the local network can resolve domain names to IP addresses. Moreover, it is possible to detect all devices within the network, and a local DNS server is not required.

mDNS works on a protocol that completely repeats the classic DNS, but requests are sent via UDP to the broadcast address. Devices listen to the same broadcast address and respond to requests on their own. The DeviceId chip (which is configured during the firmware setup) is used as the domain name. The full domain name will look like DeviceId.local.

There is an RFC6763 describing a service discovery procedure, including inside mDNS. This can be used to detect chips with our firmware. There are many utilities and libraries that implement service discovery using mDNS. For example, a chip with DeviceId 'esp-demo', found by the 'avahi-discovery' utility, will look like this:



Some modern operating systems are able to resolve such domain names from any application, for example, from a browser. Some will need to install specialized software.

3. Support popular sensors


Previously, to work with sensors, it was required to implement a communication protocol for the sensor itself. Now the list of commands includes support for reading data from popular sensors with one command. For example, to get the temperature from the DS18B20 sensor, you first need to initialize the temperature measurement procedure, wait for the measurement to finish, and read the result. And this is not the most difficult of the possible procedures. Now, in order to find out the temperature of the sensor, it is enough just to send the command 'devices / ds18b20 / read' and in response to receive JSON of the form '{' temperature ': 24.5000}'. For a complete list of supported sensors, see the list of commands .

Example of data output from MPU-6050 (accelerometer, gyroscope, plus there is a temperature sensor on the chip):



4. Local web server


Since we have a RESTful API on the HTTP server, why not just give it a web page. And, of course, he knows how. After installing the firmware on the chip, open in the browser 'http: //deviceid.local/', and you will see the web interface of the chip. By default, it contains a little help on how to use the firmware, tools for working with the local RESTful API (a page where you can try calling various commands and a base64 converter), a few examples of web pages using the RESTful API (you can see the source codes of the pages directly from browser) and so far quite simple, but a text editor web page. With this editor, you can change the main page of the chip to any of your own code directly from the browser. Page size is limited to 64KiB.

You can place on the chip a page like embedded examples that will implement any operations with the chip in JavaScript and display them to the user in a web browser. Moreover, no one forbids to access all the chips within the local network from the same page.



Practical part


Now let's connect the DS18B20 temperature sensor and equip it with a web interface. The sensor must be powered from the GND and 3V3 pins and connected to some GPIO pin. Right next to the power pins is GPIO2, let's use it. The connection can be made as follows:



In the photo, one of the most popular options for implementing a development board for the ESP8266, which immediately includes a microUSB power supply, USB-TTL adapter. It is very convenient. Using such a board, you don’t even need to pinch any outputs while flashing; the latest version of the flasher firmware will do everything itself. Simply connect the Micro-USB and run the utility. Note that the retail cost of such boards for developers on Chinese marketplaces, including delivery, dropped to 3-4 dollars.

But back to the web interface. On the chip itself, there is already a web page with an example of using the DS18B20. It is located at http: //deviceid.local/ds18b20.html. Open it, enter, if necessary, an access key and see the temperature read from the sensor:



The source code of the page can be viewed directly in the browser. If you do not like the design, you want to display data from several sensors, or you need to connect any other sensor, you can make and upload your web page to the chip, as we described above.

For example, let's make a simple web page that will control a connected relay.

The code will look like this.
 <html> <head> <script type="text/javascript"> function send(onOff) { localStorage['accesskey'] = document.getElementById('accesskey').value; var xmlhttp = new XMLHttpRequest(); xmlhttp.open('POST', "http://" + window.location.hostname + '/api/gpio/write', true); xmlhttp.setRequestHeader("Authorization", "Bearer " + localStorage['accesskey']); xmlhttp.onreadystatechange = function() { if(xmlhttp.readyState == 4){ if(xmlhttp.status < 200 || xmlhttp.status > 299) { alert('ERROR: Command return ' + xmlhttp.status + ' ' + xmlhttp.responseText, true); } } } var json = {} json["5"] = onOff ? 1 : 0; xmlhttp.send(JSON.stringify(json)); } function init() { document.getElementById('accesskey').value = localStorage['accesskey']; } </script> </head> <body onload="init()"> <label>AccesKey: </label><input type="password" id="accesskey"><br><br> <input type="button" value="On" onclick="send(true);"> <input type="button" value="Off" onclick="send(false);"> </body> </html> 

This code, using localStorage, stores the chip access key so that it does not have to be entered each time. When you click on the on / off button, XMLHttpRequest () is called, which sends a request to the local RESTful API.
Now we will load this page on the chip. We will connect the SSR-40DA solid-state relay, with which we will turn on the electric motor, which is powered from a 220-volt alternating voltage, i.e. from an outlet. Naturally, instead of an electric motor, you can connect another load, such a relay can withstand up to 40 Amps. In the video you can see how to connect such a relay and how it turns on an electric motor:


That's all, thank you all for your attention. Any criticism and suggestions are welcome, write!

Source: https://habr.com/ru/post/398813/


All Articles