Build your own online real-time collection system application of--HTML5 in embedded system

Source: Internet
Author: User

※ in the April issue of radio, we have built your online real-time collection system.
Application of--HTML5 in embedded system
Liu Chen, Xu Yang
Abstract: This application is free from the previous data collection methods of embedded system, with the help of the latest HTML5 canvas API and WebSocket API, the online real-time data acquisition function is realized. Improves the performance and experience of embedded capture systems. Provide reference for embedded developers.
keywords: html5;http server;canvas;websocket;w5500; real-time; acquisition system;
In today's information society, the message is money, but the information is bound to carry the timeliness, outdated information will not have any value. Thus, the importance of real-time information.
With the rapid development of the Internet of things in various industries in recent years, more and more terminals are connected to the network to realize remote interaction and control, and the widespread popularization of all kinds of sensors makes the data nodes more and more distributed. And these interactive data itself is a kind of raw information, which needs our collection, analysis, processing, feedback, its data authenticity, accuracy, and real-time to ensure the efficiency of the whole work, quality and value.
Here, we implement an on-line acquisition system based on W5500 and introduce a fresh element--html5 to it. Through this latest web language, we present a more real-time, efficient online real-time collection system. It is believed that with the HTML5 in the embedded field, it is inevitable to have a small effect on industrial efficiency and value promotion.
Before we introduce this kind of real-time acquisition system, let's start with a simple understanding of HTML5.
The difference between HTML5 and HTML
HTML is a markup language designed to create Web pages that enable it to be rendered in a Web browser.
HTML5 is the next revised version of HTML. The broad range of HTML5 includes new and enhanced Html,css3,javascript APIs and events in a set of technology portfolios.

Figure 1HTML5 Logo
The following are the main features of HTML5 than the new HTML enhancements:


    • Improve the optimization of page elements;
    • forms;
    • Canvas drawing;
    • Web Sockets (WebSocket)
    • local storage;
    • Information transmission between pages;
    • Video and audio (timed media playback);
    • Geographic location (communication APIs);
    • Micro-data;

Canvas API and Web Socket API
In fact, the implementation of the online real-time acquisition system, thanks to HTML5 new 2 API functions: Canvas and WebSocket.
Canvas, developed by Apple's pixel drawing elements developed for Mac OS x dashboard in 04. Consists of the canvas element and the corresponding JavaScript. Enables developers to use JavaScript's canvas graphics tools to dynamically draw graphics on canvas element artboards without the need for other third-party plugins.
Websocket provides a socket that communicates directly with the server. After the communication is established, the client (browser) can communicate with the Web server in two directions, without requiring the client to frequently poll the server for implementation. This reduces the overhead of HTTP requests, reduces packet load, and makes communication more real-time.
Through the flexible application of these 2 API functions, we implemented the function of receiving data in real time through HTTP Server, and dynamically simulating on Web page.
Online real-time capture system Demo

    • System environment

A) Microcontroller: stm32f103rc,256k byte flash,48k byte sram,2k byte EEPROM
b) Ethernet controller: The W5500,spi interface is connected to a single chip microcomputer
c) power supply: USB powered
2. Development tool: IAR for ARM v5.41, which is the version we use for our project. If you are using a different version of IAR, make a slight adjustment to the STM library.
Before looking at the code, let's take a look at the entire program flow, as shown in. After the hardware initialization completes, will carry on the network parameter configuration, this is to configure the W5500 IP address and so on according to own network the network parameter, guarantees the W5500 to be able to connect the net; In this program, we will use the W5500 two socket resources, one to create the HTTP Server, This allows you to access our hardware remotely by entering the configured IP address on the browser, and the other is to create a web Socket Server to establish a communication link with the Web page to transmit our temperature and humidity data.

Figure 2 Hardware Operation Flow
When we access the IP address of the hardware in the browser, we send an HTTP request to W5500, and W5500 sends the HTML5 Web page information to the browser after receiving the request, so that the main interface of our temperature and humidity detection system can be displayed on the browser. In the Code of the Web page, the browser will actively connect to the W5500 Web Socket Server, and after the handshake is completed, the data communication channel is established. In this way, the hardware can be a barrier-free temperature and humidity data sent to the browser side, the browser after receiving temperature and humidity data, using the canvas function, at the specified location to draw a temperature and humidity indication points and curves. The following is an introduction to the Web socket (network sockets) and canvas (canvas) code in HTML5, the W5500 Web socket handshake and the data frame protocol, and the temperature and humidity collection program.

