예제 #1
0
def run():
    # Assign configuration variables.
    # The configuration check takes care they are present.
    api_factory = APIFactory(sys.argv[1])
    with open('gateway_psk.txt', 'a+') as file:
        file.seek(0)
        psk = file.read()
        if psk:
            api_factory.psk = psk.strip()
        else:
            psk = api_factory.generate_psk(sys.argv[2])
            print('Generated PSK: ', psk)
            file.write(psk)
    api = api_factory.request

    gateway = Gateway()

    devices_command = gateway.get_devices()
    devices_commands = api(devices_command)
    devices = api(devices_commands)
    lights = [dev for dev in devices if dev.has_light_control]

    rgb = (0, 0, 102)

    # Convert RGB to XYZ using a D50 illuminant.
    xyz = convert_color(sRGBColor(rgb[0], rgb[1], rgb[2]),
                        XYZColor,
                        observer='2',
                        target_illuminant='d65')
    xy = int(xyz.xyz_x), int(xyz.xyz_y)

    #  Assuming lights[3] is a RGB bulb
    api(lights[3].light_control.set_xy_color(xy[0], xy[1]))

    #  Assuming lights[3] is a RGB bulb
    xy = lights[3].light_control.lights[0].xy_color

    #  Normalize Z
    Z = int(lights[3].light_control.lights[0].dimmer / 254 * 65535)
    xyZ = xy + (Z, )
    rgb = convert_color(XYZColor(xyZ[0], xyZ[1], xyZ[2]),
                        sRGBColor,
                        observer='2',
                        target_illuminant='d65')
    rgb = (int(rgb.rgb_r), int(rgb.rgb_g), int(rgb.rgb_b))
    print(rgb)
예제 #2
0
    def __init__(self, location, unique_name, room, device_id, host, psk_id, psk):
        super(PyTradfriLight, self).__init__(location, unique_name, room)

        self.device_id = device_id
        """The TRÅDFRI device id."""

        # set color temperature limits for TRÅDFRI lights
        self.color_cold = '#f5faf6'
        self.color_warm = '#efd275'

        self.api = APIFactory(host, psk_id, psk).request
        self.device = None
        gateway = Gateway()

        while not self.device:
            logging.debug('Try to get device \'%s\'...' % unique_name)
            try:
                self.device = self.api(gateway.get_device(self.device_id))
            except pytradfri.error.RequestTimeout:
                pass
            except FileNotFoundError:
                logging.critical('Failed to load pytradfri service \'%s\'.'
                                 % self.unique_name)
                return

        # get device information
        self.state = self.device.light_control.lights[0].state

        if self.device.light_control.can_set_color:
            self.has_color = True
        else:
            self.has_color = False

        if self.device.light_control.can_set_dimmer:
            self.has_dimlevel = True
            # convert from range [0, 254] to [0, 100]
            dimlevel_hex = self.device.light_control.lights[0].dimmer
            self.dimlevel = round(dimlevel_hex/254*100, 0)
            self.saved_dimlevel = self.dimlevel if self.dimlevel > 0 else 1
        else:
            self.has_dimlevel = False

        if self.device.light_control.can_set_temp:
            self.has_temperature = True
            # get the temperature in mired and convert to range [0, 100]
            temperature_mired = self.device.light_control.lights[0].color_temp
            self.temperature = self.mired_to_precent(temperature_mired)
        else:
            self.has_temperature = False

        # start the TRÅDFRI observation
        observation_thread = threading.Thread(target=self.observation,
                                              name='%s-thread' % unique_name)
        observation_thread.daemon = True
        observation_thread.start()
        logging.info('Initialized TRADFRI device \'%s\'.' % self.unique_name)
예제 #3
0
    def __init__(self, graph, ip, key):
        self.graph = graph
        self.ip, self.key = ip, key
        self.api = APIFactory(ip, psk=key)
        self.gateway = Gateway()

        devices_command = self.gateway.get_devices()
        self.devices_commands = self.api.request(devices_command)
        self.devices = self.api.request(self.devices_commands)

        self.ctx = ROOM['tradfriHub']
        self.graph.patch(Patch(
            addQuads=[(s,p,o,self.ctx) for s,p,o in self.deviceStatements()]))

        self.curStmts = []

        task.LoopingCall(self.updateCur).start(60)
        for dev in self.devices:
            self.startObserve(dev)
예제 #4
0
def connect():
	print("connect")
	global conf
	global api_factory	
	global lights
	global groups
	global api
	try:
		identity = conf[ip_host].get('identity')
		psk = conf[ip_host].get('key')
		api_factory = APIFactory(host=ip_host, psk_id=identity, psk=psk)
	except KeyError:
		identity = uuid.uuid4().hex
		api_factory = APIFactory(host=ip_host, psk_id=identity)

		try:
			psk = api_factory.generate_psk(key)
			print('Generated PSK: ', psk)

			conf[ip_host] = {'identity': identity,'key': psk}
			save_json(CONFIG_FILE, conf)
		except AttributeError:
			raise PytradfriError("Please provide the 'Security Code' on the back of your Tradfri gateway using the -K flag.")

	api = api_factory.request
	gateway = Gateway()

	#get all devices
	devices_command = gateway.get_devices()
	devices_commands = api(devices_command)
	devices = api(devices_commands)
	# create list of available bulbs
	lamps = [dev for dev in devices if dev.has_light_control]

	# get all available groups
	groups_command = gateway.get_groups()
	groups_commands = api(groups_command)
	groupc = api(groups_commands)
	groups = [dev for dev in groupc]
	
	lights = [dev for dev in devices if dev.has_light_control]
예제 #5
0
파일: tradfri.py 프로젝트: jtulak/huefri
    def __init__(self,
                 ip: str,
                 key: str,
                 main_light: int,
                 lights: list,
                 hue: 'Hue' = None):
        """
            Parameters
            ----------
            ip : str
                Address of Tradfri gate. DNS will be resolved.

            key : str
                The secret string written on the back of the gate.

            main_lights : int
                The light we want to watch and copy changes from.

            lights : list
                A list of IDs of Tradfri lights, which should be controlled.

            hue: Hue
                The Hue instance we are controlling with the main light.
        """
        super().__init__(ip, key, main_light, lights)

        self.hue = hue
        self.threads = []

        api_factory = APIFactory(ip)
        api_factory.psk = key
        self.api = api_factory.request
        self.gateway = Gateway()

        devices_command = self.gateway.get_devices()
        devices_commands = self.api(devices_command)
        self._devices = self.api(devices_commands)

        self.color = None
        self.state = None
        self.dimmer = None
예제 #6
0
def main():
    # Assign configuration variables.
    # The configuration check takes care they are present.
    conf = load_json(CONFIG_FILE)

    try:
        identity = conf[args.host].get('identity')
        psk = conf[args.host].get('key')
        api_factory = APIFactory(host=args.host, psk_id=identity, psk=psk)
    except KeyError:
        identity = uuid.uuid4().hex
        api_factory = APIFactory(host=args.host, psk_id=identity)

        try:
            psk = api_factory.generate_psk(args.key)
            print('Generated PSK: ', psk)

            conf[args.host] = {'identity': identity, 'key': psk}
            save_json(CONFIG_FILE, conf)
        except AttributeError:
            raise PytradfriError("Please provide the 'Security Code' on the "
                                 "back of your Tradfri gateway using the "
                                 "-K flag.")

    api = api_factory.request

    gateway = Gateway()

    client = mqtt.Client(userdata={
        "api": api,
        "gateway": gateway,
        'topic': args.topic
    })
    client.username_pw_set(args.user, args.password)
    client.on_connect = on_connect
    client.on_message = on_message

    client.connect(args.mqtt_host, 1883, 60)

    client.loop_forever()
