Help with a function

I would like to write a function that does the following:

Filters messages from topic zigbee2mqtt/Hue_dimmer_main_bedroom on payload.action = "off_press"

image

For each matching received message, the function sends one of the following msg.payload on topic zigbee2mqtt/Hue_light_main_bedroom :

{"color_temp": "coolest", "transition":0.5}
{"color_temp": "cool", "transition":0.5}
{"color_temp": "neutral", "transition":0.5}
{"color_temp": "warm", "transition":0.5}
{"color_temp": "warmest", "transition":0.5}

So each click of the button cycles through from coolest to warmest, then starts again at coolest.

Any tips would be appreciated.

here you go...

var opts = [
    {"color_temp": "coolest", "transition":0.5},
    {"color_temp": "cool", "transition":0.5},
    {"color_temp": "neutral", "transition":0.5},
    {"color_temp": "warm", "transition":0.5},
    {"color_temp": "warmest", "transition":0.5}
];

var opt = context.get("opt") || 0;
msg.payload = opts[opt];

opt++;
if(opt >= opts.length) opt = 0;
context.set("opt", opt); 

return msg;

demo flow...

[{"id":"f1e7cf45.48393","type":"inject","z":"b872cb4b.5a6448","name":"fake mqtt","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"","payloadType":"date","x":800,"y":240,"wires":[["43f0731d.f5780c"]]},{"id":"43f0731d.f5780c","type":"function","z":"b872cb4b.5a6448","name":"","func":"var opts = [\n    {\"color_temp\": \"coolest\", \"transition\":0.5},\n    {\"color_temp\": \"cool\", \"transition\":0.5},\n    {\"color_temp\": \"neutral\", \"transition\":0.5},\n    {\"color_temp\": \"warm\", \"transition\":0.5},\n    {\"color_temp\": \"warmest\", \"transition\":0.5}\n];\n\nvar opt = context.get(\"opt\") || 0;\nmsg.payload = opts[opt];\n\nopt++;\nif(opt >= opts.length) opt = 0;\ncontext.set(\"opt\", opt); \n\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","x":960,"y":240,"wires":[["c54e199.d982fe8"]]},{"id":"c54e199.d982fe8","type":"debug","z":"b872cb4b.5a6448","name":"","active":true,"tosidebar":true,"console":false,"tostatus":true,"complete":"payload","targetType":"msg","statusVal":"payload","statusType":"auto","x":1140,"y":240,"wires":[]}]
2 Likes

That's great thank you, I did not expect an answer so soon! It works!

Do I understand this correctly:

You store the variables in a table (?)
var opt = context.get("opt") || 0; (don't understand, why OR 0 ?)
Set msg.payload

Increment by one
If length is greater than table entries, reset to 0
Set opt value as opt

return the payload..

I'm sure I got a lot wrong there! :upside_down_face:

I've never used context.set / context.get.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.