Fix init of TransmissionData (#20817)

* Fix init of TransmissionData

 Fix in order to avoid null object on first update of Turtle Mode Switch

* Using async functionality

* Various fix

* HoundBot fix

* Removed some async calls

* Fix compilation Error

* Fix

* PEP fix
This commit is contained in:
MatteGary 2019-02-08 18:15:14 +01:00 committed by Martin Hjelmare
parent 6a78ad8ab6
commit faf7ae29b1
3 changed files with 59 additions and 16 deletions

View File

@ -19,6 +19,7 @@ from homeassistant.const import (
CONF_SCAN_INTERVAL CONF_SCAN_INTERVAL
) )
from homeassistant.helpers import discovery, config_validation as cv from homeassistant.helpers import discovery, config_validation as cv
from homeassistant.helpers.dispatcher import dispatcher_send
from homeassistant.helpers.event import track_time_interval from homeassistant.helpers.event import track_time_interval
@ -26,6 +27,7 @@ REQUIREMENTS = ['transmissionrpc==0.11']
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
DOMAIN = 'transmission' DOMAIN = 'transmission'
DATA_UPDATED = 'transmission_data_updated'
DATA_TRANSMISSION = 'data_transmission' DATA_TRANSMISSION = 'data_transmission'
DEFAULT_NAME = 'Transmission' DEFAULT_NAME = 'Transmission'
@ -83,6 +85,8 @@ def setup(hass, config):
tm_data = hass.data[DATA_TRANSMISSION] = TransmissionData( tm_data = hass.data[DATA_TRANSMISSION] = TransmissionData(
hass, config, api) hass, config, api)
tm_data.update()
tm_data.init_torrent_list() tm_data.init_torrent_list()
def refresh(event_time): def refresh(event_time):
@ -94,10 +98,12 @@ def setup(hass, config):
sensorconfig = { sensorconfig = {
'sensors': config[DOMAIN][CONF_MONITORED_CONDITIONS], 'sensors': config[DOMAIN][CONF_MONITORED_CONDITIONS],
'client_name': config[DOMAIN][CONF_NAME]} 'client_name': config[DOMAIN][CONF_NAME]}
discovery.load_platform(hass, 'sensor', DOMAIN, sensorconfig, config) discovery.load_platform(hass, 'sensor', DOMAIN, sensorconfig, config)
if config[DOMAIN][TURTLE_MODE]: if config[DOMAIN][TURTLE_MODE]:
discovery.load_platform(hass, 'switch', DOMAIN, sensorconfig, config) discovery.load_platform(hass, 'switch', DOMAIN, sensorconfig, config)
return True return True
@ -127,6 +133,8 @@ class TransmissionData:
self.check_completed_torrent() self.check_completed_torrent()
self.check_started_torrent() self.check_started_torrent()
dispatcher_send(self.hass, DATA_UPDATED)
_LOGGER.debug("Torrent Data updated") _LOGGER.debug("Torrent Data updated")
self.available = True self.available = True
except TransmissionError: except TransmissionError:
@ -189,4 +197,7 @@ class TransmissionData:
def get_alt_speed_enabled(self): def get_alt_speed_enabled(self):
"""Get the alternative speed flag.""" """Get the alternative speed flag."""
if self.session is None:
return None
return self.session.alt_speed_enabled return self.session.alt_speed_enabled

View File

@ -9,10 +9,11 @@ from datetime import timedelta
import logging import logging
from homeassistant.components.transmission import ( from homeassistant.components.transmission import (
DATA_TRANSMISSION, SENSOR_TYPES) DATA_TRANSMISSION, SENSOR_TYPES, DATA_UPDATED)
from homeassistant.const import STATE_IDLE from homeassistant.const import STATE_IDLE
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity import Entity from homeassistant.helpers.entity import Entity
from homeassistant.util import Throttle
DEPENDENCIES = ['transmission'] DEPENDENCIES = ['transmission']
@ -23,7 +24,11 @@ DEFAULT_NAME = 'Transmission'
SCAN_INTERVAL = timedelta(seconds=120) SCAN_INTERVAL = timedelta(seconds=120)
def setup_platform(hass, config, add_entities, discovery_info=None): async def async_setup_platform(
hass,
config,
async_add_entities,
discovery_info=None):
"""Set up the Transmission sensors.""" """Set up the Transmission sensors."""
if discovery_info is None: if discovery_info is None:
return return
@ -41,7 +46,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
SENSOR_TYPES[sensor_type][0], SENSOR_TYPES[sensor_type][0],
SENSOR_TYPES[sensor_type][1])) SENSOR_TYPES[sensor_type][1]))
add_entities(dev, True) async_add_entities(dev, True)
class TransmissionSensor(Entity): class TransmissionSensor(Entity):
@ -73,6 +78,11 @@ class TransmissionSensor(Entity):
"""Return the state of the sensor.""" """Return the state of the sensor."""
return self._state return self._state
@property
def should_poll(self):
"""Return the polling requirement for this sensor."""
return False
@property @property
def unit_of_measurement(self): def unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any.""" """Return the unit of measurement of this entity, if any."""
@ -83,10 +93,18 @@ class TransmissionSensor(Entity):
"""Could the device be accessed during the last update call.""" """Could the device be accessed during the last update call."""
return self._transmission_api.available return self._transmission_api.available
@Throttle(SCAN_INTERVAL) async def async_added_to_hass(self):
"""Handle entity which will be added."""
async_dispatcher_connect(
self.hass, DATA_UPDATED, self._schedule_immediate_update
)
@callback
def _schedule_immediate_update(self):
self.async_schedule_update_ha_state(True)
def update(self): def update(self):
"""Get the latest data from Transmission and updates the state.""" """Get the latest data from Transmission and updates the state."""
self._transmission_api.update()
self._data = self._transmission_api.data self._data = self._transmission_api.data
if self.type == 'completed_torrents': if self.type == 'completed_torrents':

View File

@ -4,16 +4,15 @@ Support for setting the Transmission BitTorrent client Turtle Mode.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.transmission/ https://home-assistant.io/components/switch.transmission/
""" """
from datetime import timedelta
import logging import logging
from homeassistant.components.transmission import ( from homeassistant.components.transmission import (
DATA_TRANSMISSION) DATA_TRANSMISSION, DATA_UPDATED)
from homeassistant.const import ( from homeassistant.const import (
STATE_OFF, STATE_ON) STATE_OFF, STATE_ON)
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity import ToggleEntity from homeassistant.helpers.entity import ToggleEntity
from homeassistant.util import Throttle
DEPENDENCIES = ['transmission'] DEPENDENCIES = ['transmission']
@ -21,10 +20,12 @@ _LOGGING = logging.getLogger(__name__)
DEFAULT_NAME = 'Transmission Turtle Mode' DEFAULT_NAME = 'Transmission Turtle Mode'
SCAN_INTERVAL = timedelta(seconds=120)
async def async_setup_platform(
def setup_platform(hass, config, add_entities, discovery_info=None): hass,
config,
async_add_entities,
discovery_info=None):
"""Set up the Transmission switch.""" """Set up the Transmission switch."""
if discovery_info is None: if discovery_info is None:
return return
@ -33,7 +34,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
transmission_api = hass.data[component_name] transmission_api = hass.data[component_name]
name = discovery_info['client_name'] name = discovery_info['client_name']
add_entities([TransmissionSwitch(transmission_api, name)], True) async_add_entities([TransmissionSwitch(transmission_api, name)], True)
class TransmissionSwitch(ToggleEntity): class TransmissionSwitch(ToggleEntity):
@ -58,7 +59,7 @@ class TransmissionSwitch(ToggleEntity):
@property @property
def should_poll(self): def should_poll(self):
"""Poll for status regularly.""" """Poll for status regularly."""
return True return False
@property @property
def is_on(self): def is_on(self):
@ -75,8 +76,21 @@ class TransmissionSwitch(ToggleEntity):
_LOGGING.debug("Turning Turtle Mode of Transmission off") _LOGGING.debug("Turning Turtle Mode of Transmission off")
self.transmission_client.set_alt_speed_enabled(False) self.transmission_client.set_alt_speed_enabled(False)
@Throttle(SCAN_INTERVAL) async def async_added_to_hass(self):
"""Handle entity which will be added."""
async_dispatcher_connect(
self.hass, DATA_UPDATED, self._schedule_immediate_update
)
@callback
def _schedule_immediate_update(self):
self.async_schedule_update_ha_state(True)
def update(self): def update(self):
"""Get the latest data from Transmission and updates the state.""" """Get the latest data from Transmission and updates the state."""
active = self.transmission_client.get_alt_speed_enabled() active = self.transmission_client.get_alt_speed_enabled()
if active is None:
return
self._state = STATE_ON if active else STATE_OFF self._state = STATE_ON if active else STATE_OFF