Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added qbittorrent sensor platform #18618

Merged
merged 24 commits into from Nov 29, 2018
Merged
Show file tree
Hide file tree
Changes from 18 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions .coveragerc
Expand Up @@ -780,6 +780,7 @@ omit =
homeassistant/components/sensor/pushbullet.py
homeassistant/components/sensor/pvoutput.py
homeassistant/components/sensor/pyload.py
homeassistant/components/sensor/qbittorrent.py
homeassistant/components/sensor/qnap.py
homeassistant/components/sensor/radarr.py
homeassistant/components/sensor/rainbird.py
Expand Down
139 changes: 139 additions & 0 deletions homeassistant/components/sensor/qbittorrent.py
@@ -0,0 +1,139 @@
"""Support for monitoring the qBittorrent API."""
import logging

import voluptuous as vol

from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
CONF_NAME, CONF_PASSWORD, CONF_URL, CONF_USERNAME, STATE_IDLE)
from homeassistant.helpers.entity import Entity
import homeassistant.helpers.config_validation as cv
from homeassistant.exceptions import PlatformNotReady

from requests.exceptions import RequestException

REQUIREMENTS = ['python-qbittorrent==0.3.1']

_LOGGER = logging.getLogger(__name__)

SENSOR_TYPE_CURRENT_STATUS = 'current_status'
SENSOR_TYPE_DOWNLOAD_SPEED = 'download_speed'
SENSOR_TYPE_UPLOAD_SPEED = 'upload_speed'

DEFAULT_NAME = 'qBittorrent'

SENSOR_TYPES = {
SENSOR_TYPE_CURRENT_STATUS: ['Status', None],
SENSOR_TYPE_DOWNLOAD_SPEED: ['Down Speed', 'kB/s'],
SENSOR_TYPE_UPLOAD_SPEED: ['Up Speed', 'kB/s'],
}

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_URL): cv.url,
vol.Required(CONF_USERNAME): cv.string,
vol.Required(CONF_PASSWORD): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string
})


async def async_setup_platform(hass, config, add_entities,
eliseomartelli marked this conversation as resolved.
Show resolved Hide resolved
discovery_info=None):
"""Set up the qbittorrent sensors."""
from qbittorrent.client import Client, LoginRequired

try:
client = Client(config.get(CONF_URL))
eliseomartelli marked this conversation as resolved.
Show resolved Hide resolved
client.login(config.get(CONF_USERNAME), config.get(CONF_PASSWORD))
except LoginRequired:
_LOGGER.info("Invalid authentication for qBittorrent. Check config.")
MartinHjelmare marked this conversation as resolved.
Show resolved Hide resolved
return
except RequestException:
_LOGGER.error("Connection to qBittorrent failed. Check config.")
raise PlatformNotReady
eliseomartelli marked this conversation as resolved.
Show resolved Hide resolved

name = config.get(CONF_NAME)

dev = []
for sensor_type in SENSOR_TYPES:
sensor = QBittorrentSensor(sensor_type, client, name, LoginRequired)
dev.append(sensor)
await sensor.async_update()
eliseomartelli marked this conversation as resolved.
Show resolved Hide resolved

add_entities(dev)
eliseomartelli marked this conversation as resolved.
Show resolved Hide resolved


def format_speed(speed):
"""Return a bytes/s measurement as a human readable string."""
kb_spd = float(speed) / 1024
return round(kb_spd, 2 if kb_spd < 0.1 else 1)


class QBittorrentSensor(Entity):
"""Representation of an qbittorrent sensor."""

def __init__(self, sensor_type, qbittorrent_client, client_name, exception):
eliseomartelli marked this conversation as resolved.
Show resolved Hide resolved
"""Initialize the sensor."""
self._name = SENSOR_TYPES[sensor_type][0]
self.client = qbittorrent_client
self.type = sensor_type
self.client_name = client_name
self._state = None
self._unit_of_measurement = SENSOR_TYPES[sensor_type][1]
self._available = False
self._exception = exception

@property
def name(self):
"""Return the name of the sensor."""
return '{} {}'.format(self.client_name, self._name)

@property
def state(self):
"""Return the state of the sensor."""
return self._state

@property
def available(self):
"""Return true if device is available."""
return self._available

@property
def unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
return self._unit_of_measurement

async def async_update(self):
"""Get the latest data from qbittorrent and updates the state."""
try:
data = self.client.sync()
eliseomartelli marked this conversation as resolved.
Show resolved Hide resolved
self._available = True
except RequestException:
_LOGGER.error("Connection to qBittorrent lost.")
eliseomartelli marked this conversation as resolved.
Show resolved Hide resolved
self._available = False
return
except self._exception:
_LOGGER.info("Invalid authentication for qBittorrent."
eliseomartelli marked this conversation as resolved.
Show resolved Hide resolved
" Check config.")
return

download = data['server_state']['dl_info_speed']
upload = data['server_state']['up_info_speed']

if self.type == SENSOR_TYPE_CURRENT_STATUS:
if data:
eliseomartelli marked this conversation as resolved.
Show resolved Hide resolved
if upload > 0 and download > 0:
self._state = 'Up/Down'
eliseomartelli marked this conversation as resolved.
Show resolved Hide resolved
elif upload > 0 and download == 0:
self._state = 'Seeding'
elif upload == 0 and download > 0:
self._state = 'Downloading'
else:
self._state = STATE_IDLE
else:
self._state = None

if data:
eliseomartelli marked this conversation as resolved.
Show resolved Hide resolved
if self.type == SENSOR_TYPE_DOWNLOAD_SPEED:
self._state = format_speed(download)
elif self.type == SENSOR_TYPE_UPLOAD_SPEED:
self._state = format_speed(upload)
3 changes: 3 additions & 0 deletions requirements_all.txt
Expand Up @@ -1233,6 +1233,9 @@ python-nmap==0.6.1
# homeassistant.components.notify.pushover
python-pushover==0.3

# homeassistant.components.sensor.qbittorrent
python-qbittorrent==0.3.1

# homeassistant.components.sensor.ripple
python-ripple-api==0.0.3

Expand Down