From 0254cf74d14d0db336cb3a3ef10c67d5e620aec7 Mon Sep 17 00:00:00 2001 From: MatteGary Date: Wed, 12 Dec 2018 18:53:45 +0100 Subject: [PATCH 01/21] New Transmission component and interaction First commit for New Transmission component and interaction --- .../components/sensor/transmission.py | 72 +++----- homeassistant/components/transmission.py | 167 ++++++++++++++++++ 2 files changed, 191 insertions(+), 48 deletions(-) create mode 100644 homeassistant/components/transmission.py diff --git a/homeassistant/components/sensor/transmission.py b/homeassistant/components/sensor/transmission.py index a669db0e5be887..ff0d081add27a3 100644 --- a/homeassistant/components/sensor/transmission.py +++ b/homeassistant/components/sensor/transmission.py @@ -18,7 +18,9 @@ from homeassistant.util import Throttle from homeassistant.exceptions import PlatformNotReady -REQUIREMENTS = ['transmissionrpc==0.11'] +#REQUIREMENTS = ['transmissionrpc==0.11'] +DEPENDENCIES = ['transmission'] +DATA_TRANSMISSION = 'TRANSMISSION' _LOGGER = logging.getLogger(__name__) @@ -32,13 +34,15 @@ 'paused_torrents': ['Paused Torrents', None], 'total_torrents': ['Total Torrents', None], 'upload_speed': ['Up Speed', 'MB/s'], + 'completed_torrents': ['Completed Torrents', None], + 'started_torrents': ['Started Torrents', None], } SCAN_INTERVAL = timedelta(minutes=2) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_HOST): cv.string, - vol.Optional(CONF_MONITORED_VARIABLES, default=['torrents']): + vol.Optional(CONF_MONITORED_VARIABLES): vol.All(cv.ensure_list, [vol.In(SENSOR_TYPES)]), vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_PASSWORD): cv.string, @@ -49,31 +53,16 @@ def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Transmission sensors.""" - import transmissionrpc - from transmissionrpc.error import TransmissionError - - name = config.get(CONF_NAME) - host = config.get(CONF_HOST) - username = config.get(CONF_USERNAME) - password = config.get(CONF_PASSWORD) - port = config.get(CONF_PORT) - - try: - transmission = transmissionrpc.Client( - host, port=port, user=username, password=password) - transmission_api = TransmissionData(transmission) - except TransmissionError as error: - if str(error).find("401: Unauthorized"): - _LOGGER.error("Credentials for Transmission client are not valid") - return - - _LOGGER.warning( - "Unable to connect to Transmission client: %s:%s", host, port) - raise PlatformNotReady + #import transmissionrpc + #from transmissionrpc.error import TransmissionError + + transmission_api = hass.data[DATA_TRANSMISSION]; + monitored_variables = discovery_info['sensors'] + name = discovery_info['client_name'] dev = [] - for variable in config[CONF_MONITORED_VARIABLES]: - dev.append(TransmissionSensor(variable, transmission_api, name)) + for variable in monitored_variables: + dev.append(TransmissionSensor(variable, transmission_api, name, hass)) add_entities(dev, True) @@ -81,7 +70,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None): class TransmissionSensor(Entity): """Representation of a Transmission sensor.""" - def __init__(self, sensor_type, transmission_api, client_name): + def __init__(self, sensor_type, transmission_api, client_name, hass): """Initialize the sensor.""" self._name = SENSOR_TYPES[sensor_type][0] self._state = None @@ -90,6 +79,8 @@ def __init__(self, sensor_type, transmission_api, client_name): self._data = None self.client_name = client_name self.type = sensor_type + self.started_torrents = [] + self.first_run = True @property def name(self): @@ -116,6 +107,13 @@ def update(self): self._transmission_api.update() self._data = self._transmission_api.data + if self.type == 'completed_torrents': + self._state = self._transmission_api.getCompletedTorrentCount() + elif self.type == 'started_torrents': + self._state = self._transmission_api.getStartedTorrentCount() + + self.first_run = False + if self.type == 'current_status': if self._data: upload = self._data.uploadSpeed @@ -146,25 +144,3 @@ def update(self): self._state = self._data.pausedTorrentCount elif self.type == 'total_torrents': self._state = self._data.torrentCount - - -class TransmissionData: - """Get the latest data and update the states.""" - - def __init__(self, api): - """Initialize the Transmission data object.""" - self.data = None - self.available = True - self._api = api - - @Throttle(SCAN_INTERVAL) - def update(self): - """Get the latest data from Transmission instance.""" - from transmissionrpc.error import TransmissionError - - try: - self.data = self._api.session_stats() - self.available = True - except TransmissionError: - self.available = False - _LOGGER.error("Unable to connect to Transmission client") diff --git a/homeassistant/components/transmission.py b/homeassistant/components/transmission.py new file mode 100644 index 00000000000000..997732c48726ff --- /dev/null +++ b/homeassistant/components/transmission.py @@ -0,0 +1,167 @@ +""" +Component for monitoring the Transmission BitTorrent client API. + +For more details about this component, please refer to the documentation at +https://home-assistant.io/components/transmission/ +""" +from datetime import timedelta +import logging +import voluptuous as vol +import homeassistant.helpers.config_validation as cv +from homeassistant.util import Throttle +from homeassistant.exceptions import PlatformNotReady +from homeassistant.helpers.event import track_time_interval +from homeassistant.helpers.discovery import load_platform +from homeassistant.const import (CONF_HOST, CONF_PASSWORD, CONF_NAME, + CONF_PORT, CONF_USERNAME, CONF_MONITORED_VARIABLES) + +REQUIREMENTS = ['transmissionrpc==0.11'] +_LOGGER = logging.getLogger(__name__) + +DOMAIN = 'transmission' +DATA_TRANSMISSION = 'TRANSMISSION' + +DEFAULT_NAME = 'Transmission' +DEFAULT_PORT = 9091 + +SENSOR_TYPES = { + 'active_torrents': ['Active Torrents', None], + 'current_status': ['Status', None], + 'download_speed': ['Down Speed', 'MB/s'], + 'paused_torrents': ['Paused Torrents', None], + 'total_torrents': ['Total Torrents', None], + 'upload_speed': ['Up Speed', 'MB/s'], + 'completed_torrents': ['Completed Torrents', None], + 'started_torrents': ['Started Torrents', None], +} + +CONFIG_SCHEMA = vol.Schema({ + DOMAIN: vol.Schema({ + vol.Required(CONF_HOST): cv.string, + vol.Required(CONF_PASSWORD): cv.string, + vol.Required(CONF_USERNAME): cv.string, + vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, + vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, + vol.Optional(CONF_MONITORED_VARIABLES, default=['current_status']): + vol.All(cv.ensure_list, [vol.In(SENSOR_TYPES)]), + }) +}, extra=vol.ALLOW_EXTRA) + +SCAN_INTERVAL = timedelta(minutes=2) + + +def setup(hass,config): + hass.data[DATA_TRANSMISSION] = TransmissionData(hass, config) + + def refresh(event_time): + hass.data[DATA_TRANSMISSION].update() + + track_time_interval(hass, refresh, SCAN_INTERVAL) + + sensorconfig = {'sensors': config[DOMAIN].get(CONF_MONITORED_VARIABLES) , 'client_name' : config[DOMAIN].get(CONF_NAME)} + load_platform(hass, 'sensor', DOMAIN, sensorconfig) + + _LOGGER.info("Transmission component setup completed.") + return True + +class TransmissionData: + """Get the latest data and update the states.""" + + def __init__(self, hass, config): + import transmissionrpc + from transmissionrpc.error import TransmissionError + try: + """Initialize the Transmission RPC API""" + name = config[DOMAIN].get(CONF_NAME) + host = config[DOMAIN].get(CONF_HOST) + username = config[DOMAIN].get(CONF_USERNAME) + password = config[DOMAIN].get(CONF_PASSWORD) + port = config[DOMAIN].get(CONF_PORT) + + api = transmissionrpc.Client( + host, port=port, user=username, password=password) + + """Initialize the Transmission data object.""" + self.data = None + self.torrents = None + self.available = True + self._api = api + self.completed_torrents = [] + self.started_torrents = [] + self.initTorrentList() + self.hass = hass + + except TransmissionError as error: + if str(error).find("401: Unauthorized"): + _LOGGER.error("Credentials for Transmission client are not valid") + return + + _LOGGER.warning( + "Unable to connect to Transmission client: %s:%s", host, port) + raise PlatformNotReady + + @Throttle(SCAN_INTERVAL) + def update(self): + """Get the latest data from Transmission instance.""" + from transmissionrpc.error import TransmissionError + + try: + self.data = self._api.session_stats() + self.torrents = self._api.get_torrents() + + self.checkCompletedTorrent() + self.checkStartedTorrent() + + _LOGGER.info("Torrent Data updated") + self.available = True + except TransmissionError: + self.available = False + _LOGGER.error("Unable to connect to Transmission client") + + def initTorrentList(self): + self.torrents = self._api.get_torrents() + self.completed_torrents = [ + x.name for x in self.torrents if x.status == "seeding"] + self.started_torrents = [ + x.name for x in self.torrents if x.status == "downloading"] + + def checkCompletedTorrent(self): + """Get completed torrent functionality""" + actual_torrents = self.torrents + actual_completed_torrents = [ + var.name for var in actual_torrents if var.status == "seeding"] + + tmp_completed_torrents = list( + set(actual_completed_torrents).difference( + self.completed_torrents)) + if tmp_completed_torrents: + for var in tmp_completed_torrents: + _LOGGER.info("Completed Torrent found") + self.hass.bus.fire( + 'transmission_downloaded_torrent', { + 'name': var}) + + self.completed_torrents = actual_completed_torrents + + def checkStartedTorrent(self): + """Get started torrent functionality""" + actual_torrents = self.torrents + actual_started_torrents = [ + var.name for var + in actual_torrents if var.status == "downloading"] + + tmp_started_torrents = list( + set(actual_started_torrents).difference( + self.started_torrents)) + if tmp_started_torrents: + for var in tmp_started_torrents: + self.hass.bus.fire( + 'transmission_started_torrent', { + 'name': var}) + self.started_torrents = actual_started_torrents + + def getStartedTorrentCount(self): + return len(self.started_torrents) + + def getCompletedTorrentCount(self): + return len(self.completed_torrents) From 2d5ce74ececef8d6e8fe258645167b9e4b1c2d6b Mon Sep 17 00:00:00 2001 From: MatteGary Date: Wed, 12 Dec 2018 22:11:51 +0100 Subject: [PATCH 02/21] Fix commit --- .../components/sensor/transmission.py | 5 +--- homeassistant/components/transmission.py | 25 +++++++++++-------- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/homeassistant/components/sensor/transmission.py b/homeassistant/components/sensor/transmission.py index ff0d081add27a3..b75e968657ba94 100644 --- a/homeassistant/components/sensor/transmission.py +++ b/homeassistant/components/sensor/transmission.py @@ -18,7 +18,6 @@ from homeassistant.util import Throttle from homeassistant.exceptions import PlatformNotReady -#REQUIREMENTS = ['transmissionrpc==0.11'] DEPENDENCIES = ['transmission'] DATA_TRANSMISSION = 'TRANSMISSION' @@ -53,10 +52,8 @@ def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Transmission sensors.""" - #import transmissionrpc - #from transmissionrpc.error import TransmissionError - transmission_api = hass.data[DATA_TRANSMISSION]; + transmission_api = hass.data[DATA_TRANSMISSION] monitored_variables = discovery_info['sensors'] name = discovery_info['client_name'] diff --git a/homeassistant/components/transmission.py b/homeassistant/components/transmission.py index 997732c48726ff..fe06de40d8e151 100644 --- a/homeassistant/components/transmission.py +++ b/homeassistant/components/transmission.py @@ -12,10 +12,10 @@ from homeassistant.exceptions import PlatformNotReady from homeassistant.helpers.event import track_time_interval from homeassistant.helpers.discovery import load_platform -from homeassistant.const import (CONF_HOST, CONF_PASSWORD, CONF_NAME, - CONF_PORT, CONF_USERNAME, CONF_MONITORED_VARIABLES) - -REQUIREMENTS = ['transmissionrpc==0.11'] +from homeassistant.const import (CONF_HOST, CONF_PASSWORD, CONF_NAME, + CONF_PORT, CONF_USERNAME, CONF_MONITORED_VARIABLES) + +REQUIREMENTS = ['transmissionrpc==0.11'] _LOGGER = logging.getLogger(__name__) DOMAIN = 'transmission' @@ -43,27 +43,30 @@ vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_MONITORED_VARIABLES, default=['current_status']): - vol.All(cv.ensure_list, [vol.In(SENSOR_TYPES)]), + vol.All(cv.ensure_list, [vol.In(SENSOR_TYPES)]), }) }, extra=vol.ALLOW_EXTRA) SCAN_INTERVAL = timedelta(minutes=2) -def setup(hass,config): +def setup(hass, config): hass.data[DATA_TRANSMISSION] = TransmissionData(hass, config) - + def refresh(event_time): hass.data[DATA_TRANSMISSION].update() track_time_interval(hass, refresh, SCAN_INTERVAL) - sensorconfig = {'sensors': config[DOMAIN].get(CONF_MONITORED_VARIABLES) , 'client_name' : config[DOMAIN].get(CONF_NAME)} + sensorconfig = { + 'sensors': config[DOMAIN].get(CONF_MONITORED_VARIABLES), + 'client_name': config[DOMAIN].get(CONF_NAME)} load_platform(hass, 'sensor', DOMAIN, sensorconfig) _LOGGER.info("Transmission component setup completed.") return True + class TransmissionData: """Get the latest data and update the states.""" @@ -72,7 +75,6 @@ def __init__(self, hass, config): from transmissionrpc.error import TransmissionError try: """Initialize the Transmission RPC API""" - name = config[DOMAIN].get(CONF_NAME) host = config[DOMAIN].get(CONF_HOST) username = config[DOMAIN].get(CONF_USERNAME) password = config[DOMAIN].get(CONF_PASSWORD) @@ -93,7 +95,8 @@ def __init__(self, hass, config): except TransmissionError as error: if str(error).find("401: Unauthorized"): - _LOGGER.error("Credentials for Transmission client are not valid") + _LOGGER + .error("Credentials for Transmission client are not valid") return _LOGGER.warning( @@ -159,7 +162,7 @@ def checkStartedTorrent(self): 'transmission_started_torrent', { 'name': var}) self.started_torrents = actual_started_torrents - + def getStartedTorrentCount(self): return len(self.started_torrents) From 6142058e95b85b2fb68a0308fa56c307d7fd8617 Mon Sep 17 00:00:00 2001 From: MatteGary Date: Wed, 12 Dec 2018 23:07:37 +0100 Subject: [PATCH 03/21] Fix commit --- homeassistant/components/sensor/transmission.py | 2 -- homeassistant/components/transmission.py | 7 ++++--- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/homeassistant/components/sensor/transmission.py b/homeassistant/components/sensor/transmission.py index b75e968657ba94..dc7445534637d5 100644 --- a/homeassistant/components/sensor/transmission.py +++ b/homeassistant/components/sensor/transmission.py @@ -15,8 +15,6 @@ CONF_USERNAME, STATE_IDLE) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity -from homeassistant.util import Throttle -from homeassistant.exceptions import PlatformNotReady DEPENDENCIES = ['transmission'] DATA_TRANSMISSION = 'TRANSMISSION' diff --git a/homeassistant/components/transmission.py b/homeassistant/components/transmission.py index fe06de40d8e151..717cdd1db742ff 100644 --- a/homeassistant/components/transmission.py +++ b/homeassistant/components/transmission.py @@ -13,7 +13,8 @@ from homeassistant.helpers.event import track_time_interval from homeassistant.helpers.discovery import load_platform from homeassistant.const import (CONF_HOST, CONF_PASSWORD, CONF_NAME, - CONF_PORT, CONF_USERNAME, CONF_MONITORED_VARIABLES) + CONF_PORT, CONF_USERNAME, + CONF_MONITORED_VARIABLES) REQUIREMENTS = ['transmissionrpc==0.11'] _LOGGER = logging.getLogger(__name__) @@ -95,8 +96,8 @@ def __init__(self, hass, config): except TransmissionError as error: if str(error).find("401: Unauthorized"): - _LOGGER - .error("Credentials for Transmission client are not valid") + _LOGGER.error("Credentials for" + " Transmission client are not valid") return _LOGGER.warning( From 8de3a2eab38ad153aee98a4860c49942165e3eb4 Mon Sep 17 00:00:00 2001 From: MatteGary Date: Mon, 17 Dec 2018 12:08:20 +0100 Subject: [PATCH 04/21] Fix + Switch checkin Fix according to failed build and request, first checkin for Turtle Mode Switch in Transmission, still have to figure it out why it's not working. --- .../components/sensor/transmission.py | 35 ++---- .../components/switch/transmission.py | 49 +++----- homeassistant/components/transmission.py | 105 +++++++++++------- 3 files changed, 85 insertions(+), 104 deletions(-) diff --git a/homeassistant/components/sensor/transmission.py b/homeassistant/components/sensor/transmission.py index dc7445534637d5..a8bbdf85ae9f85 100644 --- a/homeassistant/components/sensor/transmission.py +++ b/homeassistant/components/sensor/transmission.py @@ -10,9 +10,7 @@ import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA -from homeassistant.const import ( - CONF_HOST, CONF_MONITORED_VARIABLES, CONF_NAME, CONF_PASSWORD, CONF_PORT, - CONF_USERNAME, STATE_IDLE) +from homeassistant.const import (STATE_IDLE) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity @@ -22,7 +20,6 @@ _LOGGER = logging.getLogger(__name__) DEFAULT_NAME = 'Transmission' -DEFAULT_PORT = 9091 SENSOR_TYPES = { 'active_torrents': ['Active Torrents', None], @@ -35,21 +32,11 @@ 'started_torrents': ['Started Torrents', None], } -SCAN_INTERVAL = timedelta(minutes=2) - -PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ - vol.Required(CONF_HOST): cv.string, - vol.Optional(CONF_MONITORED_VARIABLES): - vol.All(cv.ensure_list, [vol.In(SENSOR_TYPES)]), - vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, - vol.Optional(CONF_PASSWORD): cv.string, - vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, - vol.Optional(CONF_USERNAME): cv.string, -}) - - def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Transmission sensors.""" + if (discovery_info is None): + _LOGGER.warning("Unable to connect to Transmission client.") + raise PlatformNotReady transmission_api = hass.data[DATA_TRANSMISSION] monitored_variables = discovery_info['sensors'] @@ -57,7 +44,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None): dev = [] for variable in monitored_variables: - dev.append(TransmissionSensor(variable, transmission_api, name, hass)) + dev.append(TransmissionSensor(variable, transmission_api, name)) add_entities(dev, True) @@ -65,7 +52,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None): class TransmissionSensor(Entity): """Representation of a Transmission sensor.""" - def __init__(self, sensor_type, transmission_api, client_name, hass): + def __init__(self, sensor_type, transmission_api, client_name): """Initialize the sensor.""" self._name = SENSOR_TYPES[sensor_type][0] self._state = None @@ -74,8 +61,6 @@ def __init__(self, sensor_type, transmission_api, client_name, hass): self._data = None self.client_name = client_name self.type = sensor_type - self.started_torrents = [] - self.first_run = True @property def name(self): @@ -103,11 +88,9 @@ def update(self): self._data = self._transmission_api.data if self.type == 'completed_torrents': - self._state = self._transmission_api.getCompletedTorrentCount() + self._state = self._transmission_api.get_completed_torrent_count() elif self.type == 'started_torrents': - self._state = self._transmission_api.getStartedTorrentCount() - - self.first_run = False + self._state = self._transmission_api.get_started_torrent_count() if self.type == 'current_status': if self._data: @@ -138,4 +121,4 @@ def update(self): elif self.type == 'paused_torrents': self._state = self._data.pausedTorrentCount elif self.type == 'total_torrents': - self._state = self._data.torrentCount + self._state = self._data.torrentCount \ No newline at end of file diff --git a/homeassistant/components/switch/transmission.py b/homeassistant/components/switch/transmission.py index 10ab0903dcf2cc..9fc1643892c198 100644 --- a/homeassistant/components/switch/transmission.py +++ b/homeassistant/components/switch/transmission.py @@ -10,51 +10,30 @@ from homeassistant.components.switch import PLATFORM_SCHEMA from homeassistant.const import ( - CONF_HOST, CONF_NAME, CONF_PORT, CONF_PASSWORD, CONF_USERNAME, STATE_OFF, - STATE_ON) + STATE_OFF, STATE_ON) from homeassistant.helpers.entity import ToggleEntity import homeassistant.helpers.config_validation as cv -REQUIREMENTS = ['transmissionrpc==0.11'] +DEPENDENCIES = ['transmission'] +DATA_TRANSMISSION = 'TRANSMISSION' _LOGGING = logging.getLogger(__name__) DEFAULT_NAME = 'Transmission Turtle Mode' -DEFAULT_PORT = 9091 - -PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ - vol.Required(CONF_HOST): cv.string, - vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, - vol.Optional(CONF_PASSWORD): cv.string, - vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, - vol.Optional(CONF_USERNAME): cv.string, -}) - def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Transmission switch.""" - import transmissionrpc - from transmissionrpc.error import TransmissionError - - name = config.get(CONF_NAME) - host = config.get(CONF_HOST) - username = config.get(CONF_USERNAME) - password = config.get(CONF_PASSWORD) - port = config.get(CONF_PORT) + if (discovery_info is None): + _LOGGER.warning("Unable to connect to Transmission client.") + raise PlatformNotReady - try: - transmission_api = transmissionrpc.Client( - host, port=port, user=username, password=password) - transmission_api.session_stats() - except TransmissionError as error: - _LOGGING.error( - "Connection to Transmission API failed on %s:%s with message %s", - host, port, error.original - ) - return False + transmission_api = hass.data[DATA_TRANSMISSION] + name = discovery_info['client_name'] - add_entities([TransmissionSwitch(transmission_api, name)]) + dev = [] + dev.append(TransmissionSwitch(transmission_api, name)) + add_entities(dev, True) class TransmissionSwitch(ToggleEntity): """Representation of a Transmission switch.""" @@ -88,14 +67,14 @@ def is_on(self): def turn_on(self, **kwargs): """Turn the device on.""" _LOGGING.debug("Turning Turtle Mode of Transmission on") - self.transmission_client.set_session(alt_speed_enabled=True) + self.transmission_client.set_alt_speed_enabled(True) def turn_off(self, **kwargs): """Turn the device off.""" _LOGGING.debug("Turning Turtle Mode of Transmission off") - self.transmission_client.set_session(alt_speed_enabled=False) + self.transmission_client.set_alt_speed_enabled(False) def update(self): """Get the latest data from Transmission and updates the state.""" - active = self.transmission_client.get_session().alt_speed_enabled + active = self.transmission_client.get_alt_speed_enabled() self._state = STATE_ON if active else STATE_OFF diff --git a/homeassistant/components/transmission.py b/homeassistant/components/transmission.py index 717cdd1db742ff..bd422139d29b55 100644 --- a/homeassistant/components/transmission.py +++ b/homeassistant/components/transmission.py @@ -5,16 +5,24 @@ https://home-assistant.io/components/transmission/ """ from datetime import timedelta + import logging import voluptuous as vol -import homeassistant.helpers.config_validation as cv + from homeassistant.util import Throttle from homeassistant.exceptions import PlatformNotReady +from homeassistant.helpers import discovery from homeassistant.helpers.event import track_time_interval from homeassistant.helpers.discovery import load_platform -from homeassistant.const import (CONF_HOST, CONF_PASSWORD, CONF_NAME, - CONF_PORT, CONF_USERNAME, - CONF_MONITORED_VARIABLES) +from homeassistant.const import ( + CONF_HOST, + CONF_PASSWORD, + CONF_NAME, + CONF_PORT, + CONF_USERNAME, + CONF_MONITORED_CONDITIONS, +) +import homeassistant.helpers.config_validation as cv REQUIREMENTS = ['transmissionrpc==0.11'] _LOGGER = logging.getLogger(__name__) @@ -24,6 +32,7 @@ DEFAULT_NAME = 'Transmission' DEFAULT_PORT = 9091 +TURTLE_MODE = 'turtle_mode' SENSOR_TYPES = { 'active_torrents': ['Active Torrents', None], @@ -37,15 +46,16 @@ } CONFIG_SCHEMA = vol.Schema({ - DOMAIN: vol.Schema({ - vol.Required(CONF_HOST): cv.string, - vol.Required(CONF_PASSWORD): cv.string, - vol.Required(CONF_USERNAME): cv.string, - vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, - vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, - vol.Optional(CONF_MONITORED_VARIABLES, default=['current_status']): - vol.All(cv.ensure_list, [vol.In(SENSOR_TYPES)]), - }) + DOMAIN: vol.Schema({ + vol.Required(CONF_HOST): cv.string, + vol.Required(CONF_PASSWORD): cv.string, + vol.Required(CONF_USERNAME): cv.string, + vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, + vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, + vol.Optional(TURTLE_MODE, default=False): cv.boolean, + vol.Optional(CONF_MONITORED_CONDITIONS, default=['current_status']): + vol.All(cv.ensure_list, [vol.In(SENSOR_TYPES)]), + }) }, extra=vol.ALLOW_EXTRA) SCAN_INTERVAL = timedelta(minutes=2) @@ -53,6 +63,7 @@ def setup(hass, config): hass.data[DATA_TRANSMISSION] = TransmissionData(hass, config) + hass.data[DATA_TRANSMISSION].init_torrent_list() def refresh(event_time): hass.data[DATA_TRANSMISSION].update() @@ -60,38 +71,37 @@ def refresh(event_time): track_time_interval(hass, refresh, SCAN_INTERVAL) sensorconfig = { - 'sensors': config[DOMAIN].get(CONF_MONITORED_VARIABLES), + 'sensors': config[DOMAIN].get(CONF_MONITORED_CONDITIONS), 'client_name': config[DOMAIN].get(CONF_NAME)} - load_platform(hass, 'sensor', DOMAIN, sensorconfig) + discovery.load_platform(hass, 'sensor', DOMAIN, sensorconfig) - _LOGGER.info("Transmission component setup completed.") + if config[DOMAIN].get(TURTLE_MODE) == True: + discovery.load_platform(hass, 'switch', DOMAIN, sensorconfig) return True class TransmissionData: """Get the latest data and update the states.""" - def __init__(self, hass, config): + """Initialize the Transmission RPC API""" import transmissionrpc from transmissionrpc.error import TransmissionError try: - """Initialize the Transmission RPC API""" - host = config[DOMAIN].get(CONF_HOST) - username = config[DOMAIN].get(CONF_USERNAME) - password = config[DOMAIN].get(CONF_PASSWORD) - port = config[DOMAIN].get(CONF_PORT) + host = config[DOMAIN][CONF_HOST] + username = config[DOMAIN][CONF_USERNAME] + password = config[DOMAIN][CONF_PASSWORD] + port = config[DOMAIN][CONF_PORT] api = transmissionrpc.Client( host, port=port, user=username, password=password) + api.session_stats() - """Initialize the Transmission data object.""" self.data = None self.torrents = None self.available = True self._api = api self.completed_torrents = [] self.started_torrents = [] - self.initTorrentList() self.hass = hass except TransmissionError as error: @@ -113,23 +123,23 @@ def update(self): self.data = self._api.session_stats() self.torrents = self._api.get_torrents() - self.checkCompletedTorrent() - self.checkStartedTorrent() + self.check_completed_torrent() + self.check_started_torrent() - _LOGGER.info("Torrent Data updated") + _LOGGER.debug("Torrent Data updated") self.available = True except TransmissionError: self.available = False _LOGGER.error("Unable to connect to Transmission client") - def initTorrentList(self): + def init_torrent_list(self): self.torrents = self._api.get_torrents() self.completed_torrents = [ x.name for x in self.torrents if x.status == "seeding"] self.started_torrents = [ x.name for x in self.torrents if x.status == "downloading"] - def checkCompletedTorrent(self): + def check_completed_torrent(self): """Get completed torrent functionality""" actual_torrents = self.torrents actual_completed_torrents = [ @@ -138,16 +148,15 @@ def checkCompletedTorrent(self): tmp_completed_torrents = list( set(actual_completed_torrents).difference( self.completed_torrents)) - if tmp_completed_torrents: - for var in tmp_completed_torrents: - _LOGGER.info("Completed Torrent found") - self.hass.bus.fire( - 'transmission_downloaded_torrent', { - 'name': var}) + + for var in tmp_completed_torrents: + self.hass.bus.fire( + 'transmission_downloaded_torrent', { + 'name': var}) self.completed_torrents = actual_completed_torrents - def checkStartedTorrent(self): + def check_started_torrent(self): """Get started torrent functionality""" actual_torrents = self.torrents actual_started_torrents = [ @@ -157,15 +166,25 @@ def checkStartedTorrent(self): tmp_started_torrents = list( set(actual_started_torrents).difference( self.started_torrents)) - if tmp_started_torrents: - for var in tmp_started_torrents: - self.hass.bus.fire( - 'transmission_started_torrent', { - 'name': var}) + + for var in tmp_started_torrents: + self.hass.bus.fire( + 'transmission_started_torrent', { + 'name': var}) self.started_torrents = actual_started_torrents - def getStartedTorrentCount(self): + def get_started_torrent_count(self): return len(self.started_torrents) - def getCompletedTorrentCount(self): + def get_completed_torrent_count(self): return len(self.completed_torrents) + + def set_alt_speed_enabled(self, is_enabled): + self._api.set_session(alt_speed_enabled = is_enabled) + + def get_alt_speed_enabled(self): + return self.get_session().alt_speed_enabled + + @Throttle(SCAN_INTERVAL) + def get_session(self): + return self._api.get_session() \ No newline at end of file From 86d3bea0e9e0178926e40f796cef7f3b4819bd21 Mon Sep 17 00:00:00 2001 From: MatteGary Date: Mon, 17 Dec 2018 16:52:57 +0100 Subject: [PATCH 05/21] Bugfixing --- homeassistant/components/sensor/transmission.py | 2 +- homeassistant/components/switch/transmission.py | 3 ++- homeassistant/components/transmission.py | 11 +++++------ 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/homeassistant/components/sensor/transmission.py b/homeassistant/components/sensor/transmission.py index a8bbdf85ae9f85..e84f872da31069 100644 --- a/homeassistant/components/sensor/transmission.py +++ b/homeassistant/components/sensor/transmission.py @@ -121,4 +121,4 @@ def update(self): elif self.type == 'paused_torrents': self._state = self._data.pausedTorrentCount elif self.type == 'total_torrents': - self._state = self._data.torrentCount \ No newline at end of file + self._state = self._data.torrentCount diff --git a/homeassistant/components/switch/transmission.py b/homeassistant/components/switch/transmission.py index 9fc1643892c198..aae22a540877d6 100644 --- a/homeassistant/components/switch/transmission.py +++ b/homeassistant/components/switch/transmission.py @@ -9,6 +9,7 @@ import voluptuous as vol from homeassistant.components.switch import PLATFORM_SCHEMA +from homeassistant.exceptions import PlatformNotReady from homeassistant.const import ( STATE_OFF, STATE_ON) from homeassistant.helpers.entity import ToggleEntity @@ -24,7 +25,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Transmission switch.""" if (discovery_info is None): - _LOGGER.warning("Unable to connect to Transmission client.") + _LOGGING.warning("Unable to connect to Transmission client.") raise PlatformNotReady transmission_api = hass.data[DATA_TRANSMISSION] diff --git a/homeassistant/components/transmission.py b/homeassistant/components/transmission.py index bd422139d29b55..e1ee73d880a800 100644 --- a/homeassistant/components/transmission.py +++ b/homeassistant/components/transmission.py @@ -13,7 +13,6 @@ from homeassistant.exceptions import PlatformNotReady from homeassistant.helpers import discovery from homeassistant.helpers.event import track_time_interval -from homeassistant.helpers.discovery import load_platform from homeassistant.const import ( CONF_HOST, CONF_PASSWORD, @@ -71,11 +70,11 @@ def refresh(event_time): track_time_interval(hass, refresh, SCAN_INTERVAL) sensorconfig = { - 'sensors': config[DOMAIN].get(CONF_MONITORED_CONDITIONS), - 'client_name': config[DOMAIN].get(CONF_NAME)} + 'sensors': config[DOMAIN][CONF_MONITORED_CONDITIONS], + 'client_name': config[DOMAIN][CONF_NAME]} discovery.load_platform(hass, 'sensor', DOMAIN, sensorconfig) - if config[DOMAIN].get(TURTLE_MODE) == True: + if config[DOMAIN][TURTLE_MODE] is True: discovery.load_platform(hass, 'switch', DOMAIN, sensorconfig) return True @@ -180,11 +179,11 @@ def get_completed_torrent_count(self): return len(self.completed_torrents) def set_alt_speed_enabled(self, is_enabled): - self._api.set_session(alt_speed_enabled = is_enabled) + self._api.set_session(alt_speed_enabled=is_enabled) def get_alt_speed_enabled(self): return self.get_session().alt_speed_enabled @Throttle(SCAN_INTERVAL) def get_session(self): - return self._api.get_session() \ No newline at end of file + return self._api.get_session() From ce529ff699fd40f6e410c83670262e3d37010a75 Mon Sep 17 00:00:00 2001 From: MatteGary Date: Thu, 20 Dec 2018 12:48:23 +0100 Subject: [PATCH 06/21] Fix commit Multiple fix --- .../components/sensor/transmission.py | 45 +++++++++---------- .../components/switch/transmission.py | 15 +++---- homeassistant/components/transmission.py | 22 ++++++--- 3 files changed, 42 insertions(+), 40 deletions(-) diff --git a/homeassistant/components/sensor/transmission.py b/homeassistant/components/sensor/transmission.py index e84f872da31069..82ecb355c0dc55 100644 --- a/homeassistant/components/sensor/transmission.py +++ b/homeassistant/components/sensor/transmission.py @@ -4,47 +4,38 @@ For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.transmission/ """ -from datetime import timedelta import logging -import voluptuous as vol - -from homeassistant.components.sensor import PLATFORM_SCHEMA -from homeassistant.const import (STATE_IDLE) -import homeassistant.helpers.config_validation as cv +from homeassistant.const import STATE_IDLE from homeassistant.helpers.entity import Entity DEPENDENCIES = ['transmission'] -DATA_TRANSMISSION = 'TRANSMISSION' _LOGGER = logging.getLogger(__name__) DEFAULT_NAME = 'Transmission' -SENSOR_TYPES = { - 'active_torrents': ['Active Torrents', None], - 'current_status': ['Status', None], - 'download_speed': ['Down Speed', 'MB/s'], - 'paused_torrents': ['Paused Torrents', None], - 'total_torrents': ['Total Torrents', None], - 'upload_speed': ['Up Speed', 'MB/s'], - 'completed_torrents': ['Completed Torrents', None], - 'started_torrents': ['Started Torrents', None], -} def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Transmission sensors.""" - if (discovery_info is None): - _LOGGER.warning("Unable to connect to Transmission client.") + if discovery_info is None: + _LOGGER.warning("Unable to connect to Transmission client") raise PlatformNotReady - transmission_api = hass.data[DATA_TRANSMISSION] + component_name = discovery_info['component_name'] + transmission_api = hass.data[component_name] monitored_variables = discovery_info['sensors'] name = discovery_info['client_name'] + SENSOR_TYPES = discovery_info['sensor_types'] dev = [] for variable in monitored_variables: - dev.append(TransmissionSensor(variable, transmission_api, name)) + dev.append(TransmissionSensor( + variable, + transmission_api, + name, + SENSOR_TYPES[variable][0], + SENSOR_TYPES[variable][1])) add_entities(dev, True) @@ -52,12 +43,18 @@ def setup_platform(hass, config, add_entities, discovery_info=None): class TransmissionSensor(Entity): """Representation of a Transmission sensor.""" - def __init__(self, sensor_type, transmission_api, client_name): + def __init__( + self, + sensor_type, + transmission_api, + client_name, + sensor_name, + unit_of_measurement): """Initialize the sensor.""" - self._name = SENSOR_TYPES[sensor_type][0] + self._name = sensor_name self._state = None self._transmission_api = transmission_api - self._unit_of_measurement = SENSOR_TYPES[sensor_type][1] + self._unit_of_measurement = unit_of_measurement self._data = None self.client_name = client_name self.type = sensor_type diff --git a/homeassistant/components/switch/transmission.py b/homeassistant/components/switch/transmission.py index aae22a540877d6..4e2ea6b5688e45 100644 --- a/homeassistant/components/switch/transmission.py +++ b/homeassistant/components/switch/transmission.py @@ -6,35 +6,30 @@ """ import logging -import voluptuous as vol - -from homeassistant.components.switch import PLATFORM_SCHEMA from homeassistant.exceptions import PlatformNotReady from homeassistant.const import ( STATE_OFF, STATE_ON) from homeassistant.helpers.entity import ToggleEntity -import homeassistant.helpers.config_validation as cv DEPENDENCIES = ['transmission'] -DATA_TRANSMISSION = 'TRANSMISSION' _LOGGING = logging.getLogger(__name__) DEFAULT_NAME = 'Transmission Turtle Mode' + def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Transmission switch.""" - if (discovery_info is None): + if discovery_info is None: _LOGGING.warning("Unable to connect to Transmission client.") raise PlatformNotReady - transmission_api = hass.data[DATA_TRANSMISSION] + component_name = discovery_info['component_name'] + transmission_api = hass.data[component_name] name = discovery_info['client_name'] - dev = [] - dev.append(TransmissionSwitch(transmission_api, name)) + add_entities([TransmissionSwitch(transmission_api, name)], True) - add_entities(dev, True) class TransmissionSwitch(ToggleEntity): """Representation of a Transmission switch.""" diff --git a/homeassistant/components/transmission.py b/homeassistant/components/transmission.py index e1ee73d880a800..d99f43e7fac560 100644 --- a/homeassistant/components/transmission.py +++ b/homeassistant/components/transmission.py @@ -27,7 +27,7 @@ _LOGGER = logging.getLogger(__name__) DOMAIN = 'transmission' -DATA_TRANSMISSION = 'TRANSMISSION' +DATA_TRANSMISSION = 'data_transmission' DEFAULT_NAME = 'Transmission' DEFAULT_PORT = 9091 @@ -47,8 +47,8 @@ CONFIG_SCHEMA = vol.Schema({ DOMAIN: vol.Schema({ vol.Required(CONF_HOST): cv.string, - vol.Required(CONF_PASSWORD): cv.string, - vol.Required(CONF_USERNAME): cv.string, + vol.Optional(CONF_PASSWORD): cv.string, + vol.Optional(CONF_USERNAME): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(TURTLE_MODE, default=False): cv.boolean, @@ -61,17 +61,21 @@ def setup(hass, config): + """Set up the Transmission Component.""" hass.data[DATA_TRANSMISSION] = TransmissionData(hass, config) hass.data[DATA_TRANSMISSION].init_torrent_list() def refresh(event_time): + """Get the latest data from Transmission.""" hass.data[DATA_TRANSMISSION].update() track_time_interval(hass, refresh, SCAN_INTERVAL) sensorconfig = { + 'sensor_types': SENSOR_TYPES, 'sensors': config[DOMAIN][CONF_MONITORED_CONDITIONS], - 'client_name': config[DOMAIN][CONF_NAME]} + 'client_name': config[DOMAIN][CONF_NAME], + 'component_name': DATA_TRANSMISSION} discovery.load_platform(hass, 'sensor', DOMAIN, sensorconfig) if config[DOMAIN][TURTLE_MODE] is True: @@ -132,6 +136,7 @@ def update(self): _LOGGER.error("Unable to connect to Transmission client") def init_torrent_list(self): + """Initialize torrent lists.""" self.torrents = self._api.get_torrents() self.completed_torrents = [ x.name for x in self.torrents if x.status == "seeding"] @@ -139,7 +144,7 @@ def init_torrent_list(self): x.name for x in self.torrents if x.status == "downloading"] def check_completed_torrent(self): - """Get completed torrent functionality""" + """Get completed torrent functionality.""" actual_torrents = self.torrents actual_completed_torrents = [ var.name for var in actual_torrents if var.status == "seeding"] @@ -156,7 +161,7 @@ def check_completed_torrent(self): self.completed_torrents = actual_completed_torrents def check_started_torrent(self): - """Get started torrent functionality""" + """Get started torrent functionality.""" actual_torrents = self.torrents actual_started_torrents = [ var.name for var @@ -173,17 +178,22 @@ def check_started_torrent(self): self.started_torrents = actual_started_torrents def get_started_torrent_count(self): + """Get the number of started torrents.""" return len(self.started_torrents) def get_completed_torrent_count(self): + """Get the number of completed torrents.""" return len(self.completed_torrents) def set_alt_speed_enabled(self, is_enabled): + """Set the alternative speed flag.""" self._api.set_session(alt_speed_enabled=is_enabled) def get_alt_speed_enabled(self): + """Get the alternative speed flag.""" return self.get_session().alt_speed_enabled @Throttle(SCAN_INTERVAL) def get_session(self): + """Get the Transmission session parameters.""" return self._api.get_session() From 0e8578d5de76356a6327d756a4372ac119e226cb Mon Sep 17 00:00:00 2001 From: MatteGary Date: Thu, 20 Dec 2018 13:52:24 +0100 Subject: [PATCH 07/21] Fix --- homeassistant/components/sensor/transmission.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/homeassistant/components/sensor/transmission.py b/homeassistant/components/sensor/transmission.py index 82ecb355c0dc55..cd8298d5b4c20e 100644 --- a/homeassistant/components/sensor/transmission.py +++ b/homeassistant/components/sensor/transmission.py @@ -6,6 +6,7 @@ """ import logging +from homeassistant.exceptions import PlatformNotReady from homeassistant.const import STATE_IDLE from homeassistant.helpers.entity import Entity @@ -26,7 +27,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None): transmission_api = hass.data[component_name] monitored_variables = discovery_info['sensors'] name = discovery_info['client_name'] - SENSOR_TYPES = discovery_info['sensor_types'] + sensor_types = discovery_info['sensor_types'] dev = [] for variable in monitored_variables: @@ -34,8 +35,8 @@ def setup_platform(hass, config, add_entities, discovery_info=None): variable, transmission_api, name, - SENSOR_TYPES[variable][0], - SENSOR_TYPES[variable][1])) + sensor_types[variable][0], + sensor_types[variable][1])) add_entities(dev, True) From c7e444fd8a8521792e27e639cd60d4bfbbf80df8 Mon Sep 17 00:00:00 2001 From: MatteGary Date: Tue, 1 Jan 2019 22:20:58 +0100 Subject: [PATCH 08/21] fix for missing config --- homeassistant/components/transmission.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/transmission.py b/homeassistant/components/transmission.py index d99f43e7fac560..c52fce4261df21 100644 --- a/homeassistant/components/transmission.py +++ b/homeassistant/components/transmission.py @@ -76,10 +76,10 @@ def refresh(event_time): 'sensors': config[DOMAIN][CONF_MONITORED_CONDITIONS], 'client_name': config[DOMAIN][CONF_NAME], 'component_name': DATA_TRANSMISSION} - discovery.load_platform(hass, 'sensor', DOMAIN, sensorconfig) + discovery.load_platform(hass, 'sensor', DOMAIN, sensorconfig, config) if config[DOMAIN][TURTLE_MODE] is True: - discovery.load_platform(hass, 'switch', DOMAIN, sensorconfig) + discovery.load_platform(hass, 'switch', DOMAIN, sensorconfig, config) return True From e3a645b086ae683902b33f430da02aa08a166599 Mon Sep 17 00:00:00 2001 From: MatteGary Date: Thu, 3 Jan 2019 12:28:00 +0100 Subject: [PATCH 09/21] Update on requirements_all.txt --- requirements_all.txt | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/requirements_all.txt b/requirements_all.txt index 59a29eb88b342e..1c1d89dfbee719 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -1546,8 +1546,7 @@ tp-connected==0.0.4 # homeassistant.components.device_tracker.tplink tplink==0.2.1 -# homeassistant.components.sensor.transmission -# homeassistant.components.switch.transmission +# homeassistant.components.transmission transmissionrpc==0.11 # homeassistant.components.tuya From eafafd85f2175f9a24c7300dab8cc971e6eb7e1e Mon Sep 17 00:00:00 2001 From: MatteGary Date: Thu, 3 Jan 2019 12:34:01 +0100 Subject: [PATCH 10/21] Fix in requirements_all.txt --- requirements_all.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements_all.txt b/requirements_all.txt index 1c1d89dfbee719..3491f46c36fc66 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -1546,7 +1546,7 @@ tp-connected==0.0.4 # homeassistant.components.device_tracker.tplink tplink==0.2.1 -# homeassistant.components.transmission +# homeassistant.components.transmission transmissionrpc==0.11 # homeassistant.components.tuya From c2cf11884ef5fade418a245e09570117176cfda6 Mon Sep 17 00:00:00 2001 From: MatteGary Date: Thu, 3 Jan 2019 15:10:24 +0100 Subject: [PATCH 11/21] Fix --- requirements_all.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements_all.txt b/requirements_all.txt index 3491f46c36fc66..1c1d89dfbee719 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -1546,7 +1546,7 @@ tp-connected==0.0.4 # homeassistant.components.device_tracker.tplink tplink==0.2.1 -# homeassistant.components.transmission +# homeassistant.components.transmission transmissionrpc==0.11 # homeassistant.components.tuya From 80278e716f36bc30ef5e996728fbe0986cbacf00 Mon Sep 17 00:00:00 2001 From: MatteGary Date: Thu, 3 Jan 2019 16:03:25 +0100 Subject: [PATCH 12/21] Fix for build --- homeassistant/components/transmission.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/transmission.py b/homeassistant/components/transmission.py index c52fce4261df21..f63419224b1f95 100644 --- a/homeassistant/components/transmission.py +++ b/homeassistant/components/transmission.py @@ -85,8 +85,9 @@ def refresh(event_time): class TransmissionData: """Get the latest data and update the states.""" + def __init__(self, hass, config): - """Initialize the Transmission RPC API""" + """Initialize the Transmission RPC API.""" import transmissionrpc from transmissionrpc.error import TransmissionError try: From 55a4e1df566ad52ff6c8f441e849435b6832011e Mon Sep 17 00:00:00 2001 From: MatteGary Date: Fri, 4 Jan 2019 16:07:24 +0100 Subject: [PATCH 13/21] fix --- .../components/sensor/transmission.py | 10 +-- .../components/switch/transmission.py | 8 ++- homeassistant/components/transmission.py | 66 +++++++++---------- 3 files changed, 41 insertions(+), 43 deletions(-) diff --git a/homeassistant/components/sensor/transmission.py b/homeassistant/components/sensor/transmission.py index cd8298d5b4c20e..2d407a093cf59a 100644 --- a/homeassistant/components/sensor/transmission.py +++ b/homeassistant/components/sensor/transmission.py @@ -6,6 +6,8 @@ """ import logging +from homeassistant.components.transmission import ( + DATA_TRANSMISSION, SENSOR_TYPES, SCAN_INTERVAL) from homeassistant.exceptions import PlatformNotReady from homeassistant.const import STATE_IDLE from homeassistant.helpers.entity import Entity @@ -20,14 +22,13 @@ def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Transmission sensors.""" if discovery_info is None: - _LOGGER.warning("Unable to connect to Transmission client") - raise PlatformNotReady + return - component_name = discovery_info['component_name'] + component_name = DATA_TRANSMISSION transmission_api = hass.data[component_name] monitored_variables = discovery_info['sensors'] name = discovery_info['client_name'] - sensor_types = discovery_info['sensor_types'] + sensor_types = SENSOR_TYPES dev = [] for variable in monitored_variables: @@ -80,6 +81,7 @@ def available(self): """Could the device be accessed during the last update call.""" return self._transmission_api.available + @Throttle(SCAN_INTERVAL) def update(self): """Get the latest data from Transmission and updates the state.""" self._transmission_api.update() diff --git a/homeassistant/components/switch/transmission.py b/homeassistant/components/switch/transmission.py index 4e2ea6b5688e45..261d2eb7db5a52 100644 --- a/homeassistant/components/switch/transmission.py +++ b/homeassistant/components/switch/transmission.py @@ -6,6 +6,8 @@ """ import logging +from homeassistant.components.transmission import ( + DATA_TRANSMISSION, SENSOR_TYPES, SCAN_INTERVAL) from homeassistant.exceptions import PlatformNotReady from homeassistant.const import ( STATE_OFF, STATE_ON) @@ -21,10 +23,9 @@ def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Transmission switch.""" if discovery_info is None: - _LOGGING.warning("Unable to connect to Transmission client.") - raise PlatformNotReady + return - component_name = discovery_info['component_name'] + component_name = DATA_TRANSMISSION transmission_api = hass.data[component_name] name = discovery_info['client_name'] @@ -70,6 +71,7 @@ def turn_off(self, **kwargs): _LOGGING.debug("Turning Turtle Mode of Transmission off") self.transmission_client.set_alt_speed_enabled(False) + @Throttle(SCAN_INTERVAL) def update(self): """Get the latest data from Transmission and updates the state.""" active = self.transmission_client.get_alt_speed_enabled() diff --git a/homeassistant/components/transmission.py b/homeassistant/components/transmission.py index f63419224b1f95..720b7ccaf094e6 100644 --- a/homeassistant/components/transmission.py +++ b/homeassistant/components/transmission.py @@ -62,17 +62,34 @@ def setup(hass, config): """Set up the Transmission Component.""" - hass.data[DATA_TRANSMISSION] = TransmissionData(hass, config) - hass.data[DATA_TRANSMISSION].init_torrent_list() + host = config[DOMAIN][CONF_HOST] + username = config[DOMAIN][CONF_USERNAME] + password = config[DOMAIN][CONF_PASSWORD] + port = config[DOMAIN][CONF_PORT] + + import transmissionrpc + from transmissionrpc.error import TransmissionError + try: + api = transmissionrpc.Client( + host, port=port, user=username, password=password) + api.session_stats() + except TransmissionError as error: + if str(error).find("401: Unauthorized"): + _LOGGER.error("Credentials for" + " Transmission client are not valid") + return false + + tm_data = hass.data[DATA_TRANSMISSION] + = TransmissionData(hass, config, api) + tm_data.init_torrent_list() def refresh(event_time): """Get the latest data from Transmission.""" - hass.data[DATA_TRANSMISSION].update() + tm_data.update() track_time_interval(hass, refresh, SCAN_INTERVAL) sensorconfig = { - 'sensor_types': SENSOR_TYPES, 'sensors': config[DOMAIN][CONF_MONITORED_CONDITIONS], 'client_name': config[DOMAIN][CONF_NAME], 'component_name': DATA_TRANSMISSION} @@ -85,40 +102,17 @@ def refresh(event_time): class TransmissionData: """Get the latest data and update the states.""" - - def __init__(self, hass, config): - """Initialize the Transmission RPC API.""" - import transmissionrpc - from transmissionrpc.error import TransmissionError - try: - host = config[DOMAIN][CONF_HOST] - username = config[DOMAIN][CONF_USERNAME] - password = config[DOMAIN][CONF_PASSWORD] - port = config[DOMAIN][CONF_PORT] - api = transmissionrpc.Client( - host, port=port, user=username, password=password) - api.session_stats() - - self.data = None - self.torrents = None - self.available = True - self._api = api - self.completed_torrents = [] - self.started_torrents = [] - self.hass = hass - - except TransmissionError as error: - if str(error).find("401: Unauthorized"): - _LOGGER.error("Credentials for" - " Transmission client are not valid") - return - - _LOGGER.warning( - "Unable to connect to Transmission client: %s:%s", host, port) - raise PlatformNotReady + def __init__(self, hass, config, api): + """Initialize the Transmission RPC API.""" + self.data = None + self.torrents = None + self.available = True + self._api = api + self.completed_torrents = [] + self.started_torrents = [] + self.hass = hass - @Throttle(SCAN_INTERVAL) def update(self): """Get the latest data from Transmission instance.""" from transmissionrpc.error import TransmissionError From e902ca00596eafb6f87cc120bf6473872e704af7 Mon Sep 17 00:00:00 2001 From: MatteGary Date: Fri, 4 Jan 2019 16:12:25 +0100 Subject: [PATCH 14/21] Fix --- homeassistant/components/sensor/transmission.py | 2 +- homeassistant/components/switch/transmission.py | 4 ++-- homeassistant/components/transmission.py | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/homeassistant/components/sensor/transmission.py b/homeassistant/components/sensor/transmission.py index 2d407a093cf59a..3ebca1122a5e0a 100644 --- a/homeassistant/components/sensor/transmission.py +++ b/homeassistant/components/sensor/transmission.py @@ -8,9 +8,9 @@ from homeassistant.components.transmission import ( DATA_TRANSMISSION, SENSOR_TYPES, SCAN_INTERVAL) -from homeassistant.exceptions import PlatformNotReady from homeassistant.const import STATE_IDLE from homeassistant.helpers.entity import Entity +from homeassistant.util import Throttle DEPENDENCIES = ['transmission'] diff --git a/homeassistant/components/switch/transmission.py b/homeassistant/components/switch/transmission.py index 261d2eb7db5a52..7e9e34cec0f252 100644 --- a/homeassistant/components/switch/transmission.py +++ b/homeassistant/components/switch/transmission.py @@ -7,10 +7,10 @@ import logging from homeassistant.components.transmission import ( - DATA_TRANSMISSION, SENSOR_TYPES, SCAN_INTERVAL) -from homeassistant.exceptions import PlatformNotReady + DATA_TRANSMISSION, SCAN_INTERVAL) from homeassistant.const import ( STATE_OFF, STATE_ON) +from homeassistant.util import Throttle from homeassistant.helpers.entity import ToggleEntity DEPENDENCIES = ['transmission'] diff --git a/homeassistant/components/transmission.py b/homeassistant/components/transmission.py index 720b7ccaf094e6..80009287cdc896 100644 --- a/homeassistant/components/transmission.py +++ b/homeassistant/components/transmission.py @@ -79,8 +79,8 @@ def setup(hass, config): " Transmission client are not valid") return false - tm_data = hass.data[DATA_TRANSMISSION] - = TransmissionData(hass, config, api) + tm_data = hass.data[DATA_TRANSMISSION] = TransmissionData( + hass, config, api) tm_data.init_torrent_list() def refresh(event_time): From 8bc465d47bfa6fc533c869da5f9079a8c3bdc00c Mon Sep 17 00:00:00 2001 From: MatteGary Date: Fri, 4 Jan 2019 16:13:53 +0100 Subject: [PATCH 15/21] Fix (again) --- homeassistant/components/transmission.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/homeassistant/components/transmission.py b/homeassistant/components/transmission.py index 80009287cdc896..043136995852d8 100644 --- a/homeassistant/components/transmission.py +++ b/homeassistant/components/transmission.py @@ -10,7 +10,6 @@ import voluptuous as vol from homeassistant.util import Throttle -from homeassistant.exceptions import PlatformNotReady from homeassistant.helpers import discovery from homeassistant.helpers.event import track_time_interval from homeassistant.const import ( @@ -77,7 +76,7 @@ def setup(hass, config): if str(error).find("401: Unauthorized"): _LOGGER.error("Credentials for" " Transmission client are not valid") - return false + return False tm_data = hass.data[DATA_TRANSMISSION] = TransmissionData( hass, config, api) From a66676da12d3717658a0465ac2af725c0c55ce76 Mon Sep 17 00:00:00 2001 From: MatteGary Date: Mon, 7 Jan 2019 10:12:26 +0100 Subject: [PATCH 16/21] Fix --- homeassistant/components/sensor/transmission.py | 12 +++++------- homeassistant/components/transmission.py | 14 +++++--------- 2 files changed, 10 insertions(+), 16 deletions(-) diff --git a/homeassistant/components/sensor/transmission.py b/homeassistant/components/sensor/transmission.py index 3ebca1122a5e0a..efe32b07fc095e 100644 --- a/homeassistant/components/sensor/transmission.py +++ b/homeassistant/components/sensor/transmission.py @@ -24,20 +24,18 @@ def setup_platform(hass, config, add_entities, discovery_info=None): if discovery_info is None: return - component_name = DATA_TRANSMISSION - transmission_api = hass.data[component_name] + transmission_api = hass.data[DATA_TRANSMISSION] monitored_variables = discovery_info['sensors'] name = discovery_info['client_name'] - sensor_types = SENSOR_TYPES dev = [] - for variable in monitored_variables: + for sensor_type in monitored_variables: dev.append(TransmissionSensor( - variable, + sensor_type, transmission_api, name, - sensor_types[variable][0], - sensor_types[variable][1])) + SENSOR_TYPES[sensor_type][0], + SENSOR_TYPES[sensor_type][1])) add_entities(dev, True) diff --git a/homeassistant/components/transmission.py b/homeassistant/components/transmission.py index 043136995852d8..bf79164cbbcda2 100644 --- a/homeassistant/components/transmission.py +++ b/homeassistant/components/transmission.py @@ -90,11 +90,10 @@ def refresh(event_time): sensorconfig = { 'sensors': config[DOMAIN][CONF_MONITORED_CONDITIONS], - 'client_name': config[DOMAIN][CONF_NAME], - 'component_name': DATA_TRANSMISSION} + 'client_name': config[DOMAIN][CONF_NAME]} discovery.load_platform(hass, 'sensor', DOMAIN, sensorconfig, config) - if config[DOMAIN][TURTLE_MODE] is True: + if config[DOMAIN][TURTLE_MODE]: discovery.load_platform(hass, 'switch', DOMAIN, sensorconfig, config) return True @@ -106,6 +105,7 @@ def __init__(self, hass, config, api): """Initialize the Transmission RPC API.""" self.data = None self.torrents = None + self.session = None self.available = True self._api = api self.completed_torrents = [] @@ -119,6 +119,7 @@ def update(self): try: self.data = self._api.session_stats() self.torrents = self._api.get_torrents() + self.session = self._api.get_session() self.check_completed_torrent() self.check_started_torrent() @@ -185,9 +186,4 @@ def set_alt_speed_enabled(self, is_enabled): def get_alt_speed_enabled(self): """Get the alternative speed flag.""" - return self.get_session().alt_speed_enabled - - @Throttle(SCAN_INTERVAL) - def get_session(self): - """Get the Transmission session parameters.""" - return self._api.get_session() + return self.session.alt_speed_enabled From 953a6149aaa1c57c197b554151911f055c851eba Mon Sep 17 00:00:00 2001 From: MatteGary Date: Mon, 7 Jan 2019 10:48:40 +0100 Subject: [PATCH 17/21] Fix indentation --- homeassistant/components/transmission.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/homeassistant/components/transmission.py b/homeassistant/components/transmission.py index bf79164cbbcda2..2e983c2ecbb2e4 100644 --- a/homeassistant/components/transmission.py +++ b/homeassistant/components/transmission.py @@ -105,7 +105,7 @@ def __init__(self, hass, config, api): """Initialize the Transmission RPC API.""" self.data = None self.torrents = None - self.session = None + self.session = None self.available = True self._api = api self.completed_torrents = [] From 40dd84ad14a897cedf26709d4783929400851413 Mon Sep 17 00:00:00 2001 From: MatteGary Date: Mon, 7 Jan 2019 10:53:40 +0100 Subject: [PATCH 18/21] Fix indentation --- homeassistant/components/transmission.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/homeassistant/components/transmission.py b/homeassistant/components/transmission.py index 2e983c2ecbb2e4..c50de0937065c3 100644 --- a/homeassistant/components/transmission.py +++ b/homeassistant/components/transmission.py @@ -119,7 +119,7 @@ def update(self): try: self.data = self._api.session_stats() self.torrents = self._api.get_torrents() - self.session = self._api.get_session() + self.session = self._api.get_session() self.check_completed_torrent() self.check_started_torrent() From 5dd815f2f439fa901ca7e2feb504f0b107bf7946 Mon Sep 17 00:00:00 2001 From: MatteGary Date: Mon, 7 Jan 2019 14:07:12 +0100 Subject: [PATCH 19/21] Fix Throttle --- homeassistant/components/transmission.py | 1 - 1 file changed, 1 deletion(-) diff --git a/homeassistant/components/transmission.py b/homeassistant/components/transmission.py index c50de0937065c3..291295b03881c8 100644 --- a/homeassistant/components/transmission.py +++ b/homeassistant/components/transmission.py @@ -9,7 +9,6 @@ import logging import voluptuous as vol -from homeassistant.util import Throttle from homeassistant.helpers import discovery from homeassistant.helpers.event import track_time_interval from homeassistant.const import ( From 6c6fe879bce85ccf77caa9165348683cb79a1962 Mon Sep 17 00:00:00 2001 From: MatteGary Date: Mon, 7 Jan 2019 15:46:40 +0100 Subject: [PATCH 20/21] Update .coveragerc --- .coveragerc | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.coveragerc b/.coveragerc index 7fa418f0b46033..dd1c1827f78148 100644 --- a/.coveragerc +++ b/.coveragerc @@ -348,6 +348,9 @@ omit = homeassistant/components/tradfri.py homeassistant/components/*/tradfri.py + + homeassistant/components/transmission.py + homeassistant/components/*/transmission.py homeassistant/components/notify/twilio_sms.py homeassistant/components/notify/twilio_call.py From 059f43c267f3fa0d1a8591ef58cbc8494bd8b585 Mon Sep 17 00:00:00 2001 From: MatteGary Date: Mon, 14 Jan 2019 09:03:45 +0100 Subject: [PATCH 21/21] Fix import and coveragerc --- .coveragerc | 2 -- homeassistant/components/switch/transmission.py | 2 +- homeassistant/components/transmission.py | 12 ++++++------ 3 files changed, 7 insertions(+), 9 deletions(-) diff --git a/.coveragerc b/.coveragerc index dd1c1827f78148..465267b53d3469 100644 --- a/.coveragerc +++ b/.coveragerc @@ -826,7 +826,6 @@ omit = homeassistant/components/sensor/time_date.py homeassistant/components/sensor/torque.py homeassistant/components/sensor/trafikverket_weatherstation.py - homeassistant/components/sensor/transmission.py homeassistant/components/sensor/travisci.py homeassistant/components/sensor/twitch.py homeassistant/components/sensor/uber.py @@ -870,7 +869,6 @@ omit = homeassistant/components/switch/switchmate.py homeassistant/components/switch/telnet.py homeassistant/components/switch/tplink.py - homeassistant/components/switch/transmission.py homeassistant/components/switch/vesync.py homeassistant/components/telegram_bot/* homeassistant/components/thingspeak.py diff --git a/homeassistant/components/switch/transmission.py b/homeassistant/components/switch/transmission.py index 7e9e34cec0f252..3ce3c7a98f9ce5 100644 --- a/homeassistant/components/switch/transmission.py +++ b/homeassistant/components/switch/transmission.py @@ -10,8 +10,8 @@ DATA_TRANSMISSION, SCAN_INTERVAL) from homeassistant.const import ( STATE_OFF, STATE_ON) -from homeassistant.util import Throttle from homeassistant.helpers.entity import ToggleEntity +from homeassistant.util import Throttle DEPENDENCIES = ['transmission'] diff --git a/homeassistant/components/transmission.py b/homeassistant/components/transmission.py index 291295b03881c8..cdf55c8e049486 100644 --- a/homeassistant/components/transmission.py +++ b/homeassistant/components/transmission.py @@ -9,17 +9,17 @@ import logging import voluptuous as vol -from homeassistant.helpers import discovery -from homeassistant.helpers.event import track_time_interval from homeassistant.const import ( CONF_HOST, - CONF_PASSWORD, + CONF_MONITORED_CONDITIONS, CONF_NAME, + CONF_PASSWORD, CONF_PORT, - CONF_USERNAME, - CONF_MONITORED_CONDITIONS, + CONF_USERNAME ) -import homeassistant.helpers.config_validation as cv +from homeassistant.helpers import discovery, config_validation as cv +from homeassistant.helpers.event import track_time_interval + REQUIREMENTS = ['transmissionrpc==0.11'] _LOGGER = logging.getLogger(__name__)