Bit operation with sensor value

A KNX device has a 2 Byte status information. To read this status I use the sensor entity:

sensor:
  - name: "dali_gw_errorstatus"
    state_address: "0/6/13"
    type: 2byte_unsigned

Because this entity can have the status “unkown” I want to check it, before I do the bit masking.

This is my approach:

        {% set gw_status = 0 | int %}
        {% set device_addr = 65535 | int %}
        {% if states('sensor.dali_gw_errorstatus') == 'unavailable' %}
          {% set gw_status = 0 %}
        {% else %}
          {% set gw_status = states('sensor.dali_gw_errorstatus') %}
          {% set device_addr = gw_status|bitwise_and( 0x003F ) %}
        {% endif %}
        {{ gw_status }}
        {{ device_addr }}

Which results in an error: TypeError: unsupported operand type(s) for &: ‘str’ and ‘int’

How to achieve to check against “unknow” sensor value and than do the math operation with this variable?

This template works if I use the integer value instead of the sensor status…

        {% set gw_status = 0 | int %}
        {% set device_addr = 65535 | int %}
        {% if states('sensor.dali_gw_errorstatus') == 'unavailable' %}
          {% set gw_status = 0 %}
        {% else %}
          {% set gw_status = states('sensor.dali_gw_errorstatus') %}
          {% set device_addr = device_addr|bitwise_and( 0x003F ) %}
        {% endif %}
        {{ gw_status }}
        {{ device_addr }}

I think you are using str|bitwise_and(0x003F).
Try casting to int

  {% set gw_status = states('sensor.dali_gw_errorstatus') | int %}`
  {% set device_addr = gw_status|bitwise_and( 0x003F ) %}

Thank you for the response, I got it in the meantime.

The value check must be has_value. I suppose it prevents to cast the 2 Byte value to a string.

        {% set gw_status = 0 | int %}
        {% set device_addr = 0xFFFF | int %}
        {% if has_value('sensor.dali_gw_errorstatus') %}
          {% set gw_status = states('sensor.dali_gw_errorstatus') | int %}
          {% set device_addr = gw_status|bitwise_and( 0x003F ) %}
        {% endif %}
        {{ gw_status }}
        {{ device_addr }}

By the way… farmio, thanks for your work regarding the KNX integration! :+1: