Getting number of devices turned on; not working when all off


#1

I have a device variable “lights_on” which contains all bulbs turned on. And after that, a variable “count_lights = count(lights_on)” which tells me how many bulbs are turned on. However, when no bulb is turned on “lights_on” gets the value “(not set)” and the count function do not return 0, it only returns the last value before all bulbs turned off. How do you solve this?


#2

I have learned over the years of coding to avoid using ‘0’ as a variable whenever possible. Sometimes it is seen correctly as zero, but depending on the code, it often appears as null or even blank.

You could always add an extra IF statement to resolve this

IF count_lights is between 1 and 20
    Then send SMS count_lights ' lights are on'
    ELSE send SMS 'No lights are on'
END IF

#3

The thing is I tried exactly that; if greater or equal than 1 …, else 0. But I think count(lights_on) doesn’t even work when there are no devices in lights_on… Any way of checking if count(lights_on) is an integer?


#4

Well, notice that I do not refer to the variable count_lights in the else at all.
(I did not push a zero into a variable)
If it isn’t a number within the range, then it sends a word instead.

In other words, I would avoid “Else 0”


#5

Now I understood what you meant! I tried

(isBetween(count(devices_on),1, 20) ? count(devices_on): “100”)

which I think is what you meant, right? If between 1 and 20; show the correct number. Else 100. In the expression output preview I get “100”, but when running it; nothing…


#6

I made a slight modification to your piston. This works reliably when I tested it:

Lines 27-32 only happens if something is turned on…

If any device is on, it sends a detailed text… but if no devices are on, then the null count is irrelevant, because it sends the SMS located in the ELSE block.


One caveat, when you turn off the last device, it will not touch the two variables.
(so the old data will be remembered until a device turns on)
This is why I did not reference either variable in the ELSE block.


#7

Thanks a lot for your help, I know see what I did wrong!