예제 #7
0
def get_api(settings: Settings):
    """
    Fetch API-Instance from settings object, automatically requests new session

    :param settings: Settings object, will be modified if no session is active
    """
    if settings.identity is None:
        # create new identity
        if settings.security_key is None:
            # No security key, no api instance
            return None
        settings.identity = uuid.uuid4().hex
        api_factory = APIFactory(host=settings.gateway_ip,
                                 psk_id=settings.identity)
        settings.key = api_factory.generate_psk(settings.security_key)
        settings.save()
        return api_factory.request

    api_factory = APIFactory(host=settings.gateway_ip,
                             psk_id=settings.identity,
                             psk=settings.key)
    return api_factory.request
예제 #8
0
def run():
    # Assign configuration variables.
    # The configuration check takes care they are present.
    conf = load_json(CONFIG_FILE)

    try:
        identity = conf[args.host].get('identity')
        psk = conf[args.host].get('key')
        api_factory = APIFactory(host=args.host, psk_id=identity, psk=psk)
    except KeyError:
        identity = uuid.uuid4().hex
        api_factory = APIFactory(host=args.host, psk_id=identity)

        try:
            psk = api_factory.generate_psk(args.key)
            print('Generated PSK: ', psk)

            conf[args.host] = {'identity': identity, 'key': psk}
            save_json(CONFIG_FILE, conf)
        except AttributeError:
            raise PytradfriError("Please provide the 'Security Code' on the "
                                 "back of your Tradfri gateway using the "
                                 "-K flag.")

    api = api_factory.request

    gateway = Gateway()

    devices_command = gateway.get_devices()
    devices_commands = api(devices_command)
    devices = api(devices_commands)

    lights = [dev for dev in devices if dev.has_light_control]

    for light in lights:
        if light.light_control.lights[0].state:
            api(light.light_control.set_state(0))
        else:
            api(light.light_control.set_state(1))
def setup_api(gateway_ip, config_file):
    config = load_json(config_file)

    try:
        identity = config[gateway_ip]['identity']
        psk = config[gateway_ip]['key']
        api_factory = APIFactory(host=gateway_ip, psk_id=identity, psk=psk)
    except KeyError:
        identity = uuid.uuid4().hex
        api_factory = APIFactory(host=gateway_ip, psk_id=identity)

        psk = api_factory.generate_psk(config[gateway_ip].get('security_code'))
        print('Generated PSK: ', psk)

        config[gateway_ip] = {
            'security_code': config[gateway_ip].get('security_code'),
            'identity': identity,
            'key': psk
        }

        save_json(config_file, config)

    return api_factory.request
예제 #10
0
파일: tradfri.py 프로젝트: mauzr/snake
    def setup(self):
        self.api = APIFactory(host=self.host,
                              psk_id=self.identity,
                              psk=self.psk).request
        devices = self.api(self.api(Gateway().get_devices()))
        lights = [
            dev for dev in devices
            if dev.has_light_control and dev.name == self.device_name
        ]
        if len(lights) != 1:
            raise ValueError("Light unknown")
        self.light = lights[0]

        yield
        self.api = None
예제 #11
0
파일: ikea.py 프로젝트: xibriz/tradfri-mqtt
    def _load_lights(self):
        """
        Load status of all devices
        """
        api_factory = APIFactory(host=self.ikea_ip,
                                 psk_id=self.ikea_identity,
                                 psk=self.ikea_key)
        self.api = api_factory.request

        gateway = Gateway()

        devices_command = gateway.get_devices()
        devices_commands = self.api(devices_command)
        devices = self.api(devices_commands)

        lights = [dev for dev in devices if dev.has_light_control]

        self.lights = lights
예제 #12
0
def initialize_tradlos():
    global lights
    global api

    # Load in the file, get our password for the gateway and create an API
    conf = load_json(CONFIG_FILE)
    identity = conf[IP_ADDRESS].get('identity')
    psk = conf[IP_ADDRESS].get('key')
    api_factory = APIFactory(host=IP_ADDRESS, psk_id=identity, psk=psk)

    # This section connects to the gateway and gets information on devices
    api = api_factory.request
    gateway = Gateway()
    devices_command = gateway.get_devices()
    devices_commands = api(devices_command)
    devices = api(devices_commands)

    # Create an array of objects that are lights
    lights = [dev for dev in devices if dev.has_light_control]
예제 #13
0
파일: tradfri.py 프로젝트: drewp/homeauto
    def __init__(self, graph, ip, key):
        self.graph = graph
        self.ip, self.key = ip, key
        self.api = APIFactory(ip, psk=key)
        self.gateway = Gateway()

        devices_command = self.gateway.get_devices()
        self.devices_commands = self.api.request(devices_command)
        self.devices = self.api.request(self.devices_commands)

        self.ctx = ROOM['tradfriHub']
        self.graph.patch(Patch(
            addQuads=[(s,p,o,self.ctx) for s,p,o in self.deviceStatements()]))

        self.curStmts = []

        task.LoopingCall(self.updateCur).start(60)
        for dev in self.devices:
            self.startObserve(dev)
예제 #14
0
def run():
    # Assign configuration variables.
    # The configuration check takes care they are present.
    conf = load_json(CONFIG_FILE)

    try:
        identity = conf[args.host].get("identity")
        psk = conf[args.host].get("key")
        api_factory = APIFactory(host=args.host, psk_id=identity, psk=psk)
    except KeyError:
        identity = uuid.uuid4().hex
        api_factory = APIFactory(host=args.host, psk_id=identity)

        try:
            psk = api_factory.generate_psk(args.key)
            print("Generated PSK: ", psk)

            conf[args.host] = {"identity": identity, "key": psk}
            save_json(CONFIG_FILE, conf)
        except AttributeError:
            raise PytradfriError(
                "Please provide the 'Security Code' on the "
                "back of your Tradfri gateway using the "
                "-K flag."
            )

    api = api_factory.request

    gateway = Gateway()

    devices_command = gateway.get_devices()
    devices_commands = api(devices_command)
    devices = api(devices_commands)

    lights = [dev for dev in devices if dev.has_light_control]

    # Print all lights
    print(lights)

    # Lights can be accessed by its index, so lights[1] is the second light
    if lights:
        light = lights[0]
    else:
        print("No lights found!")
        light = None

    if light:
        # Example 1: checks state of the light (true=on)
        print("Is on:", light.light_control.lights[0].state)

        # Example 2: get dimmer level of the light
        print("Dimmer:", light.light_control.lights[0].dimmer)

        # Example 3: What is the name of the light
        print("Name:", light.name)

        # Example 4: Set the light level of the light
        dim_command = light.light_control.set_dimmer(254)
        api(dim_command)

        # Example 5: Change color of the light
        # f5faf6 = cold | f1e0b5 = normal | efd275 = warm
        color_command = light.light_control.set_hex_color("efd275")
        api(color_command)

    # Get all blinds
    blinds = [dev for dev in devices if dev.has_blind_control]

    # Print all blinds
    print(blinds)

    if blinds:
        blind = blinds[0]
    else:
        print("No blinds found!")
        blind = None

    if blind:
        blind_command = blinds[0].blind_control.set_state(50)
        api(blind_command)

    tasks_command = gateway.get_smart_tasks()
    tasks_commands = api(tasks_command)
    tasks = api(tasks_commands)

    # Example 6: Return the transition time (in minutes) for task#1
    if tasks:
        print(tasks[0].task_control.tasks[0].transition_time)

        # Example 7: Set the dimmer stop value to 30 for light#1 in task#1
        dim_command_2 = tasks[0].start_action.devices[0].item_controller.set_dimmer(30)
        api(dim_command_2)

    if light:
        def observe_callback(updated_device):
            light = updated_device.light_control.lights[0]
            print("Received message for: %s" % light)

        def observe_err_callback(err):
            print("observe error:", err)

        def worker(light):
            api(light.observe(observe_callback, observe_err_callback, duration=120))

        for light in lights:
            threading.Thread(target=worker, args=(light,), daemon=True).start()

        print("Sleeping for 2 min to listen for more observation events")
        print("Try altering any light in the app, and watch the events!")
        time.sleep(120)
