Reset counter issue

Hello, I'm new with node red and programing so please do not destroy me for stupid questions.

In sweat, tears and blo0d I created this:

var count=context.get('count') || 0;
count +=1;
msg.payload=count;
context.set('count',count);
if (count == 3 )  {
count = 0;
}
return msg;

My objective is to recive in the end counter that counts 1,2,3,1,2,3 etc...
Right now I have counter that count from 1 to infinity .... My issue is that im not able to reset this counter after it reaches to some value.

Sorry for beginners question but i'm not so good with programing.

Regards, Kamil.

Try context.set after the if statement.

Thank you very much for this :slight_smile:

This is result which one is working.

var count=context.get('count') || 0;
count +=1;
msg.payload=count;
context.set('count',count);
if (count == 3 )  {
context.set("count", 0);
}
return msg;

Or

var count=context.get('count') || 0;
count +=1;
msg.payload=count;
if (count == 3 )  {
count = 0;
}
context.set('count',count);
return msg;

Or

var count=context.get('count') || 0;
count +=1;
msg.payload=count;
context.set('count',(count > 2 ? 0 : count));
return msg;

Can I add different cases for each value ?
Each number will generate different payload and I will inject it to call servcie block type.

This is possible ?

You need to explain more.

Sure.

you can use a switch node

image

image


or in JS function...

var count=context.get('count') || 0;
count +=1;
msg.payload=count;
context.set('count',(count > 2 ? 0 : count));

switch(count) {
  case 1:
  msg.payload = "value is 1";
  break; 
  case 2: 
  msg.payload = "value is 2 - who knew?";
  break;
  default: 
  msg.payload = "value is " + count;
} 

return msg;

image

Yeah I have it like this right now, insted of msg I have call services for single entity to change it states.

I was wondering if one function with longer code is better then solution above ....

If its stuid and it works, it means it not so stupid :slight_smile:

What I have to type in properties of call service block to corectly read this ?

For example I have Aquara micro switch and I would like to do:
Signle click - On/Off - I have it
Double click - select settings from 4 or 5 presets - I have it right now but Im wondering is there any more efficient wat to do it ....
Hold / release - Dimmer - no code yet....

K.

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