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 test_load_not_json(self): f = open(path.join(self.test_dir, "sample_psk_file3.txt"), "w") data = "{not valid json" f.write(data) f.close() with pytest.raises(PytradfriError): load_json(path.join(self.test_dir, "sample_psk_file3.txt"))
def test_load_not_json(self): f = open(path.join(self.test_dir, 'sample_psk_file3.txt'), 'w') data = '{not valid json' f.write(data) f.close() with pytest.raises(PytradfriError): load_json(path.join(self.test_dir, 'sample_psk_file3.txt'))
def test_load_not_json(self): """Test of load not json.""" data = "{not valid json" with open( path.join(self.test_dir, "sample_psk_file3.txt"), "w", encoding="utf-8" ) as fil: fil.write(data) with pytest.raises(PytradfriError): load_json(path.join(self.test_dir, "sample_psk_file3.txt"))
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 authenticate_api(self): #returns an authenticated API object conf = load_json(self.config_file) identity = conf[self.host].get('identity') psk = conf[self.host].get('key') api_factory = APIFactory(host=self.host, psk_id=identity, psk=psk) return api_factory.request
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 authenticate_api(host=BRIDGE_IP): #returns an authenticated API object conf = load_json(CONFIG_FILE) identity = conf[host].get('identity') psk = conf[host].get('key') api_factory = APIFactory(host=host, psk_id=identity, psk=psk,timeout=1) return api_factory.request
def __init__(self): self.gateway_address = rospy.get_param('~gateway_address') self.security_code = rospy.get_param('~security_code', None) self.lights_param = rospy.get_param('~lights', None) transition_time = rospy.get_param('~transition_time', 0.5) # in seconds self.transition_time = int(transition_time / 0.1) # in 0.1 of a second rospack = rospkg.RosPack() self.psk_config_file = rospy.get_param( '~psk_config_file', rospack.get_path('tradfri_ros') + '/config/tradfri_psk.conf') if not self.lights_param: rospy.logwarn( '\'lights\' parameter (device map) is not set, will attempt to load it from file' ) self.device_map_file = rospy.get_param( '~device_map_file', rospack.get_path('tradfri_ros') + '/config/device_map.yaml') if self.device_map_file: if not self.load_device_map(self.device_map_file): rospy.logwarn( 'Failed to load device map, will use default mappings') else: rospy.logwarn( 'Device map file was not specified, will use default mappings' ) self.conf = load_json(self.psk_config_file) self.connected = False self.color_cmd = None
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 test_json_load(self): """Test json load.""" config = {"identity": "hashstring", "key": "secretkey"} data = json.dumps(config, sort_keys=True, indent=4) with open( path.join(self.test_dir, "sample_psk_file2.txt"), "w", encoding="utf-8" ) as fil: fil.write(data) json_data = load_json(path.join(self.test_dir, "sample_psk_file2.txt")) self.assertEqual(json_data, {"identity": "hashstring", "key": "secretkey"})
def test_json_load(self): f = open(path.join(self.test_dir, "sample_psk_file2.txt"), "w") config = {"identity": "hashstring", "key": "secretkey"} data = json.dumps(config, sort_keys=True, indent=4) f.write(data) f.close() json_data = load_json(path.join(self.test_dir, "sample_psk_file2.txt")) self.assertEqual(json_data, { "identity": "hashstring", "key": "secretkey" })
def test_json_load(self): f = open(path.join(self.test_dir, 'sample_psk_file2.txt'), 'w') config = {'identity': 'hashstring', 'key': 'secretkey'} data = json.dumps(config, sort_keys=True, indent=4) f.write(data) f.close() json_data = load_json(path.join(self.test_dir, 'sample_psk_file2.txt')) self.assertEqual(json_data, { 'identity': 'hashstring', 'key': 'secretkey' })
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 initialize_tradlos(): global lights global api # Load in the file, get our password for the gateway and create an API conf = load_json(CONFIG_FILE) identity = conf[IP_ADDRESS].get('identity') psk = conf[IP_ADDRESS].get('key') api_factory = APIFactory(host=IP_ADDRESS, psk_id=identity, psk=psk) # This section connects to the gateway and gets information on devices api = api_factory.request gateway = Gateway() devices_command = gateway.get_devices() devices_commands = api(devices_command) devices = api(devices_commands) # Create an array of objects that are lights lights = [dev for dev in devices if dev.has_light_control]
async def init(): global gateway global api conf = load_json(CONFIG_FILE) identity = conf["192.168.50.30"].get("identity") psk = conf["192.168.50.30"].get("key") api_factory = await APIFactory.init(host="192.168.50.30", psk_id=identity, psk=psk) api = api_factory.request gateway = Gateway() devices_command = gateway.get_devices() devices_commands = await api(devices_command) devices = await api(devices_commands) print("Detected devices: %s" % (devices,))
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))
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 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
#logging.basicConfig(level=logging.DEBUG) parser = argparse.ArgumentParser() parser.add_argument('--host', required=False, default="192.168.0.108", type=str, help='IP Address of your Tradfri gateway') parser.add_argument('-K', '--key', dest='key', required=False, help='Security code found on your Tradfri gateway') args = parser.parse_args() if args.host not in load_json(CONFIG_FILE) and args.key is None: print( "Please provide the 'Security Code' on the back of your " "Tradfri gateway:", end=" ") key = input().strip() if len(key) != 16: raise PytradfriError("'Security Code' has to be exactly" + "16 characters long.") else: args.key = key conf = load_json(CONFIG_FILE) try: identity = conf[args.host].get('identity')
else: c=1 return c CONFIG_FILE = 'tradfri_standalone_psk.conf' parser = argparse.ArgumentParser() parser.add_argument('host', metavar='IP', type=str, help='IP Address of your Tradfri gateway') parser.add_argument('-K', '--key', dest='key', required=False, help='Key found on your Tradfri gateway') args = parser.parse_args() if args.host not in load_json(CONFIG_FILE) and args.key is None: print("Please provide the 'Security Code' on the back of your " "Tradfri gateway:", end=" ") key = input().strip() if len(key) != 16: raise PytradfriError("Invalid 'Security Code' provided.") else: args.key = key try: # pylint: disable=ungrouped-imports from asyncio import ensure_future except ImportError: # Python 3.4.3 and earlier has this as async # pylint: disable=unused-import
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)
sys.path.insert(0, os.path.normpath("%s/.." % folder)) # noqa from pytradfri import Gateway from pytradfri.api.libcoap_api import APIFactory from pytradfri.error import PytradfriError from pytradfri.util import load_json, save_json import uuid import argparse import threading import time import pychromecast CONFIG_FILE = 'tradfri_standalone_psk.conf' HALLOWEEN_CFG = 'halloween.conf' halloween = load_json(HALLOWEEN_CFG) parser = argparse.ArgumentParser() parser.add_argument('host', metavar='IP', type=str, help='IP Address of your Tradfri gateway') parser.add_argument('-K', '--key', dest='key', required=False, help='Security code found on your Tradfri gateway') args = parser.parse_args() if args.host not in load_json(CONFIG_FILE) and args.key is None: print(
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)
from pytradfri.api.libcoap_api import APIFactory from pytradfri.util import load_json, save_json from time import sleep import urllib.request import threading # Change this IP address to your gateway IP_ADDRESS = '192.168.0.158' # Make sure you're in the same directory as this file CONFIG_FILE = 'tradfri_standalone_psk.conf' WEBHOOK = 'https://maker.ifttt.com/trigger/{trigger_name}/with/key/{your_key}' # Load in the file, get our password for the gateway and create an API conf = load_json(CONFIG_FILE) identity = conf[IP_ADDRESS].get('identity') psk = conf[IP_ADDRESS].get('key') api_factory = APIFactory(host=IP_ADDRESS, psk_id=identity, psk=psk) # This section connects to the gateway and gets information on devices api = api_factory.request gateway = Gateway() devices_command = gateway.get_devices() devices_commands = api(devices_command) devices = api(devices_commands) # Create an array of objects that are lights lights = [dev for dev in devices if dev.has_light_control]
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()
import multiprocessing as mp from multiprocessing import Queue from multiprocessing.managers import SyncManager HOST = '' PORT8 = 5555 PORT9 = 5556 AUTHKEY = str("123456").encode("utf-8") ip_host = "192.168.1.75" CONFIG_FILE = 'tradfri_standalone_psk.conf' # Assign configuration variables. # The configuration check takes care they are present. conf = load_json(CONFIG_FILE) #if ip_host not in load_json(CONFIG_FILE): # key = input().strip() # if len(key) != 16: # raise PytradfriError("Invalid 'Security Code' provided.") # else: # print("Key OK") def get_index(id, list_): for i, s in enumerate(list_): if str(id) == str(s.path[1]): return i return -1 def QueueServerClient(HOST, PORT, AUTHKEY):