How to Make an Arduino WebSocket Server with an ESP32
HTML-код
- Опубликовано: 28 авг 2024
- The WebSocket protocol is a useful tool for communicating between servers and clients without the need for HTTP. Here, I show how to create an Arduino WebSocket server on an ESP32 that echoes simple text messages back to connected clients. I test the server with a basic Python script.
Arduino and Python code from the video can be found here: shawnhymel.com/...
Instead of going the Python route, I decided to download a Chrome plugin called "Simple WebSocket Client." It was way easier for me to test- especially since I know absolutely nada about Python. Just thought I'd throw that out there. Thanks for the video!!!
I really like your presentation style. Precise, easy to follow and high quality production. A shame that the channel is a bit underrated.
Glad you like them, thanks! I've only got two videos up, so I'll work on adding more :)
@@ShawnHymel please do more videos ♥️
I just got an ESP32-C3-mini-1 and I had already set up the boards and device to ESP32-C3. Following your presentation, the code worked fine on it. On to the second part! :) Thank you
Hi Shawn I didn't realise that this channel is in my subscription list...anyway welcome back...👍
Thanks :) It's been around 2 years since I posted to this channel. I'm hoping that it'll be a little more often from now on.
Very nice explanation. well structured and just the right balance between information but not to much basic stuff. thx!
Another great video, I was getting used to that devo-esque Digi-Key intro though
Thanks! I love that intro, but sadly, I did not make it. Maybe I'll see about getting Digi-Key to let me "borrow" it :)
Where have you been, Sir? Long time no see. Anyway, great Tutorial as always~
I was either writing tutorials for SparkFun or making some videos for DigiKey. It's good to be back, though 😁
Wow. Such a great channel Ive never known about. Thanks for the tutorial. Learned a lot from this.
This is so cool! I assume we could also have a websocket client on the ESP32 (instead of server)? Ideally I would have a standalone ubuntu server handling multiple esp32 clients on my local network
What would be the easiest solution to make wireless communication between a pc and an esp32 with no passwords etc.
Depends on the protocol you want to use. Bluetooth for short range and low energy, WiFi for room/house-wide access and fast transfer speeds, LoRa for low-speed and long range. The easiest is probably a point-to-point 900 MHz comm link using something like an RFM69 (www.adafruit.com/product/3070). Attach one to the Arduino and make a USB dongle out of the other that communicates through Serial.
@@ShawnHymel Thx. What I'm really wanting to do is have 4-6 ESP32 Cameras send frame buffers to a NWJS desktop app for processing. Could I do 6 websocket servers and have the PC app request a frame from each? It doesn't need to display all 6 frames i just need the pixel data.
Thank you so much for sharing~
It always a heartwarming things to get new knowledge...
#salute
You're welcome! I'm glad you enjoyed it :)
very, very clear tutorial
thanks so much
Glad it helped!
Great tutorial, looking forward to more!
Thanks! I'll try to add more videos in the future between other work :)
Nice tutorial. thanks!
Great tutorial. 我喜欢~
I have esp32 where and how to connect it, do we have to connect it to arduino board?
Excellent Tutorial. How many clients do you think an ESP32 can handle?
Hmm...that's a good question. Some people think it's around 10: arduino.stackexchange.com/questions/55693/how-many-clients-can-connect-to-an-esp32
Hello Shawn,
do you also have experience with the WebSocketsClient lib? When I use the example for ESP8266 as a client, when ESP32 is the server as you described, the client will connect to the AP-Wifi of the server, but the websocket connection becomes disconnected several times. Tested the same server connection with my python script and had no issues.
How we can send adc values from nodeMCU to python?
Can we simply write more code just below
Also how I can upload binary file from python to nodemcu so that nodemcu can reboot with new version
How do I send a websocket server data (sensor's data), I don't want it to be on browser instead on python console of a ide. can this be used for realtime stuffs ?
What is the name of the program "Capturing from Wi-fi"?
How can I do this but with a ESP32-CAM?
Hey Shawn, when i run the python code i keep getting win10060 error. what can i do to resolve it?
excellent tut, how would you do this with an sparkfun esp32 thing. no difference?
Excellent!!!
Great Tutorial .. How about making the ESP32 act as a (WebSocket Secure) WSS server ? I couldn't find any libraries supporting this.
You'd need to generate an SSL certificate and get it onto the ESP32. I haven't tried it yet. This repo might be a good place to start: github.com/fhessel/esp32_https_server
hi, can you please guide a little on how to apply the same concept but while connected with different network(my system and esp32 are not connected with same network).
Let's say esp32 is at home and I want to send any command from my office PC.
thanks
Look up "port forwarding." It allows you to forward traffic on one external port of your router to a specific IP address inside that network.
How to get payload int data?
Thank You
hi how can i implement a web page on my websocket server?
Thank you Shawn for the video! How can I convert the payload which is in uint8_t into integer? (I want to control a servo.) I don't understand that data type at all and fail to find any understandable information online. Thank you for help!
uint8_t just means "unsigned 8-bit integer" (so, something between 0 and 255). It works similar to "unsigned char." If you need it as an int, you should just be able to cast it with (int)var without any loss of precision.
Nice ...
Hi, I tried your ESP32 server example with a browser but could not make it work. Can you offer an example with ws used by browser to connect to the ESP32 please?
That is correct--the ESP32 is not serving a web page, so trying to connect to it with a browser will not work. I've created an example of how to host an HTML page (with WS) here: gist.github.com/ShawnHymel/3d124f79aee95fb274876f491a91dcf4 I have not had a chance to create a write-up or video for it, though.
Hi, do you have information about how can use the websocket, with android studio, because I want read in real time, a sensor, and what see this information on my app, but I don´t use a cloud server only the esp8266 and android studio.
Thanks for your videos, I see from Guatemala!
I'm really not versed at all in phone dev, so I won't be able to help much. A quick search yielded this tutorial that might be useful: www.pubnub.com/blog/java-websocket-programming-with-android-and-spring-boot/
Hi Shawn, very good tutorial, thank you very much. Could you also please do an video, how to implement Websockets in an Android App, to connect and communicate with the ESP8266 please? :)
Thank you! I'm glad you liked it! I really don't know app programming at all, so I won't be able to help much there. The only quick thing I can think of would be to put something together with a cross-platform app creator (like Cordova) and use a websocket library.
Hi Shawn, ok, no problem. I am learning Android Studio and a little bit of Java right now. Let's see, how far will I come :)
Hello Awesome video! I have both scripts up and running. Im wondering if there is a way to convert the String" " data send from the python script in arduino to an integer. I am trying to send pwm values to drive a motor.
You should be able to cast or convert the values with a function like atoi()
Hi,
Do I need a router?
Is there a way to config DHCP server on the ESP32 itself?
No need for a router, in the video the router is just here to fake an empty network. I guess it makes it easier to see the wireshark packets.
Just in case someone has problems with the connection like me:
import websocket
# Connect to WebSocket server
ws = websocket.WebSocket(sslopt={"check_hostname": False})
ws.connect("ws://192.168.1.250")
print("Connected to WebSocket server")
# Ask the user for some input and transmit it
str = input("Say something: ")
ws.send(str)
# Wait for server to respond and print it
result = ws.recv()
print("Received: " + result)
# Gracefully close WebSocket connection
ws.close()
That code worked for me
PS: Great video it helped me alot!!
So can I send data from python to the esp32 cam to let's say.. Move a servo?
Yes. You just need to interpret the WebSocket commands sent from Python.
How do we disable the 'Nagle' algorithm so our packets are ' actually fast' and not bundled up and delayed by evil mr Nagle.
Result is quite raw ... and outdated too. Bad idea to use static IP. It is hard to maintain. SPIFFS is assumed to be dead a few years ago already.
Hello sir, at the moment I'm working on ESP32 to control relay module via the Internet. I can connect my ESP32 board to WiFi and control the relays using web browser. However, instead of using WiFi, I want to use the Ethernet cable for connection. I've searched a lot on the Internet but found nothing useful. Could you please give me some advice on how to implement ethernet connection. (I'm using board SOM-ESP32-1 which has LAN8720, EMAC RMII interface). Thanks for your help.
I don't have any experience using Ethernet on the ESP-32. The Ethernet examples on the ESP-32 GitHub page might be a good place to start: github.com/espressif/esp-iot-solution/tree/master/examples/eth2wifi
@@ShawnHymel Thanks for your help. Using ethernet on esp32 is quite complicated to me but I'll try my best
when approaching the esp32 via python on pc, it works, but when I use android and a DNS routing, the app says connected, but the arduinoESP32 does not answer, nor say it is connected. Any clou ?
I don't have much Android dev experience, so I couldn't really say. Sorry!
@@ShawnHymel Hi, thanks anyway. I am now trying Inetaddress to use the name....
Sir how to send .wav file using esp32
You should be able to upload it using the SPIFFS tool in Arduino and then it should be accessible on the server.
Shawn, Thanks for the tutorial! I am now working on a project (based on your tutorial) where I am streaming a lux value from TSL2591 to any client who connected to a server without any request. Is there a way to continuously call the event function inside the server so that I can stream lux data to the client? Here is my code below. Obviously not streaming. It's only sending the data when there is an event. How can I stream the data as I want if it's possible? I am very new to Arduino and Websockets. Is that called Async? Please let me know!
#include
#include
#include
#include
#include "Adafruit_TSL2591.h"
// Constants
const char* ssid = "jihosooran";
const char* password = "jihosooran0725";
// Globals
WebSocketsServer webSocket = WebSocketsServer(80);
//TSL2591
Adafruit_TSL2591 tsl = Adafruit_TSL2591(2591); // pass in a number for the sensor identifier (for your use later)
// Called when receiving any WebSocket message
void onWebSocketEvent(uint8_t num,
WStype_t type,
uint8_t * payload,
size_t length) {
uint32_t lum = tsl.getFullLuminosity();
uint16_t ir, full;
ir = lum >> 16;
full = lum & 0xFFFF;
String luxVal = String(tsl.calculateLux(full, ir));
webSocket.sendTXT(num, luxVal);
// Figure out the type of WebSocket event
switch(type) {
// Client has disconnected
case WStype_DISCONNECTED:
Serial.printf("[%u] Disconnected!
", num);
break;
// New client has connected
case WStype_CONNECTED:
{
IPAddress ip = webSocket.remoteIP(num);
Serial.printf("[%u] Connection from ", num);
Serial.println(ip.toString());
}
break;
// Echo text message back to client
case WStype_TEXT:
Serial.printf("[%u] Text: %s
", num, payload);
webSocket.sendTXT(num, payload);
break;
// For everything else: do nothing
case WStype_BIN:
case WStype_ERROR:
case WStype_FRAGMENT_TEXT_START:
case WStype_FRAGMENT_BIN_START:
case WStype_FRAGMENT:
case WStype_FRAGMENT_FIN:
default:
break;
}
}
void setup(void)
{
// Start Serial Port
Serial.begin(115200);
// Connect to access point
Serial.println("Connecting");
WiFi.begin(ssid, password);
while ( WiFi.status() != WL_CONNECTED ) {
delay(500);
Serial.print(".");
}
// Print our IP address
Serial.println("Connected!");
Serial.print("My IP address: ");
Serial.println(WiFi.localIP());
// Start WebSocket server and assign callback
webSocket.begin();
webSocket.onEvent(onWebSocketEvent);
displaySensorDetails();
configureSensor();
}
void loop(void)
{
// Look for and handle WebSocket data
webSocket.loop();
delay(200);
}
void displaySensorDetails(void)
{
sensor_t sensor;
tsl.getSensor(&sensor);
delay(500);
}
void configureSensor(void)
{
tsl.setGain(TSL2591_GAIN_MED);
tsl.setTiming(TSL2591_INTEGRATIONTIME_200MS);
}
void advancedRead(void)
{
// More advanced data read example. Read 32 bits with top 16 bits IR, bottom 16 bits full spectrum
// That way you can do whatever math and comparisons you want!
uint32_t lum = tsl.getFullLuminosity();
uint16_t ir, full;
ir = lum >> 16;
full = lum & 0xFFFF;
Serial.println(tsl.calculateLux(full, ir), 2);
}
void unifiedSensorAPIRead(void)
{
/* Get a new sensor event */
sensors_event_t event;
tsl.getEvent(&event);
/* Display the results (light is measured in lux) */
Serial.print(F("[ ")); Serial.print(event.timestamp); Serial.print(F(" ms ] "));
if ((event.light == 0) |
(event.light > 4294966000.0) |
(event.light
I have not tried pushing data to the clients yet, so I don't know if this is the "right" way to do things. In your loop() function, check to see if lux has changed by some significant amount. If so, call webSocket.sendTXT() to all your connected clients.
@@ShawnHymel Thanks for the reply. I got it working with .broadcastTXT. I was checking the data streaming with Chrome extension, Web Socket Testing, which continuously printing out the lux value. But when I run your Python code, I only get 1 lux value and I lose a connection. It makes sense since the Python program only runs once whether I have ws.close() or not. Could you let me know if there is a way to keep the client connection to the server open so that I can receive the data continuously? Any advice would be greatly helpful! Please let me know!
@@sejungsong I would think that you need to put the ws.send and ws.recv in a while look so it's constantly sending and receiving. You don't want to call ws.close, as that's what terminates the connection.
Can an Arduino be used to make a VPN?
You likely can make a VPN out of one of the more powerful Arduino boards, like an ESP32, to handle the encryption. However, it would still probably be a lot of work and really slow. You're best bet would be to use something like a Raspberry Pi for that.
esp 32 will work as a broker?
Do you mean for something like MQTT? If so, it looks like others have managed to get it working on the ESP32: www.esp32.com/viewtopic.php?t=109
HOW TO DO THIS THE OTHER WAY AROUND?????????
What's the other way around? Host a webpage from your computer and browse to it from your ESP32?
niiice but can this worK with esp8266
I believe this demo would work with the ESP8266. However, you start to run out of memory very quickly if you try to add much more.