예제 #15
0
def run():
    # Assign configuration variables.
    # The configuration check takes care they are present.
    conf = load_json(CONFIG_FILE)

    try:
        identity = conf[args.host].get("identity")
        psk = conf[args.host].get("key")
        api_factory = APIFactory(host=args.host, psk_id=identity, psk=psk)
    except KeyError:
        identity = uuid.uuid4().hex
        api_factory = APIFactory(host=args.host, psk_id=identity)

        try:
            psk = api_factory.generate_psk(args.key)
            print("Generated PSK: ", psk)

            conf[args.host] = {"identity": identity, "key": psk}
            save_json(CONFIG_FILE, conf)
        except AttributeError:
            raise PytradfriError(
                "Please provide the 'Security Code' on the "
                "back of your Tradfri gateway using the "
                "-K flag."
            )

    api = api_factory.request

    gateway = Gateway()

    devices_command = gateway.get_devices()
    devices_commands = api(devices_command)
    devices = api(devices_commands)
    try:
        print(devices)
    except:
        print("Could not retrieve devices")
        return


    lights = [dev for dev in devices if dev.has_light_control]

    print(lights)

    device_names = ["Bord", "Gulvlampe", "Stue", "Klædeskab", "Knagerække", "Dør", "Pendellamper"]

    lamps = {}

    for device in device_names:
        for light in lights:
            if device.lower() in light.name.lower():
                lamps[device] = light
    

    #print(lamps["Stue"].light_control.lights[0].state)
    #api(lamps["Stue"].light_control.set_state(True))
    #api(lamps["Stue"].light_control.set_dimmer(1))
    #api(lamps["Stue"].light_control.set_state(False))
    
    for dev in device_names:
        print(dev, end = '')
        state = lamps[dev].light_control.lights[0].state
        if state == False:
            print(':off ', end = '')
        else:
            print(':',round(lamps[dev].light_control.lights[0].dimmer/254*100, 2), '% ', sep = '', end = '') 
예제 #16
0
from pprint import pprint
import sys

from .const import *  # noqa
from pytradfri.api.libcoap_api import APIFactory
from .gateway import Gateway
from .command import Command

if __name__ == '__main__':
    if len(sys.argv) != 3:
        print('Call with {} <host> <key>'.format(sys.argv[0]))
        sys.exit(1)

    logging.basicConfig(level=logging.DEBUG)

    api_factory = APIFactory(sys.argv[1])
    with open('gateway_psk.txt', 'a+') as file:
        file.seek(0)
        psk = file.read()
        if psk:
            api_factory.psk = psk.strip()
        else:
            psk = api_factory.generate_psk(sys.argv[2])
            print('Generated PSK: ', psk)
            file.write(psk)

    api = api_factory.request

    gateway = Gateway()
    devices_commands = api(gateway.get_devices())
    devices = api(devices_commands)
예제 #17
0
def run():
    # Assign configuration variables.
    # The configuration check takes care they are present.
    api_factory = APIFactory(sys.argv[1])
    with open('gateway_psk.txt', 'a+') as file:
        file.seek(0)
        psk = file.read()
        if psk:
            api_factory.psk = psk.strip()
        else:
            psk = api_factory.generate_psk(sys.argv[2])
            print('Generated PSK: ', psk)
            file.write(psk)
    api = api_factory.request

    gateway = Gateway()

    devices_command = gateway.get_devices()
    devices_commands = api(devices_command)
    devices = api(devices_commands)

    lights = [dev for dev in devices if dev.has_light_control]

    # Print all lights
    print(lights)

    # Lights can be accessed by its index, so lights[1] is the second light
    light = lights[0]

    observe(api, light)

    # Example 1: checks state of the light 2 (true=on)
    print(light.light_control.lights[0].state)

    # Example 2: get dimmer level of light 2
    print(light.light_control.lights[0].dimmer)

    # Example 3: What is the name of light 2
    print(light.name)

    # Example 4: Set the light level of light 2
    dim_command = light.light_control.set_dimmer(255)
    api(dim_command)

    # Example 5: Change color of light 2
    # f5faf6 = cold | f1e0b5 = normal | efd275 = warm
    color_command = light.light_control.set_hex_color('efd275')
    api(color_command)

    tasks_command = gateway.get_smart_tasks()
    tasks_commands = api(tasks_command)
    tasks = api(tasks_commands)

    # Example 6: Return the transition time (in minutes) for task#1
    if tasks:
        print(tasks[0].task_control.tasks[0].transition_time)

        # Example 7: Set the dimmer stop value to 30 for light#1 in task#1
        dim_command_2 = tasks[0].start_action.devices[0].item_controller\
            .set_dimmer(30)
        api(dim_command_2)

    print("Sleeping for 2 min to receive the rest of the observation events")
    print("Try altering the light (%s) in the app, and watch the events!" %
          light.name)
    time.sleep(120)
예제 #18
0
import os
import threading
import time

from pytradfri import Gateway
from pytradfri.api.libcoap_api import APIFactory

TRADFRIIP = os.getenv('TRADFRIIP')
TRADFRIidentity = os.getenv('TRADFRIidentity')
TRADFRIkey = os.getenv('TRADFRIkey')

api_factory = APIFactory(host=TRADFRIIP,
                         psk_id=TRADFRIidentity,
                         psk=TRADFRIkey)
api = api_factory.request

gateway = Gateway()

devices_command = gateway.get_devices()
devices_commands = api(devices_command)
devices = api(devices_commands)

devices = [dev for dev in devices if dev.has_light_control]


def printDevice(dev):
    print()
    print(dev.name)
    print('  model:     ' + dev.device_info.model_number)
    print('  id:        ' + str(dev.id))
    print('  light:     ' + str(dev.has_light_control))
