Hello,
i can get many device measurements
i can commande Led ON or OFF , and manage Consigne value by 2 button + –
but Led and consigne are zeroed when web page is refreched..
I think somme part of code is missing , and i need somme guidance
to solve that. I want to use the led commande and the consigne value inside the ESP32 application . So a bidirectionnal way between EPS32 and web page.
Hi.
The best way to achieve a bidirectional communication is using websockets: https://randomnerdtutorials.com/esp32-websocket-server-arduino/
But you would need to change all your code…
What sections of code are you using to display the values?
Are you saving the values on a variable? If you save the values on a variable they can be sent to the client as variables when you make a request.
Regards,
Sara
Hello,
i tried to star with a very simple example of websocket with only one led to command..it works fine
but i tried to add a second led
i can command this 2 leds ,
led #1 is D15 led#2 is D2 (inbuilt led)
click order light on the correct led ..no problem on command
but i don’t understand how to affect the correct feedback ( status of led)
Now the led #2 send feedback to led #1
here is my code
#include
#include
#include
#include "SPIFFS.h"
#define VERSION "07-07-2022"
//cde led2 ..OK mais bug sur etat Led 2 !!
const char *ssid ="ON_AIR2021";
const char *password ="cGT>1_@?LOdBqD6kd%s@v|.b5x^4PD|?s}uu*j4o)Uqpa|r1jftH+H>8_oG6}v4";
bool GPIO_State = 0;
bool GPIO_State2 = 0;
const int Led_Pin = 15;
const int Led2 = 2; // inbuilt led bleue
// Create AsyncWebServer object on port 80
AsyncWebServer server(80);
AsyncWebSocket ws("/ws");
const char html_page[] PROGMEM = R"rawliteral(
ESP32 Web Server
html {
font-family: New Times Roman;
text-align: center;
}
h1 {
font-size: 1.8rem;
color: white;
}
h2{
font-size: 1.5rem;
font-weight: bold;
color: #612b78;
}
.topnav {
overflow: hidden;
background-color: #612b78;
}
body {
margin: 0;
}
.content {
padding: 30px;
max-width: 600px;
margin: 0 auto;
}
.button {
padding: 15px 50px;
font-size: 24px;
text-align: center;
outline: none;
color: #fff;
background-color:#fa0f0f; //green
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:active {
background-color:#fa0f0f ;
transform: translateY(2px);
}
.state {
font-size: 1.5rem;
color:#120707;
font-weight: bold;
}
ESP32 Web Server
ESP32 Bleu , WebSocket Server
LED D15
Click to Toggle
D15 State: %STATE%
LED D2
Click to Toggle2
D2 State: %STATE2%
var gateway = `ws://${window.location.hostname}/ws`;
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 arrayS = event.data.split("=");
console.log(`Received a notification from ${event.origin}`);
console.log(event);
if (event.data == "1"){
state = "ON";
}
else{
state = "OFF";
}
document.getElementById('state').innerHTML = state;
if (event.data == "4"){ // <-- problemo Here ? Event =?
state2 = "ON";
}
else{
state2 = "OFF";
}
document.getElementById('state2').innerHTML = state2;
}
function onLoad(event) {
initWebSocket();
initButton();
}
function initButton() {
document.getElementById('button').addEventListener('click', toggle);
document.getElementById('button2').addEventListener('click', toggle2);
}
function toggle(){
websocket.send('toggle');
}
function toggle2(){
websocket.send('toggle2');
}
)rawliteral";
void notifyClients() {
ws.textAll(String(GPIO_State));
ws.textAll(String(GPIO_State2));
}
void handleWebSocketMessage(void *arg, uint8_t *data, size_t len) {
int xx;
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) {
GPIO_State = !GPIO_State;
xx=0;
}
if (strcmp((char*)data, "toggle2") == 0) {
GPIO_State2 = !GPIO_State2;
xx=1;
}
if (xx==0) ws.textAll(String(GPIO_State));
if (xx==1)ws.textAll(String(GPIO_State2));
}
}
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)
{
if(var == "STATE"){
if (GPIO_State){
return "ON";
}
else{
return "OFF";
}
}
if(var == "STATE2")
{
if (GPIO_State2){
return "ON";
}
else{
return "OFF";
}
}
}
void setup(){
// Serial port for debugging purposes
Serial.begin(115200);
delay(1000);
Serial.print("Version :"); Serial.println(VERSION);
Serial.println("ESP32_WebSocket_Server_2022-07 ... SANS data files");
pinMode(Led_Pin, OUTPUT);
digitalWrite(Led_Pin, LOW);
pinMode(Led2, OUTPUT);
digitalWrite(Led2, 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", html_page, processor);
});
// Start server
server.begin();
}
void loop() {
ws.cleanupClients();
Serial.print("Led 15 =");Serial.println(GPIO_State);
digitalWrite(Led_Pin, GPIO_State);
Serial.print("Led 2 =");Serial.println(GPIO_State2);
digitalWrite(Led2,GPIO_State2);
delay(1000);
}
Hi.
Your problem is on the onMessage() JavaScript function:
function onMessage(event) {
var arrayS = event.data.split(“=”);
console.log(`Received a notification from ${event.origin}`);
console.log(event);
if (event.data == “1”){
state = “ON”;
}
else{
state = “OFF”;
}
document.getElementById(‘state’).innerHTML = state;
if (event.data == “4”){ // <– problemo Here ? Event =?
state2 = “ON”;
}
else{
state2 = “OFF”;
}
document.getElementById(‘state2’).innerHTML = state2;
}
Basically, on the ESP32 you send the following:
if (xx==0) ws.textAll(String(GPIO_State));
if (xx==1)ws.textAll(String(GPIO_State2));
You’re simply texting the GPIO state. But, when you’re getting that message on JavaScript, it only receives the messages, it doens’t know from what GPIO that message is.
You need to send something on your message that identifies the GPIO.
I hope this helps.
You can also check this example from the “Build Web Servers” eBook that controls multiple GPIOs using WebSocket: https://github.com/RuiSantosdotme/build-web-servers-dl/blob/main/2_5_Multiple_Outputs_WebSocket.zip
That example is for platformIO, but you can find the Arduino code on the main.cpp file under the src folder and the JavaScript file on the data folder.
I hope this helps.
Regards,
Sara