Figure 3 Page Display interface
Canvas and Web sockets
On the browser side we use the HTML5 Canvas drawing tool and the WebSocket API to build our web interface. When there is a new temperature and humidity data to temporary, in the coordinate system of the canvas will have a point display, and identify the number, and with the increase in the number of acquisitions, multiple data lines, you can see the curve changes. The Web program steps are as follows:
1) Create the page and the style, body tag that the canvas belongs to
2) Draw axes, add headings; establish WebSocket connection
3) New data arrival, draw points and lines
Drawing with Canvas
Here's how to create a canvas and the drawing functions used in your code.
1) Create a 600x400 canvas, in pixels

2) Defines the border width, color, and padding size of the canvas.
#graph {
border:1px solid #03F;
margin:0 40px 0 80px;
}
3) to draw the canvas in JavaScript, you first need to get the drawing environment from the target canvas's ID. The code needs to get the canvas element by ID and then use the Getcontex method of this element to get a reference to the second dimension drawing environment
Canvas = document.getElementById (' graph ');
context = Canvas.getcontext (' 2d ');
4) Draw a line segment
Context.linewidth = 2;//Set line width
Context.strokestyle = ' #999 ′;//sets the color of the line
Context.moveto (x1,y1);//Move to start
Context.lineto (x2,y2);//Create a path to the end point
Context.stroke ();//actually draw this line
5) Draw a circle
Context.fillstyle = ' #000 ′;//set fill Color
Context.beginpath ();
Context.arc (x, y, 2, 0, Math.PI * 2, true);//Draw a circle of radius 2 at coordinates (x, y)
Context.closepath ();
Context.fill ();//fill the circle with color
6) write the title text at the specified position
Context.filltext (text, x, y, maxWidth);
Use the above function combination to draw the following diagram, if you think this is not flashy, HTML5 canvas also provides a gradient, rotation, illustrations and other functions, play your design to create your own front-end interface bar.

Figure 4 Canvas Sample diagram
The use of WebSocket next we introduce the use of WebSocket in HTML5 and related functions
1) in order to create a websocket connection, the code needs to create an WebSocket interface instance, pass in the Web service URL address, and the Sensorwebsocket object will attempt to connect to the service that listens to the corresponding URL
var Wsuri = ' ws:192.168.10.111:1818′;
Sensorwebsocket = new WebSocket (Wsuri);
2) Register the event and link the event to the corresponding handler function, for example, after receiving data from the server side of the browser page, trigger the OnMessage event, and then call the OnMessage function, in the code we registered OnOpen, OnMessage, OnClose and onerror four events
Sensorwebsocket.onmessage = function (evt) {onmessage (evt)};
3) Message processing function, on the hardware we will collect the temperature and humidity data with '. ' Connection, in the browser side, after receiving the data, using the string segmentation function to divide the temperature and humidity data, stored in an array object. The next code is to convert the number of displays to the coordinate values displayed on the canvas, which is not mentioned here.
function OnMessage (evt) {
Vararrayth=new Array (2);
Arrayth = Evt.data.split ('. ');
......
}
4) Active shutdown WebSocket Connection
Sensorwebsocket.close ();
Well, WebSocket's use is very simple, with this tool, you can connect with the remote server and accept and send messages, this feature is very useful in two-way communication, especially when the server needs to proactively send messages to the browser page.
Web socket handshake and data frame
After the server-side creation of the socket, the first to complete the handshake with the client to start data communication, then this handshake in the program listing how to achieve, first look at the handshake process:
Table 1 Handshake process