예제 #19
0
파일: tradfri.py 프로젝트: drewp/homeauto
class Hub(object):
    def __init__(self, graph, ip, key):
        self.graph = graph
        self.ip, self.key = ip, key
        self.api = APIFactory(ip, psk=key)
        self.gateway = Gateway()

        devices_command = self.gateway.get_devices()
        self.devices_commands = self.api.request(devices_command)
        self.devices = self.api.request(self.devices_commands)

        self.ctx = ROOM['tradfriHub']
        self.graph.patch(Patch(
            addQuads=[(s,p,o,self.ctx) for s,p,o in self.deviceStatements()]))

        self.curStmts = []

        task.LoopingCall(self.updateCur).start(60)
        for dev in self.devices:
            self.startObserve(dev)
            
    def startObserve(self, dev):
        def onUpdate(dev):
            reactor.callFromThread(self.updateCur, dev)
        def onErr(err):
            log.warn('%r; restart observe on %r', err, dev)
            reactor.callLater(1, self.startObserve, dev)
        reactor.callInThread(self.api.request, dev.observe(onUpdate, onErr))

    def description(self):
        return {
            'uri': 'huburi',
            'devices': [{
                'uri': devUri(dev),
                'className': self.__class__.__name__,
                'pinNumber': None,
                'outputPatterns': [(devUri(dev), ROOM['brightness'], None)],
                'watchPrefixes': [],
                'outputWidgets': [{
                    'element': 'output-slider',
                    'min': 0, 'max': 1, 'step': 1 / 255,
                    'subj': devUri(dev),
                    'pred': ROOM['brightness'],
                }] * dev.has_light_control,
            } for dev in self.devices],
            'graph': 'http://sticker:9059/graph', #todo
        }
        
    def updateCur(self, dev=None):
        cur = [(s,p,o,self.ctx) for s,p,o in
               self.currentStateStatements([dev] if dev else self.devices)]
        self.graph.patch(Patch(addQuads=cur, delQuads=self.curStmts))
        self.curStmts = cur
                
    def deviceStatements(self):
        for dev in self.devices:
            uri = devUri(dev)
            yield (uri, RDF.type, ROOM['IkeaDevice'])
            yield (uri, ROOM['ikeaId'], Literal(dev.id))
            if dev.last_seen:
                utcSeen = dev.last_seen
                yield (uri, ROOM['lastSeen'],
                       Literal(utcSeen.replace(tzinfo=tzutc()).astimezone(tzlocal())))
                yield (uri, ROOM['reachable'], ROOM['yes'] if dev.reachable else ROOM['no'])
            yield (uri, RDFS.label, Literal(dev.name))
            # no connection between remotes and lights?
            
    def currentStateStatements(self, devs):
        for dev in self.devices:  # could scan just devs, but the Patch line needs a fix
            uri = devUri(dev)
            di = dev.device_info
            if di.battery_level is not None:
                yield (uri, ROOM['batteryLevel'], Literal(di.battery_level / 100))
            if dev.has_light_control:
                lc = dev.light_control
                #import ipdb;ipdb.set_trace()

                lightUri = devUri(dev)
                print lc.raw
                if not lc.raw[0][ATTR_LIGHT_STATE]:
                    level = 0
                else:
                    level = lc.raw[0][ATTR_LIGHT_DIMMER] / 255
                yield (lightUri, ROOM['brightness'], Literal(level))
                #if light.hex_color:
                #    yield (lightUri, ROOM['kelvinColor'], Literal(light.kelvin_color))
                #    yield (lightUri, ROOM['color'], Literal('#%s' % light.hex_color))
            

    def outputStatements(self, stmts):
        for stmt in stmts:
            for dev in self.devices:
                uri = devUri(dev)
                if stmt[0] == uri:
                    if stmt[1] == ROOM['brightness']:
                        try:
                            self.api.request(dev.light_control.set_dimmer(
                                int(255 * float(stmt[2])), transition_time=3))
                        except:
                            traceback.print_exc()
                            raise
        self.updateCur()
예제 #20
0
def get_api():
    api_factory = APIFactory(host='192.168.1.2',
                             psk_id='f712f4d5aaa642bcbce7ab5cf501bca9',
                             psk='HkNXWgUOl2u0cUUa')
    api = api_factory.request
    return api
예제 #21
0
def safeParseInt(string):
    try:
        return int(string)
    except ValueError:
        return None


load_dotenv()

app = Flask(__name__)

psk_id = safeGetEnv('TRADFRI_ID')
psk = safeGetEnv('TRADFRI_PSK')
host = safeGetEnv('TRADFRI_IP')

api_factory = APIFactory(host=host, psk_id=psk_id, psk=psk)


@app.route('/blinds', methods=['PUT'])
def handle_blinds():
    state = safeParseInt(request.args.get('state'))

    if state is None or state < 0 or state > 100:
        return Response(response='Error, no or wrong state defined.',
                        status=400)

    api = api_factory.request
    gateway = Gateway()

    devices_command = gateway.get_devices()
    devices_commands = api(devices_command)
예제 #22
0
    try:
        from pytradfri import Gateway
        from pytradfri.api.libcoap_api import APIFactory
        from pytradfri.error import RequestError, RequestTimeout

    except ImportError as e:
        if args.debug:
            raise
        else:
            print(
                "Error: Unable to import pytradfri. Please check your installation!"
            )
            exit()

    identity = uuid.uuid4().hex
    api_factory = APIFactory(host=args.IP, psk_id=identity)

    try:
        psk = api_factory.generate_psk(args.KEY)
    except RequestTimeout:
        if args.debug:
            raise
        else:
            print(
                "Error: Connection to gateway timed out!\nPlease check IP/KEY."
            )
            exit()
    except:
        if args.debug:
            raise
        else:
예제 #23
0
    def init(self):
        if self.initialized:
            Logger().write(LogVerbosity.Info, "already init")
            return

        if sys.platform != "linux" and sys.platform != "linux2":
            Logger().write(LogVerbosity.Info, "Lighting: Not initializing, no coap client available on windows")
            self.initialized = True
            self.tradfri_state.update_group(DeviceGroup(1, "Test group", True, 128, 6))
            self.tradfri_state.update_group(DeviceGroup(2, "Test group 2", False, 18, 6))
            return

        if current_time() - self.last_init < 5000:
            Logger().write(LogVerbosity.Info, "Tried initialization less than 5s ago")
            return

        Logger().write(LogVerbosity.All, "Start LightManager init")
        self.enabled = True
        if not self.initialized:
            ip = Settings.get_string("tradfri_hub_ip")
            identity = Database().get_stat_string("LightingId")
            key = Database().get_stat_string("LightingKey")

            if identity is None or key is None:
                Logger().write(LogVerbosity.Info, "Lighting: No identity/key found, going to generate new")
                # We don't have all information to connect, reset and start from scratch
                Database().remove_stat("LightingId")
                Database().remove_stat("LightingKey")
                key = None

                identity = uuid.uuid4().hex
                Database().update_stat("LightingId", identity)  # Generate and save a new id
                self.api_factory = APIFactory(host=ip, psk_id=identity)
            else:
                self.api_factory = APIFactory(host=ip, psk_id=identity, psk=key)

            self.api = self.api_factory.request
            self.gateway = Gateway()

            if key is None:
                try:
                    security_code = SecureSettings.get_string("tradfri_hub_code")  # the code at the bottom of the hub
                    key = self.api_factory.generate_psk(security_code)
                    Database().update_stat("LightingKey", key)  # Save the new key
                    Logger().write(LogVerbosity.Info, "Lighting: New key retrieved")
                except Exception as e:
                    Logger().write_error(e, "Unhandled exception")
                    return
            else:
                Logger().write(LogVerbosity.Info, "Lighting: Previously saved key found")

            try:
                self.initialized = True
                groups = self.get_device_groups()
                for group in groups:
                    self.tradfri_state.update_group(group)
            except Exception as e:
                Logger().write(LogVerbosity.Info, "Failed to init tradfri, clearing previous key to try generate new")
                self.initialized = False
                Database().remove_stat("LightingId")
                Database().remove_stat("LightingKey")
                Logger().write_error(e, "Failed to get groups from hub")
