def main(capability=None): devs = None if capability: devs = hub.devices(capabilities=hub.capability[capability]) else: devs = hub.devices() for key, dev in devs.items(): print('{0}: {1}'.format(key, dev['name']))
def test_hub_devices_filter_single(tmp_hub): ids, devs = tmp_hub.devices() out = hub.devices(hub_id=tmp_hub.id, capabilities=hub.capability.COLOR_LOOP, mock_devices=devs) assert all(i in out for i in [ids['lamp_osram'], ids['strip_osram']]) assert len(out) == 2
def test_hub_devices_filter_and(tmp_hub): ids, devs = tmp_hub.devices() out = hub.devices( hub_id=tmp_hub.id, and_filter=True, capabilities=[hub.capability.COLOR_HS, hub.capability.COLOR_TEMP], mock_devices=devs) assert all(i in out for i in [ids['lamp_osram'], ids['strip_osram']]) assert len(out) == 2
def test_hub_devices_filter_or(tmp_hub): ids, devs = tmp_hub.devices() out = hub.devices( hub_id=tmp_hub.id, and_filter=False, capabilities=[hub.capability.TWILIGHT, hub.capability.COLOR_HS], mock_devices=devs) assert all( i in out for i in [ids['lamp_osram'], ids['strip_osram'], ids['twilight_nexa']]) assert len(out) == 3
def offline_device(): dev = None store = None for i, d in hub.devices(capabilities=hub.capability.COLOR_HS).items(): if not d['state']['reachable']: dev = i # store state so it can be restored after tests store = d['state'] break if dev is None: logging.fatal('Cannot run device tests, no offline COLOR_HS device to test against.') yield dev hub.device_state_replace(dev, store)
def main(): sensors = hub.devices(capabilities=[ hub.capability.TEMPERATURE, hub.capability.HUMIDITY, hub.capability.MOTION ]) tz = pytz.timezone(hub.tz()) try: storage.storeMultisensor(util.homogenize(sensors), tz=tz) except: print( 'Storage call failed, you may want to edit the db config at: %s' % config.config_file) raise else: print('write(%s) successful!' % len(sensors))
def online_device(): dev = None store = None devs = hub.devices(capabilities=hub.capability.BRIGHTNESS) for i, d in devs.items(): if d['state']['reachable'] and 'test' in d['name']: dev = d # store state so it can be restored after tests store = d['state'].copy() break if dev is None: logging.error( 'Cannot run certain device tests, no COLOR_HS device online where name includes \'test\'.' ) logging.info('online_device state before use ({1}): {0}'.format(store, _h6_dict(store))) yield dev logging.info('online_device state after use, before rollback ({1}): {0}'.format(dev['state'], _h6_dict(dev['state']))) hub.device_state_replace(dev['id'], store)
def main(): capabilities = [] devs = hub.devices() for id, dev in devs.items(): capabilities = capabilities + dev['capabilities']['values'] gathered = sorted(dedup(capabilities)) implemented = [e.name for e in hub.capability] not_implemented = [item for item in gathered if item not in implemented] composite = sorted(implemented + not_implemented) print('Capabilities in python-cozify version {0}'.format( cozify.__version__)) print('implemented ({0}): {1}'.format(len(implemented), implemented)) print('gathered ({0}): {1}'.format(len(gathered), gathered)) print('Not currently implemented ({0}): {1}'.format( len(not_implemented), not_implemented)) print('Fully updated capabilities string({0}): {1}'.format( len(composite), ' '.join(composite)))
def main(): global sensors # loop until interrupted, can be for example run as a systemd service while True: # cozify.hub.getDevices will return the raw devices API call blob as a dictionary # it will also trigger cozify.cloud.authentication() if we don't have a valid hub key yet. # if auth fails it will throw an APIError exception and kill this loop, so we need to check for that try: # Check connectivity and have it auto-renewed if it's deemed time to do so. cloud.ping() # Get all devices that have a temperature OR humidity capability. # Homogenize it to not have holes in the data. data = util.homogenize( hub.devices(capabilities=[ hub.capability.TEMPERATURE, hub.capability.HUMIDITY ])) except APIError as e: if e.status_code == 401: # auth failed logging.warning('Auth failed, this should not happen.') else: raise # we ignore all other APIErrors and let it burn to the ground else: # data retrieval succeeded # Data is extended into the list so that any previous cache is preserved and these are just added as new samples sensors.extend(data) # attempt storage if we have any to store if len(sensors) > 0: # InfluxDB writes can fail if for example IO conditions are bad # to mitigate this, we'll cache results and try again on the next loop with both old & new data try: print('writing to InfluxDB...') storage.storeMultisensor( sensors, verbose=False ) # disable verbose output to make the script more daemonizable. except InfluxDBServerError: print('Data kept in cache(%s), issues writing to InfluxDB' % (len(sensors))) else: # write succeeded, drop cache print('write(%s) successful!' % len(sensors)) sensors = [] cache.clear() time.sleep(60)
def metrics(): registry = dict() for device in hub.devices().values(): # pprint(device) name = device['name'] for key, value in device['state'].items(): key = 'cozify_' + camel_to_snake(key) if key in EXCLUDE_KEYS or value is None: continue try: value = float(value) except (TypeError, ValueError) as e: app.logger.exception("Failed to cast %s", key) continue # HACK: Both temperature and color temperature are reported under same key, bad capabilities = device.get("capabilities", {}).get("values", []) if (key == "cozify_temperature" and "COLOR_TEMP" in capabilities and "TEMPERATURE" not in capabilities): key = "cozify_color_temperature" registry.setdefault(key, {}) registry[key][name] = value output_lines = [] for key, values_by_name in registry.items(): metric_type = 'counter' if key in COUNTERS else 'gauge' output_lines.append(f'# TYPE {key} {metric_type}') for name, value in values_by_name.items(): output_lines.append(f'{key}{{name="{name}"}} {value}') output_lines.append('') response = Response('\n'.join(output_lines)) response.headers['Content-Type'] = 'text/plain; version=0.0.4' return response
def main(argv): del argv previous = None for step in numpy.flipud(numpy.linspace(0.0, 1.0, num=FLAGS.steps)): hub.light_brightness(FLAGS.device, step) time.sleep(FLAGS.delay) read = 'N/A' result = '?' if FLAGS.verify: devs = hub.devices() read = devs[FLAGS.device]['state']['brightness'] if step == read: result = '✔' color = green else: result = '✖' if read == previous: color = yellow else: color = red previous = step print('{3}[{2}] set: {0} vs. read: {1}{4}'.format( step, read, result, color, reset))
def main(device): devs = hub.devices() pprint.pprint(devs[device])
#!/usr/bin/env python3 from cozify import hub #ALERT BASS BATTERY_U BRIGHTNESS COLOR_HS COLOR_LOOP COLOR_TEMP CONTACT CONTROL_LIGHT CONTROL_POWER DEVICE DIMMER_CONTROL GENERATE_ALERT HUE_SWITCH HUMIDITY IDENTIFY IKEA_RC LOUDNESS LUX MOISTURE MOTION MUTE NEXT ON_OFF PAUSE PLAY PREVIOUS PUSH_NOTIFICATION REMOTE_CONTROL SEEK SMOKE STOP TEMPERATURE TRANSITION TREBLE TWILIGHT UPGRADE USER_PRESENCE VOLUME print('') print('1. Temperature/Humidity sensors') devices = hub.devices(capabilities=hub.capability.TEMPERATURE) for id, dev in devices.items(): print('{0}: {1}C'.format(dev['name'], dev['state']['temperature'])) #print('{0}'.format(dev)) print('') print('2. Motion detection sensors') devices = hub.devices(capabilities=hub.capability.MOTION) for id, dev in devices.items(): print('{0}: {1}'.format(dev['name'], dev['state']['motion'])) #print('{0}'.format(dev)) print('') print('3. Door/Window contact sensors') devices = hub.devices(capabilities=hub.capability.CONTACT) for id, dev in devices.items(): print('{0}: {1}'.format(dev['name'], dev['state']['open'])) #print('{0}'.format(dev))
def test_multisensor(live_hub): assert hub.ping() data = hub.devices() print(multisensor.getMultisensorData(data))
lastLines = [] if path.exists(fileName): size = os.path.getsize(fileName) print('File {0} exist and file size is {1} bytes.'.format(fileName, size)) lastLines = LastNlines(fileName, 10) f = open(fileName, 'a', newline='', encoding=fileFormat) else: print('File {0} does not exist.'.format(fileName)) f = open(fileName, 'w', newline='', encoding=fileFormat) header = '"Device","Timestamp","Temperature","Humidity"' f.writelines(header + '\n') print('') devices = hub.devices(capabilities=hub.capability.TEMPERATURE) for id, dev in devices.items(): row = '"{0}","{1}","{2}","{3}"'.format(dev['name'], EpochToTimeStamp(dev['state']['lastSeen']), NumberSeparatorFix(EmptyValueFix(dev['state']['temperature'])), EmptyValueFix(dev['state']['humidity'])) # check does measurement already exist on log file. matching = [s for s in lastLines if row in s] #print(row) if len(matching) > 0: print('{0}| Measurement not saved because it''s already exists.'.format(row)) else: print('{0}| Measurement saved.'.format(row)) f.writelines(row + '\n') f.close()
#!/usr/bin/env python3 from cozify import hub import json #ALERT BASS BATTERY_U BRIGHTNESS COLOR_HS COLOR_LOOP COLOR_TEMP CONTACT CONTROL_LIGHT CONTROL_POWER DEVICE DIMMER_CONTROL GENERATE_ALERT HUE_SWITCH HUMIDITY IDENTIFY IKEA_RC LOUDNESS LUX MOISTURE MOTION MUTE NEXT ON_OFF PAUSE PLAY PREVIOUS PUSH_NOTIFICATION REMOTE_CONTROL SEEK SMOKE STOP TEMPERATURE TRANSITION TREBLE TWILIGHT UPGRADE USER_PRESENCE VOLUME devices = hub.devices() result = "["; for id, dev in devices.items(): result += '{0},'.format(dev).replace('\'','"').replace(': None',': "None"').replace(': False',': "False"').replace(': True',': "True"').replace('\\x00','') if len(result) > 0: result = result[:-1] result += "]"; parsed = json.loads(result) print(json.dumps(parsed, indent=4, sort_keys=True))