ESP32 WebSockets code repeats continuously

engr_baloch
Posts: 1
Joined: Sun Dec 11, 2022 3:46 am

ESP32 WebSockets code repeats continuously

Postby engr_baloch » Sun Dec 11, 2022 5:00 am

Hello All
WhatsApp Image 2022-12-11 at 9.47.37 AM.jpeg
WhatsApp Image 2022-12-11 at 9.47.37 AM.jpeg (24.21 KiB) Viewed 1599 times

I have created a Gate Lock Device using ESP32 WebSockets Wifi Mode. On pressing button, ESP32 sends a serial command to Arduino mini and then Arduino mini operates the Output Relay.

Anytime i turn on the device, it is ok but as the button is pressed, it keeps on sending same command again and again (in a loop) and then the server gets stuck. Please advice the solution.


CODE ATTACHED
  1.  
  2.  
  3. // Import required libraries
  4. #include <WiFi.h>
  5. #include <AsyncTCP.h>
  6. #include <ESPAsyncWebServer.h>
  7.  
  8. // Replace with your network credentials
  9. const char* ssid = "wifi";                     //    hidden intentionally
  10. const char* password = "password";     //    hidden intentionally
  11.  
  12. bool ledState = 0;
  13. const int ledPin = 2;
  14.  
  15. // Create AsyncWebServer object on port 80
  16. AsyncWebServer server(80);
  17. AsyncWebSocket ws("/ws");
  18.  
  19. const char index_html[] PROGMEM = R"rawliteral(
  20. <!DOCTYPE HTML><html>
  21. <head>
  22.  <title>Gate Lock Interface</title>
  23.  <meta name="viewport" content="width=device-width, initial-scale=1">
  24.  <link rel="icon" href="data:,">
  25.  <style>
  26.  html {
  27.    font-family: Arial, Helvetica, sans-serif;
  28.    text-align: center;
  29.  }
  30.  h1 {
  31.    font-size: 1.8rem;
  32.    color: white;
  33.  }
  34.  h2{
  35.    font-size: 1.5rem;
  36.    font-weight: bold;
  37.    color: #143642;
  38.  }
  39.  .topnav {
  40.    overflow: hidden;
  41.    background-color: #143642;
  42.  }
  43.  body {
  44.    margin: 0;
  45.  }
  46.  .content {
  47.    padding: 30px;
  48.    max-width: 600px;
  49.    margin: 0 auto;
  50.  }
  51.  .card {
  52.    background-color: #F8F7F9;;
  53.    box-shadow: 2px 2px 12px 1px rgba(140,140,140,.5);
  54.    padding-top:10px;
  55.    padding-bottom:20px;
  56.  }
  57.  .button {
  58.    padding: 15px 50px;
  59.    font-size: 24px;
  60.    text-align: center;
  61.    outline: none;
  62.    color: #fff;
  63.    background-color: #0f8b8d;
  64.    border: none;
  65.    border-radius: 5px;
  66.    -webkit-touch-callout: none;
  67.    -webkit-user-select: none;
  68.    -khtml-user-select: none;
  69.    -moz-user-select: none;
  70.    -ms-user-select: none;
  71.    user-select: none;
  72.    -webkit-tap-highlight-color: rgba(0,0,0,0);
  73.   }
  74.   /*.button:hover {background-color: #0f8b8d}*/
  75.   .button:active {
  76.     background-color: #0f8b8d;
  77.     box-shadow: 2 2px #CDCDCD;
  78.     transform: translateY(2px);
  79.   }
  80.   .state {
  81.     font-size: 1.5rem;
  82.     color:#8c8c8c;
  83.     font-weight: bold;
  84.   }
  85.  </style>
  86. <title>Gate Lock Interface</title>
  87. <meta name="viewport" content="width=device-width, initial-scale=1">
  88. <link rel="icon" href="data:,">
  89. </head>
  90. <body>
  91.  <div class="topnav">
  92.    <h1>ESP GATE LOCK INTERFACE</h1>
  93.  </div>
  94.  <div class="content">
  95.    <div class="card">
  96.      <h2>Push the Button</h2>
  97.      <p class="state">state: <span id="state">%STATE%</span></p>
  98.      <p><button id="button" class="button">Press</button></p>
  99.    </div>
  100.  </div>
  101. <script>
  102.  var gateway = `ws://${window.location.hostname}/ws`;
  103.  var websocket;
  104.  window.addEventListener('load', onLoad);
  105.  function initWebSocket() {
  106.    console.log('Trying to open a WebSocket connection...');
  107.    websocket = new WebSocket(gateway);
  108.    websocket.onopen    = onOpen;
  109.    websocket.onclose   = onClose;
  110.    websocket.onmessage = onMessage; // <-- add this line
  111.  }
  112.  function onOpen(event) {
  113.    console.log('Connection opened');
  114.  }
  115.  function onClose(event) {
  116.    console.log('Connection closed');
  117.    setTimeout(initWebSocket, 2000);
  118.  }
  119.  
  120.  
  121. ////////////////////////////////////////////////// ------     LED STATE STRING UPDATE ON WEBPAGE    --------- /////////////////////////////////////////////////////////
  122.  
  123.  
  124.  
  125.  function onMessage(event) {
  126.    var state;
  127.    if (event.data == "1"){
  128.      state = "ON";
  129.    }
  130.    else{
  131.      state = "OFF";
  132.    }
  133.    document.getElementById('state').innerHTML = state;
  134.  }
  135.  function onLoad(event) {
  136.    initWebSocket();
  137.    initButton();
  138.  }
  139.  
  140.  
  141. ///////////////////////////////////////////////-----------   BUTTON CLICK  ---------//////////////////////////////////////////////////////////////////////////////
  142.  
  143.  
  144.  
  145.  
  146.  function initButton() {
  147.    document.getElementById('button').addEventListener('click', toggle);
  148.  }
  149.  function toggle(){
  150.    websocket.send('toggle');
  151.  }
  152. </script>
  153. </body>
  154. </html>
  155. )rawliteral";
  156.  
  157.  
  158.  
  159. //////////////////////////////////////////// ---    NOTIFY CLIIENTS    ------ //////////////////////////////////////////////////////////////////////////////////////
  160.  
  161.  
  162.  
  163.  
  164. void notifyClients() {
  165.   ws.textAll(String(ledState));
  166. }
  167.  
  168.  
  169. void handleWebSocketMessage(void *arg, uint8_t *data, size_t len) {
  170.   AwsFrameInfo *info = (AwsFrameInfo*)arg;
  171.   if (info->final && info->index == 0 && info->len == len && info->opcode == WS_TEXT) {
  172.     data[len] = 0;
  173.     if (strcmp((char*)data, "toggle") == 0) {
  174.       ledState = !ledState;
  175.       Serial.write('A');
  176.       notifyClients();
  177.     }
  178.   }
  179. }
  180.  
  181.  
  182.  
  183. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  184.  
  185.  
  186.  
  187.  
  188.  
  189. void onEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type,
  190.              void *arg, uint8_t *data, size_t len) {
  191.   switch (type) {
  192.     case WS_EVT_CONNECT:
  193.       Serial.printf("WebSocket client #%u connected from %s\n", client->id(), client->remoteIP().toString().c_str());
  194.       break;
  195.     case WS_EVT_DISCONNECT:
  196.       Serial.printf("WebSocket client #%u disconnected\n", client->id());
  197.       break;
  198.     case WS_EVT_DATA:
  199.       handleWebSocketMessage(arg, data, len);
  200.       break;
  201.     case WS_EVT_PONG:
  202.     case WS_EVT_ERROR:
  203.       break;
  204.   }
  205. }
  206.  
  207. void initWebSocket() {
  208.   ws.onEvent(onEvent);
  209.   server.addHandler(&ws);
  210. }
  211.  
  212. String processor(const String& var){
  213.   Serial.println(var);
  214.   if(var == "STATE"){
  215.     if (ledState){
  216.       return "ON";
  217.     }
  218.     else{
  219.       return "OFF";
  220.     }
  221.   }
  222.   return String();
  223. }
  224.  
  225. void setup(){
  226.   // Serial port for debugging purposes
  227.   Serial.begin(9600);
  228.  
  229.   pinMode(ledPin, OUTPUT);
  230.   digitalWrite(ledPin, LOW);
  231.  
  232.   // Connect to Wi-Fi
  233.   WiFi.begin(ssid, password);
  234.   while (WiFi.status() != WL_CONNECTED) {
  235.     delay(1000);
  236.     Serial.println("Connecting to WiFi..");
  237.   }
  238.  
  239.   // Print ESP Local IP Address
  240.   Serial.println(WiFi.localIP());
  241.  
  242.   initWebSocket();
  243.  
  244.   // Route for root / web page
  245.   server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
  246.     request->send_P(200, "text/html", index_html, processor);
  247.   });
  248.  
  249.   // Start server
  250.   server.begin();
  251. }
  252.  
  253. void loop() {
  254.   ws.cleanupClients();
  255.   digitalWrite(ledPin, ledState);
  256. }

User avatar
mbratch
Posts: 303
Joined: Fri Jun 11, 2021 1:51 pm

Re: ESP32 WebSockets code repeats continuously

Postby mbratch » Sun Dec 11, 2022 4:04 pm

I haven't specifically used the Arduino websocket library, but so you know what sorts of actions trigger the ebet handler? Perhaps your event handler is doing something that generates an event, and thus the loop of events occurring. For example, check if notifying a client generates an event.

Who is online

Users browsing this forum: No registered users and 131 guests