Ejemplo n.º 1
0
 def __init__(self):
     self.config_file = '/home/pi/code/python/pytradfri/tradfri_standalone_psk.conf'
     self.host = "192.168.2.167"
     self.api = self.authenticate_api()
     self.gateway = Gateway()
     self._devices = self.get_devices()
     self._lights = self.get_lights()
     self._groups = self.get_groups()
     self.clusters = None
Ejemplo n.º 2
0
def get_light(light_index):
    #returns light(s) selected by light_index 
    gateway = Gateway()
    devices_commands = run_command(gateway.get_devices())
    devices = run_command(devices_commands)
    lights = [dev for dev in devices if dev.has_light_control]
    #if many light  wanted 
    try:
        return [lights[l] for l in light_index]
    except:
        return lights[light_index]
Ejemplo n.º 3
0
def test_smart_task_set_start_action_dimmer():
    gateway = Gateway()

    cmd = (SmartTask(
        gateway, TASK).start_action.devices[0].item_controller.set_dimmer(30))

    assert cmd.method == "put"
    assert cmd.path == ["15010", 317094]
    assert cmd.data == {
        "9042": {
            "15013": [
                {
                    "5712": 18000,
                    "5851": 30,
                    "9003": 65537
                },
                {
                    "5712": 18000,
                    "5851": 254,
                    "9003": 65538
                },
            ],
            "5850":
            1,
        }
    }
def test_smart_task_info():
    """Test gateway info."""
    gateway = Gateway()

    task = SmartTask(gateway, TASK).task_control.tasks[0]
    assert task.id == 65537
    assert task.dimmer == 254
Ejemplo n.º 5
0
def test_smart_task_info(mock_api):
    mock_api.mock_request('get', [ROOT_SMART_TASKS, 271141], TASK)
    gateway = Gateway(mock_api)

    task = SmartTask(gateway, TASK).task_control.tasks[0]
    assert task.id == 65537
    assert task.dimmer == 254
Ejemplo n.º 6
0
def test_smart_task():
    gateway = Gateway()
    task = SmartTask(gateway, TASK)

    assert task.state == 1
    assert task.id == 317094
    assert task.task_type_id == 4
    assert task.repeat_days == 48
    assert task.task_start_time == datetime.time(8, 15)
Ejemplo n.º 7
0
def test_smart_task_set_start_action_dimmer(mock_api):
    mock_api.mock_request('get', [ROOT_SMART_TASKS, 271141], TASK)
    gateway = Gateway(mock_api)

    SmartTask(gateway, TASK).start_action.devices[0].\
        item_controller.set_dimmer(30)
    assert len(mock_api.calls) == 1
    req = mock_api.calls[0]
    assert req['method'] == 'put'
Ejemplo n.º 8
0
class Register():
    def __init__(self):
        self.config_file = '/home/pi/code/python/pytradfri/tradfri_standalone_psk.conf'
        self.host = "192.168.2.167"
        self.api = self.authenticate_api()
        self.gateway = Gateway()
        self._devices = self.get_devices()
        self._lights = self.get_lights()
        self._groups = self.get_groups()
        self.clusters = None

    @property
    def groups(self):
        pp(self._groups)

    @property
    def lights(self):
        pp(self._lights)

    @property
    def devices(self):
        pp(self._devices)

    def get_groups(self):
        commands_to_get_groups = self.run_command(self.gateway.get_groups())
        return self.run_command(commands_to_get_groups)

    def get_devices(self):
        commands_to_get_devices = self.run_command(self.gateway.get_devices())
        return self.run_command(commands_to_get_devices)

    def get_lights(self):
        return [dev for dev in self._devices if dev.has_light_control]

    def run_command(self, command):
        return self.api(command)

    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
Ejemplo n.º 9
0
def test_smart_task(mock_api):
    mock_api.mock_request('get', [ROOT_SMART_TASKS, 271141], TASK)
    gateway = Gateway(mock_api)
    task = SmartTask(gateway, TASK)

    assert task.state == 1
    assert task.id == 317094
    assert task.task_type_id == 4
    assert task.repeat_days == 48
    assert task.task_start_time == datetime.time(8, 15)
