Automation calculate decimal from binary

I am trying to send a decimal value through modbus TCP.
I have a working automation that sends a fixed decimal value.
I have a working template setup to calculate from binary to decimal
What I want to do is to do the calculation in automation value and use actual hour.
Minute shall always be 0
priority shall always be 2
enabled shall always be 1

Below is working in Dev tools template:

{# Define the values #}
{% set minutes = 0 %}  {# Bits 0-7 #}
{% set hour = 12 %}      {# Bits 8-12 #}
{% set priority = 2 %}  {# Bits 13-14 #}
{% set enabled = 1 %}   {# Bit 15 #}

{# Convert each value to its corresponding bit position #}
{% set binary_minutes = "{0:08b}".format(minutes) %}
{% set binary_hour = "{0:05b}".format(hour) %}
{% set binary_priority = "{0:02b}".format(priority) %}
{% set binary_enabled = "{0:01b}".format(enabled) %}

{# Combine the binary strings in the correct order: Bit15 down to Bit0 #}
{% set binary_string = binary_enabled + binary_priority + binary_hour + binary_minutes %}

{# Convert the combined binary string to a decimal number #}
{% set decimal_value = binary_string | int(base=2) %}

Binary: {{ binary_string  |batch(4)|map('join')|join(' ') }} 
Decimal: {{ decimal_value }}

gives output:

Binary: 1100 1100 0000 0000 
Decimal: 52224

below is not working but maybe you can get helped by how I think it would work :slight_smile:

action: modbus.write_register
data_template:
  hub: modbus
  slave: 1
  address: 123
  value_template: ->
  
  {% set binary_minutes = "{0:08b}".format(minutes) %}
  {% set binary_hour = "{0:05b}".format(hour) %}
  {% set binary_priority = "{0:02b}".format(priority) %}
  {% set binary_enabled = "{0:01b}".format(enabled) %}

  {% set binary_string = binary_enabled + binary_priority + binary_hour + binary_minutes %}

  {% set decimal_value = binary_string | int(base=2) %}
  value=decimal_value

reply to myself

  value: >

    {% set binary_minutes = "{0:08b}".format(0) %}
    {% set binary_hour = "{0:05b}".format(now().hour) %}
    {% set binary_priority = "{0:02b}".format(2) %}
    {% set binary_enabled = "{0:01b}".format(1) %}

    {% set binary_string = binary_enabled + binary_priority + binary_hour + binary_minutes %} {% set decimal_value = binary_string | int(base=2) %}

    [{{ decimal_value }},5888]
1 Like