Changed LIRC component so that it just fires events on the bus.

This commit is contained in:
ntouran 2016-05-23 21:26:49 -07:00
parent 4e5b5f2204
commit c1f96aabb0

View file

@ -13,12 +13,13 @@ import threading
import time
import logging
from homeassistant.helpers.entity import Entity
from homeassistant.const import EVENT_HOMEASSISTANT_STOP
REQUIREMENTS = ['python-lirc>=1.2.1']
_LOGGER = logging.getLogger(__name__)
ICON = 'mdi:remote'
EVENT_BUTTON_PRESSED = 'button_pressed'
BUTTON_NAME = 'button_name'
def setup_platform(hass, config, add_devices, discovery_info=None):
@ -31,43 +32,18 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
return False
# blocking=True gives unexpected behavior (multiple responses for 1 press)
# also by not blocking, we allow hass to shut down the thread gracefully
# on exit.
lirc.init('home-assistant', blocking=False)
sensor = LircSensor()
add_devices([sensor])
lirc_interface = LircInterface(hass)
lirc_interface.start()
hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, sensor.stop)
def _stop_lirc(_event):
lirc_interface.stopped.set()
hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, _stop_lirc)
class LircSensor(Entity):
"""Sensor entity for LIRC."""
def __init__(self, *args, **kwargs):
"""Construct a LircSensor entity."""
_LOGGER.info('Initializing LIRC sensor')
Entity.__init__(self, *args, **kwargs)
self.last_key_pressed = ''
self._lirc_interface = LircInterface(self)
self._lirc_interface.start()
@property
def name(self):
"""Name of lirc sensor."""
return 'lirc'
@property
def state(self):
"""State of LIRC sensor."""
return self.last_key_pressed
def update_state(self, new_state):
"""Inform system of update when they occur."""
self.last_key_pressed = new_state
self.update_ha_state()
def stop(self, _event):
"""Kill the helper thread on stop."""
_LOGGER.info('Ending LIRC interface thread')
self._lirc_interface.stopped.set()
return True
class LircInterface(threading.Thread):
@ -79,28 +55,22 @@ class LircInterface(threading.Thread):
around until a non-empty response is obtained from lirc.
"""
def __init__(self, parent):
def __init__(self, hass):
"""Construct a LIRC interface object."""
threading.Thread.__init__(self)
self.stopped = threading.Event()
self._parent = parent
self.hass = hass
def run(self):
"""Main loop of LIRC interface thread."""
import lirc
while not self.stopped.isSet():
code = lirc.nextcode() # list; empty if no buttons pressed
# interpret result from python-lirc
if code:
code = code[0]
else:
code = ''
# update if changed.
if code != self._parent.state:
_LOGGER.info('Got new LIRC code %s', code)
self._parent.update_state(code)
self.hass.bus.fire(EVENT_BUTTON_PRESSED, {BUTTON_NAME: code})
else:
time.sleep(0.1) # avoid high CPU in this thread