Convert status code to input_text

I have a Z-Wave device that sends a status code, which I have to translate in human language.

What is the best way to do this? Using a template/sensor?

Example

sensor.device sends 3722
translated to "string1"
sensor.device sends 33
translated to "string2"
...

The list is quiet big.

You can do it with a template sensor using a dictionary:

template:
  - sensor:
      - name: "Device sensor"
        state: >
          {% set c = states('sensor.device') %}
          {% set d = {
          '3722': 'string1',
          '33': 'string2' } 
          %}
          {{ d.get(c) }}

That fits perfectly.

Is there a case if “nothing matches”?

Also I need to check for an input boolean and if that is true and the case is 636, then the return value should be changed to something else instead of the case above.

Sure, for just one possible substitution you can add a default and an if statement:

template:
  - sensor:
      - name: "Device sensor"
        state: >
          {% set d = {
          '3722': 'string1',
          '33': 'string2',
          '636': 'stringX' } 
          %}
          {% set e = d.get( states('sensor.device'), 'Unknown Status Code') %}
          {% set f = (is_state('input_boolean.XXXX', 'on') and e == 'stringX') %}
          {{ iif(f, 'stringXB', e)}}

EDIT: Incorporated Taras’ suggestion about setting default.

1 Like

A dictionary’s get method can accept a second argument that represent what to report when the specified key does not exist in the dictionary.

In the following example, if the value of states('sensor.device') does not exist in the dictionary, the get method will report unknown.

template:
  - sensor:
      - name: "Device sensor"
        state: "{{ {'3722': 'string1', '33': 'string2'}.get(states('sensor.device'), 'unknown') }}"
                                                                                      ^^^^^^^
                                                                             This will be the result 
                                                                         if the value of sensor.device 
                                                                        is not found in the dictionary
2 Likes

Thanks both of you, I will try that.