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/...

Комментарии • 84

  • @jmsiefer
    @jmsiefer 4 года назад +3

    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!!!

  • @colanuss4985
    @colanuss4985 5 лет назад +2

    I really like your presentation style. Precise, easy to follow and high quality production. A shame that the channel is a bit underrated.

    • @ShawnHymel
      @ShawnHymel  5 лет назад

      Glad you like them, thanks! I've only got two videos up, so I'll work on adding more :)

    • @totallyrandom4664
      @totallyrandom4664 2 года назад

      @@ShawnHymel please do more videos ♥️

  • @lenreinhart2020
    @lenreinhart2020 2 года назад

    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

  • @BharatMohanty
    @BharatMohanty 5 лет назад +2

    Hi Shawn I didn't realise that this channel is in my subscription list...anyway welcome back...👍

    • @ShawnHymel
      @ShawnHymel  5 лет назад +3

      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.

  • @savejeff15
    @savejeff15 4 года назад +2

    Very nice explanation. well structured and just the right balance between information but not to much basic stuff. thx!

  • @globalns
    @globalns 5 лет назад +2

    Another great video, I was getting used to that devo-esque Digi-Key intro though

    • @ShawnHymel
      @ShawnHymel  5 лет назад

      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 :)

  • @lintangwisesa
    @lintangwisesa 5 лет назад +10

    Where have you been, Sir? Long time no see. Anyway, great Tutorial as always~

    • @ShawnHymel
      @ShawnHymel  5 лет назад +5

      I was either writing tutorials for SparkFun or making some videos for DigiKey. It's good to be back, though 😁

  • @fareli91
    @fareli91 3 года назад

    Wow. Such a great channel Ive never known about. Thanks for the tutorial. Learned a lot from this.

  • @kasra8106
    @kasra8106 Год назад

    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

  • @FPChris
    @FPChris 3 года назад +1

    What would be the easiest solution to make wireless communication between a pc and an esp32 with no passwords etc.

    • @ShawnHymel
      @ShawnHymel  3 года назад +1

      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.

    • @FPChris
      @FPChris 3 года назад

      @@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.

  • @visitor5914
    @visitor5914 5 лет назад +3

    Thank you so much for sharing~
    It always a heartwarming things to get new knowledge...
    #salute

    • @ShawnHymel
      @ShawnHymel  5 лет назад

      You're welcome! I'm glad you enjoyed it :)

  • @supermamaoo
    @supermamaoo 4 года назад

    very, very clear tutorial
    thanks so much

  • @jamesanderegg7655
    @jamesanderegg7655 5 лет назад

    Great tutorial, looking forward to more!

    • @ShawnHymel
      @ShawnHymel  5 лет назад

      Thanks! I'll try to add more videos in the future between other work :)

  • @jupiterjs031
    @jupiterjs031 5 лет назад +1

    Nice tutorial. thanks!

  • @caesarchu3427
    @caesarchu3427 5 лет назад +1

    Great tutorial. 我喜欢~

  • @HG-jl4ed
    @HG-jl4ed Год назад

    I have esp32 where and how to connect it, do we have to connect it to arduino board?

  • @AlfieMakes
    @AlfieMakes 5 лет назад

    Excellent Tutorial. How many clients do you think an ESP32 can handle?

    • @ShawnHymel
      @ShawnHymel  5 лет назад +1

      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

  • @lernenmitrobin
    @lernenmitrobin 4 года назад

    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.

  • @jayantpanhalkar4224
    @jayantpanhalkar4224 Год назад

    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

  • @Alhasan-kd3tq
    @Alhasan-kd3tq Год назад

    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 ?

  • @MemoxCid
    @MemoxCid 2 года назад

    What is the name of the program "Capturing from Wi-fi"?

  • @MemoxCid
    @MemoxCid 2 года назад

    How can I do this but with a ESP32-CAM?

  • @akulanvn381
    @akulanvn381 Год назад

    Hey Shawn, when i run the python code i keep getting win10060 error. what can i do to resolve it?

  • @alvarobyrne
    @alvarobyrne 5 лет назад

    excellent tut, how would you do this with an sparkfun esp32 thing. no difference?

  • @rubenmata73
    @rubenmata73 2 года назад

    Excellent!!!

  • @asmaklad
    @asmaklad 4 года назад

    Great Tutorial .. How about making the ESP32 act as a (WebSocket Secure) WSS server ? I couldn't find any libraries supporting this.

    • @ShawnHymel
      @ShawnHymel  4 года назад

      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

  • @FuxionTech
    @FuxionTech 4 года назад

    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

    • @ShawnHymel
      @ShawnHymel  4 года назад

      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.

  • @bibekbarman4139
    @bibekbarman4139 2 года назад

    How to get payload int data?

  • @TOMTOM-nh3nl
    @TOMTOM-nh3nl 3 года назад

    Thank You

  • @MrAndreapas79
    @MrAndreapas79 4 года назад

    hi how can i implement a web page on my websocket server?

  • @peterkortvel
    @peterkortvel 4 года назад

    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!

    • @ShawnHymel
      @ShawnHymel  4 года назад +1

      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.

  • @annoorkhan4219
    @annoorkhan4219 2 года назад

    Nice ...

  • @SA-oj3bo
    @SA-oj3bo 5 лет назад

    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?

    • @ShawnHymel
      @ShawnHymel  5 лет назад +1

      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.

  • @catalan6300
    @catalan6300 4 года назад

    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!

    • @ShawnHymel
      @ShawnHymel  4 года назад +1

      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/

  • @lindnerlars81
    @lindnerlars81 4 года назад

    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? :)

    • @ShawnHymel
      @ShawnHymel  4 года назад

      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.

    • @lindnerlars81
      @lindnerlars81 4 года назад

      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 :)

  • @andrewczar1384
    @andrewczar1384 5 лет назад

    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.

    • @ShawnHymel
      @ShawnHymel  5 лет назад +1

      You should be able to cast or convert the values with a function like atoi()

  • @srinidhig4566
    @srinidhig4566 Год назад

    Hi,
    Do I need a router?
    Is there a way to config DHCP server on the ESP32 itself?

    • @theolephay
      @theolephay Год назад

      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.

  • @steinmax6980
    @steinmax6980 5 лет назад

    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

    • @steinmax6980
      @steinmax6980 5 лет назад

      PS: Great video it helped me alot!!

  • @dansv9778
    @dansv9778 3 года назад

    So can I send data from python to the esp32 cam to let's say.. Move a servo?

    • @ShawnHymel
      @ShawnHymel  3 года назад

      Yes. You just need to interpret the WebSocket commands sent from Python.

  • @rokljhui864
    @rokljhui864 6 месяцев назад

    How do we disable the 'Nagle' algorithm so our packets are ' actually fast' and not bundled up and delayed by evil mr Nagle.

  • @zhuk462
    @zhuk462 2 года назад

    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.

  • @fantasty9999
    @fantasty9999 5 лет назад

    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.

    • @ShawnHymel
      @ShawnHymel  5 лет назад

      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

    • @fantasty9999
      @fantasty9999 5 лет назад

      @@ShawnHymel Thanks for your help. Using ethernet on esp32 is quite complicated to me but I'll try my best

  • @ludokustermans
    @ludokustermans 5 лет назад

    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 ?

    • @ShawnHymel
      @ShawnHymel  5 лет назад

      I don't have much Android dev experience, so I couldn't really say. Sorry!

    • @ludokustermans
      @ludokustermans 5 лет назад +1

      @@ShawnHymel Hi, thanks anyway. I am now trying Inetaddress to use the name....

  • @shrikantnikam2426
    @shrikantnikam2426 4 года назад

    Sir how to send .wav file using esp32

    • @ShawnHymel
      @ShawnHymel  4 года назад

      You should be able to upload it using the SPIFFS tool in Arduino and then it should be accessible on the server.

  • @sejungsong
    @sejungsong 4 года назад

    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

    • @ShawnHymel
      @ShawnHymel  4 года назад +1

      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.

    • @sejungsong
      @sejungsong 4 года назад +1

      @@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!

    • @ShawnHymel
      @ShawnHymel  4 года назад

      @@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.

  • @rev.kenshostad2888
    @rev.kenshostad2888 4 года назад

    Can an Arduino be used to make a VPN?

    • @ShawnHymel
      @ShawnHymel  4 года назад

      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.

  • @madhusudhang8254
    @madhusudhang8254 5 лет назад

    esp 32 will work as a broker?

    • @ShawnHymel
      @ShawnHymel  5 лет назад

      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

  • @albineriksson8418
    @albineriksson8418 5 лет назад

    HOW TO DO THIS THE OTHER WAY AROUND?????????

    • @ShawnHymel
      @ShawnHymel  5 лет назад

      What's the other way around? Host a webpage from your computer and browse to it from your ESP32?

  • @med6402
    @med6402 5 лет назад

    niiice but can this worK with esp8266

    • @ShawnHymel
      @ShawnHymel  5 лет назад +1

      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.