I have a problem with the project on ESP8266. I use a color sensor that collects RGB values and sends them via WebSockets to a server created on ESP, the values pass normally and display on the website in real time. I also wanted to add functionality so that the resulting color appears in the color box. Unfortunately, I can't get this, I have searched all I could. This is how it looks, this olive-green color is permanently assigned rgb(120, 120, 0)
This is code I use for this:
websock.onmessage=function(event)
{
var obj = JSON.parse(event.data);
document.getElementById('Rvalue').innerHTML = obj.Rvalue;
document.getElementById('Gvalue').innerHTML = obj.Gvalue;
document.getElementById('Bvalue').innerHTML = obj.Bvalue;
const root = document.documentElement;
root.style.setProperty('--box-color', '120, 120, 0');
}
}
window.onload = function(event)
{
InitWebSocket();
}
I want to change this line: root.style.setProperty('--box-color', '120, 120, 0'); to look like this and work if it is possible. root.style.setProperty('--box-color', 'Rvalue, Bvalue, Gvalue');
I also used this code to send data to server via WebSocket. Now I have random values, but later I want to attach it to the sensor.
unsigned long now = millis();
if ((unsigned long)(now - previousMillis) > interval)
{
String jsonString = "";
StaticJsonDocument<200> doc;
JsonObject object = doc.to<JsonObject>();
object["Rvalue"] = random(100);
object["Gvalue"] = random(100);
object["Bvalue"] = random(100);
serializeJson(doc, jsonString);
Serial.println(jsonString);
webSocket.broadcastTXT(jsonString);
previousMillis = now;
}
I thought it was a problem with the fact that RGB values are string not INT.
I tried to convert string into INT values in different ways, e.g.: int Rvalue_int = Integer.valueOf((String) "Rvalue"); or int Rvalue_int = jsonObj.get("Rvalue").asInt(); but this blocks sending RGB values
You need to update the --box-color property value using the received RGB values from the WebSocket message. Change the line:
root.style.setProperty('--box-color', '120, 120, 0');
to:
root.style.setProperty('--box-color', `${obj.Rvalue}, ${obj.Gvalue}, ${obj.Bvalue}`);
This will set the --box-color property to the received RGB values in the format 'Rvalue, Gvalue, Bvalue'.
For more information on setting CSS variables using JavaScript, refer to this link: https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration/setProperty