Browse Source

Код переделан под WebSocket'ы - сначала клиент скачивает страницу, затем подключается по сокету к ESP. Далее ESP начинает каждый интервал времени присылать массив с данными на клиент, используя JSON-формат.

master
Nikita Romanenko 7 years ago
parent
commit
573b934c07
  1. 1
      .gitignore
  2. 4
      .vscode/launch.json
  3. 26
      html/acc.html
  4. 30
      src/html.h
  5. 91
      src/main.cpp

1
.gitignore

@ -1,3 +1,4 @@
.pioenvs .pioenvs
.piolibdeps .piolibdeps
.vscode/c_cpp_properties.json .vscode/c_cpp_properties.json
lib

4
.vscode/launch.json

@ -6,8 +6,8 @@
"request": "launch", "request": "launch",
"cwd": "${workspaceRoot}", "cwd": "${workspaceRoot}",
"name": "PlatformIO Debugger", "name": "PlatformIO Debugger",
"target": "c:/Users/itsmy_000/Desktop/VSCode Workplace/node_mcu_001/.pioenvs/nodemcuv2/firmware.elf", "target": "c:/Users/itsmy/Desktop/VSCodeWorkspace/nodemcu-lab-work-1/.pioenvs/nodemcuv2/firmware.elf",
"gdbpath": "C:/Users/itsmy_000/.platformio/penv/Scripts/piodebuggdb", "gdbpath": "C:/Users/itsmy/.platformio/penv/Scripts/piodebuggdb",
"autorun": [ "source .pioinit" ] "autorun": [ "source .pioinit" ]
} }
] ]

26
html/acc.html

@ -37,20 +37,36 @@
</canvas> </canvas>
<script> <script>
var socket = new WebSocket("ws://192.168.4.1:81");
var data;
var c = document.getElementById("myCanvas"); var c = document.getElementById("myCanvas");
var context = c.getContext("2d"); var context = c.getContext("2d");
var randomNumbers, randNumsLength;
socket.onopen = function () {
alert("Соединение установлено.");
};
socket.onclose = function (event) {
if (!event.wasClean) {
alert('Обрыв соединения');
}
};
socket.onmessage = function (event) {
context.clearRect(0, 0, c.width, c.height);
data = event.data;
context.moveTo(0, 0); context.moveTo(0, 0);
for (i = 0; i != 400; i+=4) { for (i = 0; i != 400; i += 2) {
context.lineTo(i, Math.random() * 100 + 50); context.lineTo(i, data.root[i]);
} }
context.stroke(); context.stroke();
};
context.font = "50px Arial"; context.font = "50px Arial";
context.fillText("24",320,170); context.fillText("24", 320, 170);
</script> </script>
<div id="navs"> <div id="navs">
<button onclick="window.location.href='/hbs.html'"class="button">Оптодатчик</button> <button onclick="window.location.href='/hbs.html'" class="button">Оптодатчик</button>
</div> </div>
<div class="clear"></div> <div class="clear"></div>

30
src/html.h

