def run_pytradfri(): api_factory = APIFactory('192.168.1.123', 'myUserName', 'password123456789') api = api_factory.request gateway = Gateway() devices_command = gateway.get_devices() devices_commands = yield from api(devices_command) devices = yield from api(devices_commands) groups_command = gateway.get_groups() groups_commands = yield from api(groups_command) groups = yield from api(groups_commands) for device in devices: observe_command = device.observe(observe_device_callback, observe_err_callback, duration=0) # Start observation as a second task on the loop. ensure_future(api(observe_command)) yield from asyncio.sleep(0) for group in groups: observe_command = group.observe(observe_group_callback, observe_err_callback, duration=0) # Start observation as a second task on the loop. ensure_future(api(observe_command)) yield from asyncio.sleep(0) # Sleep in an infinite loop to keep this running but also allow other tasks to execute while True: yield from asyncio.sleep(1)
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 _setup_gateway(hass, hass_config, host, key, allow_tradfri_groups): """Create a gateway.""" from pytradfri import cli_api_factory, Gateway, RequestError, retry_timeout try: api = retry_timeout(cli_api_factory(host, key)) except RequestError: return False gateway = Gateway(api) gateway_id = gateway.get_gateway_info().id hass.data.setdefault(KEY_GATEWAY, {}) gateways = hass.data[KEY_GATEWAY] hass.data.setdefault(KEY_TRADFRI_GROUPS, {}) tradfri_groups = hass.data[KEY_TRADFRI_GROUPS] tradfri_groups[gateway_id] = allow_tradfri_groups # Check if already set up if gateway_id in gateways: return True gateways[gateway_id] = gateway hass.async_add_job(discovery.async_load_platform( hass, 'light', DOMAIN, {'gateway': gateway_id}, hass_config)) return True
def _setup_gateway(hass, hass_config, host, key, allow_tradfri_groups): """Create a gateway.""" from pytradfri import Gateway, RequestError from pytradfri.api.libcoap_api import api_factory try: api = api_factory(host, key) except RequestError: return False gateway = Gateway() # pylint: disable=no-member gateway_id = api(gateway.get_gateway_info()).id hass.data.setdefault(KEY_API, {}) hass.data.setdefault(KEY_GATEWAY, {}) gateways = hass.data[KEY_GATEWAY] hass.data[KEY_API][gateway_id] = api hass.data.setdefault(KEY_TRADFRI_GROUPS, {}) tradfri_groups = hass.data[KEY_TRADFRI_GROUPS] tradfri_groups[gateway_id] = allow_tradfri_groups # Check if already set up if gateway_id in gateways: return True gateways[gateway_id] = gateway hass.async_add_job(discovery.async_load_platform( hass, 'light', DOMAIN, {'gateway': gateway_id}, hass_config)) return True
def get_lights(api): gateway = Gateway() devices_commands = yield from api(gateway.get_devices()) devices = yield from api(devices_commands) return [dev for dev in devices if dev.has_light_control]
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
async def get_gateway_info(hass, host, identity, key): """Return info for the gateway.""" from pytradfri.api.aiocoap_api import APIFactory from pytradfri import Gateway, RequestError try: factory = APIFactory( host, psk_id=identity, psk=key, loop=hass.loop ) api = factory.request gateway = Gateway() gateway_info_result = await api(gateway.get_gateway_info()) await factory.shutdown() except (OSError, RequestError): # We're also catching OSError as PyTradfri doesn't catch that one yet # Upstream PR: https://github.com/ggravlingen/pytradfri/pull/189 raise AuthError('cannot_connect') return { CONF_HOST: host, CONF_IDENTITY: identity, CONF_KEY: key, CONF_GATEWAY_ID: gateway_info_result.id, }
async def refresh(self): gateway = Gateway() logging.info("Refreshing group with id: {}".format(self._group.id)) self._group = await self._api(gateway.get_group(int(self._group.id))) for aMember in self._members: await aMember.refresh()
def configure_api(self): logger.info("Configuring api!") api_factory = APIFactory(host=self.config['host'], psk_id=self.config['identity'], psk=self.config['psk']) self.api = api_factory.request self.gateway = Gateway() self.lights = {}
async def _async_init(self, config_path): self.api_factory = await self.create_api_factory(config_path) self.api = self.api_factory.request self.gateway = Gateway() self.devices_command = self.gateway.get_devices() self.devices_commands = await self.api(self.devices_command) self.devices = await self.api(self.devices_commands) self.lights = [dev for dev in self.devices if dev.has_light_control]
async def tradfri_get_api_device(device_id): api_factory = APIFactory(host=GATEWAY_IP, psk_id=GATEWAY_ID, psk=GATEWAY_PSK) api = api_factory.request gateway = Gateway() device = await api(gateway.get_device(device_id)) return api, device
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 async_setup_entry(hass, entry): """Create a gateway.""" # host, identity, key, allow_tradfri_groups from pytradfri import Gateway, RequestError # pylint: disable=import-error from pytradfri.api.aiocoap_api import APIFactory factory = APIFactory( entry.data[CONF_HOST], psk_id=entry.data[CONF_IDENTITY], psk=entry.data[CONF_KEY], loop=hass.loop ) async def on_hass_stop(event): """Close connection when hass stops.""" await factory.shutdown() hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, on_hass_stop) api = factory.request gateway = Gateway() try: gateway_info = await api(gateway.get_gateway_info()) except RequestError: _LOGGER.error("Tradfri setup failed.") return False hass.data.setdefault(KEY_API, {})[entry.entry_id] = api hass.data.setdefault(KEY_GATEWAY, {})[entry.entry_id] = gateway dev_reg = await hass.helpers.device_registry.async_get_registry() dev_reg.async_get_or_create( config_entry_id=entry.entry_id, connections=set(), identifiers={ (DOMAIN, entry.data[CONF_GATEWAY_ID]) }, manufacturer='IKEA', name='Gateway', # They just have 1 gateway model. Type is not exposed yet. model='E1526', sw_version=gateway_info.firmware_version, ) hass.async_create_task(hass.config_entries.async_forward_entry_setup( entry, 'light' )) hass.async_create_task(hass.config_entries.async_forward_entry_setup( entry, 'sensor' )) hass.async_create_task(hass.config_entries.async_forward_entry_setup( entry, 'switch' )) return True
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)
def __init__(self, appctx): super().__init__() self.appctx = appctx self.api = None self.settings = Settings() self.gateway = Gateway() self.timers: Dict[str, QTimer] = {} self.init_ui()
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 run(): # Assign configuration variables. # The configuration check takes care they are present. api = api_factory(sys.argv[1], sys.argv[2]) 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] tasks_command = gateway.get_smart_tasks() tasks = api(tasks_command) # 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) # 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 async_setup_entry(hass, entry): """Create a gateway.""" # host, identity, key, allow_tradfri_groups from pytradfri import Gateway, RequestError # pylint: disable=import-error from pytradfri.api.aiocoap_api import APIFactory factory = APIFactory( entry.data[CONF_HOST], psk_id=entry.data[CONF_IDENTITY], psk=entry.data[CONF_KEY], loop=hass.loop, ) async def on_hass_stop(event): """Close connection when hass stops.""" await factory.shutdown() hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, on_hass_stop) api = factory.request gateway = Gateway() try: gateway_info = await api(gateway.get_gateway_info()) except RequestError: _LOGGER.error("Tradfri setup failed.") return False hass.data.setdefault(KEY_API, {})[entry.entry_id] = api hass.data.setdefault(KEY_GATEWAY, {})[entry.entry_id] = gateway dev_reg = await hass.helpers.device_registry.async_get_registry() dev_reg.async_get_or_create( config_entry_id=entry.entry_id, connections=set(), identifiers={(DOMAIN, entry.data[CONF_GATEWAY_ID])}, manufacturer="IKEA", name="Gateway", # They just have 1 gateway model. Type is not exposed yet. model="E1526", sw_version=gateway_info.firmware_version, ) hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, "light") ) hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, "sensor") ) hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, "switch") ) return True
async def async_setup_entry(hass, entry): """Create a gateway.""" # host, identity, key, allow_tradfri_groups tradfri_data = hass.data.setdefault(DOMAIN, {})[entry.entry_id] = {} listeners = tradfri_data[LISTENERS] = [] factory = await APIFactory.init( entry.data[CONF_HOST], psk_id=entry.data[CONF_IDENTITY], psk=entry.data[CONF_KEY], ) async def on_hass_stop(event): """Close connection when hass stops.""" await factory.shutdown() listeners.append( hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, on_hass_stop)) api = factory.request gateway = Gateway() try: gateway_info = await api(gateway.get_gateway_info()) devices_commands = await api(gateway.get_devices()) devices = await api(devices_commands) groups_commands = await api(gateway.get_groups()) groups = await api(groups_commands) except RequestError as err: await factory.shutdown() raise ConfigEntryNotReady from err tradfri_data[KEY_API] = api tradfri_data[FACTORY] = factory tradfri_data[DEVICES] = devices tradfri_data[GROUPS] = groups dev_reg = await hass.helpers.device_registry.async_get_registry() dev_reg.async_get_or_create( config_entry_id=entry.entry_id, connections=set(), identifiers={(DOMAIN, entry.data[CONF_GATEWAY_ID])}, manufacturer=ATTR_TRADFRI_MANUFACTURER, name=ATTR_TRADFRI_GATEWAY, # They just have 1 gateway model. Type is not exposed yet. model=ATTR_TRADFRI_GATEWAY_MODEL, sw_version=gateway_info.firmware_version, ) for component in PLATFORMS: hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, component)) return True
async def async_setup_entry(hass, entry): """Create a gateway.""" # host, identity, key, allow_tradfri_groups factory = APIFactory( entry.data[CONF_HOST], psk_id=entry.data[CONF_IDENTITY], psk=entry.data[CONF_KEY], loop=hass.loop, ) async def on_hass_stop(event): """Close connection when hass stops.""" await factory.shutdown() hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, on_hass_stop) api = factory.request gateway = Gateway() try: gateway_info = await api(gateway.get_gateway_info()) except RequestError: await factory.shutdown() raise ConfigEntryNotReady hass.data.setdefault(KEY_API, {})[entry.entry_id] = api hass.data.setdefault(KEY_GATEWAY, {})[entry.entry_id] = gateway dev_reg = await hass.helpers.device_registry.async_get_registry() dev_reg.async_get_or_create( config_entry_id=entry.entry_id, connections=set(), identifiers={(DOMAIN, entry.data[CONF_GATEWAY_ID])}, manufacturer=ATTR_TRADFRI_MANUFACTURER, name=ATTR_TRADFRI_GATEWAY, # They just have 1 gateway model. Type is not exposed yet. model=ATTR_TRADFRI_GATEWAY_MODEL, sw_version=gateway_info.firmware_version, ) for device in TRADFRI_DEVICE_TYPES: hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, device)) async def keepalive(): while True: await api(gateway.get_gateway_info()) await asyncio.sleep(45) asyncio.ensure_future(keepalive(), loop=asyncio.get_event_loop()) return True
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()
def get_lights(): api = get_api() gateway = Gateway() devices = [] while (True): try: devices = api(api(gateway.get_devices())) break except: print("Trying again") return [dev for dev in devices if dev.has_light_control]
def get_dining_room_lamp(api): 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 and dev.light_control.can_set_xy ] for light in lights: if light.name == lamp_name: return light
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 init(self): if self.hubip is None: conf = configparser.ConfigParser() conf.read('tradfri.cfg') #print(conf) self.hubip = conf.get('tradfri', 'hubip') self.securityid = conf.get('tradfri', 'securityid') self.api = api_factory(self.hubip, self.securityid) self.gateway = Gateway() groups_command = self.gateway.get_groups() groups_commands = self.api(groups_command) groups = self.api(*groups_commands) self.groups = dict((g.name, g) for g in groups) print(str(self.groups))
class Ikea: api = "" devices_command = "" devices_commands = "" gateway = "" devices = "" lights = "" 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 jsonify(self, input): return json.dumps( input, sort_keys=True, indent=4, ensure_ascii=False, ) def updateDevices(self): self.devices_command = self.gateway.get_devices() self.devices_commands = self.api(self.devices_command) self.devices = self.api(self.devices_commands) self.lights = [dev for dev in self.devices if dev.has_light_control] def getStatus(self, light): self.updateDevices() return self.lights[light].light_control.lights[0].state def turnOnLight(self, light, value): self.api(self.lights[light].light_control.set_dimmer(value))
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)
async def connect_to_gateway(hostConfig): api_factory = APIFactory(hostConfig["Gateway"], hostConfig["Identity"], hostConfig["Passkey"]) api = api_factory.request gateway = Gateway() return api, gateway, api_factory
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
def run(args): # Assign configuration variables. id=-1 level=-1 args.pop(0) ip=args.pop(0) if args: id = int(args.pop(0)) if args: level=int(args.pop(0)) conf=load_json(CONFFILE) if not conf: print("Could not load {}:".format(CONFFILE)) print("pre-shared-key (generated by gateway device) needed: see example_sync.py") return identity=conf[ip].get('identity') psk=conf[ip].get('key') api = APIFactory(host=ip,psk_id=identity,psk=psk).request gateway = Gateway() devices = api(api(gateway.get_devices())) lights = [Switchable(api,gateway,dev) for dev in devices if dev.has_light_control or dev.has_socket_control] if id<0: # Print all lights for l in lights: print(l.reprline()) return ids = [l.id for l in lights] if not id in ids: print("id not found ({} lights)".format(len(lights))) return i=ids.index(id); light=lights[i] prelevel=light.leveltext light.set_level(level) light.update() print("{} -> {}".format(prelevel,light.leveltext))
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]
async def _setup_gateway(hass, hass_config, host, identity, key, allow_tradfri_groups): """Create a gateway.""" from pytradfri import Gateway, RequestError # pylint: disable=import-error try: from pytradfri.api.aiocoap_api import APIFactory except ImportError: _LOGGER.exception("Looks like something isn't installed!") return False try: factory = APIFactory(host, psk_id=identity, psk=key, loop=hass.loop) api = factory.request gateway = Gateway() gateway_info_result = await api(gateway.get_gateway_info()) except RequestError: _LOGGER.exception("Tradfri setup failed.") return False gateway_id = gateway_info_result.id hass.data.setdefault(KEY_API, {}) hass.data.setdefault(KEY_GATEWAY, {}) gateways = hass.data[KEY_GATEWAY] hass.data[KEY_API][gateway_id] = api hass.data.setdefault(KEY_TRADFRI_GROUPS, {}) tradfri_groups = hass.data[KEY_TRADFRI_GROUPS] tradfri_groups[gateway_id] = allow_tradfri_groups # Check if already set up if gateway_id in gateways: return True gateways[gateway_id] = gateway hass.async_create_task(discovery.async_load_platform( hass, 'light', DOMAIN, {'gateway': gateway_id}, hass_config)) hass.async_create_task(discovery.async_load_platform( hass, 'sensor', DOMAIN, {'gateway': gateway_id}, hass_config)) return True
def _setup_gateway(hass, hass_config, host, key): """Create a gateway.""" from pytradfri import cli_api_factory, Gateway, RequestError, retry_timeout try: api = retry_timeout(cli_api_factory(host, key)) except RequestError: return False gateway = Gateway(api) gateway_id = gateway.get_gateway_info().id hass.data.setdefault(KEY_GATEWAY, {}) gateways = hass.data[KEY_GATEWAY] # Check if already set up if gateway_id in gateways: return True gateways[gateway_id] = gateway hass.async_add_job(discovery.async_load_platform( hass, 'light', DOMAIN, {'gateway': gateway_id}, hass_config)) return True
async def get_gateway_info(hass, host, identity, key): """Return info for the gateway.""" from pytradfri.api.aiocoap_api import APIFactory from pytradfri import Gateway, RequestError try: factory = APIFactory( host, psk_id=identity, psk=key, loop=hass.loop ) api = factory.request gateway = Gateway() gateway_info_result = await api(gateway.get_gateway_info()) except RequestError: raise AuthError('cannot_connect') return { CONF_HOST: host, CONF_IDENTITY: identity, CONF_KEY: key, CONF_GATEWAY_ID: gateway_info_result.id, }
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 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)
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()
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) 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]
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() api = api_factory.request gateway = Gateway() #devices_command = gateway.get_devices() #devices_commands = api(devices_command) #evices = api(devices_commands) #lights = [dev for dev in devices if dev.has_light_control] groups_command = gateway.get_groups() groups_commands = api(groups_command) groups = api(groups_commands) #----------------------------- # End Global Variable declaration #----------------------------- #-- function to extract integer from strings
def get_lights(api): gateway = TradfriGateway() devices_command = gateway.get_devices() devices_commands = api(devices_command) devices = api(devices_commands) return [dev for dev in devices if dev.has_light_control]
def get_light(api, device_id): gateway = TradfriGateway() device_command = gateway.get_device(device_id) device = api(device_command) return device