当前位置:网站首页>Real time lighting of websocket server based on esp32cam
Real time lighting of websocket server based on esp32cam
2022-06-13 07:05:00 【daodanjishui】
ESP32-CAM ArduinoIDE Development series article catalog
Chapter one :ESP32-CAM High cost performance WIFI Quick start tutorial of image transmission scheme
Second articles :ESP32-CAM The first wireless lighting program
Third articles :ESP32-CAM Design and implementation of intelligent gateway
Fourth articles :ESP32-CAM Create a hot spot composition and style DNS The server
Chapter five :ESP32-CAM High cost performance temperature and humidity monitoring system
Chapter 6 : be based on ESP32CAM Realization WebSocket The server lights up in real time
List of articles
Preface
daodanjishui The core original technology of the Internet of things ESP32 Arduino IDE The developed Internet of things system design is up-to-date Websocket Technology exploration .
One 、 be based on ESP32CAM Realization WebSocket What is the real-time lighting of the server ?
daodanjishui The project in the previous article :ESP32-CAM The cost-effective temperature and humidity monitoring system introduces in detail the use of ESP32 The embedded webserver Server development technology , The network communication protocol used is Tcp/Ip,http agreement , But I didn't use WebSocket technology , Therefore, long-time communication between web pages and server hardware cannot be realized , This is also the deficiency of the previous article , Internet of things system design about web The design of requires a long link between the web page and the hardware , So this WebSocket Technology needs to be explored .
daodanjishui In the project of this article , Adopt new technology , Use the most popular WebSocket Front end technology in ESP32CAM Build a Websocket The server responds to the request of the browser client in real time , Realize real-time lighting , This time the client doesn't have to send get perhaps post The request responds , I will use this later WebSocket Do some image processing and MQTT Remotely controlled “ Frightening ” The core of high technology . The hardware effect is shown in the figure below :
The running effect of the program is as follows :
The video demonstration effect is as follows :
ESP32-CAM Implementation of embedded WebSocket Server lighting
The video website is as follows :https://www.bilibili.com/video/BV1BU4y1d7iZ?t=0.0
Link jump
Two 、 Software development process
1. understand WebSocket technology
Websocket Technology is introduced : Now there are ways of communication between web pages and single chip computers 2 Kind of : One is tcp/ip Under the agreement post and get request , One is Websocket communication mode . The former is reflected in many circuit schemes I have released , But the latter is the first time , Later, I will combine the two to build an IOT monitoring system . To sum up the functions of the latter : Let the web page link with the server for a long time without refreshing the web page , Therefore, the status of the switch lights and the messages returned by the server can be printed in real time on the web page . Run on the single chip computer Websocket What's the use ? First, it can be online OTA Firmware upgrade , Second, it can realize the real-time interaction between web pages and MCU , No need to use get Requests can also submit forms . Play a good effect of real-time feedback in the Internet of things . I will do some special projects later , Include :Websocket Biography 、Websocket Smart car 、Websocket Web intelligent distribution network 、Websocket Internet of things monitoring system, etc .
This time the code is not complicated , There is a hot spot in the program , Mobile phones and laptops enter... In the browser 192.168.4.1 You can access websocket The home page of , This home page is written in the MCU . Can be easily changed .
2. Edit code
The screenshot of the source code is as follows :
#include <WiFi.h>
#include <ESPAsyncWebServer.h> // Import the corresponding library
AsyncWebServer server(80); // Statement WebServer object
AsyncWebSocket ws("/"); // WebSocket object ,url by /
#define LAMP_PIN 4 // Define the pin of the flash ,ESP32CAM Own flash
// The following is a web page file
String indexhtml = String("") +
"<!DOCTYPE html>\n" +
"<head>\n" +
" <meta charset=\"UTF-8\">\n" +
" <title>WebSocket Test</title>\n" +
" <script>\n" +
" var ws;\n" +
" if (\"WebSocket\" in window) {\n" +
" ws = new WebSocket(\"ws://\" + window.location.host + \"/\"); // establish WebSocket Connect \n" +
" ws.onopen = function () { // Triggered when the connection is successfully established \n" +
" document.getElementById(\"info\").innerHTML += \"WebSocket Successful connection !\" + \"<br>\";\n" +
" ws.send(\"connect ok!\"); // Send data to the server \n" +
" };\n" +
" ws.onmessage = function (evt) { // Triggered when server data is received \n" +
" document.getElementById(\"info\").innerHTML += evt.data + \"<br>\";\n" +
" };\n" +
" ws.onerror = function () { // Trigger when an error occurs \n" +
" document.getElementById(\"info\").innerHTML += \" Communication sending error !\" + \"<br>\";\n" +
" };\n" +
" ws.onclose = function () { // Triggered when the connection is closed \n" +
" document.getElementById(\"info\").innerHTML += \"WebSocketTest Connection closed !\" + \"<br>\";\n" +
" };\n" +
" }\n" +
" else {\n" +
" document.getElementById(\"info\").innerHTML = \" Browser does not support WebSocket!\";\n" +
" }\n" +
" function send() {\n" +
" ws.send(\"ON\"); // Send data to the server \n" +
" }\n" +
" function send1() {\n" +
" ws.send(\"OFF\"); // Send data to the server \n" +
" }\n" +
" </script>\n" +
"</head>\n" +
"<body>\n" +
" <h1>daodanjishui ESP32-CAM Free and open source WebSocket Server lighting program , Original classics are worth having </h1><p>"+
" <h2> explain : Click the key - turn on the light , Turn on the light , conversely - Turn off the lights , Turn off the lights , The web page will display debugging information in real time </h2>"+
" <button type=\"button\" οnclick=\"send()\"> turn on the light </button>\n" +
" <button type=\"button\" οnclick=\"send1()\"> Turn off the lights </button>\n" +
" <h3> Real time debugging information :</h3>\n" +
" <h3><div id=\"info\"></div></h3>\n" +
"</body>\n" +
"</html>\n";
void wifi_init();// establish AP Hotspots connect wireless devices , initialization websocket
void lamp_init();// Flash initialization
void controlLamp(bool lampVal);// Lighting function , The transmission parameters are bool type
void wifi_init(){
WiFi.softAP("daodanjishui_websocket_AP");
WiFi.mode(WIFI_AP);// Set mode to AP, Can be used in the browser 192.168.4.1 logon server
IPAddress myIP = WiFi.softAPIP();
Serial.print("AP IP address: ");
Serial.println(myIP);
ws.onEvent(onEventHandle); // Bind callback function
server.addHandler(&ws); // take WebSocket Add to the server
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
// Register link "/" And the corresponding callback function ( Anonymous function formal declaration )
request->send(200, "text/html", indexhtml); // Send the response and content to the client
});
server.begin(); // start-up websocket The server
Serial.println("Web server started");
}
void lamp_init(){
pinMode(LAMP_PIN, OUTPUT);// Set as output
digitalWrite(LAMP_PIN, false);// Output low level
}
void controlLamp(bool lampVal) {
// Lighting function
digitalWrite(LAMP_PIN, lampVal);// control IO port
Serial.printf("Turn lamp %s\n", lampVal ? "On" : "Off");
}
// WebSocket Event callback function
void onEventHandle(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type, void *arg, uint8_t *data, size_t len)
{
if (type == WS_EVT_CONNECT) // A client establishes a connection
{
Serial.printf("ws[%s][%u] connect\n", server->url(), client->id());
client->printf("Hello Client %u !", client->id()); // Send data to client
client->ping(); // Send to the client ping
}
else if (type == WS_EVT_DISCONNECT) // A client is disconnected
{
Serial.printf("ws[%s][%u] disconnect: %u\n", server->url(), client->id());
}
else if (type == WS_EVT_ERROR) // An error occurred
{
Serial.printf("ws[%s][%u] error(%u): %s\n", server->url(), client->id(), *((uint16_t *)arg), (char *)data);
}
else if (type == WS_EVT_PONG) // Received a message from the client to the server ping Respond (pong news )
{
Serial.printf("ws[%s][%u] pong[%u]: %s\n", server->url(), client->id(), len, (len) ? (char *)data : "");
}
else if (type == WS_EVT_DATA) // Received data from client
{
AwsFrameInfo *info = (AwsFrameInfo *)arg;
Serial.printf("ws[%s][%u] frame[%u] %s[%llu - %llu]: ", server->url(), client->id(), info->num, (info->message_opcode == WS_TEXT) ? "text" : "binary", info->index, info->index + len);
data[len] = 0;
Serial.printf("%s\n", (char *)data);
// Write the receiving and responding functions here
String datacome=(char *)data;
if(datacome.indexOf("ON")>=0){
controlLamp(true);
ws.textAll("Lamp is ON");
}else if(datacome.indexOf("OFF")>=0){
controlLamp(false);
ws.textAll("Lamp is OFF");
}else controlLamp(false);
}
}
void setup()
{
Serial.begin(115200);
Serial.println();
lamp_init();// Flash initialization
wifi_init();//AP Initialization and Websocket initialization
}
void loop()
{
delay(10000);// Send a string of data to the client every ten seconds
ws.textAll("information come from server!"); // Send data to all connected clients
ws.cleanupClients(); // Close too many WebSocket Connect to save resources
}
3. matters needing attention
Readers need to go to the download link at the end of the blog to download a library ESPAsyncWebServer-master, So the code in front of #include <ESPAsyncWebServer.h> // Import the corresponding library No mistake .
summary
daodanjishui This issue has a new attempt compared with the previous one , Used WebSocket Technology to try IOT system design , Although the whole system has not been set up , But this attempt is a good start . Readers can refer to my code , My scheme can push information from web pages to MCU , SCM can also push information to all web pages , It's quite powerful , Of course, my classic lighting program . The following is the serial port Print debug output :
There is nothing to say later , Welcome to download the test , Readers can use this program to write a web remote control , Or what web games are no problem , But if you want to write a web distribution program , I guess you still have to refer to my procedures , Because I wrote websocket The web distribution program is really silky , Most people really can't write it .
Later I will launch java Version and JavaWeb Version of Websocket The server and ESP32 Client pass Websocket Mutual communication , Including image transmission technology ,MQTT technology , Image processing technology ,3D VR Smart glasses and so on , Constitute the Internet of things monitoring system , National exclusive original , Worth waiting for .
Code transfer address :https://www.cirmall.com/circuit/29794/
Click jump to download
边栏推荐
- Tidb dashboard modify port
- 线程池中的 工作线程如何被回收
- 杭州网上开户是安全的吗?
- Xiaomi's one-sided interview questions (self sorting answers)
- NFV基本概述
- An article allows you to quickly understand the fission growth password of social e-commerce user marketing and avoid stepping on the pit
- 10 Honest Facts I Want To Share With All Junior Developers
- 树莓派高级开发——“IO口驱动代码的编写“ 包含总线地址、物理_虚拟地址、BCM2835芯片手册知识
- 尝试使用RenderDoc查看UE的Shader代码
- 杭州证券开户是安全的吗?
猜你喜欢