@ -41,7 +41,6 @@ const char style[] PROGMEM = {
}\n\ }\n\
</style>\n\ </style>\n\
<meta charset=\"UTF-8\">\n\ <meta charset=\"UTF-8\">\n\
<meta http-equiv=\"refresh\" content=\"1\">\n\
</head>\n\ </head>\n\
<body>\n\ <body>\n\
\n\ \n\
@ -57,14 +56,33 @@ const char style[] PROGMEM = {
const char script_begin[] PROGMEM = { const char script_begin[] PROGMEM = {
"<script>\n\ "<script>\n\
var socket = new WebSocket(\"ws://192.168.4.1:81\");\n\
var i, data;\n\
var c = document.getElementById(\"myCanvas\");\n\ var c = document.getElementById(\"myCanvas\");\n\
var context = c.getContext(\"2d\");\n\ var context = c.getContext(\"2d\");\n\
var randomNumbers, randNumsLength;\n\ \n\
context.moveTo(0, 200);\n"}; socket.onopen = function () {\n\
alert('Соединение установлено.');\n\
};\n\
socket.onclose = function (event) {\n\
if (!event.wasClean) {\n\
alert('Обрыв соединения'); \n\
}\n\
};\n\
socket.onmessage = function (event) {\n\
context.clearRect(0, 0, 400, 200);\n\
context.beginPath();\n\
data = JSON.parse(event.data);\n\
context.moveTo(0, data.data[0]);\n\
for (i = 0; i < 200; i++) {\n\
context.lineTo(i*2, data.data[i]);\n\
}\n\
context.stroke();\n\
};\n\
</script>\n\
"};
const char script_end[] PROGMEM = { const char script_end[] PROGMEM = {""};
"context.stroke();\n\
</script>\n"};
const char html_end[] PROGMEM = { const char html_end[] PROGMEM = {
"<div class=\"clear\"></div>\n\ "<div class=\"clear\"></div>\n\

91
src/main.cpp

@ -1,34 +1,38 @@
#include <Arduino.h> #include <Arduino.h>
#include <ESP8266WiFi.h> #include <ESP8266WiFi.h>
#include <WiFiClient.h> //#include <WiFiClient.h>
#include <ESP8266WebServer.h> #include <ESP8266WebServer.h>
#include <ESP8266mDNS.h> //#include <ESP8266mDNS.h>
#include <html.h> #include <html.h>
#include <Graph.h> #include <Graph.h>
#include <Sensor.h> #include <Sensor.h>
#include <WebSocketsServer.h>
#include <ArduinoJson.h>
const char *ssid = "NodeMCU"; const char *ssid = "NodeMCU";
ESP8266WebServer server(80); ESP8266WebServer server(80);
Sensor accelerometer = Sensor(); Sensor accelerometer = Sensor();
Graph graphAcc = Graph(200, 50); Graph graphAcc = Graph(200, 50);
int lastDataSend = 0;
WebSocketsServer webSocket = WebSocketsServer(81);
void handleAccelerometer() void handleAccelerometer()
{ {
int16_t bias = 0; int16_t bias = 0;
const int arr_size = 10000; const int arr_size = 10000;
char *html_code = new char[arr_size]; char *html_code = new char[arr_size];
memset(html_code, '\0', sizeof(char)*arr_size); memset(html_code, '\0', sizeof(char) * arr_size);
bias += getHtml(HTML_BEGIN, *html_code, arr_size, 0); bias += getHtml(HTML_BEGIN, *html_code, arr_size, 0);
bias += getHtml(STYLE, *html_code, arr_size, bias); bias += getHtml(STYLE, *html_code, arr_size, bias);
bias += getHtml(SCRIPT_BEGIN, *html_code, arr_size, bias); bias += getHtml(SCRIPT_BEGIN, *html_code, arr_size, bias);
for (int i = 0; i != graphAcc.graphSize - 1; i++) { // for (int i = 0; i != graphAcc.graphSize - 1; i++)
bias += snprintf((html_code+bias), arr_size - bias, "context.lineTo(%i*2, %i);\n", i, graphAcc.graphArray[i]); // {
} // bias += snprintf((html_code + bias), arr_size - bias, "context.lineTo(%i*2, %i);\n", i, graphAcc.graphArray[i]);
// }
bias += getHtml(SCRIPT_END, *html_code, arr_size, bias); bias += getHtml(SCRIPT_END, *html_code, arr_size, bias);
//bias += snprintf((html_code+bias), arr_size - bias, "<br />Current accelerometer: %i", acc); //bias += snprintf((html_code+bias), arr_size - bias, "<br />Current accelerometer: %i", acc);
bias += getHtml(HTML_END, *html_code, arr_size, bias); bias += getHtml(HTML_END, *html_code, arr_size, bias);
@ -38,20 +42,38 @@ void handleAccelerometer()
delete[] html_code; delete[] html_code;
} }
void cookAccelerometer(String &in, int *in_array, int array_size) {
String *output = &in;
int *array = in_array;
DynamicJsonBuffer jsonBuffer;
JsonObject& root = jsonBuffer.createObject();
JsonArray& data = root.createNestedArray("data");
for (int i = 0; i != array_size; i++) {
data.add(*(array + i));
}
root.printTo(*output);
}
void updateAccelerometer() void updateAccelerometer()
{ {
if ((millis() - accelerometer.lastUpdate) > (1000 / graphAcc.graphUpdateRate)) if ((millis() - accelerometer.lastUpdate) > (1000 / graphAcc.graphUpdateRate))
{ {
accelerometer.lastValue = map(analogRead(A0), 512, 768, 200, 0); accelerometer.lastValue = map(analogRead(A0), 512, 768, 200, 0);
if (graphAcc.graphCounter < graphAcc.graphSize - 1) { if (graphAcc.graphCounter < graphAcc.graphSize - 1)
{
graphAcc.graphArray[graphAcc.graphCounter] = accelerometer.lastValue; graphAcc.graphArray[graphAcc.graphCounter] = accelerometer.lastValue;
graphAcc.graphCounter++; graphAcc.graphCounter++;
} else { }
for(int i = 0; i != graphAcc.graphCounter; i++) { else
{
for (int i = 0; i != graphAcc.graphCounter; i++)
{
graphAcc.graphArray[i] = graphAcc.graphArray[i + 1]; graphAcc.graphArray[i] = graphAcc.graphArray[i + 1];
} }
graphAcc.graphArray[graphAcc.graphCounter] = accelerometer.lastValue; graphAcc.graphArray[graphAcc.graphCounter] = accelerometer.lastValue;
} }
accelerometer.lastUpdate = millis(); accelerometer.lastUpdate = millis();
} }
} }
@ -73,10 +95,41 @@ void handleNotFound()
server.send(404, "text/plain", message); server.send(404, "text/plain", message);
} }
void sendAccelerometerData() {
if (millis() - lastDataSend > 100) {
String word;
cookAccelerometer(word, graphAcc.graphArray, graphAcc.graphSize);
webSocket.broadcastTXT(word);
lastDataSend = millis();
}
}
//** WEBSOCKET TEST **//
void webSocketEvent(uint8_t num, WStype_t type, uint8_t *payload, size_t length)
{
switch (type)
{
case WStype_DISCONNECTED:
Serial.printf("[%u] Disconnected!\n", num);
break;
case WStype_CONNECTED:
{
IPAddress ip = webSocket.remoteIP(num);
Serial.println("Client connected!");
Serial.printf("[%u] Connected from %d.%d.%d.%d url: %s\n", num, ip[0], ip[1], ip[2], ip[3], payload);
}
break;
}
}
//** WEBSOCKET TEST END**//
void setup(void) void setup(void)
{ {
pinMode(A0, INPUT);
Serial.begin(115200); Serial.begin(115200);
Serial.setDebugOutput(true);
Serial.println();
pinMode(A0, INPUT);
WiFi.softAP(ssid); WiFi.softAP(ssid);
IPAddress myIP = WiFi.softAPIP(); IPAddress myIP = WiFi.softAPIP();
@ -85,16 +138,24 @@ void setup(void)
server.on("/accelerometer", handleAccelerometer); server.on("/accelerometer", handleAccelerometer);
server.on("/", []() { server.on("/", []() {
server.send(200, "text/plain", "http://192.168.4.1/accelerometer"); server.send(200, "text/html", "<a href=\"http://192.168.4.1/accelerometer\">Main Page</a>");
}); });
server.onNotFound(handleNotFound); server.onNotFound(handleNotFound);
server.begin(); server.begin();
Serial.println("HTTP server started"); Serial.println("HTTP server started");
//** WEBSOCKET TEST **//
webSocket.begin();
webSocket.onEvent(webSocketEvent);
//** WEBSOCKET TEST END**//
} }
void loop(void) void loop(void)
{ {
updateAccelerometer();
server.handleClient(); server.handleClient();
webSocket.loop();
updateAccelerometer();
sendAccelerometerData();
} }
Loading…
Cancel
Save