Turning a TV On / Off via Kodi CEC (LibreElec & no Hass device attached)

Didn’t see this one anywhere, sorry if it’s a repeat. My Hass install and Kodi are on seperate machines - so I put this together.

If you have a TV with a Kodi device but not a Hass connected - you can still turn it on / off via Kodi’s CEC connection.

The snippet from my switches.yaml :

  platform: command_line
  switches:
    tv_kodi:
      command_on: ssh root@[LibreElec IP] "echo 'on 0' | cec-client -s"
      command_off: ssh root@[LibreElec IP] "echo 'standby 0' | cec-client -s"
      friendly_name: TV

Your TV may not be device 0, if you think that’s the case - ssh into the Kodi and check with ‘cec-client -l’.

For this to work, of course, ssh keys must be exchanged between the Kodi device and the machine running Hass.

I imagine this will work with OpenElec too, and probably any Kodi install that has ‘cec-client’ installed, ssh enabled, keys exchanged.

There are a whole bunch of codes to choose from, though success seems to vary widely by TV make & model:

http://www.cec-o-matic.com/

Other tips I came accross:

3 Likes

Works on rasplex also, you could add little more if you want it to update when not using HA. Don’t know how often it’ll update, might be too often.

- platform: command_line
  switches:
    tv_rpi:
      command_on: ssh root@[IP] "echo 'on 0' | cec-client -s"
      command_off: ssh root@[IP] "echo 'standby 0' | cec-client -s"
      command_state: ssh root@[IP] "echo 'pow 0' | cec-client -s |grep 'power status:'"
      value_template: '{{ value == "power status: on" }}'
2 Likes

Just an update for some TVs that may not return the TV’s remote control to Kodi after this ‘on’ command:

command_on: ssh root@[LibreElec IP] "echo 'on 0' | cec-client -s"

This is a common enough situation, and stems from CEC limiting itself to one designated controlling device at a time.

To workaround this, change the ‘on’ command to a restart for Kodi - this doesn’t reboot the Kodi device.

Restarting Kodi will trigger a HDMI-CEC message and so bring the TV out of standby. The following can replace your TV ‘on’ command.

command_on: ssh root@[LibreElec IP] "systemctl restart kodi"

If you’re using an animated splash screen for Kodi you’ll get to see that in motion as the TV comes out of standby, which adds a nice little flourish to the event.

I can get this to work no probs all through the terminal.

When I run this in Home Assistant, it asks for the password to osmc in the console window. I’ve swapped SSH keys so I’m not sure why it’s doing this. If I ssh into my kodi from the terminal it doesn’t ask me, just when it’s done through Home Assistant. Any ideas? I’ve spent hours on this.

Is Home Assistant running as a different user? e.g. ‘hass’

Perhaps keys haven’t been exchanged for that user?

Where can i input password for ssh of kodi?

Perhaps a better way would be to use kodi’s own CEC addon than restarting kodi itself:

kodi-send --action="CECActivateSource"