Shell Command Switch running "curl" returns an error when pinged device is offline

Hi there,

i am running HASSBIAN 0.60.2 and set up a switch runing shell commands to ping my TV and check if its on or off.

switch:

  • platform: command_line
    television:
    command_on: “sudo irsend SEND_ONCE fernseher KEY_POWER”
    command_off: “sudo irsend SEND_ONCE fernseher KEY_POWER”
    command_state: “sudo /usr/bin/curl -sL -w ‘%{http_code}’ 192.168.178.35 -o /dev/null --max-time 0.3”
    value_template: ‘{{ value == “404” }}’

When the TV is on, it works fine and signals this by setting the switch to on. But when the TV is off, the IP cant be reached and a get a ton of error messages in the log saying:

Command failed: sudo /usr/bin/curl -sL -w ‘%{http_code}’ 192.168.178.35 -o /dev/null --max-time 0.3
12:21 components/switch/command_line.py (ERROR)
Command failed: sudo /usr/bin/curl -sL -w ‘%{http_code}’ 192.168.178.35 -o /dev/null --max-time 0.3
12:20 components/switch/command_line.py (ERROR)
Command failed: sudo /usr/bin/curl -sL -w ‘%{http_code}’ 192.168.178.35 -o /dev/null --max-time 0.3
12:20 components/switch/command_line.py (ERROR)
Command failed: sudo /usr/bin/curl -sL -w ‘%{http_code}’ 192.168.178.35 -o /dev/null --max-time 0.3
12:19 components/switch/command_line.py (ERROR)
Command failed: sudo /usr/bin/curl -sL -w ‘%{http_code}’ 192.168.178.35 -o /dev/null --max-time 0.3
12:19 components/switch/command_line.py (ERROR)

As soon as the TV is on and can be reached, the shell command works as intended. Is there a way to have curl not fail but rather just return something like “timeout” or “0”?

If you’re just checking if the TV is on or off, why not use ping? I suspect if you can’t curl it you can’t ping it?
if I’m wrong, what’s the value of your sensor when the TV is off? Maybe you could create a template sensor out of it which returns on when the value is expected (and then whatever is not expected, including unknown / error) would return off?

the shell command will return 000 if the tv is off and 404 when its online, thats why i have value_template: ‘{{ value == “404” }}’ for “status on”.

i have to admit that i’m a dummie for templates. have read the documentation 2 times, but havent figured it out yet. could you help? thank you!

Have you tried to set a default value to see if that fixes it?
value_template: ‘{{ (value | default(000) ) == “404” }}

Don’t think it’ll fix your log errors, but might fix your state issue…

Here’s how I deal with that problem…
Instead of calling curl directly, I call a bash script that contains the curl command.
Then, inside the bash script, I can evaluate the response, and return an error value (in this case zero).

TEMP=$(curl -s --connect-timeout 5 -X GET http://192.168.1.96:8000/temperature)
if [[ -z $TEMP ]]; then
  echo 0
else
  echo "$TEMP"
fi