The client's code is described above, the following is the hardware of the server 1, 2 of the Code:
#define Ws_server_port 1818//defines the port number that the server listens on
Socket (s, sn_mr_tcp, Ws_server_port, 0x20), socket connection in//w5500
Listen (s);//Turn on the socket sequence that listens for s variable W5500, use number 2nd in this routine
The following is the network information that is configured for W5500, where the IP address is the listening address of the WebSocket object of our browser page program.
Uint8 mac [6]={0x00, 0x08, 0xdc, 0x11, 0x11, 0x11};
Uint8 Lip [4]={192, 168, 10, 111};
Uint8 Sub [4]={255, 255, 255, 0};
UINT8GW [4]={192, 168, 10, 1};
Setshar (MAC);
SETSUBR (sub);
Setgar (GW);
SETSIPR (LIP);
Code for the server 5, 6, 7 processes in the hardware:
Charsec_ws_key []={0x00,};
Characcept_key []={0x00,};
Get Sec-websocket-key:
if (STRSTR (Charconst *) Wsrxbuf, "Sec-websocket-key:"))
{
Mid ((char *) wsrxbuf, "Sec-websocket-key:", "RN", sec_ws_key);//Intercept Sec_key
Calc_accept_key (Sec_ws_key, Accept_key);//Coding function
sprintf (char *) wstxbuf, "http/1.1 101 switchingprotocolsrnupgrade:websocketrnconnection: Upgradernsec-websocket-accept:%srnrn ", accept_key);//Generate Handshake message
Send (S, Wstxbuf, strlen ((char *) wstxbuf));//Send to Client
}
handshaked = 1;
This may seem a bit abstract, we look at the actual packet bar, the top red font for the browser page handshake request, sec-websoket-key after we intercept the Sec_key, behind the blue font for the server side of the handshake reply, After sec-websoket-accept for our code after the Accept_key, how, at a glance.


Figure 5 Grasping the packet information in the handshake process
After the handshake succeeds, the temperature and humidity data collected at each interval can be sent to the browser page at the hardware side. The packet of the WebSocket protocol is very lightweight, and the following describes the frame format of the packet:

Figure 6WebSocket Data Frame format
Is the official structure, the first byte, the first bit is fin, the back three bits are RSV1 to 3. The RSV is a reserved space, filled with 0, then the first 4 bits of the fin need to be set only. The next four bits are the values that store the opcode, and the opcode defines the interpretation of the payload data. Fin is used to indicate the last fragment of the message, if there is only one message, then fin is 1; here we use opcode to define the data is the text -0x1, so the first word binary is 1000001 (0X81), the first 1 is the value of fin, the last 1 is the value of opcode.
Next is the second byte of data, which consists of a 1-bit mask and a 7-bit payloadlen, mask identifies whether the data frame data uses a mask, Payloadlen represents the length of the data part. But Payloadlen only 7 bits, for unsigned integers only 0 to 127 of the value, such a small number of course can not describe the larger data, it is specified when the length of the data is less than or equal to 125 when it is a description of the length of the data, if the value is 126, Two bytes later to store the stored data length, or 127 to store the data length with the eight bytes in the back. Here we send the temperature and humidity data only 5 bytes, and do not use a mask, so configured to 0x05.
Then the maskingkey in the chart above, which occupies four bytes, stores the solid portion of the mask. However, this data is only available if the previous mask is set to 1, otherwise the data will not be used without a mask. Finally, the data section, if the mask exists, then all the data needs to do a different or operation with the mask. If there is no mask, then the data behind it can be used directly.
Let's see how the code we send the data is implemented:
wstxbuf [0]= 0x81;
wstxbuf [1]= 0x05;
Wstxbuf [2]= TEMP/10 + 0x30;
Wstxbuf [3]= Temp% + 0x30;
wstxbuf [1]= 0x2e;//delimiter '. ’
Wstxbuf [2]= HUMI/10 + 0x30;
Wstxbuf [3]= Humi% + 0x30;
Send (S, Wstxbuf, strlen ((char *) wstxbuf));
Is the code very easy!?
Data acquisition
Then another brief description of the data acquisition process. We use temperature and humidity sensor DHT11, to carry out the real-time data collection and upload of indoor temperature and humidity. Here with the DHT11 with a single-chip computer connection (W5500), it and SCM Communication only need an I/O port, the use is very simple. Specific DHT11 and SCM connection and related debugging, here is not explained in detail. Can search for relevant information.
It is believed that with the continuous maturation of HTML5, it brings not only the Web revolution of PC environment. For the embedded domain, it can also bring better customer experience and product performance. Of course, we still need to use W5500, a feature of the Ethernet chip. Its full hardware TCP/IP stack not only greatly saves valuable embedded resources, but also saves a lot of development steps and difficulties, so that we can more resources and energy to achieve more exciting web features.
If you're interested, hurry up and make a real-time online capture system of your own.

Build your own online real-time collection system application of--HTML5 in embedded system

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.