Update docstrings to match PEP257

This commit is contained in:
Fabian Affolter 2016-03-07 18:12:06 +01:00
parent 032f06e015
commit 7ff9aecd4e
19 changed files with 146 additions and 247 deletions

View File

@ -1,6 +1,4 @@
"""
homeassistant.components.device_tracker
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provides functionality to keep track of devices.
For more details about this component, please refer to the documentation at
@ -89,7 +87,7 @@ def see(hass, mac=None, dev_id=None, host_name=None, location_name=None,
def setup(hass, config):
""" Setup device tracker """
"""Setup device tracker."""
yaml_path = hass.config.path(YAML_DEVICES)
conf = config.get(DOMAIN, {})
@ -163,7 +161,7 @@ def setup(hass, config):
class DeviceTracker(object):
""" Track devices """
"""Represents a device tracker."""
def __init__(self, hass, consider_home, track_new, home_range, devices):
self.hass = hass
self.devices = {dev.dev_id: dev for dev in devices}
@ -236,8 +234,7 @@ class DeviceTracker(object):
class Device(Entity):
""" Tracked device. """
"""Represents a tracked device."""
host_name = None
location_name = None
gps = None
@ -245,7 +242,7 @@ class Device(Entity):
last_seen = None
battery = None
# Track if the last update of this device was HOME
# Track if the last update of this device was HOME.
last_update_home = False
_state = STATE_NOT_HOME
@ -288,17 +285,17 @@ class Device(Entity):
@property
def state(self):
""" State of the device. """
"""Return the state of the device."""
return self._state
@property
def entity_picture(self):
"""Picture of the device."""
"""Return the picture of the device."""
return self.config_picture
@property
def state_attributes(self):
""" Device state attributes. """
"""Return the device state attributes."""
attr = {}
if self.gps:
@ -365,7 +362,7 @@ class Device(Entity):
def load_config(path, hass, consider_home, home_range):
""" Load devices from YAML config file. """
"""Load devices from YAML configuration file."""
if not os.path.isfile(path):
return []
return [
@ -401,7 +398,7 @@ def setup_scanner_platform(hass, config, scanner, see_device):
def update_config(path, dev_id, device):
""" Add device to YAML config file. """
"""Add device to YAML configuration file."""
with open(path, 'a') as out:
out.write('\n')
out.write('{}:\n'.format(device.dev_id))

View File

@ -1,8 +1,5 @@
"""
homeassistant.components.device_tracker.actiontec
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Device tracker platform that supports scanning an Actiontec MI424WR
(Verizon FIOS) router for device presence.
Support for Actiontec MI424WR (Verizon FIOS) routers.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/device_tracker.actiontec/
@ -20,7 +17,7 @@ from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME
from homeassistant.helpers import validate_config
from homeassistant.util import Throttle
# Return cached results if last scan was less then this time ago
# Return cached results if last scan was less then this time ago.
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=5)
_LOGGER = logging.getLogger(__name__)
@ -34,7 +31,7 @@ _LEASES_REGEX = re.compile(
# pylint: disable=unused-argument
def get_scanner(hass, config):
""" Validates config and returns an Actiontec scanner. """
"""Validates configuration and returns an Actiontec scanner."""
if not validate_config(config,
{DOMAIN: [CONF_HOST, CONF_USERNAME, CONF_PASSWORD]},
_LOGGER):
@ -50,7 +47,6 @@ class ActiontecDeviceScanner(object):
This class queries a an actiontec router for connected devices.
Adapted from DD-WRT scanner.
"""
def __init__(self, config):
self.host = config[CONF_HOST]
self.username = config[CONF_USERNAME]
@ -65,7 +61,6 @@ class ActiontecDeviceScanner(object):
"""
Scans for new devices and return a list containing found device ids.
"""
self._update_info()
return [client.mac for client in self.last_results]

View File

@ -1,8 +1,5 @@
"""
homeassistant.components.device_tracker.aruba
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Device tracker platform that supports scanning a Aruba Access Point for device
presence.
Support for Aruba Access Points.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/device_tracker.aruba/
@ -31,7 +28,7 @@ _DEVICES_REGEX = re.compile(
# pylint: disable=unused-argument
def get_scanner(hass, config):
""" Validates config and returns a Aruba scanner. """
"""Validates configuration and returns a Aruba scanner."""
if not validate_config(config,
{DOMAIN: [CONF_HOST, CONF_USERNAME, CONF_PASSWORD]},
_LOGGER):
@ -43,8 +40,7 @@ def get_scanner(hass, config):
class ArubaDeviceScanner(object):
""" This class queries a Aruba Acces Point for connected devices. """
"""This class queries a Aruba Access Point for connected devices."""
def __init__(self, config):
self.host = config[CONF_HOST]
self.username = config[CONF_USERNAME]
@ -62,7 +58,6 @@ class ArubaDeviceScanner(object):
"""
Scans for new devices and return a list containing found device IDs.
"""
self._update_info()
return [client['mac'] for client in self.last_results]
@ -94,7 +89,6 @@ class ArubaDeviceScanner(object):
def get_aruba_data(self):
"""Retrieve data from Aruba Access Point and return parsed result."""
import pexpect
connect = "ssh {}@{}"
ssh = pexpect.spawn(connect.format(self.username, self.host))

View File

@ -1,8 +1,5 @@
"""
homeassistant.components.device_tracker.asuswrt
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Device tracker platform that supports scanning a ASUSWRT router for device
presence.
Support for ASUSWRT routers.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/device_tracker.asuswrt/
@ -18,7 +15,7 @@ from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME
from homeassistant.helpers import validate_config
from homeassistant.util import Throttle
# Return cached results if last scan was less then this time ago
# Return cached results if last scan was less then this time ago.
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=5)
_LOGGER = logging.getLogger(__name__)
@ -39,7 +36,7 @@ _IP_NEIGH_REGEX = re.compile(
# pylint: disable=unused-argument
def get_scanner(hass, config):
""" Validates config and returns an ASUS-WRT scanner. """
"""Validates configuration and returns an ASUS-WRT scanner."""
if not validate_config(config,
{DOMAIN: [CONF_HOST, CONF_USERNAME, CONF_PASSWORD]},
_LOGGER):
@ -55,7 +52,6 @@ class AsusWrtDeviceScanner(object):
This class queries a router running ASUSWRT firmware
for connected devices. Adapted from DD-WRT scanner.
"""
def __init__(self, config):
self.host = config[CONF_HOST]
self.username = str(config[CONF_USERNAME])
@ -73,7 +69,6 @@ class AsusWrtDeviceScanner(object):
"""
Scans for new devices and return a list containing found device IDs.
"""
self._update_info()
return [client['mac'] for client in self.last_results]
@ -138,9 +133,8 @@ class AsusWrtDeviceScanner(object):
_LOGGER.warning("Could not parse lease row: %s", lease)
continue
# For leases where the client doesn't set a hostname, ensure
# it is blank and not '*', which breaks the entity_id down
# the line
# For leases where the client doesn't set a hostname, ensure it is
# blank and not '*', which breaks the entity_id down the line.
host = match.group('host')
if host == '*':
host = ''

View File

@ -1,8 +1,5 @@
"""
homeassistant.components.device_tracker.ddwrt
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Device tracker platform that supports scanning a DD-WRT router for device
presence.
Support for DD-WRT routers.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/device_tracker.ddwrt/
@ -19,7 +16,7 @@ from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME
from homeassistant.helpers import validate_config
from homeassistant.util import Throttle
# Return cached results if last scan was less then this time ago
# Return cached results if last scan was less then this time ago.
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=5)
_LOGGER = logging.getLogger(__name__)
@ -47,7 +44,6 @@ class DdWrtDeviceScanner(object):
This class queries a wireless router running DD-WRT firmware
for connected devices. Adapted from Tomato scanner.
"""
def __init__(self, config):
self.host = config[CONF_HOST]
self.username = config[CONF_USERNAME]
@ -68,16 +64,14 @@ class DdWrtDeviceScanner(object):
"""
Scans for new devices and return a list containing found device ids.
"""
self._update_info()
return self.last_results
def get_device_name(self, device):
"""Returns the name of the given device or None if we don't know."""
with self.lock:
# if not initialised and not already scanned and not found
# If not initialised and not already scanned and not found.
if device not in self.mac2name:
url = 'http://{}/Status_Lan.live.asp'.format(self.host)
data = self.get_ddwrt_data(url)
@ -90,15 +84,15 @@ class DdWrtDeviceScanner(object):
if not dhcp_leases:
return None
# remove leading and trailing single quotes
# Remove leading and trailing single quotes.
cleaned_str = dhcp_leases.strip().strip('"')
elements = cleaned_str.split('","')
num_clients = int(len(elements)/5)
self.mac2name = {}
for idx in range(0, num_clients):
# this is stupid but the data is a single array
# This is stupid but the data is a single array
# every 5 elements represents one hosts, the MAC
# is the third element and the name is the first
# is the third element and the name is the first.
mac_index = (idx * 5) + 2
if mac_index < len(elements):
mac = elements[mac_index]
@ -135,7 +129,7 @@ class DdWrtDeviceScanner(object):
# regex's out values so I guess I have to do the same,
# LAME!!!
# remove leading and trailing single quotes
# Remove leading and trailing single quotes.
clean_str = active_clients.strip().strip("'")
elements = clean_str.split("','")

View File

@ -1,10 +1,5 @@
"""
homeassistant.components.device_tracker.demo
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Demo platform for the device tracker.
device_tracker:
platform: demo
"""
import random
@ -12,8 +7,7 @@ from homeassistant.components.device_tracker import DOMAIN
def setup_scanner(hass, config, see):
""" Set up a demo tracker. """
"""Setup the demo tracker."""
def offset():
"""Return random offset."""
return (random.randrange(500, 2000)) / 2e5 * random.choice((-1, 1))

View File

@ -1,8 +1,5 @@
"""
homeassistant.components.device_tracker.fritz
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Device tracker platform that supports scanning a FRITZ!Box router for device
presence.
Support for FRITZ!Box routers.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/device_tracker.fritz/
@ -17,15 +14,14 @@ from homeassistant.util import Throttle
REQUIREMENTS = ['fritzconnection==0.4.6']
# Return cached results if last scan was less then this time ago
# Return cached results if last scan was less then this time ago.
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=5)
_LOGGER = logging.getLogger(__name__)
# noinspection PyUnusedLocal
def get_scanner(hass, config):
""" Validates config and returns FritzBoxScanner. """
"""Validates configuration and returns FritzBoxScanner."""
if not validate_config(config,
{DOMAIN: []},
_LOGGER):
@ -52,7 +48,7 @@ class FritzBoxScanner(object):
"""
def __init__(self, config):
self.last_results = []
self.host = '169.254.1.1' # This IP is valid for all fritzboxes
self.host = '169.254.1.1' # This IP is valid for all FRITZ!Box router.
self.username = 'admin'
self.password = ''
self.success_init = True
@ -68,7 +64,7 @@ class FritzBoxScanner(object):
if CONF_PASSWORD in config.keys():
self.password = config[CONF_PASSWORD]
# Establish a connection to the FRITZ!Box
# Establish a connection to the FRITZ!Box.
try:
self.fritz_box = fc.FritzHosts(address=self.host,
user=self.username,
@ -77,7 +73,7 @@ class FritzBoxScanner(object):
self.fritz_box = None
# At this point it is difficult to tell if a connection is established.
# So just check for null objects ...
# So just check for null objects.
if self.fritz_box is None or not self.fritz_box.modelname:
self.success_init = False

View File

@ -1,7 +1,5 @@
"""
homeassistant.components.device_tracker.icloud
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Device tracker platform that supports scanning iCloud devices.
Support for iCloud connected devices.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/device_tracker.icloud/
@ -26,7 +24,7 @@ def setup_scanner(hass, config, see):
from pyicloud.exceptions import PyiCloudFailedLoginException
from pyicloud.exceptions import PyiCloudNoDevicesException
# Get the username and password from the configuration
# Get the username and password from the configuration.
username = config.get(CONF_USERNAME)
password = config.get(CONF_PASSWORD)

View File

@ -1,7 +1,5 @@
"""
homeassistant.components.device_tracker.locative
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Locative platform for the device tracker.
Support for the Locative platform.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/device_tracker.locative/
@ -20,12 +18,10 @@ URL_API_LOCATIVE_ENDPOINT = "/api/locative"
def setup_scanner(hass, config, see):
""" Set up an endpoint for the Locative app. """
"""Setup an endpoint for the Locative application."""
# POST would be semantically better, but that currently does not work
# since Locative sends the data as key1=value1&key2=value2
# in the request body, while Home Assistant expects json there.
hass.http.register_path(
'GET', URL_API_LOCATIVE_ENDPOINT,
partial(_handle_get_api_locative, hass, see))
@ -35,7 +31,6 @@ def setup_scanner(hass, config, see):
def _handle_get_api_locative(hass, see, handler, path_match, data):
"""Locative message received."""
if not _check_data(handler, data):
return
@ -76,6 +71,7 @@ def _handle_get_api_locative(hass, see, handler, path_match, data):
def _check_data(handler, data):
"""Check the data."""
if 'latitude' not in data or 'longitude' not in data:
handler.write_text("Latitude and longitude not specified.",
HTTP_UNPROCESSABLE_ENTITY)

View File

@ -1,8 +1,5 @@
"""
homeassistant.components.device_tracker.luci
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Device tracker platform that supports scanning a OpenWRT router for device
presence.
Support for OpenWRT routers.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/device_tracker.luci/
@ -20,14 +17,14 @@ from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME
from homeassistant.helpers import validate_config
from homeassistant.util import Throttle
# Return cached results if last scan was less then this time ago
# Return cached results if last scan was less then this time ago.
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=5)
_LOGGER = logging.getLogger(__name__)
def get_scanner(hass, config):
""" Validates config and returns a Luci scanner. """
"""Validates configuration and returns a Luci scanner."""
if not validate_config(config,
{DOMAIN: [CONF_HOST, CONF_USERNAME, CONF_PASSWORD]},
_LOGGER):
@ -52,7 +49,6 @@ class LuciDeviceScanner(object):
(Currently, we do only wifi iwscan, and no DHCP lease access.)
"""
def __init__(self, config):
host = config[CONF_HOST]
username, password = config[CONF_USERNAME], config[CONF_PASSWORD]
@ -73,14 +69,12 @@ class LuciDeviceScanner(object):
"""
Scans for new devices and return a list containing found device ids.
"""
self._update_info()
return self.last_results
def get_device_name(self, device):
"""Returns the name of the given device or None if we don't know."""
with self.lock:
if self.mac2name is None:
url = 'http://{}/cgi-bin/luci/rpc/uci'.format(self.host)

View File

@ -1,7 +1,5 @@
"""
homeassistant.components.device_tracker.mqtt
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
MQTT platform for the device tracker.
Support for tracking MQTT enabled devices.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/device_tracker.mqtt/
@ -22,7 +20,7 @@ _LOGGER = logging.getLogger(__name__)
def setup_scanner(hass, config, see):
""" Set up a MQTT tracker. """
"""Setup the MQTT tracker."""
devices = config.get(CONF_DEVICES)
qos = util.convert(config.get(CONF_QOS), int, DEFAULT_QOS)

View File

@ -1,8 +1,5 @@
"""
homeassistant.components.device_tracker.netgear
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Device tracker platform that supports scanning a Netgear router for device
presence.
Support for Netgear routers.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/device_tracker.netgear/
@ -15,7 +12,7 @@ from homeassistant.components.device_tracker import DOMAIN
from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME
from homeassistant.util import Throttle
# Return cached results if last scan was less then this time ago
# Return cached results if last scan was less then this time ago.
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=5)
_LOGGER = logging.getLogger(__name__)
@ -23,7 +20,7 @@ REQUIREMENTS = ['pynetgear==0.3.2']
def get_scanner(hass, config):
""" Validates config and returns a Netgear scanner. """
"""Validates configuration and returns a Netgear scanner."""
info = config[DOMAIN]
host = info.get(CONF_HOST)
username = info.get(CONF_USERNAME)
@ -39,8 +36,7 @@ def get_scanner(hass, config):
class NetgearDeviceScanner(object):
""" This class queries a Netgear wireless router using the SOAP-API. """
"""Queries a Netgear wireless router using the SOAP-API."""
def __init__(self, host, username, password):
import pynetgear

View File

@ -1,7 +1,5 @@
"""
homeassistant.components.device_tracker.nmap
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Device tracker platform that supports scanning a network with nmap.
Support for scanning a network with nmap.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/device_tracker.nmap_scanner/
@ -30,7 +28,7 @@ REQUIREMENTS = ['python-nmap==0.4.3']
def get_scanner(hass, config):
""" Validates config and returns a Nmap scanner. """
"""Validates configuration and returns a Nmap scanner."""
if not validate_config(config, {DOMAIN: [CONF_HOSTS]},
_LOGGER):
return None
@ -56,7 +54,6 @@ def _arp(ip_address):
class NmapDeviceScanner(object):
"""This class scans for devices using nmap."""
def __init__(self, config):
self.last_results = []
@ -71,14 +68,12 @@ class NmapDeviceScanner(object):
"""
Scans for new devices and return a list containing found device ids.
"""
self._update_info()
return [device.mac for device in self.last_results]
def get_device_name(self, mac):
"""Returns the name of the given device or None if we don't know."""
filter_named = [device.name for device in self.last_results
if device.mac == mac]

View File

@ -1,7 +1,5 @@
"""
homeassistant.components.device_tracker.owntracks
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
OwnTracks platform for the device tracker.
Support the OwnTracks platform.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/device_tracker.owntracks/
@ -33,12 +31,10 @@ CONF_MAX_GPS_ACCURACY = 'max_gps_accuracy'
def setup_scanner(hass, config, see):
"""Setup an OwnTracks tracker."""
max_gps_accuracy = config.get(CONF_MAX_GPS_ACCURACY)
def owntracks_location_update(topic, payload, qos):
"""MQTT message received."""
# Docs on available data:
# http://owntracks.org/booklet/tech/json/#_typelocation
try:
@ -70,7 +66,6 @@ def setup_scanner(hass, config, see):
def owntracks_event_update(topic, payload, qos):
# pylint: disable=too-many-branches, too-many-statements
"""MQTT event (geofences) received."""
# Docs on available data:
# http://owntracks.org/booklet/tech/json/#_typetransition
try:
@ -157,8 +152,7 @@ def setup_scanner(hass, config, see):
return
def see_beacons(dev_id, kwargs_param):
""" Set active beacons to the current location """
"""Set active beacons to the current location."""
kwargs = kwargs_param.copy()
# the battery state applies to the tracking device, not the beacon
kwargs.pop('battery', None)
@ -168,16 +162,13 @@ def setup_scanner(hass, config, see):
see(**kwargs)
mqtt.subscribe(hass, LOCATION_TOPIC, owntracks_location_update, 1)
mqtt.subscribe(hass, EVENT_TOPIC, owntracks_event_update, 1)
return True
def _parse_see_args(topic, data):
""" Parse the OwnTracks location parameters,
into the format see expects. """
"""Parse the OwnTracks location parameters, into the format see expects."""
parts = topic.split('/')
dev_id = '{}_{}'.format(parts[1], parts[2])
host_name = parts[1]
@ -194,8 +185,7 @@ def _parse_see_args(topic, data):
def _set_gps_from_zone(kwargs, zone):
""" Set the see parameters from the zone parameters """
"""Set the see parameters from the zone parameters."""
if zone is not None:
kwargs['gps'] = (
zone.attributes['latitude'],

View File

@ -1,8 +1,5 @@
"""
homeassistant.components.device_tracker.snmp
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Device tracker platform that supports fetching WiFi associations
through SNMP.
Support for fetching WiFi associations through SNMP.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/device_tracker.snmp/
@ -17,7 +14,7 @@ from homeassistant.const import CONF_HOST
from homeassistant.helpers import validate_config
from homeassistant.util import Throttle
# Return cached results if last scan was less then this time ago
# Return cached results if last scan was less then this time ago.
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=10)
_LOGGER = logging.getLogger(__name__)
@ -29,7 +26,7 @@ CONF_BASEOID = "baseoid"
# pylint: disable=unused-argument
def get_scanner(hass, config):
""" Validates config and returns an snmp scanner """
"""Validates configuration and returns an snmp scanner."""
if not validate_config(config,
{DOMAIN: [CONF_HOST, CONF_COMMUNITY, CONF_BASEOID]},
_LOGGER):
@ -41,9 +38,7 @@ def get_scanner(hass, config):
class SnmpScanner(object):
"""
This class queries any SNMP capable Acces Point for connected devices.
"""
"""Queries any SNMP capable Acces Point for connected devices."""
def __init__(self, config):
from pysnmp.entity.rfc3413.oneliner import cmdgen
self.snmp = cmdgen.CommandGenerator()
@ -64,7 +59,6 @@ class SnmpScanner(object):
"""
Scans for new devices and return a list containing found device IDs.
"""
self._update_info()
return [client['mac'] for client in self.last_results
if client.get('mac')]
@ -94,8 +88,7 @@ class SnmpScanner(object):
return True
def get_snmp_data(self):
""" Fetch mac addresses from WAP via SNMP. """
"""Fetch MAC addresses from WAP via SNMP."""
devices = []
errindication, errstatus, errindex, restable = self.snmp.nextCmd(

View File

@ -1,8 +1,5 @@
"""
homeassistant.components.device_tracker.thomson
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Device tracker platform that supports scanning a THOMSON router for device
presence.
Support for THOMSON routers.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/device_tracker.thomson/
@ -18,7 +15,7 @@ from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME
from homeassistant.helpers import validate_config
from homeassistant.util import Throttle
# Return cached results if last scan was less then this time ago
# Return cached results if last scan was less then this time ago.
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=10)
_LOGGER = logging.getLogger(__name__)
@ -35,7 +32,7 @@ _DEVICES_REGEX = re.compile(
# pylint: disable=unused-argument
def get_scanner(hass, config):
""" Validates config and returns a THOMSON scanner. """
"""Validates configuration and returns a THOMSON scanner."""
if not validate_config(config,
{DOMAIN: [CONF_HOST, CONF_USERNAME, CONF_PASSWORD]},
_LOGGER):
@ -48,10 +45,9 @@ def get_scanner(hass, config):
class ThomsonDeviceScanner(object):
"""
This class queries a router running THOMSON firmware
for connected devices. Adapted from ASUSWRT scanner.
This class queries a router running THOMSON firmware for connected devices.
Adapted from ASUSWRT scanner.
"""
def __init__(self, config):
self.host = config[CONF_HOST]
self.username = config[CONF_USERNAME]
@ -66,15 +62,14 @@ class ThomsonDeviceScanner(object):
self.success_init = data is not None
def scan_devices(self):
""" Scans for new devices and return a
list containing found device ids. """
"""
Scans for new devices and return a list containing found device IDs.
"""
self._update_info()
return [client['mac'] for client in self.last_results]
def get_device_name(self, device):
""" Returns the name of the given device
or None if we don't know. """
"""Returns the name of the given device or None if we don't know."""
if not self.last_results:
return None
for client in self.last_results:

View File

@ -1,8 +1,5 @@
"""
homeassistant.components.device_tracker.tomato
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Device tracker platform that supports scanning a Tomato router for device
presence.
Support for Tomato routers.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/device_tracker.tomato/
@ -20,7 +17,7 @@ from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME
from homeassistant.helpers import validate_config
from homeassistant.util import Throttle
# Return cached results if last scan was less then this time ago
# Return cached results if last scan was less then this time ago.
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=5)
CONF_HTTP_ID = "http_id"
@ -29,7 +26,7 @@ _LOGGER = logging.getLogger(__name__)
def get_scanner(hass, config):
""" Validates config and returns a Tomato scanner. """
"""Validates configuration and returns a Tomato scanner."""
if not validate_config(config,
{DOMAIN: [CONF_HOST, CONF_USERNAME,
CONF_PASSWORD, CONF_HTTP_ID]},
@ -46,7 +43,6 @@ class TomatoDeviceScanner(object):
A description of the Tomato API can be found on
http://paulusschoutsen.nl/blog/2013/10/tomato-api-documentation/
"""
def __init__(self, config):
host, http_id = config[CONF_HOST], config[CONF_HTTP_ID]
username, password = config[CONF_USERNAME], config[CONF_PASSWORD]
@ -68,16 +64,15 @@ class TomatoDeviceScanner(object):
self.success_init = self._update_tomato_info()
def scan_devices(self):
""" Scans for new devices and return a
list containing found device ids. """
"""
Scans for new devices and return a list containing found device IDs.
"""
self._update_tomato_info()
return [item[1] for item in self.last_results['wldev']]
def get_device_name(self, device):
"""Returns the name of the given device or None if we don't know."""
filter_named = [item[0] for item in self.last_results['dhcpd_lease']
if item[2] == device]
@ -89,18 +84,15 @@ class TomatoDeviceScanner(object):
@Throttle(MIN_TIME_BETWEEN_SCANS)
def _update_tomato_info(self):
"""Ensures the information from the Tomato router is up to date.
Returns boolean if scanning successful. """
Returns boolean if scanning successful.
"""
with self.lock:
self.logger.info("Scanning")
try:
response = requests.Session().send(self.req, timeout=3)
# Calling and parsing the Tomato api here. We only need the
# wldev and dhcpd_lease values. For API description see:
# http://paulusschoutsen.nl/
# blog/2013/10/tomato-api-documentation/
# wldev and dhcpd_lease values.
if response.status_code == 200:
for param, value in \
@ -109,7 +101,6 @@ class TomatoDeviceScanner(object):
if param == 'wldev' or param == 'dhcpd_lease':
self.last_results[param] = \
json.loads(value.replace("'", '"'))
return True
elif response.status_code == 401:
@ -117,29 +108,25 @@ class TomatoDeviceScanner(object):
self.logger.exception((
"Failed to authenticate, "
"please check your username and password"))
return False
except requests.exceptions.ConnectionError:
# We get this if we could not connect to the router or
# an invalid http_id was supplied
# an invalid http_id was supplied.
self.logger.exception((
"Failed to connect to the router"
" or invalid http_id supplied"))
return False
except requests.exceptions.Timeout:
# We get this if we could not connect to the router or
# an invalid http_id was supplied
# an invalid http_id was supplied.
self.logger.exception(
"Connection to the router timed out")
return False
except ValueError:
# If json decoder could not parse the response
# If JSON decoder could not parse the response.
self.logger.exception(
"Failed to parse response from router")
return False

View File

@ -1,8 +1,5 @@
"""
homeassistant.components.device_tracker.ubus
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Device tracker platform that supports scanning a OpenWRT router for device
presence.
Support for OpenWRT (ubus) routers.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/device_tracker.ubus/
@ -20,14 +17,14 @@ from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME
from homeassistant.helpers import validate_config
from homeassistant.util import Throttle
# Return cached results if last scan was less then this time ago
# Return cached results if last scan was less then this time ago.
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=5)
_LOGGER = logging.getLogger(__name__)
def get_scanner(hass, config):
""" Validates config and returns a Luci scanner. """
"""Validates configuration and returns a Luci scanner."""
if not validate_config(config,
{DOMAIN: [CONF_HOST, CONF_USERNAME, CONF_PASSWORD]},
_LOGGER):
@ -74,16 +71,13 @@ class UbusDeviceScanner(object):
def scan_devices(self):
"""
Scans for new devices and return a list containing found device ids.
Scans for new devices and return a list containing found device IDs.
"""
self._update_info()
return self.last_results
def get_device_name(self, device):
"""Returns the name of the given device or None if we don't know."""
with self.lock:
if self.leasefile is None:
result = _req_json_rpc(self.url, self.session_id,
@ -142,7 +136,6 @@ class UbusDeviceScanner(object):
def _req_json_rpc(url, session_id, rpcmethod, subsystem, method, **params):
"""Perform one JSON RPC operation."""
data = json.dumps({"jsonrpc": "2.0",
"id": 1,
"method": rpcmethod,
@ -167,7 +160,7 @@ def _req_json_rpc(url, session_id, rpcmethod, subsystem, method, **params):
def _get_session_id(url, username, password):
""" Get authentication token for the given host+username+password. """
"""Get the authentication token for the given host+username+password."""
res = _req_json_rpc(url, "00000000000000000000000000000000", 'call',
'session', 'login', username=username,
password=password)

View File

@ -1,7 +1,8 @@
"""
homeassistant.components.device_tracker.unifi
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Device tracker platform that supports scanning a Unifi WAP controller
Support for Unifi WAP controllers.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/device_tracker.unifi/
"""
import logging
import urllib
@ -17,7 +18,7 @@ CONF_PORT = 'port'
def get_scanner(hass, config):
""" Sets up unifi device_tracker """
"""Setup Unifi device_tracker."""
from unifi.controller import Controller
if not validate_config(config, {DOMAIN: [CONF_USERNAME,
@ -48,7 +49,6 @@ def get_scanner(hass, config):
class UnifiScanner(object):
"""Provide device_tracker support from Unifi WAP client data."""
def __init__(self, controller):
self._controller = controller
self._update()