Skip to content

Instantly share code, notes, and snippets.

@fake666
Last active June 19, 2022 14:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fake666/a3fec3c686ccc343b7f76cc5286e487b to your computer and use it in GitHub Desktop.
Save fake666/a3fec3c686ccc343b7f76cc5286e487b to your computer and use it in GitHub Desktop.
a simple homeassistant component for using irtrans IR blasters. place in custom_components/switch/ - simple as i only need it to fire up my webos tv, i can then control it using the separate binding.
"""
Support for irtrans IP devices with irdb
See: http://www.irtrans.de/
a simple homeassistant component for using irtrans IR blasters. place in custom_components/switch/
simple as i only need it to fire up my webos tv, i can then control it using the separate component.
usage:
switch:
platform: irtrans
switches:
mytv:
host: 192.168.0.22
remote: 'my_remote'
command_on: 'power_on'
command_off: 'power_off'
"""
import logging
import socket
import voluptuous as vol
from homeassistant.components.switch import (
ENTITY_ID_FORMAT, PLATFORM_SCHEMA, SwitchEntity)
from homeassistant.const import (
CONF_NAME, CONF_HOST, CONF_PORT, CONF_COMMAND_ON, CONF_COMMAND_OFF, CONF_SWITCHES)
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
DOMAIN = "irtrans"
DEFAULT_PORT = 21000
SWITCH_SCHEMA = vol.Schema({
vol.Required('remote'): cv.string,
vol.Required(CONF_COMMAND_ON): cv.string,
vol.Required(CONF_COMMAND_OFF): cv.string,
vol.Required(CONF_HOST): cv.string,
vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port,
vol.Optional(CONF_NAME): cv.string,
})
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_SWITCHES): vol.Schema({cv.slug: SWITCH_SCHEMA}),
})
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the irtrans component."""
devices = config.get(CONF_SWITCHES, {})
switches = []
for object_id, device_config in devices.items():
switches.append(
IrTransSwitch(
hass,
object_id,
device_config.get(CONF_HOST),
device_config.get('remote'),
device_config.get(CONF_COMMAND_ON),
device_config.get(CONF_COMMAND_OFF),
device_config.get(CONF_PORT),
device_config.get(CONF_NAME, object_id),
)
)
if not switches:
_LOGGER.error("No switches added")
return
add_devices(switches);
class IrTransSwitch(SwitchEntity):
"""Representation of a switch that can be toggled using irtrans commands."""
def __init__(self, hass, object_id, host, remote, command_on, command_off, port, friendly_name):
"""Initialize the switch."""
self._hass = hass
self.entity_id = ENTITY_ID_FORMAT.format(object_id)
self._host = host
self._port = port
self._remote = remote
self._command_on = command_on
self._command_off = command_off
self._name = friendly_name
@property
def name(self):
"""Return the name of the switch."""
return self._name
@property
def should_poll(self):
""" no polling """
return False
@property
def is_on(self):
""" never on """
return False
@property
def assumed_state(self):
""" always on """
return True
def _irtrans_command(self, command):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((self._host, self._port))
s.sendall(b"ASCI")
cmd = ("Asnd %s,%s\r\n" % (self._remote, command))
s.sendall(cmd.encode('ascii'))
data = s.recv(1024)
s.close()
ret = data.decode('ascii').strip()
if not 'RESULT OK' in ret:
_LOGGER.error('error returned for command "%s": "%s"', command, ret)
except IOError as error:
_LOGGER.error(
'Command "%s" failed with exception: %s',
command, repr(error))
def turn_on(self, **kwargs):
""" turn the device on. """
ret = self._irtrans_command(self._command_on)
def turn_off(self, **kwargs):
""" turn the device off. """
ret = self._irtrans_command(self._command_off)
@sesma24
Copy link

sesma24 commented Feb 27, 2020

Can I use somethig like that with openhab?

@fake666
Copy link
Author

fake666 commented Feb 29, 2020

Can I use somethig like that with openhab?

sure, there's an official binding for irtrans devices: https://www.openhab.org/addons/bindings/irtrans/

@sesma24
Copy link

sesma24 commented Feb 29, 2020

Sorry for this question, but I'm a begineer, what should I change in the code so that it works with openhab without problem? Only the lines from 24 to 28?

@fake666
Copy link
Author

fake666 commented Feb 29, 2020

you should really use the openhab binding for openhab, this script is only for homeassistant.

the network protocol for irtrans is pretty simple and well documented though, if you want to write your own openhab binding for any reason.

@PITP2
Copy link

PITP2 commented Feb 9, 2021

Hi,
thank you for this script :-)

Could you help me to understand your code.

Do you use an irtrans with db ?
If it's the case, in the code below, you use the name registered in the db of the irtrans to send the command ?

usage:
switch:
platform: irtrans
switches:
mytv:
host: 192.168.0.22
remote: 'my_remote'
command_on: 'power_on'
command_off: 'power_off'

If I understood I have to register the IR code in the db and labelled the code "vol_up" and modified your code like that

usage:
switch:
platform: irtrans
switches:
mytv:
host: 192.168.0.22
remote: 'my_remote'
command_on: 'vol_up'

@fake666
Copy link
Author

fake666 commented Feb 10, 2021

Hi PITP2,

If I understood I have to register the IR code in the db and labelled the code "vol_up" and modified your code like that

usage:
switch:
platform: irtrans
switches:
mytv:
host: 192.168.0.22
remote: 'my_remote'
command_on: 'vol_up'

this would send the following to the irtrans device when you call the switch.turn_on service with this entity:

ASCI
ASnd my_remote,vol_up

see lines 113 and 114 of the script. you can easily test this using netcat, unrelated to homeassistant and this component. if that works, your database command name and remote name are correct, if not, you might get a more or less helpful error message back ;)

good luck!

@PITP2
Copy link

PITP2 commented Feb 10, 2021

Thank you for your reply.

So I put the file into /config/custom_components/irtrans/switch.py

I added irtrans: in my configuration.yaml

I reloaded "scripts"

But I have an error message : Component error: irtrans - Integration 'irtrans' not found.

Where I did a mistake ?

@fake666
Copy link
Author

fake666 commented Feb 10, 2021

I added irtrans: in my configuration.yaml

you will just need to add the switch with the 'platform' irtrans, as you stated above. a line 'itrans:' is not required.

after copying the file where you copied it, adding the switch and re-starting HA, you should see a line in the log:

[homeassistant.loader] You are using a custom integration for irtrans which has not been tested by Home Assistant. This component might cause stability problems, be sure to disable it if you experience issues with Home Assistant.

@PITP2
Copy link

PITP2 commented Feb 10, 2021

Thank you for your help :-)

I remove the "irtrans:" and added in the configuration.yaml

########## HIKVISION ###########
switch:

  • platform: hikvisioncam
    host: 192.168.178.9
    username: 'xxx'
    password: 'xxxxxx'
  • platform: irtrans
    switches:
    mytv:
    host: 192.168.0.22
    remote: 'my_remote'
    command_on: 'vol_up'

but I always have the error message :

image

@fake666
Copy link
Author

fake666 commented Feb 10, 2021

sorry.. i don't know why this happens. it works for me (TM) ;-) have you checked your logfile?

@fake666
Copy link
Author

fake666 commented Feb 10, 2021

this is what i have in my config. best to use the code formatting here, as to avoid the markdown magic formatting ;)

switch:
  - platform: irtrans
    switches:
      lgtv:
        host: 192.168.168.192
        remote: 'lgtv_new'
        command_on: 'power'
        command_off: 'ignored'

@fake666
Copy link
Author

fake666 commented Feb 10, 2021

come to think of it, command_off is a required parameter ;) i used the lg tv integration to switch off the tv, so i just set a command that is unknown to the irtrans and ignore the error ;)

@PITP2
Copy link

PITP2 commented Feb 10, 2021

I tried to copy past your code in my configuration.yaml and I always have the error

It's really strange

@PITP2
Copy link

PITP2 commented Feb 10, 2021

image

@PITP2
Copy link

PITP2 commented Feb 10, 2021

image

@PITP2
Copy link

PITP2 commented Feb 12, 2021

Hi,

I tried again and again and I always have this issue.
It could be a problem of version ?
My sever has the last software version of hass.
It's the same for you ?

@fake666
Copy link
Author

fake666 commented Feb 12, 2021

Do any other custom components work in your setup? I don't know about hass, i use homeassistant core installed with pip/virtualenv.

@PITP2
Copy link

PITP2 commented Feb 12, 2021

you're a master of hass if you use homeassistant core :-)

Yes I use HACS and he's in the same location
image

Always the same error message
Platform error switch.irtrans - Integration 'irtrans' not found.

@fake666
Copy link
Author

fake666 commented Feb 12, 2021

sorry, i'm afraid i can't help you any further.. i don't even use my irtrans thingy anymore; my new tv has wake-on-lan. good luck figuring it out though! :)

@fake666
Copy link
Author

fake666 commented Jun 19, 2022

as i now need the device again (for an old AC this time) i discovered that i can also simply trigger IR commands via http, so i'm now using rest_command much like described here:

https://community.home-assistant.io/t/how-to-create-a-card-with-buttons-that-execute-trigger-urls/193694/6

the URL i call on the irtrans for the above example is:

http://<irtrans ip>/send.htm?remote=lgtv_new&command=power

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment