def init(): 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] return lights,api
def __init__(self, ip, key): folder = os.path.dirname(os.path.abspath('.')) # noqa sys.path.insert(0, os.path.normpath("%s/.." % folder)) # noqa conf = load_json(CONFIG_FILE) try: identity = conf[ip].get("identity") psk = conf[ip].get("key") api_factory = APIFactory(host=ip, psk_id=identity, psk=psk) except KeyError: identity = uuid.uuid4().hex api_factory = APIFactory(host=ip, psk_id=identity) try: psk = api_factory.generate_psk(key) print("Generated PSK: ", psk) conf[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." ) self.api = api_factory.request self.gateway = Gateway() self.updateDevices()
def test_os_error(self): """Test os error is thrown.""" with patch("builtins.open", side_effect=OSError(-1)): with pytest.raises(PytradfriError): load_json("whatever") with pytest.raises(PytradfriError): save_json("whatever", {})
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 for bulb in lights: print(bulb.name) observe(api, bulb) #print("State: {}".format(bulb.light_control.lights[0].state)) if args.state == "ON": if bulb.light_control.lights[0].state: print("The light is already ON") logging.warning( 'Could not turn on light %s, light was already ON' % (bulb.name)) else: print("The light is OFF, turning it ON") api(bulb.light_control.set_state(True)) logging.info('Turning the light %s ON' % (bulb.name)) elif args.state == "OFF": if not (bulb.light_control.lights[0].state): print("The light is already OFF") logging.warning( 'Could not turn off light %s, light was already OFF' % (bulb.name)) else: print("The light is ON, turning it OFF") api(bulb.light_control.set_state(False)) logging.info('Turning the light %s OFF' % (bulb.name))
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 = yield from 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 = yield from api(devices_command) devices = yield from 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 xy_command = lights[3].light_control.set_xy_color(xy[0], xy[1]) yield from api(xy_command) # 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) yield from asyncio.sleep(120)
async 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 = await 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 = await api(devices_command) devices = await 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 def turnOnOff(bulb, state): lights[bulb].light_control.set_state(state) def setColor(bulb, color): lights[bulb].light_control.set_hex_color(color) turnOnOff(0, 1) await asyncio.sleep(30) await api_factory.shutdown()
async 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 = await 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.") # Create API devices -- from example api = api_factory.request gateway = Gateway() devices_command = gateway.get_devices() devices_commands = await api(devices_command) devices = await api(devices_commands) lights = [dev for dev in devices if dev.has_light_control] light = None # Find a bulb that can set color -- from example for dev in lights: if dev.light_control.can_set_color: light = dev break if not light: print("No color bulbs found") return # Get auth with open("tokens.json") as f: js = json.load(f) spotify_key = js['spotify']['auth'] bpm_key = js['bpm']['api_key'] # Check what procedure to run if args.cycle: await cycle(light, api) elif args.strobe: await strobe(light, api) elif args.brightness: await slider_brightness(light, api) print("Run ended.") return # shutdown() throws an error so just exit
def __init__(self, conf): logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) ch = logging.StreamHandler() ch.setLevel(logging.INFO) formatter = logging.Formatter("[%(asctime)s] %(levelname)s in %(module)s: %(message)s") ch.setFormatter(formatter) logger.addHandler(ch) self.Logger = logger hubconf = load_json(os.path.join(os.path.dirname(os.path.realpath(__file__)),"tradfri.conf")) with open(os.path.join(os.path.dirname(os.path.realpath(__file__)),conf)) as f: config = json.load(f) self.hub_gateway = config['hub_gateway'] self.hub_secret = config['hub_securitycode'] if not hubconf: self.Logger.info("Empty .conf file") randid = uuid4().hex api_factory = APIFactory(host=self.hub_gateway, psk_id=randid) psk = api_factory.generate_psk(self.hub_secret) self.Logger.info("Generated new psk: %s"%psk) save_json('tradfri.conf',{ self.hub_gateway:{ 'identity': randid, 'key': psk } }) self.api = api_factory.request else: identity = hubconf[self.hub_gateway].get('identity') psk = hubconf[self.hub_gateway].get('key') api_factory = APIFactory(host=self.hub_gateway, psk_id=identity, psk=psk) self.api = api_factory.request self.gateway = Gateway() self.refresh_devices()
async def run() -> None: """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 = await APIFactory.init(host=args.host, psk_id=identity, psk=psk) except KeyError: identity = uuid.uuid4().hex api_factory = await APIFactory.init(host=args.host, psk_id=identity) try: psk = await api_factory.generate_psk(args.key) print("Generated PSK: ", psk) conf[args.host] = {"identity": identity, "key": psk} save_json(CONFIG_FILE, conf) except AttributeError as err: raise PytradfriError("Please provide the 'Security Code' on the " "back of your Tradfri gateway using the " "-K flag.") from err api = api_factory.request gateway = Gateway() devices_command = gateway.get_devices() devices_commands = await api(devices_command) devices = await api(devices_commands) air_purifiers = [dev for dev in devices if dev.has_air_purifier_control] # Print all air purifiers print(air_purifiers) for air_purifier in air_purifiers: control = air_purifier.air_purifier_control assert control is not None print(control.air_purifiers[0].air_quality) # Set mode auto command = control.turn_on_auto_mode() await api(command) await api_factory.shutdown()
def test_json_save(self): """Test json save.""" filename = path.join(self.test_dir, "sample_psk_file.txt") conf = {"identity": "pytradfri", "key": "123abc"} written_file = save_json(filename, conf) self.assertTrue(written_file)
async def run(): global makestate # 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 = await 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 = await api(devices_command) devices = await api(devices_commands) sockets = [dev for dev in devices if dev.has_socket_control] for socket in sockets: # Print all sockets state = (socket.socket_control.sockets[0].state) print(socket.name, state, 'naar', makestate) state_command = socket.socket_control.set_state(makestate) await api(state_command) await asyncio.sleep(2) print('\n') await api_factory.shutdown()
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]
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()
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
async 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 = await APIFactory.init(host=args.host, psk_id=identity, psk=psk) except KeyError: identity = uuid.uuid4().hex api_factory = await APIFactory.init(host=args.host, psk_id=identity) try: psk = await 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 = await api(devices_command) devices = await 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 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) for light in lights: observe_command = light.observe( observe_callback, observe_err_callback, duration=120 ) # Start observation as a second task on the loop. asyncio.ensure_future(api(observe_command)) # Yield to allow observing to start. await asyncio.sleep(0) 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) await 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") await 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) await api(blind_command) tasks_command = gateway.get_smart_tasks() tasks_commands = await api(tasks_command) tasks = await 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) await api(dim_command_2) print("Waiting for observation to end (2 mins)") print("Try altering any light in the app, and watch the events!") await asyncio.sleep(120) await api_factory.shutdown()
async def init_api(self): try: identity = self.conf[self.gateway_address].get('identity') psk = self.conf[self.gateway_address].get('key') api_factory = APIFactory(host=self.gateway_address, psk_id=identity, psk=psk) except KeyError: identity = uuid.uuid4().hex api_factory = APIFactory(host=self.gateway_address, psk_id=identity) try: psk = await api_factory.generate_psk(self.security_code) # rospy.loginfo('Generated PSK: {}'.format(psk)) self.conf[self.gateway_address] = { 'identity': identity, 'key': psk } save_json(self.psk_config_file, self.conf) rospy.logwarn( f'Generated PSK was stored in {self.psk_config_file}') except AttributeError: rospy.logfatal("Please provide the 'Security Code' from the " "back of your Tradfri gateway using the " "~security_code param.") raise except RequestTimeout as e: rospy.logfatal(e) raise except Exception as e: rospy.logfatal('Unknown error occurred') raise self.api = api_factory.request # Connect to gateway and get configured devices (these are not necessarily available) while not self.connected and not rospy.is_shutdown(): try: rospy.loginfo(f'Connecting to gateway: {self.gateway_address}') gateway = Gateway() devices_command = gateway.get_devices() devices_commands = await self.api(devices_command) rospy.loginfo('Requesting configured devices') devices = await self.api(devices_commands) self.connected = True except RequestTimeout: rospy.logwarn('Request timed out. Keep trying...') # User canceled request, e.g. with Ctrl-C if not self.connected: return # Lights devices self.lights = { hex(dev.id): dev for dev in devices if dev.has_light_control } if not self.lights_param: # if no lights configured, set the param with default values self.lights_param = { k: { 'alias_id': idx + 1 } for idx, k in enumerate(sorted(self.lights.keys())) } rospy.set_param('~lights', self.lights_param) # Print all lights rospy.loginfo('Configured (paired) lights: {}'.format( [f'ID: {k}, Name: {v.name}' for k, v in self.lights.items()])) self.lights_set = { int(light_id, 16) for light_id in self.lights_param.keys() } self.discover_set = copy.deepcopy(self.lights_set) # Check if user-specified devices are actually available while len(self.discover_set) and not rospy.is_shutdown(): try: rospy.loginfo('Looking for lights: {}'.format( {hex(dev_id) for dev_id in self.discover_set})) devices = await self.api(devices_commands) found_set = {dev.id for dev in devices if dev.reachable} self.discover_set.difference_update(found_set) # Wait 1 sec and try again if len(self.discover_set): await asyncio.sleep(1.0) except RequestTimeout: rospy.logwarn('Request timed out. Keep trying...') # Create subscribers for configured lights self.subs_color = [] self.pubs_color = {} for dev_id, params in self.lights_param.items(): func = partial(self.color_cb, dev_id=dev_id) sub = rospy.Subscriber('light{}/color'.format(params['alias_id']), ColorRGBA, func) self.subs_color.append(sub) if len(self.lights_param): self.sub_all_color = rospy.Subscriber('all_lights/color', ColorRGBA, self.all_color_cb) rospy.loginfo('Ready')
def test_json_save(self): FILENAME = path.join(self.test_dir, 'sample_psk_file.txt') conf = {'identity': 'pytradfri', 'key': '123abc'} written_file = save_json(FILENAME, conf) self.assertTrue(written_file)
async def run(shutdown): # 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 = await 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() # end copy/pasted # # set and regularly renew the commissioning timeout, remove when done # async def keep_commissioning_alive(readiness): try: while True: await api(gateway.set_commissioning_timeout(60)) if readiness is not None: readiness() readiness = None await asyncio.sleep(45) finally: await api(gateway.set_commissioning_timeout(00)) commissioning_ready = asyncio.Future() commissioning = asyncio.Task( keep_commissioning_alive(lambda: commissioning_ready.set_result(None))) # # monitor the device list and give instructions # last_devices = None def devices_updated(result): nonlocal last_devices if last_devices is None: print("Originally, %s device(s) are known" % len(result)) else: for r in result: if r not in last_devices: asyncio.Task(new_device(r)) last_devices = result async def new_device(devno): nonlocal commissioning print("New device, fetching details...", end="", flush=True) device_command = gateway.get_device(devno) device = await api(device_command) print() print(" New device description: %s" % (device, )) if commissioning: if device.has_light_control: print("That was not in the expected sequence: This device was" " a light and not a controller. You can still pair" " another controller device.") else: print("Found a controller. You can now go ahead and add light" " bulbs by pairing them to the switch as you would do" " without a gateway. Press Ctrl-C when done.") commissioning.cancel() commissioning = None # if you wanted to implemente infinite-commissioning mode, you # should cancel or restart keep_commissioning_alive in a way # that resets the timeout, because the timeout will have gone # to 0 the moment the device was added. else: if not device.has_light_control: print("That was unexpected: A controller showed up even though" " the gateway was not in pairing mode any more.") else: print("You can still add more light bulbs; press Ctrl-C when" " done.") observe_devices = Command('get', [ROOT_DEVICES], observe=True, process_result=devices_updated) await api(observe_devices) await commissioning_ready print("Ready to start: Gateway is in commissioning mode.") print("Pressing the pairing button on a switch, dimmer or motion detector" " for 10s near the gateway until the gateway blinks fast. A few" " seconds later, it the new device shows up here. You may need to" " switch off light bulbs in the immediate vicinity (?).") # # run until the outer loop says not to any more # await api_factory.shutdown() await shutdown if commissioning is not None: print("Please allow for the commissioning mode to be disabled") commissioning.cancel()
async 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 = await APIFactory.init(host=args.host, psk_id=identity, psk=psk) except KeyError: identity = uuid.uuid4().hex api_factory = await APIFactory.init(host=args.host, psk_id=identity) try: psk = await 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 = await api(devices_command) devices = await 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) light = None # Find a bulb that can set color for dev in lights: if dev.light_control.can_set_color: light = dev break if not light: print("No color bulbs found") return xy_command = light.light_control.set_xy_color(xy[0], xy[1]) await api(xy_command) xy = light.light_control.lights[0].xy_color # Normalize Z Z = int(light.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) await asyncio.sleep(120) await api_factory.shutdown()
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 = '')
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: 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) # 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: print("Sleeping for 2 min to listen for more observation events") print( "Try altering the light (%s) in the app, and watch the events!" % light.name ) time.sleep(120)
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): print(str(datetime.datetime.now().time())[:8] + " "+ str(x)) sys.stdout.flush() api = api_factory.request gateway = Gateway() #get all devices devices_command = gateway.get_devices() devices_commands = api(devices_command)
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)
def test_os_error(self): with patch("builtins.open", side_effect=OSError(-1)): with pytest.raises(PytradfriError): load_json('whatever') with pytest.raises(PytradfriError): save_json('whatever', {})
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 = yield from 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 = yield from api(devices_command) devices = yield from api(devices_commands) lights = [dev for dev in devices if dev.has_light_control] #insert lights in the arrays for light in lights: lightArrayId.append(light.id) lightArraySts.append(light.light_control.lights[0].state) lightArrayValue.append(light.light_control.lights[0].dimmer) lightArrayColor.append(get_color_temp_idx(light.light_control.lights[0].hex_color)) savelights() # 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 def observe_callback(updated_device): light = updated_device.light_control.lights[0] output("Received message for: %s" % light) light = updated_device x = get_index(light.id, lightArrayId) lightArraySts[x] = light.light_control.lights[0].state lightArrayValue[x] = light.light_control.lights[0].dimmer lightArrayColor[x] = get_color_temp_idx(light.light_control.lights[0].hex_color) savelights() def observe_err_callback(err): output('observe error:', err) for light in lights: observe_command = light.observe(observe_callback, observe_err_callback, duration=120) # Start observation as a second task on the loop. ensure_future(api(observe_command)) # Yield to allow observing to start. yield from asyncio.sleep(0) print("Waiting for observation to end (2 mins)") print("Try altering any light in the app, and watch the events!") while True: print("restart") yield from asyncio.sleep(10)
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)
async 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 = await 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 = await api(devices_command) devices = await api(devices_commands) blinds = [dev for dev in devices if dev.has_blind_control] repeaters = [dev for dev in devices if dev.has_signal_repeater_control] # Print all sockets print("All blinds") print(blinds) print("All repeatersK") print(repeaters) # Sockets can be accessed by its index, so sockets[1] is the second blind if blinds: blind = blinds[0] else: print("No sockets found!") blind = None def observe_callback(updated_device): blind = updated_device.blind_control.blinds[0] print("Received message for: %s" % blind) def observe_err_callback(err): print('observe error:', err) for blind in blinds: observe_command = blind.observe(observe_callback, observe_err_callback, duration=120) # Start observation as a second task on the loop. asyncio.ensure_future(api(observe_command)) # Yield to allow observing to start. await asyncio.sleep(0) if blind: # Example 1: What is the name of the blind print("Name:", blind.name) # Example 2: checks current battery level of blind print("Battery (%):", blind.device_info.battery_level) # Current level of the blind print("Battery (%):", blinds[0].blind_control.blinds[0].current_cover_position) # Example 3: Set blind to 50% open state_command = blinds[0].blind_control.set_state(50) await api(state_command) print("Waiting for observation to end (30 secs)") await asyncio.sleep(30) await api_factory.shutdown()
def test_json_save(self): FILENAME = path.join(self.test_dir, "sample_psk_file.txt") conf = {"identity": "pytradfri", "key": "123abc"} written_file = save_json(FILENAME, conf) self.assertTrue(written_file)
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)
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 = yield from 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 = yield from api(devices_command) devices = yield from api(devices_commands) sockets = [dev for dev in devices if dev.has_socket_control] # Print all sockets print(sockets) # Sockets can be accessed by its index, so sockets[1] is the second socket if sockets: socket = sockets[0] else: print("No sockets found!") socket = None def observe_callback(updated_device): socket = updated_device.socket_control.sockets[0] print("Received message for: %s" % socket) def observe_err_callback(err): print('observe error:', err) for socket in sockets: observe_command = socket.observe(observe_callback, observe_err_callback, duration=120) # Start observation as a second task on the loop. ensure_future(api(observe_command)) # Yield to allow observing to start. yield from asyncio.sleep(0) if socket: # Example 1: checks state of the socket (true=on) print("Is on:", socket.socket_control.sockets[0].state) # Example 2: What is the name of the socket print("Name:", socket.name) # Example 3: Turn socket on state_command = socket.socket_control.set_state(True) yield from api(state_command) print("Waiting for observation to end (10 secs)") yield from asyncio.sleep(10)
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_commands = api(gateway.get_devices()) devices = api(devices_commands) lights = [dev for dev in devices if dev.has_light_control] if lights: light = lights[0] else: print("No lights found!")
def test_save_not_serializable(self): FILENAME = path.join(self.test_dir, 'should_not_save') conf = b'bytes are not serializable' with pytest.raises(PytradfriError): save_json(FILENAME, conf)