예제 #24
0
config = YAML(typ='safe').load(open(CONFIG_PATH))

from pytradfri import Gateway
from pytradfri.api.libcoap_api import APIFactory
from pytradfri.error import PytradfriError, RequestTimeout
from pytradfri.util import load_json, save_json

from pathlib import Path
import uuid
import argparse
import threading
import time
import datetime

api_factory = APIFactory(host=config['host'],
                         psk_id=config['identity'],
                         psk=config['psk'])

api = api_factory.request

gateway = Gateway()

devices_commands = api(gateway.get_devices())

while True:
    try:
        devices = api(devices_commands)
        lights = [dev for dev in devices if dev.has_light_control]

        print(datetime.datetime.now())
예제 #25
0
from flask import Flask

from pytradfri import Gateway
from pytradfri.api.libcoap_api import APIFactory
from pytradfri.error import PytradfriError
from pytradfri.util import load_json

import os

CONFIG_FILE = 'tradfri_standalone_psk.conf'
HOST = os.environ['HOST']

conf = load_json(CONFIG_FILE)
identity = conf[HOST].get('identity')
psk = conf[HOST].get('key')
api_factory = APIFactory(host=HOST, psk_id=identity, psk=psk)
api = api_factory.request
gateway = Gateway()
devices_command = gateway.get_devices()
devices_commands = api(devices_command)
devices = api(devices_commands)
lights = [dev for dev in devices if dev.has_light_control]

app = Flask(__name__)


@app.route('/pytradfri/bulbs/<bulb_id>/state/<bulb_state>', methods=['POST'])
def bulb_set_state(bulb_id, bulb_state):
    bulb = next((dev for dev in lights if dev.id == int(bulb_id)), None)
    api(bulb.light_control.set_state(int(bulb_state)))
    return 'success'
예제 #26
0
class Hub(object):
    def __init__(self, graph, ip, key):
        self.graph = graph
        self.ip, self.key = ip, key
        self.api = APIFactory(ip, psk=key)
        self.gateway = Gateway()

        devices_command = self.gateway.get_devices()
        self.devices_commands = self.api.request(devices_command)
        self.devices = self.api.request(self.devices_commands)

        self.ctx = ROOM['tradfriHub']
        self.graph.patch(Patch(
            addQuads=[(s,p,o,self.ctx) for s,p,o in self.deviceStatements()]))

        self.curStmts = []

        task.LoopingCall(self.updateCur).start(60)
        for dev in self.devices:
            self.startObserve(dev)

    def startObserve(self, dev):
        def onUpdate(dev):
            reactor.callFromThread(self.updateCur, dev)
        def onErr(err):
            log.warn('%r; restart observe on %r', err, dev)
            reactor.callLater(1, self.startObserve, dev)
        reactor.callInThread(self.api.request, dev.observe(onUpdate, onErr))

    def description(self):
        return {
            'uri': 'huburi',
            'devices': [{
                'uri': devUri(dev),
                'className': self.__class__.__name__,
                'pinNumber': None,
                'outputPatterns': [(devUri(dev), ROOM['brightness'], None)],
                'watchPrefixes': [],
                'outputWidgets': [{
                    'element': 'output-slider',
                    'min': 0, 'max': 1, 'step': 1 / 255,
                    'subj': devUri(dev),
                    'pred': ROOM['brightness'],
                }] * dev.has_light_control,
            } for dev in self.devices],
            'graph': 'http://sticker:9059/graph', #todo
        }

    def updateCur(self, dev=None):
        cur = [(s,p,o,self.ctx) for s,p,o in
               self.currentStateStatements([dev] if dev else self.devices)]
        self.graph.patch(Patch(addQuads=cur, delQuads=self.curStmts))
        self.curStmts = cur

    def deviceStatements(self):
        for dev in self.devices:
            uri = devUri(dev)
            yield (uri, RDF.type, ROOM['IkeaDevice'])
            yield (uri, ROOM['ikeaId'], Literal(dev.id))
            if dev.last_seen:
                utcSeen = dev.last_seen
                yield (uri, ROOM['lastSeen'],
                       Literal(utcSeen.replace(tzinfo=tzutc()).astimezone(tzlocal())))
                yield (uri, ROOM['reachable'], ROOM['yes'] if dev.reachable else ROOM['no'])
            yield (uri, RDFS.label, Literal(dev.name))
            # no connection between remotes and lights?

    def currentStateStatements(self, devs):
        for dev in self.devices:  # could scan just devs, but the Patch line needs a fix
            uri = devUri(dev)
            di = dev.device_info
            if di.battery_level is not None:
                yield (uri, ROOM['batteryLevel'], Literal(di.battery_level / 100))
            if dev.has_light_control:
                lc = dev.light_control
                #import ipdb;ipdb.set_trace()

                lightUri = devUri(dev)
                print lc.raw
                if not lc.raw[0][ATTR_LIGHT_STATE]:
                    level = 0
                else:
                    level = lc.raw[0][ATTR_LIGHT_DIMMER] / 255
                yield (lightUri, ROOM['brightness'], Literal(level))
                #if light.hex_color:
                #    yield (lightUri, ROOM['kelvinColor'], Literal(light.kelvin_color))
                #    yield (lightUri, ROOM['color'], Literal('#%s' % light.hex_color))


    def outputStatements(self, stmts):
        for stmt in stmts:
            for dev in self.devices:
                uri = devUri(dev)
                if stmt[0] == uri:
                    if stmt[1] == ROOM['brightness']:
                        try:
                            self.api.request(dev.light_control.set_dimmer(
                                int(255 * float(stmt[2])), transition_time=3))
                        except:
                            traceback.print_exc()
                            raise
        self.updateCur()
예제 #27
0
 def save(self, *args, **kwargs):
     if not self.id or self._initial_host != self.host or self._initial_key != self.key:
         self.identity = uuid.uuid4().hex
         api_factory = APIFactory(host=self.host, psk_id=self.identity)
         self.psk = api_factory.generate_psk(self.key)
     super(Gateway, self).save(*args, **kwargs)