Ejemplo n.º 10
0
def main():
    logging.basicConfig(filename='plantnet.log', level=logging.INFO)

    # api setup
    host = '192.168.15.11'
    with open('gateway.key', 'r') as keyfile:
        gateway_key = keyfile.read().replace('\n', '')

    api = api_factory(host, gateway_key)
    gateway = Gateway()
    devices_commands = api(gateway.get_devices())
    devices = api(*devices_commands)
    lights = [dev for dev in devices if dev.has_light_control]

    # If number is supplied on
    light_setlevel = -1
    tc = -1
    if len(sys.argv) > 1:
        try:
            light_setlevel = int(sys.argv[1])
            tc = -1
        except ValueError:
            None

    if light_setlevel < 0:
        light_setlevel, tc = computelightlevel()

    # Set lights
    logstr = 'plantnet {}: tc = {:0.2f}, setting lights to {}'.format(
        time.strftime('%c'), tc, light_setlevel)
    logging.info(logstr)

    for light in lights:
        # Set on/off state
        target_state = light_setlevel > 0
        current_state = light.light_control.lights[0].state

        if not current_state == target_state:
            api(light.light_control.set_state(target_state))

        if target_state == True:
            api(light.light_control.set_dimmer(light_setlevel))
Ejemplo n.º 11
0
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
Ejemplo n.º 12
0
def test_smart_task():
    gateway = Gateway()
    task = SmartTask(gateway, TASK)
    task1 = SmartTask(gateway, TASK2)
    task2 = SmartTask(gateway, TASK3)

    assert task.state == 1
    assert task.id == 317094
    assert task.task_type_id == 4
    assert task.repeat_days == 48
    assert task.task_start_time == datetime.time(8, 15)
    assert task.task_type_name == "Wake Up"

    assert task1.task_type_id == 2
    assert task1.task_type_name == "Lights Off"

    assert task2.task_type_id == 1
    assert task2.task_type_name == "Not At Home"
Ejemplo n.º 13
0
class TradfriDevice(Interface):
    _devices: List[Device] = Api.execute(Gateway().get_devices(),
                                         execute_response=True)

    def __init__(self, name: str) -> None:
        super().__init__(name)
        self._device: Device
        self._first_update()

    def _first_update(self) -> None:
        for device in TradfriDevice._devices:
            if device.name == self.name:
                self._device = device

    def update(self) -> None:
        if self._device:
            device = Api.execute(self._device.update())
            if isinstance(device, Device):
                self._device = device
        else:
            self._first_update()
Ejemplo n.º 14
0
def test_smart_task_set_start_action_dimmer():
    gateway = Gateway()

    cmd = SmartTask(gateway, TASK).start_action.devices[0]. \
        item_controller.set_dimmer(30)

    assert cmd.method == 'put'
    assert cmd.path == ['15010', 317094]
    assert cmd.data == {
        '9042': {
            '15013': [{
                '5712': 18000,
                '5851': 30,
                '9003': 65537
            }, {
                '5712': 18000,
                '5851': 254,
                '9003': 65538
            }],
            '5850':
            1
        }
    }
Ejemplo n.º 15
0
    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!")
    light = None
groups = api(gateway.get_groups())
if groups:
    group = groups[0]
else:
    print("No groups found!")
    group = None
moods = api(gateway.get_moods())
Ejemplo n.º 16
0
def gateway():
    return Gateway()
Ejemplo n.º 17
0
def gateway_fixture() -> Gateway:
    """Return gateway."""
    return Gateway()
Ejemplo n.º 18
0
def test_get_device():
    gateway = Gateway()
    command = gateway.get_device(123)

    assert command.method == 'get'
    assert command.path == [ROOT_DEVICES, 123]
Ejemplo n.º 19
0
def gateway_fixture():
    """Fixture that returns a gateway."""
    return Gateway()