Command Line scan interval wipes out sensor state

Hey everyone, i’ve got a command line sensor setup that essentially calls a script, which sends a telnet command to an HDMI switcher and converts the returned value to a string on which input is in use. This was working fine for the past few years, but Ive noticed it has stopped working recently (could be anytime in the last 6 months).

When I update the sensor manually using the homeassistant.update_entity service, it works and I get the value back that is expected.

Then when the command line scan interval runs (defaulted at 60 seconds), it wipes out the state leaving it blank.

Here’s my command line code:

command_line:
  - sensor:
      name: Matrix Living Room Input
      unique_id: somenumbers
      command: !secret matrix_get_input_1

That calls this from the secrets file (IP blocked out):

matrix_get_input_1: '/config/scripts/hdmi_matrix/get_input.sh x.x.x.x 23 1'

And here’s the contents of that script - get_input.sh:

#! /bin/bash

host="$1"
port="$2"
output="$3"

result=`{ echo "get out$output vs"; sleep 1; } | telnet $host $port 2>/dev/null | grep OUT | awk '{print $3}'`

case "$result" in
  IN1)
    echo "Shield"
    ;;
  IN2)
    echo "PS5"
    ;;
  IN3)
    echo "Switch"
    ;;
  IN4)
    echo "PC"
    ;;
esac

As mentioned, when i call the script manually from the command line it works every time. When I use the update service in HA, it works too every time. When the sensor runs on its default scan interval, the resulting state is wiped away. Any suggestions?

To help debug it, add a default clause to the case statement and return the $result. Because right now if an unexpected value is returned the script will return a blank. Given this is the behavior you are seeing (blank state) my guess is it’s returning an unexpected value.

Great suggestion! I added in a default and it does in fact return the default value.
I set the default value to show what the actual response is and it appears to be sending back double the data.

Expected result: IN1
Actual result: IN1 IN1

But it’s odd to me that this only happens with the default interval, when manually run, it gets the single result and parses normally. Still, that’s progress!

I’m still unsure why i get duplicate results, so i’ve added this under the results line to remove the dupe:

result=`{ echo "get out$output vs"; sleep 1; } | telnet $host $port 2>/dev/null | grep OUT | awk '{print $3}'`
result=`echo $result | cut -d ' ' -f1`

This seems to work. One of the commands (echo, grep, awk) are outputing twice the results only when HA calls it. :man_shrugging:

1 Like