예제 #28
0
class TradfriManager(metaclass=Singleton):

    api_factory = None
    api = None
    gateway = None
    enabled = False
    initialized = False
    last_init = 0

    def __init__(self):
        self.tradfri_state = TradfriState()
        self.observing_end = 0
        self.observing = False
        self.observe_thread = None

    def init(self):
        if self.initialized:
            Logger().write(LogVerbosity.Info, "already init")
            return

        if sys.platform != "linux" and sys.platform != "linux2":
            Logger().write(LogVerbosity.Info, "Lighting: Not initializing, no coap client available on windows")
            self.initialized = True
            self.tradfri_state.update_group(DeviceGroup(1, "Test group", True, 128, 6))
            self.tradfri_state.update_group(DeviceGroup(2, "Test group 2", False, 18, 6))
            return

        if current_time() - self.last_init < 5000:
            Logger().write(LogVerbosity.Info, "Tried initialization less than 5s ago")
            return

        Logger().write(LogVerbosity.All, "Start LightManager init")
        self.enabled = True
        if not self.initialized:
            ip = Settings.get_string("tradfri_hub_ip")
            identity = Database().get_stat_string("LightingId")
            key = Database().get_stat_string("LightingKey")

            if identity is None or key is None:
                Logger().write(LogVerbosity.Info, "Lighting: No identity/key found, going to generate new")
                # We don't have all information to connect, reset and start from scratch
                Database().remove_stat("LightingId")
                Database().remove_stat("LightingKey")
                key = None

                identity = uuid.uuid4().hex
                Database().update_stat("LightingId", identity)  # Generate and save a new id
                self.api_factory = APIFactory(host=ip, psk_id=identity)
            else:
                self.api_factory = APIFactory(host=ip, psk_id=identity, psk=key)

            self.api = self.api_factory.request
            self.gateway = Gateway()

            if key is None:
                try:
                    security_code = SecureSettings.get_string("tradfri_hub_code")  # the code at the bottom of the hub
                    key = self.api_factory.generate_psk(security_code)
                    Database().update_stat("LightingKey", key)  # Save the new key
                    Logger().write(LogVerbosity.Info, "Lighting: New key retrieved")
                except Exception as e:
                    Logger().write_error(e, "Unhandled exception")
                    return
            else:
                Logger().write(LogVerbosity.Info, "Lighting: Previously saved key found")

            try:
                self.initialized = True
                groups = self.get_device_groups()
                for group in groups:
                    self.tradfri_state.update_group(group)
            except Exception as e:
                Logger().write(LogVerbosity.Info, "Failed to init tradfri, clearing previous key to try generate new")
                self.initialized = False
                Database().remove_stat("LightingId")
                Database().remove_stat("LightingKey")
                Logger().write_error(e, "Failed to get groups from hub")

    def start_observing(self):
        Logger().write(LogVerbosity.Debug, "Start observing light data")
        self.observing = True
        if self.observing_end > current_time():
            Logger().write(LogVerbosity.All, "Still observing, not starting again")
            return  # still observing, the check observing thread will renew

        if not self.check_state():
            return

        self.observing_end = current_time() + 30000
        groups_commands = self.api(self.gateway.get_groups())
        result = self.api(groups_commands)
        for group in result:
            self.observe_group(group)

    def observe_group(self, group):
        Logger().write(LogVerbosity.All, "Starting observe for group " + group.name)
        self.observe_thread = CustomThread(lambda: self.api(group.observe(
            self.tradfri_state.update_group,
            lambda x: self.check_observe(group), duration=30)), "Light group observer", [])
        self.observe_thread.start()

    def check_observe(self, group):
        if self.observing:
            # Restart observing since it timed out
            Logger().write(LogVerbosity.Debug, "Restarting observing for group " + str(group.name))
            self.observe_group(group)

    def stop_observing(self):
        Logger().write(LogVerbosity.Debug, "Stop observing light data")
        self.observing = False

    def get_devices(self):
        if not self.check_state():
            return []

        Logger().write(LogVerbosity.All, "Get devices")
        devices_commands = self.api(self.gateway.get_devices())
        devices = self.api(devices_commands)
        return [d for d in [self.parse_device(x) for x in devices] if d is not None]

    def set_state(self, device_id, state):
        if not self.check_state():
            return

        Logger().write(LogVerbosity.All, "Set device state")
        device = self.api(self.gateway.get_device(device_id))
        if device.has_light_control:
            self.api(device.light_control.set_state(state))
        else:
            self.api(device.socket_control.set_state(state))

    def set_light_warmth(self, device_id, warmth):
        if not self.check_state():
            return

        Logger().write(LogVerbosity.All, "Set light warmth")
        device = self.api(self.gateway.get_device(device_id))
        self.api(device.light_control.set_color_temp(warmth))

    def set_light_dimmer(self, device_id, amount):
        if not self.check_state():
            return

        Logger().write(LogVerbosity.All, "Set light dimmer")
        device = self.api(self.gateway.get_device(device_id))
        self.api(device.light_control.set_dimmer(amount))

    def set_device_name(self, device_id, name):
        if not self.check_state():
            return

        Logger().write(LogVerbosity.All, "Set device name")
        device = self.api(self.gateway.get_device(device_id))
        self.api(device.set_name(name))

    def get_device_groups(self):
        if not self.check_state():
            return []

        Logger().write(LogVerbosity.All, "Get device groups")
        groups_commands = self.api(self.gateway.get_groups())
        result = self.api(groups_commands)
        Logger().write(LogVerbosity.All, "Get device groups: " + str([x.raw for x in result]))
        return [DeviceGroup(group.id, group.name, group.state, group.dimmer, len(group.member_ids)) for group in result]

    def get_devices_in_group(self, group):
        if not self.check_state():
            return []

        Logger().write(LogVerbosity.All, "Get lights in group")
        group = self.api(self.gateway.get_group(group))
        members = group.member_ids
        result = [self.api(self.gateway.get_device(x)) for x in members]
        return [d for d in [self.parse_device(x) for x in result] if d is not None]

    def set_group_name(self, group, name):
        if not self.check_state():
            return

        Logger().write(LogVerbosity.All, "Set group name")
        group = self.api(self.gateway.get_group(group))
        self.api(group.set_name(name))

    def set_group_state(self, group, state):
        if not self.check_state():
            return

        Logger().write(LogVerbosity.All, "Set group state")
        group = self.api(self.gateway.get_group(group))
        self.api(group.set_state(state))

    def set_group_dimmer(self, group, dimmer):
        if not self.check_state():
            return

        Logger().write(LogVerbosity.All, "Set group dimmer")
        group = self.api(self.gateway.get_group(group))
        self.api(group.set_dimmer(dimmer))

    def check_state(self):
        if not self.enabled:
            return False  # not available

        if not self.initialized:
            self.init()
            if not self.initialized:
                return False  # init failed
        return True

    @staticmethod
    def parse_device(data):
        if data.has_light_control:
            lights = []
            for light in data.light_control.lights:
                lights.append(LightDevice(
                    light.state,
                    light.dimmer,
                    light.color_temp,
                    light.hex_color))

            return LightControl(data.id,
                                data.name,
                                data.application_type,
                                data.last_seen.timestamp(),
                                data.reachable,
                                data.light_control.can_set_dimmer,
                                data.light_control.can_set_temp,
                                data.light_control.can_set_color,
                                lights)

        elif data.has_socket_control:
            sockets = []
            for socket in data.socket_control.sockets:
                sockets.append(SocketDevice(socket.state))

            return SocketControl(data.id, data.name, data.application_type, data.last_seen.timestamp(), data.reachable, sockets)
