platypush/platypush/plugins/switch/wemo/__init__.py

47 lines
1.3 KiB
Python
Raw Normal View History

2017-11-04 00:13:22 +01:00
import logging
import json
2017-11-04 00:13:22 +01:00
from ouimeaux.environment import Environment, UnknownDevice
from platypush.message.response import Response
2017-11-04 00:13:22 +01:00
from .. import SwitchPlugin
class SwitchWemoPlugin(SwitchPlugin):
def _init(self, discovery_seconds=3):
self.discovery_seconds=discovery_seconds
2017-11-04 00:13:22 +01:00
self.env = Environment()
self.env.start()
self.refresh_devices()
def refresh_devices(self):
2017-11-04 00:13:22 +01:00
logging.info('Starting WeMo discovery')
self.env.discover(seconds=self.discovery_seconds)
self.devices = self.env.devices
def _exec(self, method, device, *args, **kwargs):
if device not in self.devices:
self.refresh_devices()
if device not in self.devices:
raise RuntimeError('Device {} not found'.format(device))
logging.info('{} -> {}'.format(device, method))
dev = self.devices[device]
getattr(dev, method)(*args, **kwargs)
resp = {'device': device, 'state': dev.get_state()}
return Response(output=json.dumps(resp))
2017-11-04 00:13:22 +01:00
def on(self, device):
return self._exec('on', device)
2017-11-04 00:13:22 +01:00
def off(self, device):
return self._exec('off', device)
2017-11-04 00:13:22 +01:00
def toggle(self, device):
return self._exec('toggle', device)
2017-11-04 00:13:22 +01:00
# vim:sw=4:ts=4:et: