Skip to content

Instantly share code, notes, and snippets.

@tylermenezes
Created September 25, 2017 06:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tylermenezes/cac7e22b15843e463436e41807076176 to your computer and use it in GitHub Desktop.
Save tylermenezes/cac7e22b15843e463436e41807076176 to your computer and use it in GitHub Desktop.
ESP8266 IR Blaster Controller for Home Assistant
import voluptuous as vol
from homeassistant.components.switch import (SwitchDevice, PLATFORM_SCHEMA)
from homeassistant.const import (
STATE_ON, STATE_OFF, STATE_UNKNOWN, CONF_NAME, CONF_FILENAME)
import homeassistant.helpers.config_validation as cv
import struct
import socket
DOMAIN = 'esp8266_blaster'
DEFAULT_NAME = 'ESP8266'
ICON = 'mdi:switch'
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required('ip'): cv.string,
vol.Optional('port', default=31442): cv.positive_int,
vol.Required('off_command'): cv.string,
vol.Required('on_command'): cv.string,
vol.Optional('frequency', default=38): cv.positive_int
})
def setup_platform(hass, config, add_devices, discovery_info=None):
add_devices([Esp8266Switch(config.get('ip'), config.get('port'), config.get('on_command'), config.get('off_command'), config.get('frequency'))])
class Esp8266Switch(SwitchDevice):
def __init__(self, ip, port, on_command, off_command, frequency):
self.ip = ip
self.port = port
self._state = False
self.on_command = on_command
self.off_command = off_command
self.frequency = frequency
@property
def available(self):
return True
@property
def name(self):
return "ESP8266 Switch"
@property
def is_on(self):
return self._state
@property
def state_attributes(self):
return False
def _send(self, command):
command = [int(i) for i in command.split(',')]
commandBytes = list(sum([struct.unpack('2B', struct.pack('H', i)) for i in command], ()))
lenBytes = struct.unpack('2B', struct.pack('H', len(commandBytes)))
packet = (((0, self.frequency) + lenBytes + tuple(commandBytes))[1:])
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(5)
s.connect((self.ip, self.port))
s.send(bytearray(packet))
s.close()
def update(self):
pass
def turn_on(self):
self._send(self.on_command)
self._state = True
def turn_off(self):
self._send(self.off_command)
self._state = False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment