How to use the pytradfri.gateway.Gateway function in pytradfri

To help you get started, we’ve selected a few pytradfri examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github ggravlingen / pytradfri / tests / test_smart_task.py View on Github external
def test_smart_task_info():
    gateway = Gateway()

    task = SmartTask(gateway, TASK).task_control.tasks[0]
    assert task.id == 65537
    assert task.dimmer == 254
github ggravlingen / pytradfri / tests / api / test_libcoap_api.py View on Github external
def test_constructor_timeout_passed_to_subprocess(monkeypatch):
    """Test that original timeout is passed to subprocess."""
    capture = {}

    def capture_args(*args, **kwargs):
        capture.update(kwargs)
        return json.dumps([])

    monkeypatch.setattr("subprocess.check_output", capture_args)

    api = APIFactory('anything', timeout=20)
    api.request(Gateway().get_devices())
    assert capture["timeout"] == 20
github ggravlingen / pytradfri / tests / api / test_libcoap_api.py View on Github external
def test_custom_timeout_passed_to_subprocess(monkeypatch):
    """Test that custom timeout is passed to subprocess."""
    capture = {}

    def capture_args(*args, **kwargs):
        capture.update(kwargs)
        return json.dumps([])

    monkeypatch.setattr("subprocess.check_output", capture_args)

    api = APIFactory('anything')
    api.request(Gateway().get_devices(), timeout=1)
    assert capture["timeout"] == 1
github moroen / IKEA-Tradfri-plugin / tradfri.py View on Github external
SaveConfig(args)

if args.key != None:
    config["Gateway"]["key"] = args.key
    SaveConfig(args)

if config["Gateway"]["ip"]=="UNDEF":
    print("Gateway not set. Use --gateway to specify")
    quit()

if config["Gateway"]["key"]=="UNDEF":
    print("Key not set. Use --key to specify")
    quit()

api = pytradfri.coap_cli.api_factory(config["Gateway"]["ip"], config["Gateway"]["key"])
gateway = pytradfri.gateway.Gateway(api)

device = gateway.get_device(int(args.id))

if args.command == "on":
    device.light_control.set_state(True)

if args.command == "off":
    device.light_control.set_state(False)

if args.command == "level":
    device.light_control.set_dimmer(int(args.value))

if args.command == "whitetemp":
    device.light_control.set_hex_color(whiteTemps[args.value])

if args.command == "list":
github ggravlingen / pytradfri / pytradfri / __main__.py View on Github external
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!")
        light = None
    groups = api(gateway.get_groups())
    if groups:
        group = groups[0]
    else:
        print("No groups found!")
        group = None
    moods = api(gateway.get_moods())
    if moods:
github ggravlingen / pytradfri / pytradfri / api / libcoap_api.py View on Github external
def generate_psk(self, security_key):
        """
        Generate and set a psk from the security key.
        """
        if not self._psk:
            # Backup the real identity.
            existing_psk_id = self._psk_id

            # Set the default identity and security key for generation.
            self._psk_id = 'Client_identity'
            self._psk = security_key

            # Ask the Gateway to generate the psk for the identity.
            self._psk = self.request(Gateway().generate_psk(existing_psk_id))

            # Restore the real identity.
            self._psk_id = existing_psk_id

        return self._psk
github ggravlingen / pytradfri / pytradfri / api / aiocoap_api.py View on Github external
async def generate_psk(self, security_key):
        """Generate and set a psk from the security key."""
        if not self._psk:
            PatchedDTLSSecurityStore.IDENTITY = 'Client_identity'.encode(
                'utf-8')
            PatchedDTLSSecurityStore.KEY = security_key.encode('utf-8')

            command = Gateway().generate_psk(self._psk_id)
            self._psk = await self.request(command)

            PatchedDTLSSecurityStore.IDENTITY = self._psk_id.encode('utf-8')
            PatchedDTLSSecurityStore.KEY = self._psk.encode('utf-8')

            # aiocoap has now cached our psk, so it must be reset.
            # We also no longer need the protocol, so this will clean that up.
            await self._reset_protocol()

        return self._psk
github ggravlingen / pytradfri / example.py View on Github external
To run the script, do the following:
$ pip3 install pytradfri
$ Download this file (example.py)
$ python3 test_pytradfri.py  

Where  is the address to your IKEA gateway and
 is found on the back of your IKEA gateway.
"""

import sys
import pytradfri

# Assign configuration variables.
# The configuration check takes care they are present.
api = pytradfri.coap_cli.api_factory(sys.argv[1], sys.argv[2])
gateway = pytradfri.gateway.Gateway(api)
devices = gateway.get_devices()
lights = [dev for dev in devices if dev.has_light_control]
tasks = gateway.get_smart_tasks()

# Print all lights
print(lights)

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

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

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

# Example 3: What is the name of light 2