Embed all platforms into components (#20677)

* Consolidate all components with platforms

* Organize tests

* Fix more tests

* Fix Verisure tests

* one final test fix

* Add change

* Fix coverage
This commit is contained in:
Paulus Schoutsen authored and GitHub committed 2019-02-02 07:13:16 -08:00
1 parent a24da611c5
commit e2d3c27e85
490 files changed
+255 -517

No files matched your search

@@ -1,58 +0,0 @@
"""Device tracker for BMW Connected Drive vehicles.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/device_tracker.bmw_connected_drive/
"""
import logging
from homeassistant.components.bmw_connected_drive import DOMAIN \
as BMW_DOMAIN
from homeassistant.util import slugify
DEPENDENCIES = ['bmw_connected_drive']
_LOGGER = logging.getLogger(__name__)
def setup_scanner(hass, config, see, discovery_info=None):
"""Set up the BMW tracker."""
accounts = hass.data[BMW_DOMAIN]
_LOGGER.debug('Found BMW accounts: %s',
', '.join([a.name for a in accounts]))
for account in accounts:
for vehicle in account.account.vehicles:
tracker = BMWDeviceTracker(see, vehicle)
account.add_update_listener(tracker.update)
tracker.update()
return True
class BMWDeviceTracker:
"""BMW Connected Drive device tracker."""
def __init__(self, see, vehicle):
"""Initialize the Tracker."""
self._see = see
self.vehicle = vehicle
def update(self) -> None:
"""Update the device info.
Only update the state in home assistant if tracking in
the car is enabled.
"""
dev_id = slugify(self.vehicle.name)
if not self.vehicle.state.is_vehicle_tracking_enabled:
_LOGGER.debug('Tracking is disabled for vehicle %s', dev_id)
return
_LOGGER.debug('Updating %s', dev_id)
attrs = {
'vin': self.vehicle.vin,
}
self._see(
dev_id=dev_id, host_name=self.vehicle.name,
gps=self.vehicle.state.gps_position, attributes=attrs,
icon='mdi:car'
)
@@ -1,71 +0,0 @@
"""
Support for Freebox devices (Freebox v6 and Freebox mini 4K).
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/device_tracker.freebox/
"""
from collections import namedtuple
import logging
from homeassistant.components.device_tracker import DeviceScanner
from homeassistant.components.freebox import DATA_FREEBOX
DEPENDENCIES = ['freebox']
_LOGGER = logging.getLogger(__name__)
async def async_get_scanner(hass, config):
"""Validate the configuration and return a Freebox scanner."""
scanner = FreeboxDeviceScanner(hass.data[DATA_FREEBOX])
await scanner.async_connect()
return scanner if scanner.success_init else None
Device = namedtuple('Device', ['id', 'name', 'ip'])
def _build_device(device_dict):
return Device(
device_dict['l2ident']['id'],
device_dict['primary_name'],
device_dict['l3connectivities'][0]['addr'])
class FreeboxDeviceScanner(DeviceScanner):
"""Queries the Freebox device."""
def __init__(self, fbx):
"""Initialize the scanner."""
self.last_results = {}
self.success_init = False
self.connection = fbx
async def async_connect(self):
"""Initialize connection to the router."""
# Test the router is accessible.
data = await self.connection.lan.get_hosts_list()
self.success_init = data is not None
async def async_scan_devices(self):
"""Scan for new devices and return a list with found device IDs."""
await self.async_update_info()
return [device.id for device in self.last_results]
async def get_device_name(self, device):
"""Return the name of the given device or None if we don't know."""
name = next((
result.name for result in self.last_results
if result.id == device), None)
return name
async def async_update_info(self):
"""Ensure the information from the Freebox router is up to date."""
_LOGGER.debug('Checking Devices')
hosts = await self.connection.lan.get_hosts_list()
last_results = [_build_device(device)
for device in hosts
if device['active']]
self.last_results = last_results
@@ -1,86 +0,0 @@
"""
Support for Google Home bluetooth tacker.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/device_tracker.googlehome/
"""
import logging
from datetime import timedelta
from homeassistant.components.device_tracker import DeviceScanner
from homeassistant.components.googlehome import (
CLIENT, DOMAIN as GOOGLEHOME_DOMAIN, NAME)
from homeassistant.helpers.event import async_track_time_interval
from homeassistant.util import slugify
DEPENDENCIES = ['googlehome']
DEFAULT_SCAN_INTERVAL = timedelta(seconds=10)
_LOGGER = logging.getLogger(__name__)
async def async_setup_scanner(hass, config, async_see, discovery_info=None):
"""Validate the configuration and return a Google Home scanner."""
if discovery_info is None:
_LOGGER.warning(
"To use this you need to configure the 'googlehome' component")
return False
scanner = GoogleHomeDeviceScanner(hass, hass.data[CLIENT],
discovery_info, async_see)
return await scanner.async_init()
class GoogleHomeDeviceScanner(DeviceScanner):
"""This class queries a Google Home unit."""
def __init__(self, hass, client, config, async_see):
"""Initialize the scanner."""
self.async_see = async_see
self.hass = hass
self.rssi = config['rssi_threshold']
self.device_types = config['device_types']
self.host = config['host']
self.client = client
async def async_init(self):
"""Further initialize connection to Google Home."""
await self.client.update_data(self.host)
data = self.hass.data[GOOGLEHOME_DOMAIN][self.host]
info = data.get('info', {})
connected = bool(info)
if connected:
await self.async_update()
async_track_time_interval(self.hass,
self.async_update,
DEFAULT_SCAN_INTERVAL)
return connected
async def async_update(self, now=None):
"""Ensure the information from Google Home is up to date."""
_LOGGER.debug('Checking Devices on %s', self.host)
await self.client.update_data(self.host)
data = self.hass.data[GOOGLEHOME_DOMAIN][self.host]
info = data.get('info')
bluetooth = data.get('bluetooth')
if info is None or bluetooth is None:
return
google_home_name = info.get('name', NAME)
for device in bluetooth:
if (device['device_type'] not in
self.device_types or device['rssi'] < self.rssi):
continue
name = "{} {}".format(self.host, device['mac_address'])
attributes = {}
attributes['btle_mac_address'] = device['mac_address']
attributes['ghname'] = google_home_name
attributes['rssi'] = device['rssi']
attributes['source_type'] = 'bluetooth'
if device['name']:
attributes['name'] = device['name']
await self.async_see(dev_id=slugify(name),
attributes=attributes)
@@ -1,68 +0,0 @@
"""
Support for Huawei LTE routers.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/device_tracker.huawei_lte/
"""
from typing import Any, Dict, List, Optional
import attr
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.components.device_tracker import (
PLATFORM_SCHEMA, DeviceScanner,
)
from homeassistant.const import CONF_URL
from ..huawei_lte import DATA_KEY, RouterData
DEPENDENCIES = ['huawei_lte']
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Optional(CONF_URL): cv.url,
})
HOSTS_PATH = "wlan_host_list.Hosts"
def get_scanner(hass, config):
"""Get a Huawei LTE router scanner."""
data = hass.data[DATA_KEY].get_data(config)
data.subscribe(HOSTS_PATH)
return HuaweiLteScanner(data)
@attr.s
class HuaweiLteScanner(DeviceScanner):
"""Huawei LTE router scanner."""
data = attr.ib(type=RouterData)
_hosts = attr.ib(init=False, factory=dict)
def scan_devices(self) -> List[str]:
"""Scan for devices."""
self.data.update()
self._hosts = {
x["MacAddress"]: x
for x in self.data[HOSTS_PATH + ".Host"]
if x.get("MacAddress")
}
return list(self._hosts)
def get_device_name(self, device: str) -> Optional[str]:
"""Get name for a device."""
host = self._hosts.get(device)
return host.get("HostName") or None if host else None
def get_extra_attributes(self, device: str) -> Dict[str, Any]:
"""
Get extra attributes of a device.
Some known extra attributes that may be returned in the dict
include MacAddress (MAC address), ID (client ID), IpAddress
(IP address), AssociatedSsid (associated SSID), AssociatedTime
(associated time in seconds), and HostName (host name).
"""
return self._hosts.get(device) or {}
@@ -1,60 +0,0 @@
"""
Support for tracking MySensors devices.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/device_tracker.mysensors/
"""
from homeassistant.components import mysensors
from homeassistant.components.device_tracker import DOMAIN
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.util import slugify
async def async_setup_scanner(hass, config, async_see, discovery_info=None):
"""Set up the MySensors device scanner."""
new_devices = mysensors.setup_mysensors_platform(
hass, DOMAIN, discovery_info, MySensorsDeviceScanner,
device_args=(hass, async_see))
if not new_devices:
return False
for device in new_devices:
gateway_id = id(device.gateway)
dev_id = (
gateway_id, device.node_id, device.child_id,
device.value_type)
async_dispatcher_connect(
hass, mysensors.const.CHILD_CALLBACK.format(*dev_id),
device.async_update_callback)
async_dispatcher_connect(
hass,
mysensors.const.NODE_CALLBACK.format(gateway_id, device.node_id),
device.async_update_callback)
return True
class MySensorsDeviceScanner(mysensors.device.MySensorsDevice):
"""Represent a MySensors scanner."""
def __init__(self, hass, async_see, *args):
"""Set up instance."""
super().__init__(*args)
self.async_see = async_see
self.hass = hass
async def _async_update_callback(self):
"""Update the device."""
await self.async_update()
node = self.gateway.sensors[self.node_id]
child = node.children[self.child_id]
position = child.values[self.value_type]
latitude, longitude, _ = position.split(',')
await self.async_see(
dev_id=slugify(self.name),
host_name=self.name,
gps=(latitude, longitude),
battery=node.battery_level,
attributes=self.device_state_attributes
)
@@ -1,143 +0,0 @@
"""
Support for Tado Smart Thermostat.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/device_tracker.tado/
"""
import logging
from datetime import timedelta
from collections import namedtuple
import asyncio
import aiohttp
import async_timeout
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.const import CONF_USERNAME, CONF_PASSWORD
from homeassistant.util import Throttle
from homeassistant.components.device_tracker import (
DOMAIN, PLATFORM_SCHEMA, DeviceScanner)
from homeassistant.helpers.aiohttp_client import async_create_clientsession
_LOGGER = logging.getLogger(__name__)
CONF_HOME_ID = 'home_id'
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=30)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_USERNAME): cv.string,
vol.Required(CONF_PASSWORD): cv.string,
vol.Optional(CONF_HOME_ID): cv.string
})
def get_scanner(hass, config):
"""Return a Tado scanner."""
scanner = TadoDeviceScanner(hass, config[DOMAIN])
return scanner if scanner.success_init else None
Device = namedtuple("Device", ["mac", "name"])
class TadoDeviceScanner(DeviceScanner):
"""This class gets geofenced devices from Tado."""
def __init__(self, hass, config):
"""Initialize the scanner."""
self.last_results = []
self.username = config[CONF_USERNAME]
self.password = config[CONF_PASSWORD]
# The Tado device tracker can work with or without a home_id
self.home_id = config[CONF_HOME_ID] if CONF_HOME_ID in config else None
# If there's a home_id, we need a different API URL
if self.home_id is None:
self.tadoapiurl = 'https://my.tado.com/api/v2/me'
else:
self.tadoapiurl = 'https://my.tado.com/api/v2' \
'/homes/{home_id}/mobileDevices'
# The API URL always needs a username and password
self.tadoapiurl += '?username={username}&password={password}'
self.websession = async_create_clientsession(
hass, cookie_jar=aiohttp.CookieJar(unsafe=True, loop=hass.loop))
self.success_init = asyncio.run_coroutine_threadsafe(
self._async_update_info(), hass.loop
).result()
_LOGGER.info("Scanner initialized")
async def async_scan_devices(self):
"""Scan for devices and return a list containing found device ids."""
await self._async_update_info()
return [device.mac for device in self.last_results]
async def async_get_device_name(self, device):
"""Return the name of the given device or None if we don't know."""
filter_named = [result.name for result in self.last_results
if result.mac == device]
if filter_named:
return filter_named[0]
return None
@Throttle(MIN_TIME_BETWEEN_SCANS)
async def _async_update_info(self):
"""
Query Tado for device marked as at home.
Returns boolean if scanning successful.
"""
_LOGGER.debug("Requesting Tado")
last_results = []
try:
with async_timeout.timeout(10):
# 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)
response = await self.websession.get(url)
if response.status != 200:
_LOGGER.warning(
"Error %d on %s.", response.status, self.tadoapiurl)
return False
tado_json = await response.json()
except (asyncio.TimeoutError, aiohttp.ClientError):
_LOGGER.error("Cannot load Tado data")
return False
# Without a home_id, we fetched an URL where the mobile devices can be
# found under the mobileDevices key.
if 'mobileDevices' in tado_json:
tado_json = tado_json['mobileDevices']
# Find devices that have geofencing enabled, and are currently at home.
for mobile_device in tado_json:
if mobile_device.get('location'):
if mobile_device['location']['atHome']:
device_id = mobile_device['id']
device_name = mobile_device['name']
last_results.append(Device(device_id, device_name))
self.last_results = last_results
_LOGGER.debug(
"Tado presence query successful, %d device(s) at home",
len(self.last_results)
)
return True
@@ -1,58 +0,0 @@
"""
Support for the Tesla platform.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/device_tracker.tesla/
"""
import logging
from homeassistant.components.tesla import DOMAIN as TESLA_DOMAIN
from homeassistant.helpers.event import track_utc_time_change
from homeassistant.util import slugify
_LOGGER = logging.getLogger(__name__)
DEPENDENCIES = ['tesla']
def setup_scanner(hass, config, see, discovery_info=None):
"""Set up the Tesla tracker."""
TeslaDeviceTracker(
hass, config, see,
hass.data[TESLA_DOMAIN]['devices']['devices_tracker'])
return True
class TeslaDeviceTracker:
"""A class representing a Tesla device."""
def __init__(self, hass, config, see, tesla_devices):
"""Initialize the Tesla device scanner."""
self.hass = hass
self.see = see
self.devices = tesla_devices
self._update_info()
track_utc_time_change(
self.hass, self._update_info, second=range(0, 60, 30))
def _update_info(self, now=None):
"""Update the device info."""
for device in self.devices:
device.update()
name = device.name
_LOGGER.debug("Updating device position: %s", name)
dev_id = slugify(device.uniq_name)
location = device.get_location()
if location:
lat = location['latitude']
lon = location['longitude']
attrs = {
'trackr_id': dev_id,
'id': dev_id,
'name': name
}
self.see(
dev_id=dev_id, host_name=name,
gps=(lat, lon), attributes=attrs
)
@@ -1,38 +0,0 @@
"""
Support for tracking a Volvo.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/device_tracker.volvooncall/
"""
import logging
from homeassistant.util import slugify
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.components.device_tracker import SOURCE_TYPE_GPS
from homeassistant.components.volvooncall import DATA_KEY, SIGNAL_STATE_UPDATED
_LOGGER = logging.getLogger(__name__)
async def async_setup_scanner(hass, config, async_see, discovery_info=None):
"""Set up the Volvo tracker."""
if discovery_info is None:
return
vin, component, attr = discovery_info
data = hass.data[DATA_KEY]
instrument = data.instrument(vin, component, attr)
async def see_vehicle():
"""Handle the reporting of the vehicle position."""
host_name = instrument.vehicle_name
dev_id = 'volvo_{}'.format(slugify(host_name))
await async_see(dev_id=dev_id,
host_name=host_name,
source_type=SOURCE_TYPE_GPS,
gps=instrument.state,
icon='mdi:car')
async_dispatcher_connect(hass, SIGNAL_STATE_UPDATED, see_vehicle)
return True
@@ -1,81 +0,0 @@
"""
Support for Xiaomi Mi WiFi Repeater 2.
For more details about this platform, please refer to the documentation
https://home-assistant.io/components/device_tracker.xiaomi_miio/
"""
import logging
import voluptuous as vol
from homeassistant.components.device_tracker import (
DOMAIN, PLATFORM_SCHEMA, DeviceScanner)
from homeassistant.const import CONF_HOST, CONF_TOKEN
import homeassistant.helpers.config_validation as cv
REQUIREMENTS = ['python-miio==0.4.4', 'construct==2.9.45']
_LOGGER = logging.getLogger(__name__)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_HOST): cv.string,
vol.Required(CONF_TOKEN): vol.All(cv.string, vol.Length(min=32, max=32)),
})
def get_scanner(hass, config):
"""Return a Xiaomi MiIO device scanner."""
from miio import WifiRepeater, DeviceException
scanner = None
host = config[DOMAIN].get(CONF_HOST)
token = config[DOMAIN].get(CONF_TOKEN)
_LOGGER.info(
"Initializing with host %s (token %s...)", host, token[:5])
try:
device = WifiRepeater(host, token)
device_info = device.info()
_LOGGER.info("%s %s %s detected",
device_info.model,
device_info.firmware_version,
device_info.hardware_version)
scanner = XiaomiMiioDeviceScanner(device)
except DeviceException as ex:
_LOGGER.error("Device unavailable or token incorrect: %s", ex)
return scanner
class XiaomiMiioDeviceScanner(DeviceScanner):
"""This class queries a Xiaomi Mi WiFi Repeater."""
def __init__(self, device):
"""Initialize the scanner."""
self.device = device
async def async_scan_devices(self):
"""Scan for devices and return a list containing found device IDs."""
from miio import DeviceException
devices = []
try:
station_info = \
await self.hass.async_add_executor_job(self.device.status)
_LOGGER.debug("Got new station info: %s", station_info)
for device in station_info.associated_stations:
devices.append(device['mac'])
except DeviceException as ex:
_LOGGER.error("Unable to fetch the state: %s", ex)
return devices
async def async_get_device_name(self, device):
"""Return None.
The repeater doesn't provide the name of the associated device.
"""
return None