Hello respected members.
I working on a personal home automation project. My objective is to control my home appliances through a relay connected to an ESP8266. The issue is if I upload the sketch with any port other than 80, the Esp8266 page with controls is displayed, but when I click the toggle to change the state, nothing happens. The situation mentioned above is where the ESP8266 and I are on the same WIFI. I plan to control the ESP8266 even when I'm not at home. Which method will be the best to use here? Websocket or the GET/POST. Please guide.
Thank you. Below is the code I'm using.
#include <ESP8266WiFi.h> #include <ESPAsyncTCP.h> #include <WiFiClientSecure.h> #include <ESPAsyncWebServer.h> // Replace with your network credentials const char* ssid = "ssid"; const char* password = "password"; bool ledState = 0; const int ledPin = 13; // Create AsyncWebServer object on port 80 AsyncWebServer server(8005); AsyncWebSocket ws("/ws"); const char index_html[] PROGMEM = R"rawliteral( <!DOCTYPE HTML><html> <head> <title>ESP Web Server</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" href="data:,"> <style> html { font-family: Arial, Helvetica, sans-serif; text-align: center; } h1 { font-size: 1.8rem; color: white; } h2{ font-size: 1.5rem; font-weight: bold; color: #143642; } .topnav { overflow: hidden; background-color: #143642; } body { margin: 0; } .content { padding: 30px; max-width: 600px; margin: 0 auto; } .card { background-color: #F8F7F9;; box-shadow: 2px 2px 12px 1px rgba(140,140,140,.5); padding-top:10px; padding-bottom:20px; } .button { padding: 15px 50px; font-size: 24px; text-align: center; outline: none; color: #fff; background-color: #0f8b8d; border: none; border-radius: 5px; -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; -webkit-tap-highlight-color: rgba(0,0,0,0); } /*.button:hover {background-color: #0f8b8d}*/ .button:active { background-color: #0f8b8d; box-shadow: 2 2px #CDCDCD; transform: translateY(2px); } .state { font-size: 1.5rem; color:#8c8c8c; font-weight: bold; } </style> <title>ESP Web Server</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" href="data:,"> </head> <body> <div class="topnav"> <h1>ESP WebSocket Server</h1> </div> <div class="content"> <div class="card"> <h2>Output - GPIO 13</h2> <p class="state">state: <span id="state">%STATE%</span></p> <p><button id="button" class="button">Toggle</button></p> </div> </div> <script> var gateway = `ws://${window.location.hostname}/8005`; var websocket; window.addEventListener('load', onLoad); function initWebSocket() { console.log('Trying to open a WebSocket connection...'); websocket = new WebSocket(gateway); websocket.onopen = onOpen; websocket.onclose = onClose; websocket.onmessage = onMessage; // <-- add this line } function onOpen(event) { console.log('Connection opened'); } function onClose(event) { console.log('Connection closed'); setTimeout(initWebSocket, 2000); } function onMessage(event) { var state; if (event.data == "1"){ state = "ON"; } else{ state = "OFF"; } document.getElementById('state').innerHTML = state; } function onLoad(event) { initWebSocket(); initButton(); } function initButton() { document.getElementById('button').addEventListener('click', toggle); } function toggle(){ websocket.send('toggle'); } </script> </body> </html> )rawliteral"; void notifyClients() { ws.textAll(String(ledState)); } void handleWebSocketMessage(void *arg, uint8_t *data, size_t len) { AwsFrameInfo *info = (AwsFrameInfo*)arg; if (info->final && info->index == 0 && info->len == len && info->opcode == WS_TEXT) { data[len] = 0; if (strcmp((char*)data, "toggle") == 0) { ledState = !ledState; notifyClients(); } } } void onEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type, void *arg, uint8_t *data, size_t len) { switch (type) { case WS_EVT_CONNECT: Serial.printf("WebSocket client #%u connected from %s\n", client->id(), client->remoteIP().toString().c_str()); break; case WS_EVT_DISCONNECT: Serial.printf("WebSocket client #%u disconnected\n", client->id()); break; case WS_EVT_DATA: handleWebSocketMessage(arg, data, len); break; case WS_EVT_PONG: case WS_EVT_ERROR: break; } } void initWebSocket() { ws.onEvent(onEvent); server.addHandler(&ws); } String processor(const String& var){ Serial.println(var); if(var == "STATE"){ if (ledState){ return "ON"; } else{ return "OFF"; } } return String(); } void setup(){ // Serial port for debugging purposes Serial.begin(115200); pinMode(ledPin, OUTPUT); digitalWrite(ledPin, LOW); // Connect to Wi-Fi WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.println("Connecting to WiFi.."); } // Print ESP Local IP Address Serial.println(WiFi.localIP()); initWebSocket(); // Route for root / web page server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){ request->send_P(200, "text/html", index_html, processor); }); // Start server server.begin(); } void loop() { ws.cleanupClients(); digitalWrite(ledPin, ledState); }
This is what I get in console.
msgport.js:70 {"notify":"init_tab"} (index):88 Trying to open a WebSocket connection... (index):119 Uncaught DOMException: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state. at HTMLButtonElement.toggle ( http://192.168.1.3:8005/:119:15) toggle @ (index):119 (index):119 Uncaught DOMException: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state. at HTMLButtonElement.toggle ( http://192.168.1.3:8005/:119:15) toggle @ (index):119 (index):119 Uncaught DOMException: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state. at HTMLButtonElement.toggle ( http://192.168.1.3:8005/:119:15) toggle @ (index):119 (index):119 Uncaught DOMException: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state. at HTMLButtonElement.toggle ( http://192.168.1.3:8005/:119:15) toggle @ (index):119 (index):119 Uncaught DOMException: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state. at HTMLButtonElement.toggle ( http://192.168.1.3:8005/:119:15) toggle @ (index):119 (index):119 Uncaught DOMException: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state. at HTMLButtonElement.toggle ( http://192.168.1.3:8005/:119:15) toggle @ (index):119 (index):119 Uncaught DOMException: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state. at HTMLButtonElement.toggle ( http://192.168.1.3:8005/:119:15) toggle @ (index):119 (index):89 WebSocket connection to 'ws://192.168.1.3/ws' failed: initWebSocket @ (index):89 onLoad @ (index):112 (index):98 Connection closed (index):88 Trying to open a WebSocket connection... 192.168.1.3/:1 Uncaught (in promise) Error: A listener indicated an asynchronous response by returning true, but the message channel closed before a response was received (index):89 WebSocket connection to 'ws://192.168.1.3/ws' failed: initWebSocket @ (index):89 (index):98 Connection closed (index):88 Trying to open a WebSocket connection... (index):89 WebSocket connection to 'ws://192.168.1.3/ws' failed: initWebSocket @ (index):89 (index):98 Connection closed (index):88 Trying to open a WebSocket connection... (index):89 WebSocket connection to 'ws://192.168.1.3/ws' failed: initWebSocket @ (index):89 (index):98 Connection closed (index):88 Trying to open a WebSocket connection... (index):89 WebSocket connection to 'ws://192.168.1.3/ws' failed: initWebSocket @ (index):89 (index):98 Connection closed (index):88 Trying to open a WebSocket connection... WebSocket connection to 'ws://192.168.1.3/ws' failed: initWebSocket @ 192.168.1.3/:89 Connection closed Trying to open a WebSocket connection... WebSocket connection to 'ws://192.168.1.3/ws' failed: initWebSocket @ 192.168.1.3/:89 Connection closed
@mrbond007 There is a lot going on there, maybe start with something simple. Also let's remove some 'can't be done' and some weird.
Accessing a private network such as 192.168.0.x from the web can't be done without some help.
WEb servers as the code comments say go on port 80. Yes they can go elsewhere but if you are using off the shelf components they may not work. Start by using port 80 then if you want/need to once everything is working change the port.
You did not appear to provide an ssid or password, how did you connect?
Given the sketches and your comments you may have some relevant experience, in order to provide better answers, how many languages are you schooled in and how many years (40hrs x 50 wks) experience do you have?
First computer 1959. Retired from my own computer company 2004.
Hardware - Expert in 1401, 360, fairly knowledge in PC plus numerous MPU's & MCU's
Major Languages - Machine language, 360 Macro Assembler, Intel Assembler, PL/I and PL1, Pascal, Basic, C plus numerous job control and scripting languages.
My personal scorecard is now 1 PC hardware fix (circa 1982), 1 open source fix (at age 82), and 2 zero day bugs in a major OS.