corbanmailloux / esp-mqtt-rgb-led

MQTT RGB LEDs Using JSON for Home Assistant
MIT License
270 stars 74 forks source link

Taking #RRGGBB hex string and using it to create the JSON block with decimal values #19

Closed linker3000 closed 7 years ago

linker3000 commented 7 years ago

One for the notes/wiki??

I was using a color wheel icon/function in an Android-based MQTT app to test my RGB LED build with esp-mqtt-rgb-led and Node-red. I created this node function to turn the received hex MQTT payload (#RRGGBB) from the app into an input string for this code on an ESP8266. Might be useful for others...

// Convert #RRGGBB hex payload into JSON formatted string for
// corbanmailloux/esp-mqtt-rgb-led code
// https://github.com/corbanmailloux/esp-mqtt-rgb-led

if ((msg.payload.toString().length != 7) &&
    (msg.payload.toString().substring(0.1) != "#"))
  {return null;}

msg.payload = '{"state": "ON","brightness": 255,"color": {' + 
  '"r": ' + parseInt(msg.payload.toString().substring(1,3),16) + ',' + 
  '"g": ' + parseInt(msg.payload.toString().substring(3,5),16) + ',' +
  '"b": ' + parseInt(msg.payload.toString().substring(5),16) + 
  '},"transition": 2' +
  '}';

return msg;
corbanmailloux commented 7 years ago

@linker3000 Thank you for this addition. I've added a wiki page here and credited you.

linker3000 commented 7 years ago

Thanks! In further testing I modified the code slightly:

// Convert #RRGGBB hex payload into JSON formatted string for
// corbanmailloux/esp-mqtt-rgb-led code
// https://github.com/corbanmailloux/esp-mqtt-rgb-led

if ((msg.payload.toString().length != 7) ||
    (msg.payload.toString().substring(0,1) != "#"))
  {return null;}

msg.payload = '{"state": "ON","brightness": 255,"color": {' + 
  '"r": ' + parseInt(msg.payload.toString().substring(1,3),16) + ',' + 
  '"g": ' + parseInt(msg.payload.toString().substring(3,5),16) + ',' +
  '"b": ' + parseInt(msg.payload.toString().substring(5),16) + 
  '}' +
  '}';

return msg;