Hello, I have a 8 channel usb relay board, with FTDI ft232rl controller. Controlling those relays is very simple, you can just send a character corresponding to number of the relay. For example: “1” turns on relay no.1, sending it again turns it off. etc.
The serial port also returns an analog number from 0 to 255, for example:
relay no.1 is on = 1
relay no.2 is on = 2
relay no.8 is on = 128
relay no.1 and no.8 = 128 + 1 = 129
So the question is, is it possible to create a binary sensor that can tell which relays are on based on the decimal output? I know you can create 64 combinations of “or’s” for each relay but that would be very, very, inefficient and time consuming way of doing it.
It seems that bitwise operation doesn’t exists in HA Jinja
I’d go with the way binary is constructed.
If you take any number and want to convert it, it is like so
You do a constant division by 2 and keep the remainder until you reach zero
{% set relay_status = 233 %}
starting with {{ relay_status }}
bit 1 is {{ relay_status % 2 }} {% set relay_status = (relay_status / 2) | int %}
bit 2 is {{ relay_status % 2 }} {% set relay_status = (relay_status / 2) | int %}
bit 3 is {{ relay_status % 2 }} {% set relay_status = (relay_status / 2) | int %}
bit 4 is {{ relay_status % 2 }} {% set relay_status = (relay_status / 2) | int %}
bit 5 is {{ relay_status % 2 }} {% set relay_status = (relay_status / 2) | int %}
bit 6 is {{ relay_status % 2 }} {% set relay_status = (relay_status / 2) | int %}
bit 7 is {{ relay_status % 2 }} {% set relay_status = (relay_status / 2) | int %}
bit 8 is {{ relay_status % 2 }}
In Developer Tools > Template
Gives
starting with 233
bit 1 is 1
bit 2 is 0
bit 3 is 0
bit 4 is 1
bit 5 is 0
bit 6 is 1
bit 7 is 1
bit 8 is 1
Create an input_number helper, to initialise with the value returned by your serial port (I let this part for you).
Lets call it input_number.relay in this exemple.
Create 8 input_boolean helpers named input_boolean.relay1 to input_boolean.relay8 in this exemple.
Thank you very much! This is a solution I’ve been looking for. I am fairly new to HA and I’m still learning this “Jinja” thing.
So, I copied the automation you wrote me above, created all the helpers and made another automation to set the input_number value to value of sensor.kartausb. Just like that:
The only problem left to solve: If you turn off last relay, it stays on even though input_value is 0.
I’m thinking of making yet another automation turning off group of those input_boolean helpers after sensor.kartausb is 0.
No, it should work like this.
The reason is that HA is smart.
As the value of the input_number is 0 and you set it to 0, there is no change, so the automation is not triggered.
So, in the automation that set the input_number, I’d put an additional action