/
wemo.py
181 lines (135 loc) · 5.48 KB
/
wemo.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
"""
Support for WeMo device discovery.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/wemo/
"""
import logging
import requests
import voluptuous as vol
from homeassistant.components.discovery import SERVICE_WEMO
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers import discovery
from homeassistant.const import (
EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP)
REQUIREMENTS = ['pywemo==0.4.34']
DOMAIN = 'wemo'
# Mapping from Wemo device type to Home Assistant component type.
WEMO_DEVICE_TYPE_DISPATCH = {
'Bridge': 'light',
'CoffeeMaker': 'switch',
'Dimmer': 'light',
'Humidifier': 'fan',
'Insight': 'switch',
'LightSwitch': 'switch',
'Maker': 'switch',
'Motion': 'binary_sensor',
'Switch': 'switch'
}
SUBSCRIPTION_REGISTRY = None
KNOWN_DEVICES = []
_LOGGER = logging.getLogger(__name__)
def coerce_host_port(value):
"""Validate that provided value is either just host or host:port.
Returns (host, None) or (host, port) respectively.
"""
host, _, port = value.partition(':')
if not host:
raise vol.Invalid('host cannot be empty')
if port:
port = cv.port(port)
else:
port = None
return host, port
CONF_STATIC = 'static'
CONF_DISCOVERY = 'discovery'
DEFAULT_DISCOVERY = True
CONFIG_SCHEMA = vol.Schema({
DOMAIN: vol.Schema({
vol.Optional(CONF_STATIC, default=[]): vol.Schema([
vol.All(cv.string, coerce_host_port)
]),
vol.Optional(CONF_DISCOVERY,
default=DEFAULT_DISCOVERY): cv.boolean
}),
}, extra=vol.ALLOW_EXTRA)
def setup(hass, config):
"""Set up for WeMo devices."""
import pywemo
# Keep track of WeMo devices
devices = []
# Keep track of WeMo device subscriptions for push updates
global SUBSCRIPTION_REGISTRY
SUBSCRIPTION_REGISTRY = pywemo.SubscriptionRegistry()
SUBSCRIPTION_REGISTRY.start()
def stop_wemo(event):
"""Shutdown Wemo subscriptions and subscription thread on exit."""
_LOGGER.debug("Shutting down WeMo event subscriptions")
SUBSCRIPTION_REGISTRY.stop()
hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_wemo)
def setup_url_for_device(device):
"""Determine setup.xml url for given device."""
return 'http://{}:{}/setup.xml'.format(device.host, device.port)
def setup_url_for_address(host, port):
"""Determine setup.xml url for given host and port pair."""
if not port:
port = pywemo.ouimeaux_device.probe_wemo(host)
if not port:
return None
return 'http://{}:{}/setup.xml'.format(host, port)
def discovery_dispatch(service, discovery_info):
"""Dispatcher for incoming WeMo discovery events."""
# name, model, location, mac
device_type = discovery_info.get('device_type')
serial = discovery_info.get('serial')
# Only register a device once
if serial in KNOWN_DEVICES:
_LOGGER.debug('Ignoring known device %s %s',
service, discovery_info)
return
_LOGGER.debug('Discovered unique WeMo device: %s', serial)
KNOWN_DEVICES.append(serial)
component = WEMO_DEVICE_TYPE_DISPATCH.get(device_type, 'switch')
discovery.load_platform(hass, component, DOMAIN,
discovery_info, config)
discovery.listen(hass, SERVICE_WEMO, discovery_dispatch)
def discover_wemo_devices(now):
"""Run discovery for WeMo devices."""
_LOGGER.debug("Beginning WeMo device discovery...")
_LOGGER.debug("Adding statically configured WeMo devices...")
for host, port in config.get(DOMAIN, {}).get(CONF_STATIC, []):
url = setup_url_for_address(host, port)
if not url:
_LOGGER.error(
'Unable to get description url for WeMo at: %s',
'{}:{}'.format(host, port) if port else host)
continue
try:
device = pywemo.discovery.device_from_description(url, None)
except (requests.exceptions.ConnectionError,
requests.exceptions.Timeout) as err:
_LOGGER.error('Unable to access WeMo at %s (%s)', url, err)
continue
if not [d[1] for d in devices
if d[1].serialnumber == device.serialnumber]:
devices.append((url, device))
if config.get(DOMAIN, {}).get(CONF_DISCOVERY):
_LOGGER.debug("Scanning network for WeMo devices...")
for device in pywemo.discover_devices():
if not [d[1] for d in devices
if d[1].serialnumber == device.serialnumber]:
devices.append((setup_url_for_device(device),
device))
for url, device in devices:
_LOGGER.debug('Adding WeMo device at %s:%i',
device.host, device.port)
discovery_info = {
'device_type': device.__class__.__name__,
'serial': device.serialnumber,
'mac_address': device.mac,
'ssdp_description': url,
}
discovery.discover(hass, SERVICE_WEMO, discovery_info)
_LOGGER.debug("WeMo device discovery has finished")
hass.bus.listen_once(EVENT_HOMEASSISTANT_START,
discover_wemo_devices)
return True