Browse Source

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

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

1
.gitignore

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

4
.vscode/launch.json

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

32
html/acc.html

@ -37,20 +37,36 @@
</canvas>
<script>
var socket = new WebSocket("ws://192.168.4.1:81");
var data;
var c = document.getElementById("myCanvas");
var context = c.getContext("2d");
var randomNumbers, randNumsLength;
context.moveTo(0, 0);
for (i = 0; i != 400; i+=4) {
context.lineTo(i, Math.random() * 100 + 50);
}
context.stroke();
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);
for (i = 0; i != 400; i += 2) {
context.lineTo(i, data.root[i]);
}
context.stroke();
};
context.font = "50px Arial";
context.fillText("24",320,170);
context.fillText("24", 320, 170);
</script>
<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 class="clear"></div>

30
src/html.h

@ -41,7 +41,6 @@ const char style[] PROGMEM = {
}\n\
</style>\n\
<meta charset=\"UTF-8\">\n\
<meta http-equiv=\"refresh\" content=\"1\">\n\
</head>\n\
<body>\n\
\n\
@ -57,14 +56,33 @@ const char style[] PROGMEM = {
const char script_begin[] PROGMEM = {
"<script>\n\
var socket = new WebSocket(\"ws://192.168.4.1:81\");\n\
var i, data;\n\
var c = document.getElementById(\"myCanvas\");\n\
var context = c.getContext(\"2d\");\n\
var randomNumbers, randNumsLength;\n\
context.moveTo(0, 200);\n"};
\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 = {
"context.stroke();\n\
</script>\n"};
const char script_end[] PROGMEM = {""};
const char html_end[] PROGMEM = {
"<div class=\"clear\"></div>\n\

97
src/main.cpp

@ -1,34 +1,38 @@
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
//#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
//#include <ESP8266mDNS.h>
#include <html.h>
#include <Graph.h>
#include <Sensor.h>
#include <WebSocketsServer.h>
#include <ArduinoJson.h>
const char *ssid = "NodeMCU";
ESP8266WebServer server(80);
Sensor accelerometer = Sensor();
Graph graphAcc = Graph(200, 50);
int lastDataSend = 0;
WebSocketsServer webSocket = WebSocketsServer(81);
void handleAccelerometer()
{
int16_t bias = 0;
const int arr_size = 10000;
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(STYLE, *html_code, arr_size, bias);
bias += getHtml(SCRIPT_BEGIN, *html_code, arr_size, bias);
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]);
}
// 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 += getHtml(SCRIPT_END, *html_code, arr_size, bias);
//bias += snprintf((html_code+bias), arr_size - bias, "<br />Current accelerometer: %i", acc);
bias += getHtml(HTML_END, *html_code, arr_size, bias);
@ -38,20 +42,38 @@ void handleAccelerometer()
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()
{
if ((millis() - accelerometer.lastUpdate) > (1000 / graphAcc.graphUpdateRate))
{
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.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[graphAcc.graphCounter] = accelerometer.lastValue;
}
accelerometer.lastUpdate = millis();
}
}
@ -73,28 +95,67 @@ void handleNotFound()
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)
{
pinMode(A0, INPUT);
Serial.begin(115200);
Serial.setDebugOutput(true);
Serial.println();
pinMode(A0, INPUT);
WiFi.softAP(ssid);
IPAddress myIP = WiFi.softAPIP();
Serial.print("AP IP address: ");
Serial.println(myIP);
IPAddress myIP = WiFi.softAPIP();
Serial.print("AP IP address: ");
Serial.println(myIP);
server.on("/accelerometer", handleAccelerometer);
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.begin();
Serial.println("HTTP server started");
//** WEBSOCKET TEST **//
webSocket.begin();
webSocket.onEvent(webSocketEvent);
//** WEBSOCKET TEST END**//
}
void loop(void)
{
updateAccelerometer();
server.handleClient();
webSocket.loop();
updateAccelerometer();
sendAccelerometerData();
}
Loading…
Cancel
Save