예제 #29
0
import urllib.request
import threading

# Change this IP address to your gateway
IP_ADDRESS = '192.168.0.158'

# Make sure you're in the same directory as this file
CONFIG_FILE = 'tradfri_standalone_psk.conf'

WEBHOOK = 'https://maker.ifttt.com/trigger/{trigger_name}/with/key/{your_key}'

# Load in the file, get our password for the gateway and create an API
conf = load_json(CONFIG_FILE)
identity = conf[IP_ADDRESS].get('identity')
psk = conf[IP_ADDRESS].get('key')
api_factory = APIFactory(host=IP_ADDRESS, psk_id=identity, psk=psk)

# This section connects to the gateway and gets information on devices
api = api_factory.request
gateway = Gateway()
devices_command = gateway.get_devices()
devices_commands = api(devices_command)
devices = api(devices_commands)

# Create an array of objects that are lights
lights = [dev for dev in devices if dev.has_light_control]


def observe(api, device):
    def callback(updated_device):
        light = updated_device.light_control.lights[0]
예제 #30
0
from pytradfri import Gateway
from pytradfri.api.libcoap_api import APIFactory
   
def output(x):
	print(str(datetime.datetime.now().time())[:8] + " "+ str(x))
	sys.stdout.flush()
	
#----------------------------- 
# Global Variable declaration  
#----------------------------- 
ip = "192.168.1.75"

# Assign configuration variables.
# The configuration check takes care they are present.
api_factory = APIFactory(ip)
print(api_factory)
with open('gateway_psk.txt', 'a+') as file_psk, open('gateway_key.txt', 'a+') as file_key:
	file_psk.seek(0)
	psk = file_psk.read()
	if psk:
		api_factory.psk = psk.strip()
	else:
		file_key.seek(0)
		key = file.read()
		if key:
			psk = api_factory.generate_psk(key)
			print('Generated PSK: ', psk)
		file_psk.write(psk)
	file_psk.close()
	file_key.close()
예제 #31
0
def run():
    # Assign configuration variables.
    # The configuration check takes care they are present.
    conf = load_json(CONFIG_FILE)

    try:
        identity = conf[args.host].get('identity')
        psk = conf[args.host].get('key')
        api_factory = APIFactory(host=args.host, psk_id=identity, psk=psk)
    except KeyError:
        identity = uuid.uuid4().hex
        api_factory = APIFactory(host=args.host, psk_id=identity)

        try:
            psk = api_factory.generate_psk(args.key)
            print('Generated PSK: ', psk)

            conf[args.host] = {'identity': identity, 'key': psk}
            save_json(CONFIG_FILE, conf)

        except AttributeError:
            raise PytradfriError("Please provide your Key")

    api = api_factory.request

    gateway = Gateway()

    devices_command = gateway.get_devices()
    devices_commands = api(devices_command)
    devices = api(devices_commands)

    lights = [dev for dev in devices if dev.has_light_control]

    # Print all lights
    print(lights)

    # Lights can be accessed by its index, so lights[1] is the second light
    light = lights[0]

    observe(api, light)

    # Example 1: checks state of the light (true=on)
    print(light.light_control.lights[0].state)

    # Example 2: get dimmer level of the light
    print(light.light_control.lights[0].dimmer)

    # Example 3: What is the name of the light
    print(light.name)

    # Example 4: Set the light level of the light
    dim_command = light.light_control.set_dimmer(254)
    api(dim_command)

    # Example 5: Change color of the light
    # f5faf6 = cold | f1e0b5 = normal | efd275 = warm
    color_command = light.light_control.set_hex_color('efd275')
    api(color_command)

    tasks_command = gateway.get_smart_tasks()
    tasks_commands = api(tasks_command)
    tasks = api(tasks_commands)

    # Example 6: Return the transition time (in minutes) for task#1
    if tasks:
        print(tasks[0].task_control.tasks[0].transition_time)

        # Example 7: Set the dimmer stop value to 30 for light#1 in task#1
        dim_command_2 = tasks[0].start_action.devices[0].item_controller\
            .set_dimmer(30)
        api(dim_command_2)

    print("Sleeping for 2 min to receive the rest of the observation events")
    print("Try altering the light (%s) in the app, and watch the events!" %
          light.name)
    time.sleep(120)
예제 #32
0
def run():
    # Assign configuration variables.
    # The configuration check takes care they are present.
    conf = load_json(CONFIG_FILE)

    try:
        identity = conf[args.host].get('identity')
        psk = conf[args.host].get('key')
        api_factory = APIFactory(host=args.host, psk_id=identity, psk=psk)
    except KeyError:
        identity = uuid.uuid4().hex
        api_factory = APIFactory(host=args.host, psk_id=identity)

        try:
            psk = api_factory.generate_psk(args.key)
            print('Generated PSK: ', psk)

            conf[args.host] = {'identity': identity, 'key': psk}
            save_json(CONFIG_FILE, conf)
        except AttributeError:
            raise PytradfriError("Please provide the 'Security Code' on the "
                                 "back of your Tradfri gateway using the "
                                 "-K flag.")

    api = api_factory.request

    gateway = Gateway()

    devices_command = gateway.get_devices()
    devices_commands = api(devices_command)
    devices = api(devices_commands)

    lights = [dev for dev in devices if dev.has_light_control]

    # Print all lights
    print(lights)

    # Lights can be accessed by its index, so lights[1] is the second light
    if lights:
        light = lights[0]
    else:
        print("No lights found!")
        light = None

    if light:
        light_command = [
            light.light_control.set_dimmer(0),
            light.light_control.set_dimmer(64),
            light.light_control.set_dimmer(128),
            light.light_control.set_dimmer(192),
            light.light_control.set_dimmer(254)
        ]
        dark_command = light.light_control.set_dimmer(0)
        api(dark_command)

        with PiCamera() as camera:
            # Configure camera
            camera.resolution = (1640, 922)  # Full Frame, 16:9 (Camera v2)
            camera.start_preview()

            # Do inference on VisionBonnet
            with CameraInference(face_detection.model()) as inference:
                for result in inference.run():
                    facecount = len(face_detection.get_faces(result))
                    if facecount >= 1:
                        if facecount > 4:
                            facecount = 4
                        print('I see you')
                        api(light_command[facecount])
                        time.sleep(5)
                        api(dark_command)
