armzilla / amazon-echo-ha-bridge

emulates philips hue api to other home automation gateways
Apache License 2.0
732 stars 168 forks source link

Automatically discover devices from Vera #22

Open bitglue opened 9 years ago

bitglue commented 9 years ago

The Vera can list devices it knows about so there's no need to manually go and add them all. Here's a quick Python script I wrote to do it:

import json
import requests
import sys

LIGHT_TYPES = {
    'urn:schemas-upnp-org:device:BinaryLight:1',
    'urn:schemas-upnp-org:device:DimmableLight:1',
}

def add_device(proxy_ip, name, on_url, off_url):
    payload = {
        "name": name,
        "deviceType": "switch",
        "onUrl": on_url,
        "offUrl": off_url,
    }
    url = 'http://%s:8080/api/devices' % (proxy_ip,)
    response = requests.post(url, data=json.dumps(payload), headers={'content-type': 'application/json'})
    if response.status_code != 201:
        raise Exception('unexpected response code %r' % (response.status_code,))

def on_url(ip, device_id):
    return 'http://%s:3480/data_request?id=action&output_format=json&serviceId=urn:upnp-org:serviceId:SwitchPower1&action=SetTarget&newTargetValue=1&DeviceNum=%s' % (
        ip, device_id)

def off_url(ip, device_id):
    return 'http://%s:3480/data_request?id=action&output_format=json&serviceId=urn:upnp-org:serviceId:SwitchPower1&action=SetTarget&newTargetValue=0&DeviceNum=%s' % (
        ip, device_id)

def main(vera_ip, proxy_ip):
    url = 'http://%s:3480/data_request?id=user_data' % (vera_ip,)
    user_data = requests.get(url).json()
    devices = user_data['devices']
    for device in devices:
        if device['device_type'] not in LIGHT_TYPES:
            continue
        add_device(
            proxy_ip,
            device['name'],
            on_url(vera_ip, device['id']),
            off_url(vera_ip, device['id']),
        )

if __name__ == '__main__':
    main(*sys.argv[1:])