Update docstrings (#7361)

* Update docstrings

* Update docstrings

* Update docstrings

* Update docstrings

* update docstrings

* Update docstrings

* Update docstrings

* Update docstrings

* Update docstrings

* Update docstrings

* Update tomato.py

* Update isy994.py

* Lint + fix tests

* Lint
This commit is contained in:
Fabian Affolter authored and Paulus Schoutsen committed 2017-04-29 22:04:49 -07:00
1 parent e22e70a01a
commit 3ee4d1060f
264 files changed
+1686 -1768

No files matched your search

@@ -34,7 +34,7 @@ from homeassistant.util.yaml import dump
from homeassistant.helpers.event import async_track_utc_time_change
from homeassistant.const import (
ATTR_GPS_ACCURACY, ATTR_LATITUDE, ATTR_LONGITUDE,
ATTR_GPS_ACCURACY, ATTR_LATITUDE, ATTR_LONGITUDE, CONF_NAME, CONF_MAC,
DEVICE_DEFAULT_NAME, STATE_HOME, STATE_NOT_HOME, ATTR_ENTITY_ID)
_LOGGER = logging.getLogger(__name__)
@@ -65,13 +65,14 @@ EVENT_NEW_DEVICE = 'device_tracker_new_device'
SERVICE_SEE = 'see'
ATTR_MAC = 'mac'
ATTR_ATTRIBUTES = 'attributes'
ATTR_BATTERY = 'battery'
ATTR_DEV_ID = 'dev_id'
ATTR_GPS = 'gps'
ATTR_HOST_NAME = 'host_name'
ATTR_LOCATION_NAME = 'location_name'
ATTR_GPS = 'gps'
ATTR_BATTERY = 'battery'
ATTR_ATTRIBUTES = 'attributes'
ATTR_MAC = 'mac'
ATTR_NAME = 'name'
ATTR_SOURCE_TYPE = 'source_type'
SOURCE_TYPE_GPS = 'gps'
@@ -117,7 +118,7 @@ def see(hass: HomeAssistantType, mac: str=None, dev_id: str=None,
@asyncio.coroutine
def async_setup(hass: HomeAssistantType, config: ConfigType):
"""Setup device tracker."""
"""Set up the device tracker."""
yaml_path = hass.config.path(YAML_DEVICES)
try:
@@ -135,7 +136,7 @@ def async_setup(hass: HomeAssistantType, config: ConfigType):
@asyncio.coroutine
def async_setup_platform(p_type, p_config, disc_info=None):
"""Setup a device tracker platform."""
"""Set up a device tracker platform."""
platform = yield from async_prepare_setup_platform(
hass, config, DOMAIN, p_type)
if platform is None:
@@ -167,11 +168,11 @@ def async_setup(hass: HomeAssistantType, config: ConfigType):
return
if not setup:
_LOGGER.error('Error setting up platform %s', p_type)
_LOGGER.error("Error setting up platform %s", p_type)
return
except Exception: # pylint: disable=broad-except
_LOGGER.exception('Error setting up platform %s', p_type)
_LOGGER.exception("Error setting up platform %s", p_type)
setup_tasks = [async_setup_platform(p_type, p_config) for p_type, p_config
in config_per_platform(config, DOMAIN)]
@@ -182,7 +183,7 @@ def async_setup(hass: HomeAssistantType, config: ConfigType):
@callback
def async_device_tracker_discovered(service, info):
"""Called when a device tracker platform is discovered."""
"""Handle the discovery of device tracker platforms."""
hass.async_add_job(
async_setup_platform(DISCOVERY_PLATFORMS[service], {}, info))
@@ -191,7 +192,7 @@ def async_setup(hass: HomeAssistantType, config: ConfigType):
@asyncio.coroutine
def async_platform_discovered(platform, info):
"""Callback to load a platform."""
"""Load a platform."""
yield from async_setup_platform(platform, {}, disc_info=info)
discovery.async_listen_platform(hass, DOMAIN, async_platform_discovered)
@@ -272,9 +273,9 @@ class DeviceTracker(object):
device = self.devices.get(dev_id)
if device:
yield from device.async_seen(host_name, location_name, gps,
gps_accuracy, battery, attributes,
source_type)
yield from device.async_seen(
host_name, location_name, gps, gps_accuracy, battery,
attributes, source_type)
if device.track:
yield from device.async_update_ha_state()
return
@@ -288,9 +289,9 @@ class DeviceTracker(object):
if mac is not None:
self.mac_to_dev[mac] = device
yield from device.async_seen(host_name, location_name, gps,
gps_accuracy, battery, attributes,
source_type)
yield from device.async_seen(
host_name, location_name, gps, gps_accuracy, battery, attributes,
source_type)
if device.track:
yield from device.async_update_ha_state()
@@ -310,8 +311,8 @@ class DeviceTracker(object):
# update known_devices.yaml
self.hass.async_add_job(
self.async_update_config(self.hass.config.path(YAML_DEVICES),
dev_id, device)
self.async_update_config(
self.hass.config.path(YAML_DEVICES), dev_id, device)
)
@asyncio.coroutine
@@ -349,7 +350,7 @@ class DeviceTracker(object):
@asyncio.coroutine
def async_setup_tracked_device(self):
"""Setup all not exists tracked devices.
"""Set up all not exists tracked devices.
This method is a coroutine.
"""
@@ -486,8 +487,8 @@ class Device(Entity):
except (ValueError, TypeError, IndexError):
self.gps = None
self.gps_accuracy = 0
_LOGGER.warning('Could not parse gps value for %s: %s',
self.dev_id, gps)
_LOGGER.warning(
"Could not parse gps value for %s: %s", self.dev_id, gps)
# pylint: disable=not-an-iterable
yield from self.async_update()
@@ -535,7 +536,6 @@ class Device(Entity):
@asyncio.coroutine
def get_vendor_for_mac(self):
"""Try to find the vendor string for a given MAC address."""
# can't continue without a mac
if not self.mac:
return None
@@ -544,11 +544,10 @@ class Device(Entity):
else:
mac = self.mac
# prevent lookup of invalid macs
if not len(mac.split(':')) == 6:
return 'unknown'
# we only need the first 3 bytes of the mac for a lookup
# We only need the first 3 bytes of the MAC for a lookup
# this improves somewhat on privacy
oui_bytes = mac.split(':')[0:3]
# bytes like 00 get truncates to 0, API needs full bytes
@@ -563,7 +562,7 @@ class Device(Entity):
if resp.status == 200:
vendor_string = yield from resp.text()
return vendor_string
# if vendor is not known to the API (404) or there
# If vendor is not known to the API (404) or there
# was a failure during the lookup (500); set vendor
# to something other then None to prevent retry
# as the value is only relevant when it is to be stored
@@ -571,12 +570,12 @@ class Device(Entity):
# the first time the device is seen.
return 'unknown'
except (asyncio.TimeoutError, aiohttp.ClientError):
# same as above
# Same as above
return 'unknown'
@asyncio.coroutine
def async_added_to_hass(self):
"""Called when entity about to be added to hass."""
"""Add an entity."""
state = yield from async_get_last_state(self.hass, self.entity_id)
if not state:
return
@@ -637,10 +636,10 @@ def async_load_config(path: str, hass: HomeAssistantType,
This method is a coroutine.
"""
dev_schema = vol.Schema({
vol.Required('name'): cv.string,
vol.Required(CONF_NAME): cv.string,
vol.Optional('track', default=False): cv.boolean,
vol.Optional('mac', default=None): vol.Any(None, vol.All(cv.string,
vol.Upper)),
vol.Optional(CONF_MAC, default=None):
vol.Any(None, vol.All(cv.string, vol.Upper)),
vol.Optional(CONF_AWAY_HIDE, default=DEFAULT_AWAY_HIDE): cv.boolean,
vol.Optional('gravatar', default=None): vol.Any(None, cv.string),
vol.Optional('picture', default=None): vol.Any(None, cv.string),
@@ -654,7 +653,7 @@ def async_load_config(path: str, hass: HomeAssistantType,
devices = yield from hass.loop.run_in_executor(
None, load_yaml_config_file, path)
except HomeAssistantError as err:
_LOGGER.error('Unable to load %s: %s', path, str(err))
_LOGGER.error("Unable to load %s: %s", path, str(err))
return []
for dev_id, device in devices.items():
@@ -675,7 +674,7 @@ def async_load_config(path: str, hass: HomeAssistantType,
def async_setup_scanner_platform(hass: HomeAssistantType, config: ConfigType,
scanner: Any, async_see_device: Callable,
platform: str):
"""Helper method to connect scanner-based platform to device tracker.
"""Set up the connect scanner-based platform to device tracker.
This method must be run in the event loop.
"""
@@ -688,7 +687,7 @@ def async_setup_scanner_platform(hass: HomeAssistantType, config: ConfigType,
@asyncio.coroutine
def async_device_tracker_scan(now: dt_util.dt.datetime):
"""Called when interval matches."""
"""Handle interval matches."""
if update_lock.locked():
_LOGGER.warning(
"Updating device list from %s took longer than the scheduled "
@@ -727,8 +726,8 @@ def update_config(path: str, dev_id: str, device: Device):
"""Add device to YAML configuration file."""
with open(path, 'a') as out:
device = {device.dev_id: {
'name': device.name,
'mac': device.mac,
ATTR_NAME: device.name,
ATTR_MAC: device.mac,
'picture': device.config_picture,
'track': device.track,
CONF_AWAY_HIDE: device.away_hide,
@@ -19,7 +19,6 @@ from homeassistant.components.device_tracker import (
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.
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=5)
_LOGGER = logging.getLogger(__name__)
@@ -44,7 +43,7 @@ def get_scanner(hass, config):
return scanner if scanner.success_init else None
Device = namedtuple("Device", ["mac", "ip", "last_update"])
Device = namedtuple('Device', ['mac', 'ip', 'last_update'])
class ActiontecDeviceScanner(DeviceScanner):
@@ -59,7 +58,7 @@ class ActiontecDeviceScanner(DeviceScanner):
self.last_results = []
data = self.get_actiontec_data()
self.success_init = data is not None
_LOGGER.info("actiontec scanner initialized")
_LOGGER.info("canner initialized")
def scan_devices(self):
"""Scan for new devices and return a list with found device IDs."""
@@ -93,7 +92,7 @@ class ActiontecDeviceScanner(DeviceScanner):
self.last_results = [Device(data['mac'], name, now)
for name, data in actiontec_data.items()
if data['timevalid'] > -60]
_LOGGER.info("actiontec scan successful")
_LOGGER.info("Scan successful")
return True
def get_actiontec_data(self):
@@ -115,8 +114,7 @@ class ActiontecDeviceScanner(DeviceScanner):
_LOGGER.exception("Unexpected response from router")
return
except ConnectionRefusedError:
_LOGGER.exception("Connection refused by router," +
" is telnet enabled?")
_LOGGER.exception("Connection refused by router. Telnet enabled?")
return None
devices = {}
@@ -17,11 +17,11 @@ from homeassistant.components.device_tracker import (
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
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=10)
_LOGGER = logging.getLogger(__name__)
REQUIREMENTS = ['pexpect==4.0.1']
_LOGGER = logging.getLogger(__name__)
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=10)
_DEVICES_REGEX = re.compile(
r'(?P<name>([^\s]+))\s+' +
@@ -102,22 +102,22 @@ class ArubaDeviceScanner(DeviceScanner):
'Connection refused',
'Connection timed out'], timeout=120)
if query == 1:
_LOGGER.error('Timeout')
_LOGGER.error("Timeout")
return
elif query == 2:
_LOGGER.error('Unexpected response from router')
_LOGGER.error("Unexpected response from router")
return
elif query == 3:
ssh.sendline('yes')
ssh.expect('password:')
elif query == 4:
_LOGGER.error('Host key Changed')
_LOGGER.error("Host key changed")
return
elif query == 5:
_LOGGER.error('Connection refused by server')
_LOGGER.error("Connection refused by server")
return
elif query == 6:
_LOGGER.error('Connection timed out')
_LOGGER.error("Connection timed out")
return
ssh.sendline(self.password)
ssh.expect('#')
@@ -21,14 +21,19 @@ from homeassistant.const import (
from homeassistant.util import Throttle
import homeassistant.helpers.config_validation as cv
# Return cached results if last scan was less then this time ago.
REQUIREMENTS = ['pexpect==4.0.1']
_LOGGER = logging.getLogger(__name__)
CONF_MODE = 'mode'
CONF_PROTOCOL = 'protocol'
CONF_PUB_KEY = 'pub_key'
CONF_SSH_KEY = 'ssh_key'
DEFAULT_SSH_PORT = 22
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=5)
CONF_PROTOCOL = 'protocol'
CONF_MODE = 'mode'
DEFAULT_SSH_PORT = 22
CONF_SSH_KEY = 'ssh_key'
CONF_PUB_KEY = 'pub_key'
SECRET_GROUP = 'Password or SSH Key'
PLATFORM_SCHEMA = vol.All(
@@ -47,9 +52,6 @@ PLATFORM_SCHEMA = vol.All(
}))
_LOGGER = logging.getLogger(__name__)
REQUIREMENTS = ['pexpect==4.0.1']
_LEASES_CMD = 'cat /var/lib/misc/dnsmasq.leases'
_LEASES_REGEX = re.compile(
r'\w+\s' +
@@ -57,7 +59,7 @@ _LEASES_REGEX = re.compile(
r'(?P<ip>([0-9]{1,3}[\.]){3}[0-9]{1,3})\s' +
r'(?P<host>([^\s]+))')
# command to get both 5GHz and 2.4GHz clients
# Command to get both 5GHz and 2.4GHz clients
_WL_CMD = '{ wl -i eth2 assoclist & wl -i eth1 assoclist ; }'
_WL_REGEX = re.compile(
r'\w+\s' +
@@ -126,12 +128,12 @@ class AsusWrtDeviceScanner(DeviceScanner):
elif self.password:
self.ssh_args['password'] = self.password
else:
_LOGGER.error('No password or private key specified')
_LOGGER.error("No password or private key specified")
self.success_init = False
return
else:
if not self.password:
_LOGGER.error('No password specified')
_LOGGER.error("No password specified")
self.success_init = False
return
@@ -188,10 +190,10 @@ class AsusWrtDeviceScanner(DeviceScanner):
try:
ssh.login(self.host, self.username, **self.ssh_args)
except exceptions.EOF as err:
_LOGGER.error('Connection refused. Is SSH enabled?')
_LOGGER.error("Connection refused. SSH enabled?")
return None
except pxssh.ExceptionPxssh as err:
_LOGGER.error('Unable to connect via SSH: %s', str(err))
_LOGGER.error("Unable to connect via SSH: %s", str(err))
return None
try:
@@ -218,7 +220,7 @@ class AsusWrtDeviceScanner(DeviceScanner):
return AsusWrtResult(neighbors, leases_result, arp_result,
nvram_result)
except pxssh.ExceptionPxssh as exc:
_LOGGER.error('Unexpected response from router: %s', exc)
_LOGGER.error("Unexpected response from router: %s", exc)
return None
def telnet_connection(self):
@@ -252,16 +254,16 @@ class AsusWrtDeviceScanner(DeviceScanner):
return AsusWrtResult(neighbors, leases_result, arp_result,
nvram_result)
except EOFError:
_LOGGER.error('Unexpected response from router')
_LOGGER.error("Unexpected response from router")
return None
except ConnectionRefusedError:
_LOGGER.error('Connection refused by router, is telnet enabled?')
_LOGGER.error("Connection refused by router. Telnet enabled?")
return None
except socket.gaierror as exc:
_LOGGER.error('Socket exception: %s', exc)
_LOGGER.error("Socket exception: %s", exc)
return None
except OSError as exc:
_LOGGER.error('OSError: %s', exc)
_LOGGER.error("OSError: %s", exc)
return None
def get_asuswrt_data(self):
@@ -289,7 +291,7 @@ class AsusWrtDeviceScanner(DeviceScanner):
match = _WL_REGEX.search(lease.decode('utf-8'))
if not match:
_LOGGER.warning('Could not parse wl row: %s', lease)
_LOGGER.warning("Could not parse wl row: %s", lease)
continue
host = ''
@@ -301,7 +303,7 @@ class AsusWrtDeviceScanner(DeviceScanner):
arp_match = _ARP_REGEX.search(
arp.decode('utf-8').lower())
if not arp_match:
_LOGGER.warning('Could not parse arp row: %s', arp)
_LOGGER.warning("Could not parse arp row: %s", arp)
continue
devices[arp_match.group('ip')] = {
@@ -316,7 +318,7 @@ class AsusWrtDeviceScanner(DeviceScanner):
if match.group('mac').upper() in nvr.decode('utf-8'):
nvram_match = _NVRAM_REGEX.search(nvr.decode('utf-8'))
if not nvram_match:
_LOGGER.warning('Could not parse nvr row: %s', nvr)
_LOGGER.warning("Could not parse nvr row: %s", nvr)
continue
# skip current check if already in ARP table
@@ -337,7 +339,7 @@ class AsusWrtDeviceScanner(DeviceScanner):
match = _LEASES_REGEX.search(lease.decode('utf-8'))
if not match:
_LOGGER.warning('Could not parse lease row: %s', lease)
_LOGGER.warning("Could not parse lease row: %s", lease)
continue
# For leases where the client doesn't set a hostname, ensure it
@@ -356,7 +358,7 @@ class AsusWrtDeviceScanner(DeviceScanner):
for neighbor in result.neighbors:
match = _IP_NEIGH_REGEX.search(neighbor.decode('utf-8'))
if not match:
_LOGGER.warning('Could not parse neighbor row: %s', neighbor)
_LOGGER.warning("Could not parse neighbor row: %s", neighbor)
continue
if match.group('ip') in devices:
devices[match.group('ip')]['status'] = match.group('status')
@@ -99,7 +99,7 @@ class AutomaticData(object):
@asyncio.coroutine
def update_vehicle(self, vehicle, name):
"""Updated the specified vehicle's data."""
"""Update the specified vehicle's data."""
import aioautomatic
kwargs = {
@@ -37,7 +37,7 @@ class BboxDeviceScanner(DeviceScanner):
self.last_results = [] # type: List[Device]
self.success_init = self._update_info()
_LOGGER.info("Bbox scanner initialized")
_LOGGER.info("Scanner initialized")
def scan_devices(self):
"""Scan for new devices and return a list with found device IDs."""
@@ -57,7 +57,7 @@ class BboxDeviceScanner(DeviceScanner):
@Throttle(MIN_TIME_BETWEEN_SCANS)
def _update_info(self):
"""Check the bbox for devices.
"""Check the Bbox for devices.
Returns boolean if scanning successful.
"""
@@ -79,5 +79,5 @@ class BboxDeviceScanner(DeviceScanner):
self.last_results = last_results
_LOGGER.info("Bbox scan successful")
_LOGGER.info("Scan successful")
return True
@@ -1,4 +1,9 @@
"""Tracking for bluetooth low energy devices."""
"""
Tracking for bluetooth low energy devices.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/device_tracker.bluetooth_le_tracker/
"""
import logging
import voluptuous as vol
@@ -16,17 +21,17 @@ REQUIREMENTS = ['gattlib==0.20150805']
BLE_PREFIX = 'BLE_'
MIN_SEEN_NEW = 5
CONF_SCAN_DURATION = "scan_duration"
CONF_BLUETOOTH_DEVICE = "device_id"
CONF_SCAN_DURATION = 'scan_duration'
CONF_BLUETOOTH_DEVICE = 'device_id'
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Optional(CONF_SCAN_DURATION, default=10): cv.positive_int,
vol.Optional(CONF_BLUETOOTH_DEVICE, default="hci0"): cv.string
vol.Optional(CONF_BLUETOOTH_DEVICE, default='hci0'): cv.string
})
def setup_scanner(hass, config, see, discovery_info=None):
"""Setup the Bluetooth LE Scanner."""
"""Set up the Bluetooth LE Scanner."""
# pylint: disable=import-error
from gattlib import DiscoveryService
@@ -36,8 +41,8 @@ def setup_scanner(hass, config, see, discovery_info=None):
"""Mark a device as seen."""
if new_device:
if address in new_devices:
_LOGGER.debug("Seen %s %s times", address,
new_devices[address])
_LOGGER.debug(
"Seen %s %s times", address, new_devices[address])
new_devices[address] += 1
if new_devices[address] >= MIN_SEEN_NEW:
_LOGGER.debug("Adding %s to tracked devices", address)
@@ -1,4 +1,9 @@
"""Tracking for bluetooth devices."""
"""
Tracking for bluetooth devices.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/device_tracker.bluetooth_tracker/
"""
import logging
import voluptuous as vol
@@ -22,7 +27,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
def setup_scanner(hass, config, see, discovery_info=None):
"""Setup the Bluetooth Scanner."""
"""Set up the Bluetooth Scanner."""
# pylint: disable=import-error
import bluetooth
@@ -31,11 +36,10 @@ def setup_scanner(hass, config, see, discovery_info=None):
see(mac=BT_PREFIX + device[0], host_name=device[1])
def discover_devices():
"""Discover bluetooth devices."""
result = bluetooth.discover_devices(duration=8,
lookup_names=True,
flush_cache=True,
lookup_class=False)
"""Discover Bluetooth devices."""
result = bluetooth.discover_devices(
duration=8, lookup_names=True, flush_cache=True,
lookup_class=False)
_LOGGER.debug("Bluetooth devices discovered = " + str(len(result)))
return result
@@ -47,14 +51,14 @@ def setup_scanner(hass, config, see, discovery_info=None):
# We just need the devices so set consider_home and home range
# to 0
for device in load_config(yaml_path, hass, 0):
# check if device is a valid bluetooth device
# Check if device is a valid bluetooth device
if device.mac and device.mac[:3].upper() == BT_PREFIX:
if device.track:
devs_to_track.append(device.mac[3:])
else:
devs_donot_track.append(device.mac[3:])
# if track new devices is true discover new devices on startup.
# If track new devices is true discover new devices on startup.
track_new = config.get(CONF_TRACK_NEW, DEFAULT_TRACK_NEW)
if track_new:
for dev in discover_devices():
@@ -66,7 +70,7 @@ def setup_scanner(hass, config, see, discovery_info=None):
interval = config.get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL)
def update_bluetooth(now):
"""Lookup bluetooth device and update status."""
"""Lookup Bluetooth device and update status."""
try:
if track_new:
for dev in discover_devices():
@@ -74,14 +78,14 @@ def setup_scanner(hass, config, see, discovery_info=None):
dev[0] not in devs_donot_track:
devs_to_track.append(dev[0])
for mac in devs_to_track:
_LOGGER.debug("Scanning " + mac)
_LOGGER.debug("Scanning %s", mac)
result = bluetooth.lookup_name(mac, timeout=5)
if not result:
# Could not lookup device name
continue
see_device((mac, result))
except bluetooth.BluetoothError:
_LOGGER.exception('Error looking up bluetooth device!')
_LOGGER.exception("Error looking up Bluetooth device")
track_point_in_utc_time(
hass, update_bluetooth, dt_util.utcnow() + interval)
@@ -21,13 +21,11 @@ from homeassistant.components.device_tracker import (
from homeassistant.const import CONF_HOST
from homeassistant.util import Throttle
# Return cached results if last scan was less then this time ago.
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=10)
_LOGGER = logging.getLogger(__name__)
_MAC_REGEX = re.compile(r'(([0-9A-Fa-f]{1,2}\:){5}[0-9A-Fa-f]{1,2})')
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=10)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_HOST): cv.string
})
@@ -46,7 +44,7 @@ class BTHomeHub5DeviceScanner(DeviceScanner):
def __init__(self, config):
"""Initialise the scanner."""
_LOGGER.info('Initialising BT Home Hub 5')
_LOGGER.info("Initialising BT Home Hub 5")
self.host = config.get(CONF_HOST, '192.168.1.254')
self.lock = threading.Lock()
@@ -87,12 +85,12 @@ class BTHomeHub5DeviceScanner(DeviceScanner):
return False
with self.lock:
_LOGGER.info('Scanning')
_LOGGER.info("Scanning")
data = _get_homehub_data(self.url)
if not data:
_LOGGER.warning('Error scanning devices')
_LOGGER.warning("Error scanning devices")
return False
self.last_results = data
@@ -16,7 +16,6 @@ from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME, \
CONF_PORT
from homeassistant.util import Throttle
# Return cached results if last scan was less then this time ago.
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=5)
_LOGGER = logging.getLogger(__name__)
@@ -57,7 +56,7 @@ class CiscoDeviceScanner(DeviceScanner):
# pylint: disable=no-self-use
def get_device_name(self, device):
"""The firmware doesn't save the name of the wireless device."""
"""Get the firmware doesn't save the name of the wireless device."""
return None
def scan_devices(self):
@@ -135,9 +134,9 @@ class CiscoDeviceScanner(DeviceScanner):
devices_result = cisco_ssh.before
return devices_result.decode("utf-8")
return devices_result.decode('utf-8')
except pxssh.ExceptionPxssh as px_e:
_LOGGER.error("pxssh failed on login.")
_LOGGER.error("pxssh failed on login")
_LOGGER.error(px_e)
return None
@@ -18,7 +18,6 @@ from homeassistant.components.device_tracker import (
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.
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=5)
_LOGGER = logging.getLogger(__name__)
@@ -108,7 +107,7 @@ class DdWrtDeviceScanner(DeviceScanner):
Return boolean if scanning successful.
"""
with self.lock:
_LOGGER.info('Checking ARP')
_LOGGER.info("Checking ARP")
url = 'http://{}/Status_Wireless.live.asp'.format(self.host)
data = self.get_ddwrt_data(url)
@@ -137,22 +136,19 @@ class DdWrtDeviceScanner(DeviceScanner):
"""Retrieve data from DD-WRT and return parsed result."""
try:
response = requests.get(
url,
auth=(self.username, self.password),
timeout=4)
url, auth=(self.username, self.password), timeout=4)
except requests.exceptions.Timeout:
_LOGGER.exception('Connection to the router timed out')
_LOGGER.exception("Connection to the router timed out")
return
if response.status_code == 200:
return _parse_ddwrt_response(response.text)
elif response.status_code == 401:
# Authentication error
_LOGGER.exception(
'Failed to authenticate, '
'please check your username and password')
"Failed to authenticate, check your username and password")
return
else:
_LOGGER.error('Invalid response from ddwrt: %s', response)
_LOGGER.error("Invalid response from DD-WRT: %s", response)
def _parse_ddwrt_response(data_str):
@@ -1,11 +1,16 @@
"""Demo platform for the device tracker."""
"""
Demo platform for the Device tracker component.
For more details about this platform, please refer to the documentation
https://home-assistant.io/components/demo/
"""
import random
from homeassistant.components.device_tracker import DOMAIN
def setup_scanner(hass, config, see, discovery_info=None):
"""Setup the demo tracker."""
"""Set up the demo tracker."""
def offset():
"""Return random offset."""
return (random.randrange(500, 2000)) / 2e5 * random.choice((-1, 1))
@@ -17,7 +17,6 @@ from homeassistant.util import Throttle
REQUIREMENTS = ['fritzconnection==0.6.3']
# Return cached results if last scan was less then this time ago.
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=5)
_LOGGER = logging.getLogger(__name__)
@@ -53,9 +52,8 @@ class FritzBoxScanner(DeviceScanner):
# Establish a connection to the FRITZ!Box.
try:
self.fritz_box = fc.FritzHosts(address=self.host,
user=self.username,
password=self.password)
self.fritz_box = fc.FritzHosts(
address=self.host, user=self.username, password=self.password)
except (ValueError, TypeError):
self.fritz_box = None
@@ -65,12 +63,12 @@ class FritzBoxScanner(DeviceScanner):
self.success_init = False
if self.success_init:
_LOGGER.info('Successfully connected to %s',
_LOGGER.info("Successfully connected to %s",
self.fritz_box.modelname)
self._update_info()
else:
_LOGGER.error('Failed to establish connection to FRITZ!Box '
'with IP: %s', self.host)
_LOGGER.error("Failed to establish connection to FRITZ!Box "
"with IP: %s", self.host)
def scan_devices(self):
"""Scan for new devices and return a list of found device ids."""
@@ -96,6 +94,6 @@ class FritzBoxScanner(DeviceScanner):
if not self.success_init:
return False
_LOGGER.info('Scanning')
_LOGGER.info("Scanning")
self.last_results = self.fritz_box.get_hosts_info()
return True
@@ -20,14 +20,14 @@ DEPENDENCIES = ['http']
def setup_scanner(hass, config, see, discovery_info=None):
"""Setup an endpoint for the GPSLogger application."""
"""Set up an endpoint for the GPSLogger application."""
hass.http.register_view(GPSLoggerView(see))
return True
class GPSLoggerView(HomeAssistantView):
"""View to handle gpslogger requests."""
"""View to handle GPSLogger requests."""
url = '/api/gpslogger'
name = 'api:gpslogger'
@@ -38,21 +38,20 @@ class GPSLoggerView(HomeAssistantView):
@asyncio.coroutine
def get(self, request):
"""A GPSLogger message received as GET."""
"""Handle for GPSLogger message received as GET."""
res = yield from self._handle(request.app['hass'], request.GET)
return res
@asyncio.coroutine
def _handle(self, hass, data):
"""Handle gpslogger request."""
"""Handle GPSLogger requests."""
if 'latitude' not in data or 'longitude' not in data:
return ('Latitude and longitude not specified.',
HTTP_UNPROCESSABLE_ENTITY)
if 'device' not in data:
_LOGGER.error('Device id not specified.')
return ('Device id not specified.',
HTTP_UNPROCESSABLE_ENTITY)
_LOGGER.error("Device id not specified")
return ('Device id not specified.', HTTP_UNPROCESSABLE_ENTITY)
device = data['device'].replace('-', '')
gps_location = (data['latitude'], data['longitude'])
@@ -55,8 +55,12 @@ DEVICESTATUSSET = ['features', 'maxMsgChar', 'darkWake', 'fmlyShare',
'wipedTimestamp', 'modelDisplayName', 'locationEnabled',
'isMac', 'locFoundEnabled']
DEVICESTATUSCODES = {'200': 'online', '201': 'offline', '203': 'pending',
'204': 'unregistered'}
DEVICESTATUSCODES = {
'200': 'online',
'201': 'offline',
'203': 'pending',
'204': 'unregistered',
}
SERVICE_SCHEMA = vol.Schema({
vol.Optional(ATTR_ACCOUNTNAME): vol.All(cv.ensure_list, [cv.slugify]),
@@ -87,7 +91,7 @@ def setup_scanner(hass, config: dict, see, discovery_info=None):
return False
def lost_iphone(call):
"""Call the lost iphone function if the device is found."""
"""Call the lost iPhone function if the device is found."""
accounts = call.data.get(ATTR_ACCOUNTNAME, ICLOUDTRACKERS)
devicename = call.data.get(ATTR_DEVICENAME)
for account in accounts:
@@ -97,7 +101,7 @@ def setup_scanner(hass, config: dict, see, discovery_info=None):
schema=SERVICE_SCHEMA)
def update_icloud(call):
"""Call the update function of an icloud account."""
"""Call the update function of an iCloud account."""
accounts = call.data.get(ATTR_ACCOUNTNAME, ICLOUDTRACKERS)
devicename = call.data.get(ATTR_DEVICENAME)
for account in accounts:
@@ -107,7 +111,7 @@ def setup_scanner(hass, config: dict, see, discovery_info=None):
schema=SERVICE_SCHEMA)
def reset_account_icloud(call):
"""Reset an icloud account."""
"""Reset an iCloud account."""
accounts = call.data.get(ATTR_ACCOUNTNAME, ICLOUDTRACKERS)
for account in accounts:
if account in ICLOUDTRACKERS:
@@ -116,7 +120,7 @@ def setup_scanner(hass, config: dict, see, discovery_info=None):
reset_account_icloud, schema=SERVICE_SCHEMA)
def setinterval(call):
"""Call the update function of an icloud account."""
"""Call the update function of an iCloud account."""
accounts = call.data.get(ATTR_ACCOUNTNAME, ICLOUDTRACKERS)
interval = call.data.get(ATTR_INTERVAL)
devicename = call.data.get(ATTR_DEVICENAME)
@@ -132,7 +136,7 @@ def setup_scanner(hass, config: dict, see, discovery_info=None):
class Icloud(DeviceScanner):
"""Represent an icloud account in Home Assistant."""
"""Representation of an iCloud account."""
def __init__(self, hass, username, password, name, see):
"""Initialize an iCloud account."""
@@ -157,12 +161,10 @@ class Icloud(DeviceScanner):
randomseconds = random.randint(10, 59)
track_utc_time_change(
self.hass, self.keep_alive,
second=randomseconds
)
self.hass, self.keep_alive, second=randomseconds)
def reset_account_icloud(self):
"""Reset an icloud account."""
"""Reset an iCloud account."""
from pyicloud import PyiCloudService
from pyicloud.exceptions import (
PyiCloudFailedLoginException, PyiCloudNoDevicesException)
@@ -178,7 +180,7 @@ class Icloud(DeviceScanner):
verify=True)
except PyiCloudFailedLoginException as error:
self.api = None
_LOGGER.error('Error logging into iCloud Service: %s', error)
_LOGGER.error("Error logging into iCloud Service: %s", error)
return
try:
@@ -196,12 +198,12 @@ class Icloud(DeviceScanner):
_LOGGER.error('No iCloud Devices found!')
def icloud_trusted_device_callback(self, callback_data):
"""The trusted device is chosen."""
"""Handle chosen trusted devices."""
self._trusted_device = int(callback_data.get('trusted_device'))
self._trusted_device = self.api.trusted_devices[self._trusted_device]
if not self.api.send_verification_code(self._trusted_device):
_LOGGER.error('Failed to send verification code')
_LOGGER.error("Failed to send verification code")
self._trusted_device = None
return
@@ -223,8 +225,7 @@ class Icloud(DeviceScanner):
devices = self.api.trusted_devices
for i, device in enumerate(devices):
devicename = device.get(
'deviceName',
'SMS to %s' % device.get('phoneNumber'))
'deviceName', 'SMS to %s' % device.get('phoneNumber'))
devicesstring += "{}: {};".format(i, devicename)
_CONFIGURING[self.accountname] = configurator.request_config(
@@ -239,7 +240,7 @@ class Icloud(DeviceScanner):
)
def icloud_verification_callback(self, callback_data):
"""The trusted device is chosen."""
"""Handle the chosen trusted device."""
from pyicloud.exceptions import PyiCloudException
self._verification_code = callback_data.get('code')
@@ -249,7 +250,7 @@ class Icloud(DeviceScanner):
raise PyiCloudException('Unknown failure')
except PyiCloudException as error:
# Reset to the inital 2FA state to allow the user to retry
_LOGGER.error('Failed to verify verification code: %s', error)
_LOGGER.error("Failed to verify verification code: %s", error)
self._trusted_device = None
self._verification_code = None
@@ -262,7 +263,7 @@ class Icloud(DeviceScanner):
configurator.request_done(request_id)
def icloud_need_verification_code(self):
"""We need a verification code."""
"""Return the verification code."""
configurator = get_component('configurator')
if self.accountname in _CONFIGURING:
return
@@ -277,7 +278,7 @@ class Icloud(DeviceScanner):
)
def keep_alive(self, now):
"""Keep the api alive."""
"""Keep the API alive."""
if self.api is None:
self.reset_account_icloud()
@@ -302,7 +303,7 @@ class Icloud(DeviceScanner):
self._trusted_device = None
self._verification_code = None
except PyiCloudException as error:
_LOGGER.error("Error setting up 2fa: %s", error)
_LOGGER.error("Error setting up 2FA: %s", error)
else:
self.api.authenticate()
@@ -320,8 +321,8 @@ class Icloud(DeviceScanner):
zone_state = self.hass.states.get('zone.home')
zone_state_lat = zone_state.attributes['latitude']
zone_state_long = zone_state.attributes['longitude']
distancefromhome = distance(latitude, longitude, zone_state_lat,
zone_state_long)
distancefromhome = distance(
latitude, longitude, zone_state_lat, zone_state_long)
distancefromhome = round(distancefromhome / 1000, 1)
currentzone = active_zone(self.hass, latitude, longitude)
@@ -400,7 +401,7 @@ class Icloud(DeviceScanner):
_LOGGER.error('No iCloud Devices found!')
def lost_iphone(self, devicename):
"""Call the lost iphone function if the device is found."""
"""Call the lost iPhone function if the device is found."""
if self.api is None:
return
@@ -428,13 +429,13 @@ class Icloud(DeviceScanner):
for device in self.devices:
self.devices[device].location()
except PyiCloudNoDevicesException:
_LOGGER.error('No iCloud Devices found!')
_LOGGER.error("No iCloud Devices found")
def setinterval(self, interval=None, devicename=None):
"""Set the interval of the given devices."""
devs = [devicename] if devicename else self.devices
for device in devs:
devid = DOMAIN + '.' + device
devid = '{}.{}'.format(DOMAIN, device)
devicestate = self.hass.states.get(devid)
if interval is not None:
if devicestate is not None:
@@ -99,9 +99,8 @@ class LinksysAPDeviceScanner(object):
# No, the '&&' is not a typo - this is expected by the web interface.
login = base64.b64encode(bytes(self.username, 'utf8')).decode('ascii')
pwd = base64.b64encode(bytes(self.password, 'utf8')).decode('ascii')
url = 'https://{}/StatusClients.htm&&unit={}&vap=0'.format(
self.host, unit)
return requests.get(
'https://%s/StatusClients.htm&&unit=%s&vap=0' % (self.host, unit),
timeout=DEFAULT_TIMEOUT,
verify=self.verify_ssl,
cookies={'LoginName': login,
'LoginPWD': pwd})
url, timeout=DEFAULT_TIMEOUT, verify=self.verify_ssl,
cookies={'LoginName': login, 'LoginPWD': pwd})
@@ -20,7 +20,6 @@ from homeassistant.components.device_tracker import (
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.
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=5)
_LOGGER = logging.getLogger(__name__)
@@ -46,10 +45,7 @@ def get_scanner(hass, config):
class LuciDeviceScanner(DeviceScanner):
"""This class queries a wireless router running OpenWrt firmware.
Adapted from Tomato scanner.
"""
"""This class queries a wireless router running OpenWrt firmware."""
def __init__(self, config):
"""Initialize the scanner."""
@@ -106,7 +102,7 @@ class LuciDeviceScanner(DeviceScanner):
return False
with self.lock:
_LOGGER.info('Checking ARP')
_LOGGER.info("Checking ARP")
url = 'http://{}/cgi-bin/luci/rpc/sys'.format(self.host)
@@ -114,7 +110,7 @@ class LuciDeviceScanner(DeviceScanner):
result = _req_json_rpc(url, 'net.arptable',
params={'auth': self.token})
except InvalidLuciTokenError:
_LOGGER.info('Refreshing token')
_LOGGER.info("Refreshing token")
self.refresh_token()
return False
@@ -138,28 +134,27 @@ def _req_json_rpc(url, method, *args, **kwargs):
try:
res = requests.post(url, data=data, timeout=5, **kwargs)
except requests.exceptions.Timeout:
_LOGGER.exception('Connection to the router timed out')
_LOGGER.exception("Connection to the router timed out")
return
if res.status_code == 200:
try:
result = res.json()
except ValueError:
# If json decoder could not parse the response
_LOGGER.exception('Failed to parse response from luci')
_LOGGER.exception("Failed to parse response from luci")
return
try:
return result['result']
except KeyError:
_LOGGER.exception('No result in response from luci')
_LOGGER.exception("No result in response from luci")
return
elif res.status_code == 401:
# Authentication error
_LOGGER.exception(
"Failed to authenticate, "
"please check your username and password")
"Failed to authenticate, check your username and password")
return
elif res.status_code == 403:
_LOGGER.error('Luci responded with a 403 Invalid token')
_LOGGER.error("Luci responded with a 403 Invalid token")
raise InvalidLuciTokenError
else:
@@ -27,7 +27,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(mqtt.SCHEMA_BASE).extend({
@asyncio.coroutine
def async_setup_scanner(hass, config, async_see, discovery_info=None):
"""Setup the MQTT tracker."""
"""Set up the MQTT tracker."""
devices = config[CONF_DEVICES]
qos = config[CONF_QOS]
@@ -35,7 +35,7 @@ def async_setup_scanner(hass, config, async_see, discovery_info=None):
@callback
def async_tracker_message_received(topic, payload, qos):
"""MQTT message received."""
"""Handle received MQTT message."""
hass.async_add_job(
async_see(dev_id=dev_id_lookup[topic], location_name=payload))
@@ -37,7 +37,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(mqtt.SCHEMA_BASE).extend({
@asyncio.coroutine
def async_setup_scanner(hass, config, async_see, discovery_info=None):
"""Setup the MQTT tracker."""
"""Set up the MQTT JSON tracker."""
devices = config[CONF_DEVICES]
qos = config[CONF_QOS]
@@ -45,18 +45,18 @@ def async_setup_scanner(hass, config, async_see, discovery_info=None):
@callback
def async_tracker_message_received(topic, payload, qos):
"""MQTT message received."""
"""Handle received MQTT message."""
dev_id = dev_id_lookup[topic]
try:
data = GPS_JSON_PAYLOAD_SCHEMA(json.loads(payload))
except vol.MultipleInvalid:
_LOGGER.error('Skipping update for following data '
'because of missing or malformatted data: %s',
_LOGGER.error("Skipping update for following data "
"because of missing or malformatted data: %s",
payload)
return
except ValueError:
_LOGGER.error('Error parsing JSON payload: %s', payload)
_LOGGER.error("Error parsing JSON payload: %s", payload)
return
kwargs = _parse_see_args(dev_id, data)
@@ -15,12 +15,12 @@ _LOGGER = logging.getLogger(__name__)
def setup_scanner(hass, config, see, discovery_info=None):
"""Setup the MySensors tracker."""
"""Set up the MySensors tracker."""
def mysensors_callback(gateway, msg):
"""Callback for mysensors platform."""
node = gateway.sensors[msg.node_id]
if node.sketch_name is None:
_LOGGER.debug('No sketch_name: node %s', msg.node_id)
_LOGGER.debug("No sketch_name: node %s", msg.node_id)
return
pres = gateway.const.Presentation
@@ -35,8 +35,8 @@ def setup_scanner(hass, config, see, discovery_info=None):
try:
latitude, longitude, _ = position.split(',')
except ValueError:
_LOGGER.error('Payload for V_POSITION %s is not of format '
'latitude,longitude,altitude', position)
_LOGGER.error("Payload for V_POSITION %s is not of format "
"latitude, longitude, altitude", position)
return
name = '{} {} {}'.format(
node.sketch_name, msg.node_id, child.id)
@@ -17,11 +17,11 @@ from homeassistant.const import (
CONF_HOST, CONF_PASSWORD, CONF_USERNAME, CONF_PORT)
from homeassistant.util import Throttle
# Return cached results if last scan was less then this time ago.
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=5)
REQUIREMENTS = ['pynetgear==0.3.3']
_LOGGER = logging.getLogger(__name__)
REQUIREMENTS = ['pynetgear==0.3.3']
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=5)
DEFAULT_HOST = 'routerlogin.net'
DEFAULT_USER = 'admin'
@@ -60,7 +60,7 @@ class NetgearDeviceScanner(DeviceScanner):
self._api = pynetgear.Netgear(password, host, username, port)
_LOGGER.info('Logging in')
_LOGGER.info("Logging in")
results = self._api.get_attached_devices()
@@ -69,7 +69,7 @@ class NetgearDeviceScanner(DeviceScanner):
if self.success_init:
self.last_results = results
else:
_LOGGER.error('Failed to Login')
_LOGGER.error("Failed to Login")
def scan_devices(self):
"""Scan for new devices and return a list with found device IDs."""
@@ -95,11 +95,11 @@ class NetgearDeviceScanner(DeviceScanner):
return
with self.lock:
_LOGGER.info('Scanning')
_LOGGER.info("Scanning")
results = self._api.get_attached_devices()
if results is None:
_LOGGER.warning('Error scanning devices')
_LOGGER.warning("Error scanning devices")
self.last_results = results or []
@@ -80,7 +80,7 @@ class NmapDeviceScanner(DeviceScanner):
self.home_interval = timedelta(minutes=minutes)
self.success_init = self._update_info()
_LOGGER.info("nmap scanner initialized")
_LOGGER.info("Scanner initialized")
def scan_devices(self):
"""Scan for new devices and return a list with found device IDs."""
@@ -85,8 +85,8 @@ def async_setup_scanner(hass, config, async_see, discovery_info=None):
try:
keylen, decrypt = get_cipher()
except OSError:
_LOGGER.warning('Ignoring encrypted payload '
'because libsodium not installed.')
_LOGGER.warning(
"Ignoring encrypted payload because libsodium not installed")
return None
if isinstance(secret, dict):
@@ -95,9 +95,9 @@ def async_setup_scanner(hass, config, async_see, discovery_info=None):
key = secret
if key is None:
_LOGGER.warning('Ignoring encrypted payload '
'because no decryption key known '
'for topic %s.', topic)
_LOGGER.warning(
"Ignoring encrypted payload because no decryption key known "
"for topic %s", topic)
return None
key = key.encode("utf-8")
@@ -111,9 +111,9 @@ def async_setup_scanner(hass, config, async_see, discovery_info=None):
_LOGGER.debug("Decrypted payload: %s", message)
return message
except ValueError:
_LOGGER.warning('Ignoring encrypted payload '
'because unable to decrypt using key '
'for topic %s.', topic)
_LOGGER.warning(
"Ignoring encrypted payload because unable to decrypt using "
"key for topic %s", topic)
return None
# pylint: disable=too-many-return-statements
@@ -123,7 +123,7 @@ def async_setup_scanner(hass, config, async_see, discovery_info=None):
data = json.loads(payload)
except ValueError:
# If invalid JSON
_LOGGER.error('Unable to parse payload as JSON: %s', payload)
_LOGGER.error("Unable to parse payload as JSON: %s", payload)
return None
if isinstance(data, dict) and \
@@ -136,22 +136,22 @@ def async_setup_scanner(hass, config, async_see, discovery_info=None):
return validate_payload(topic, plaintext_payload, data_type)
if not isinstance(data, dict) or data.get('_type') != data_type:
_LOGGER.debug('Skipping %s update for following data '
'because of missing or malformatted data: %s',
_LOGGER.debug("Skipping %s update for following data "
"because of missing or malformatted data: %s",
data_type, data)
return None
if data_type == VALIDATE_TRANSITION or data_type == VALIDATE_WAYPOINTS:
return data
if max_gps_accuracy is not None and \
convert(data.get('acc'), float, 0.0) > max_gps_accuracy:
_LOGGER.info('Ignoring %s update because expected GPS '
'accuracy %s is not met: %s',
_LOGGER.info("Ignoring %s update because expected GPS "
"accuracy %s is not met: %s",
data_type, max_gps_accuracy, payload)
return None
if convert(data.get('acc'), float, 1.0) == 0.0:
_LOGGER.warning('Ignoring %s update because GPS accuracy '
'is zero: %s',
data_type, payload)
_LOGGER.warning(
"Ignoring %s update because GPS accuracy is zero: %s",
data_type, payload)
return None
return data
@@ -169,7 +169,7 @@ def async_setup_scanner(hass, config, async_see, discovery_info=None):
if regions_entered[dev_id]:
_LOGGER.debug(
"location update ignored - inside region %s",
"Location update ignored, inside region %s",
regions_entered[-1])
return
@@ -178,7 +178,7 @@ def async_setup_scanner(hass, config, async_see, discovery_info=None):
@callback
def async_owntracks_event_update(topic, payload, qos):
"""MQTT event (geofences) received."""
"""Handle MQTT event (geofences)."""
# Docs on available data:
# http://owntracks.org/booklet/tech/json/#_typetransition
data = validate_payload(topic, payload, VALIDATE_TRANSITION)
@@ -242,15 +242,14 @@ def async_setup_scanner(hass, config, async_see, discovery_info=None):
if data['acc'] == 0.0:
valid_gps = False
_LOGGER.warning(
'Ignoring GPS in region exit because accuracy'
'is zero: %s',
payload)
"Ignoring GPS in region exit because accuracy"
"is zero: %s", payload)
if (max_gps_accuracy is not None and
data['acc'] > max_gps_accuracy):
valid_gps = False
_LOGGER.info(
'Ignoring GPS in region exit because expected '
'GPS accuracy %s is not met: %s',
"Ignoring GPS in region exit because expected "
"GPS accuracy %s is not met: %s",
max_gps_accuracy, payload)
if valid_gps:
hass.async_add_job(async_see(**kwargs))
@@ -267,7 +266,7 @@ def async_setup_scanner(hass, config, async_see, discovery_info=None):
leave_event()
else:
_LOGGER.error(
'Misformatted mqtt msgs, _type=transition, event=%s',
"Misformatted mqtt msgs, _type=transition, event=%s",
data['event'])
return
@@ -37,8 +37,8 @@ class Host(object):
self.ip_address = ip_address
self.dev_id = dev_id
self._count = config[CONF_PING_COUNT]
if sys.platform == "win32":
self._ping_cmd = ['ping', '-n 1', '-w 1000', self.ip_address]
if sys.platform == 'win32':
self._ping_cmd = ['ping', '-n 1', '-w', '1000', self.ip_address]
else:
self._ping_cmd = ['ping', '-n', '-q', '-c1', '-W1',
self.ip_address]
@@ -67,7 +67,7 @@ class Host(object):
def setup_scanner(hass, config, see, discovery_info=None):
"""Setup the Host objects and return the update function."""
"""Set up the Host objects and return the update function."""
hosts = [Host(ip, dev_id, hass, config) for (dev_id, ip) in
config[const.CONF_HOSTS].items()]
interval = timedelta(seconds=len(hosts) * config[CONF_PING_COUNT]) + \
@@ -17,7 +17,6 @@ from homeassistant.components.device_tracker import (
from homeassistant.const import CONF_HOST
from homeassistant.util import Throttle
# Return cached results if last scan was less then this time ago.
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=5)
_LOGGER = logging.getLogger(__name__)
@@ -69,7 +69,7 @@ class TadoDeviceScanner(DeviceScanner):
hass, cookie_jar=aiohttp.CookieJar(unsafe=True, loop=hass.loop))
self.success_init = self._update_info()
_LOGGER.info("Tado scanner initialized")
_LOGGER.info("Scanner initialized")
@asyncio.coroutine
def async_scan_devices(self):
@@ -108,14 +108,12 @@ class TadoDeviceScanner(DeviceScanner):
with async_timeout.timeout(10, loop=self.hass.loop):
# Format the URL here, so we can log the template URL if
# anything goes wrong without exposing username and password.
url = self.tadoapiurl.format(home_id=self.home_id,
username=self.username,
password=self.password)
url = self.tadoapiurl.format(
home_id=self.home_id, username=self.username,
password=self.password)
# Go get 'em!
response = yield from self.websession.get(url)
# error on Tado webservice
if response.status != 200:
_LOGGER.warning(
"Error %d on %s.", response.status, self.tadoapiurl)
@@ -18,7 +18,6 @@ from homeassistant.components.device_tracker import (
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.
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=10)
_LOGGER = logging.getLogger(__name__)
@@ -88,7 +87,7 @@ class ThomsonDeviceScanner(DeviceScanner):
return False
with self.lock:
_LOGGER.info('Checking ARP')
_LOGGER.info("Checking ARP")
data = self.get_thomson_data()
if not data:
return False
@@ -112,11 +111,11 @@ class ThomsonDeviceScanner(DeviceScanner):
devices_result = telnet.read_until(b'=>').split(b'\r\n')
telnet.write('exit\r\n'.encode('ascii'))
except EOFError:
_LOGGER.exception('Unexpected response from router')
_LOGGER.exception("Unexpected response from router")
return
except ConnectionRefusedError:
_LOGGER.exception('Connection refused by router,'
' is telnet enabled?')
_LOGGER.exception(
"Connection refused by router. Telnet enabled?")
return
devices = {}
@@ -19,10 +19,9 @@ from homeassistant.components.device_tracker import (
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.
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=5)
CONF_HTTP_ID = "http_id"
CONF_HTTP_ID = 'http_id'
_LOGGER = logging.getLogger(__name__)
@@ -47,12 +46,10 @@ class TomatoDeviceScanner(DeviceScanner):
host, http_id = config[CONF_HOST], config[CONF_HTTP_ID]
username, password = config[CONF_USERNAME], config[CONF_PASSWORD]
self.req = requests.Request('POST',
'http://{}/update.cgi'.format(host),
data={'_http_id': http_id,
'exec': 'devlist'},
auth=requests.auth.HTTPBasicAuth(
username, password)).prepare()
self.req = requests.Request(
'POST', 'http://{}/update.cgi'.format(host),
data={'_http_id': http_id, 'exec': 'devlist'},
auth=requests.auth.HTTPBasicAuth(username, password)).prepare()
self.parse_api_pattern = re.compile(r"(?P<param>\w*) = (?P<value>.*);")
@@ -112,20 +109,17 @@ class TomatoDeviceScanner(DeviceScanner):
except requests.exceptions.ConnectionError:
# We get this if we could not connect to the router or
# an invalid http_id was supplied.
self.logger.exception((
"Failed to connect to the router"
" or invalid http_id 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.
self.logger.exception(
"Connection to the router timed out")
self.logger.exception("Connection to the router timed out")
return False
except ValueError:
# If JSON decoder could not parse the response.
self.logger.exception(
"Failed to parse response from router")
self.logger.exception("Failed to parse response from router")
return False
@@ -20,7 +20,6 @@ from homeassistant.components.device_tracker import (
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
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=5)
_LOGGER = logging.getLogger(__name__)
@@ -69,7 +68,7 @@ class TplinkDeviceScanner(DeviceScanner):
# pylint: disable=no-self-use
def get_device_name(self, device):
"""The firmware doesn't save the name of the wireless device."""
"""Get firmware doesn't save the name of the wireless device."""
return None
@Throttle(MIN_TIME_BETWEEN_SCANS)
@@ -83,8 +82,9 @@ class TplinkDeviceScanner(DeviceScanner):
url = 'http://{}/userRpm/WlanStationRpm.htm'.format(self.host)
referer = 'http://{}'.format(self.host)
page = requests.get(url, auth=(self.username, self.password),
headers={'referer': referer})
page = requests.get(
url, auth=(self.username, self.password),
headers={'referer': referer}, timeout=4)
result = self.parse_macs.findall(page.text)
@@ -105,7 +105,7 @@ class Tplink2DeviceScanner(TplinkDeviceScanner):
# pylint: disable=no-self-use
def get_device_name(self, device):
"""The firmware doesn't save the name of the wireless device."""
"""Get firmware doesn't save the name of the wireless device."""
return self.last_results.get(device)
@Throttle(MIN_TIME_BETWEEN_SCANS)
@@ -130,8 +130,9 @@ class Tplink2DeviceScanner(TplinkDeviceScanner):
cookie = 'Authorization=Basic {}' \
.format(b64_encoded_username_password)
response = requests.post(url, headers={'referer': referer,
'cookie': cookie})
response = requests.post(
url, headers={'referer': referer, 'cookie': cookie},
timeout=4)
try:
result = response.json().get('data')
@@ -166,7 +167,7 @@ class Tplink3DeviceScanner(TplinkDeviceScanner):
# pylint: disable=no-self-use
def get_device_name(self, device):
"""The firmware doesn't save the name of the wireless device.
"""Get the firmware doesn't save the name of the wireless device.
We are forced to use the MAC address as name here.
"""
@@ -181,17 +182,16 @@ class Tplink3DeviceScanner(TplinkDeviceScanner):
referer = 'http://{}/webpages/login.html'.format(self.host)
# If possible implement rsa encryption of password here.
response = requests.post(url,
params={'operation': 'login',
'username': self.username,
'password': self.password},
headers={'referer': referer})
response = requests.post(
url, params={'operation': 'login', 'username': self.username,
'password': self.password},
headers={'referer': referer}, timeout=4)
try:
self.stok = response.json().get('data').get('stok')
_LOGGER.info(self.stok)
regex_result = re.search('sysauth=(.*);',
response.headers['set-cookie'])
regex_result = re.search(
'sysauth=(.*);', response.headers['set-cookie'])
self.sysauth = regex_result.group(1)
_LOGGER.info(self.sysauth)
return True
@@ -37,18 +37,18 @@ class TrackRDeviceScanner(object):
"""Initialize the TrackR device scanner."""
from pytrackr.api import trackrApiInterface
self.hass = hass
self.api = trackrApiInterface(config.get(CONF_USERNAME),
config.get(CONF_PASSWORD))
self.api = trackrApiInterface(
config.get(CONF_USERNAME), config.get(CONF_PASSWORD))
self.see = see
self.devices = self.api.get_trackrs()
self._update_info()
track_utc_time_change(self.hass, self._update_info,
second=range(0, 60, 30))
track_utc_time_change(
self.hass, self._update_info, second=range(0, 60, 30))
def _update_info(self, now=None) -> None:
"""Update the device info."""
_LOGGER.debug('Updating devices %s', now)
_LOGGER.debug("Updating devices %s", now)
# Update self.devices to collect new devices added
# to the users account.
+10 -10
View File
@@ -70,9 +70,9 @@ class UbusDeviceScanner(DeviceScanner):
"""Return 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,
'call', 'uci', 'get',
config="dhcp", type="dnsmasq")
result = _req_json_rpc(
self.url, self.session_id, 'call', 'uci', 'get',
config="dhcp", type="dnsmasq")
if result:
values = result["values"].values()
self.leasefile = next(iter(values))["leasefile"]
@@ -80,9 +80,9 @@ class UbusDeviceScanner(DeviceScanner):
return
if self.mac2name is None:
result = _req_json_rpc(self.url, self.session_id,
'call', 'file', 'read',
path=self.leasefile)
result = _req_json_rpc(
self.url, self.session_id, 'call', 'file', 'read',
path=self.leasefile)
if result:
self.mac2name = dict()
for line in result["data"].splitlines():
@@ -107,15 +107,15 @@ class UbusDeviceScanner(DeviceScanner):
_LOGGER.info("Checking ARP")
if not self.hostapd:
hostapd = _req_json_rpc(self.url, self.session_id,
'list', 'hostapd.*', '')
hostapd = _req_json_rpc(
self.url, self.session_id, 'list', 'hostapd.*', '')
self.hostapd.extend(hostapd.keys())
self.last_results = []
results = 0
for hostapd in self.hostapd:
result = _req_json_rpc(self.url, self.session_id,
'call', hostapd, 'get_clients')
result = _req_json_rpc(
self.url, self.session_id, 'call', hostapd, 'get_clients')
if result:
results = results + 1
@@ -15,29 +15,31 @@ from homeassistant.components.device_tracker import (
from homeassistant.const import CONF_HOST, CONF_USERNAME, CONF_PASSWORD
from homeassistant.const import CONF_VERIFY_SSL
# Unifi package doesn't list urllib3 as a requirement
REQUIREMENTS = ['pyunifi==2.0']
_LOGGER = logging.getLogger(__name__)
CONF_PORT = 'port'
CONF_SITE_ID = 'site_id'
DEFAULT_HOST = 'localhost'
DEFAULT_PORT = 8443
DEFAULT_VERIFY_SSL = True
NOTIFICATION_ID = 'unifi_notification'
NOTIFICATION_TITLE = 'Unifi Device Tracker Setup'
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Optional(CONF_HOST, default='localhost'): cv.string,
vol.Optional(CONF_HOST, default=DEFAULT_HOST): cv.string,
vol.Optional(CONF_SITE_ID, default='default'): cv.string,
vol.Required(CONF_PASSWORD): cv.string,
vol.Required(CONF_USERNAME): cv.string,
vol.Required(CONF_PORT, default=8443): cv.port,
vol.Required(CONF_PORT, default=DEFAULT_PORT): cv.port,
vol.Optional(CONF_VERIFY_SSL, default=DEFAULT_VERIFY_SSL): cv.boolean,
})
def get_scanner(hass, config):
"""Setup Unifi device_tracker."""
"""Set up the Unifi device_tracker."""
from pyunifi.controller import Controller
host = config[DOMAIN].get(CONF_HOST)
@@ -52,7 +54,7 @@ def get_scanner(hass, config):
ctrl = Controller(host, username, password, port, version='v4',
site_id=site_id, ssl_verify=verify_ssl)
except urllib.error.HTTPError as ex:
_LOGGER.error('Failed to connect to Unifi: %s', ex)
_LOGGER.error("Failed to connect to Unifi: %s", ex)
persistent_notification.create(
hass, 'Failed to connect to Unifi. '
'Error: {}<br />'
@@ -78,7 +80,7 @@ class UnifiScanner(DeviceScanner):
try:
clients = self._controller.get_clients()
except urllib.error.HTTPError as ex:
_LOGGER.error('Failed to scan clients: %s', ex)
_LOGGER.error("Failed to scan clients: %s", ex)
clients = []
self._clients = {client['mac']: client for client in clients}
@@ -96,5 +98,5 @@ class UnifiScanner(DeviceScanner):
"""
client = self._clients.get(mac, {})
name = client.get('name') or client.get('hostname')
_LOGGER.debug('Device %s name %s', mac, name)
_LOGGER.debug("Device %s name %s", mac, name)
return name
@@ -95,7 +95,7 @@ class UPCDeviceScanner(DeviceScanner):
@asyncio.coroutine
def async_get_device_name(self, device):
"""The firmware doesn't save the name of the wireless device."""
"""Ge the firmware doesn't save the name of the wireless device."""
return None
@asyncio.coroutine
@@ -118,7 +118,7 @@ class UPCDeviceScanner(DeviceScanner):
'Password': self.password,
})
# successfull?
# Successful?
return data is not None
except (asyncio.TimeoutError, aiohttp.ClientError):
@@ -13,7 +13,7 @@ _LOGGER = logging.getLogger(__name__)
def setup_scanner(hass, config, see, discovery_info=None):
"""Setup Volvo tracker."""
"""Set up the Volvo tracker."""
if discovery_info is None:
return
@@ -24,7 +24,7 @@ def setup_scanner(hass, config, see, discovery_info=None):
dev_id = 'volvo_' + slugify(host_name)
def see_vehicle(vehicle):
"""Callback for reporting vehicle position."""
"""Handle the reporting of the vehicle position."""
see(dev_id=dev_id,
host_name=host_name,
gps=(vehicle.position['latitude'],
@@ -17,11 +17,10 @@ from homeassistant.components.device_tracker import (
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.
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=5)
_LOGGER = logging.getLogger(__name__)
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=5)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_HOST): cv.string,
vol.Required(CONF_USERNAME, default='admin'): cv.string,
@@ -98,12 +97,12 @@ class XiaomiDeviceScanner(DeviceScanner):
Return the list if successful.
"""
_LOGGER.info('Refreshing device list')
_LOGGER.info("Refreshing device list")
result = _retrieve_list(self.host, self.token)
if result:
return result
else:
_LOGGER.info('Refreshing token and retrying device list refresh')
_LOGGER.info("Refreshing token and retrying device list refresh")
self.token = _get_token(self.host, self.username, self.password)
return _retrieve_list(self.host, self.token)
@@ -117,40 +116,40 @@ class XiaomiDeviceScanner(DeviceScanner):
def _retrieve_list(host, token, **kwargs):
""""Get device list for the given host."""
"""Get device list for the given host."""
url = "http://{}/cgi-bin/luci/;stok={}/api/misystem/devicelist"
url = url.format(host, token)
try:
res = requests.get(url, timeout=5, **kwargs)
except requests.exceptions.Timeout:
_LOGGER.exception('Connection to the router timed out at URL [%s]',
url)
_LOGGER.exception(
"Connection to the router timed out at URL %s", url)
return
if res.status_code != 200:
_LOGGER.exception('Connection failed with http code [%s]',
res.status_code)
_LOGGER.exception(
"Connection failed with http code %s", res.status_code)
return
try:
result = res.json()
except ValueError:
# If json decoder could not parse the response
_LOGGER.exception('Failed to parse response from mi router')
_LOGGER.exception("Failed to parse response from mi router")
return
try:
xiaomi_code = result['code']
except KeyError:
_LOGGER.exception('No field code in response from mi router. %s',
result)
_LOGGER.exception(
"No field code in response from mi router. %s", result)
return
if xiaomi_code == 0:
try:
return result['list']
except KeyError:
_LOGGER.exception('No list in response from mi router. %s', result)
_LOGGER.exception("No list in response from mi router. %s", result)
return
else:
_LOGGER.info(
'Receive wrong Xiaomi code [%s], expected [0] in response [%s]',
"Receive wrong Xiaomi code %s, expected 0 in response %s",
xiaomi_code, result)
return
@@ -162,14 +161,14 @@ def _get_token(host, username, password):
try:
res = requests.post(url, data=data, timeout=5)
except requests.exceptions.Timeout:
_LOGGER.exception('Connection to the router timed out')
_LOGGER.exception("Connection to the router timed out")
return
if res.status_code == 200:
try:
result = res.json()
except ValueError:
# If json decoder could not parse the response
_LOGGER.exception('Failed to parse response from mi router')
# If JSON decoder could not parse the response
_LOGGER.exception("Failed to parse response from mi router")
return
try:
return result['token']