예제 #33
0
def run():
    # Assign configuration variables.
    # The configuration check takes care they are present.
    conf = load_json(CONFIG_FILE)

    try:
        identity = conf[args.host].get('identity')
        psk = conf[args.host].get('key')
        api_factory = APIFactory(host=args.host, psk_id=identity, psk=psk)
    except KeyError:
        identity = uuid.uuid4().hex
        api_factory = APIFactory(host=args.host, psk_id=identity)

        try:
            psk = api_factory.generate_psk(args.key)
            print('Generated PSK: ', psk)

            conf[args.host] = {'identity': identity, 'key': psk}
            save_json(CONFIG_FILE, conf)
        except AttributeError:
            raise PytradfriError("Please provide the 'Security Code' on the "
                                 "back of your Tradfri gateway using the "
                                 "-K flag.")

    chromecasts = pychromecast.get_chromecasts()
    cast = next(cc for cc in chromecasts
                if cc.device.friendly_name == "Högtalare Kök")
    cast.wait()
    mc = cast.media_controller
    api = api_factory.request

    gateway = Gateway()

    devices_command = gateway.get_devices()
    devices_commands = api(devices_command)
    devices = api(devices_commands)

    lights = [dev for dev in devices if dev.has_light_control]

    # Print all lights
    #    print(lights)

    #    for light in lights:
    #        observe(api,light)
    #        print("Name: {}".format(light.name) + " Index: {}".format(lights.index(light)))
    #    exit()

    # Lights can be accessed by its index, so lights[1] is the second light
    #    if lights:
    #        light = lights[0]
    #    else:
    #        print("No lights found!")
    #        light = None
    #
    #    if light:
    #        observe(api, light)

    # Example 1: checks state of the light (true=on)
    #        print("State: {}".format(light.light_control.lights[0].state))

    # Example 2: get dimmer level of the light
    #        print("Dimmer: {}".format(light.light_control.lights[0].dimmer))

    # Example 3: What is the name of the light
    #        print("Name: {}".format(light.name))

    # Example 4: Set the light level of the light
    #        dim_command = light.light_control.set_dimmer(254)
    #        api(dim_command)

    # Example 5: Change color of the light
    # f5faf6 = cold | f1e0b5 = normal | efd275 = warm
    #        color_command = light.light_control.set_color_temp(250)
    #        api(color_command)

    msleep = lambda x: time.sleep(x / 1000.0)

    porch = lights[int(halloween['porch']['id'])]
    #    observe(api,light)

    cmd_on = porch.light_control.set_dimmer(254)
    cmd_low = porch.light_control.set_dimmer(20)
    cmd_off = porch.light_control.set_dimmer(00)

    #  xy = light.light_control.lights[0].xy_color
    #print(xy)
    #  (25022, 24884) white
    #  (42926, 21299) red
    xy_white = porch.light_control.set_xy_color(25022, 24884)
    xy_red = porch.light_control.set_xy_color(42926, 21299)

    api(cmd_off)
    mc.play_media('http://172.22.16.7/sound/killer.mp3', 'audio/mpeg')
    mc.block_until_active()
    msleep(1000)
    api(cmd_on)
    msleep(100)
    api(cmd_low)
    msleep(200)
    api(cmd_on)
    msleep(100)
    api(cmd_low)
    msleep(20)
    api(cmd_on)
    msleep(20)
    api(cmd_low)
    msleep(20)
    api(cmd_on)
    msleep(20)
    api(cmd_low)
    msleep(20)
    api(cmd_on)
    msleep(100)
    api(cmd_low)
    msleep(20)
    api(cmd_on)
    msleep(100)
    api(cmd_low)
    msleep(200)
    api(cmd_on)
    msleep(100)
    api(cmd_low)
    msleep(20)
    api(cmd_on)
    msleep(20)
    api(cmd_low)
    msleep(20)
    api(cmd_on)
    msleep(20)
    api(cmd_low)
    msleep(20)
    api(cmd_on)
    msleep(100)
    api(cmd_low)
    msleep(20)
    api(cmd_on)
    msleep(20)
    api(cmd_low)
    msleep(20)
    api(cmd_on)
    msleep(100)
    api(cmd_low)
    msleep(20)
    api(cmd_on)
    msleep(20)
    api(cmd_low)
    msleep(100)
    api(cmd_on)
    msleep(20)
    api(cmd_low)
    msleep(100)
    api(cmd_on)
    msleep(100)
    api(cmd_off)
    time.sleep(2)
    api(xy_red)
    api(cmd_on)
예제 #34
0
파일: test.py 프로젝트: fg-uulm/burg_tools
                        api(lights[i].light_control.set_dimmer(
                            min(data[START_ADDR + i - 1], 254)))
            LAST_DATA = data
    except:
        #LAST_SEND = 0
        #print("NAS")
        LAST_DATA = data


# Init Tradfri
conf = load_json(CONFIG_FILE)

try:
    identity = conf[TRADFRI_IP].get('identity')
    psk = conf[TRADFRI_IP].get('key')
    api_factory = APIFactory(host=TRADFRI_IP, psk_id=identity, psk=psk)
except KeyError:
    identity = uuid.uuid4().hex
    api_factory = APIFactory(host=TRADFRI_IP, psk_id=identity)

    try:
        psk = api_factory.generate_psk(args.key)
        print('Generated PSK: ', psk)

        conf[TRADFRI_IP] = {'identity': identity, 'key': psk}
        save_json(CONFIG_FILE, conf)
    except AttributeError:
        raise PytradfriError("Please provide the 'Security Code' on the "
                             "back of your Tradfri gateway using the "
                             "-K flag.")
예제 #35
0
파일: blink_lys.py 프로젝트: knivKim/ljus
        "Please provide the 'Security Code' on the back of your "
        "Tradfri gateway:",
        end=" ")
    key = input().strip()
    if len(key) != 16:
        raise PytradfriError("'Security Code' has to be exactly" +
                             "16 characters long.")
    else:
        args.key = key

conf = load_json(CONFIG_FILE)

try:
    identity = conf[args.host].get('identity')
    psk = conf[args.host].get('key')
    api_factory = APIFactory(host=args.host, psk_id=identity, psk=psk)
except KeyError:
    identity = uuid.uuid4().hex
    api_factory = APIFactory(host=args.host, psk_id=identity)

    try:
        psk = api_factory.generate_psk(args.key)
        print('Generated PSK: ', psk)

        conf[args.host] = {'identity': identity, 'key': psk}
        save_json(CONFIG_FILE, conf)
    except AttributeError:
        raise PytradfriError("Please provide the 'Security Code' on the "
                             "back of your Tradfri gateway using the "
                             "-K flag.")
예제 #36
0
    manager.connect() # This starts the connected client
    return manager

#------- Main section ----------------------------#
#------- Run once --------------------------------#
# create three connected managers
qmLightManager = QueueServerClient(HOST, PORT8, AUTHKEY)
qmLightResponseManager = QueueServerClient(HOST, PORT9, AUTHKEY)
# Get the queue objects from the clients
qLightCommand = qmLightManager.get_queue()
qLightResponse = qmLightResponseManager.get_queue()
	
try:
	identity = conf[ip_host].get('identity')
	psk = conf[ip_host].get('key')
	api_factory = APIFactory(host=ip_host, psk_id=identity, psk=psk)
except KeyError:
	identity = uuid.uuid4().hex
	api_factory = APIFactory(host=ip_host, psk_id=identity)

	try:
		psk = api_factory.generate_psk(key)
		print('Generated PSK: ', psk)

		conf[ip_host] = {'identity': identity,'key': psk}
		save_json(CONFIG_FILE, conf)
	except AttributeError:
		raise PytradfriError("Please provide the 'Security Code' on the back of your Tradfri gateway using the -K flag.")


def outputq(x):