[Solved] Command line binary sensor is not working

I have a command line binary sensor to check for HTTP status code from some of my locally running applications. For example, this is for checking HTTP status code for Grafana:

curl -I http://192.168.86.45:3000 2>/dev/null | head -n 1 | cut -d$' ' -f2

This returns 302, which is a successful HTTP status code. In my binary sensor configuration file I have the following sensor code set up:

- platform: command_line
  command: "curl -I http://192.168.86.45:3000 2>/dev/null | head -n 1 | cut -d$' ' -f2"
  name: "Grafana status"
  value_template: >
    {% if value | int in [200, 301, 302, 303, 304, 307] -%}
      on
    {%- else -%}
      off
    {%- endif %}
  scan_interval: 300
  device_class: connectivity

I tested the code with the template tool in Developer Tools tab, and the if check should work, but the sensor is always reporting Disconnected.

I also tried running the command logged in over SSH, and that works fine.

What is wrong with my code? :frowning:

I managed to solve this by some Googling. This only checks for one specific status code, and not against several types of successful HTTP status codes:

- platform: command_line
  command: 'response=$(curl -LIk 192.168.86.45:3000 -o /dev/null -w ''%{http_code}'' -s); test "$response" -eq 200 && echo "ON" || echo "OFF"'
  name: "Grafana status"
  scan_interval: 300
  device_class: connectivity
  payload_on: "ON"
  payload_off: "OFF"
1 Like