Chain 2+1 reward, what kind of mode is beautiful everyday seconds?

SDN basic overview

Recently, the popular social e-commerce marketing model, blind box e-commerce, how beautiful every second is accurately drained

Host computer development (Architecture Design of firmware download software)

上位机开发(固件下载软件之架构设计)

玄武云科技通过上市聆讯:业绩波动明显,陈永辉等三人为控股股东

Normalizing y-axis in histograms in R ggplot to proportion

Comment utiliser le logiciel wangyou DFM pour l'analyse des plaques froides

Ticdc introduction

Differences between SQL and NoSQL of mongodb series
随机推荐
【腾讯阿里最全面试题集锦】(四面:3轮技术+1轮HR)
RT thread simulator lvgl control: switch switch button control
号称下一代监控系统 来看看它有多牛逼
Detailed description of drawing ridge plot, overlapping densities of overlapping kernel density estimation curve, facetgrid object and function sns Kdeplot, function facetgrid map
First day of learning MySQL Basics
Tidb data migration (DM) Introduction
Tidb implementation plan -- III
Br tool backup recovery
Through the function seaborn cubehelix_ Palette build order palette
MySQL系列之分库分表学习笔记
Eureka server multi node deployment
Computer network interview questions
That is, after the negative impact of gcat advertising e-commerce, is there no stable advertising e-commerce platform?
Local file upload FTP or remote directory
Intelligent entertainment has developed steadily, and jinglianwen technology provides data collection and labeling services
Is it safe for Hangzhou Securities to open an account?
ML之FE:Vintage曲线/Vintage分析的简介、计算逻辑、案例应用之详细攻略
同花顺可以开股票账户吗?安全吗?
Br backup test
The new retail market has set off blind box e-commerce. Can the new blind box marketing model bring dividends to businesses?