diff --git a/docs/account.html b/docs/account.html index b67b335..0467e7a 100644 --- a/docs/account.html +++ b/docs/account.html @@ -2,19 +2,22 @@ - - + + pyControl4.account API documentation - - - - - +controller info, and retrieves a bearer token for connecting to a Control4 …"> + + + + + - - + +
@@ -25,250 +28,6 @@

Module pyControl4.account

Authenticates with the Control4 API, retrieves account and registered controller info, and retrieves a bearer token for connecting to a Control4 Director.

-
- -Expand source code - -
"""Authenticates with the Control4 API, retrieves account and registered
-controller info, and retrieves a bearer token for connecting to a Control4 Director.
-"""
-import aiohttp
-import async_timeout
-import json
-import logging
-import datetime
-
-from .error_handling import checkResponseForError
-
-AUTHENTICATION_ENDPOINT = "https://apis.control4.com/authentication/v1/rest"
-CONTROLLER_AUTHORIZATION_ENDPOINT = (
-    "https://apis.control4.com/authentication/v1/rest/authorization"
-)
-GET_CONTROLLERS_ENDPOINT = "https://apis.control4.com/account/v3/rest/accounts"
-APPLICATION_KEY = "78f6791373d61bea49fdb9fb8897f1f3af193f11"
-
-_LOGGER = logging.getLogger(__name__)
-
-
-class C4Account:
-    def __init__(
-        self,
-        username,
-        password,
-        session: aiohttp.ClientSession = None,
-    ):
-        """Creates a Control4 account object.
-
-        Parameters:
-            `username` - Control4 account username/email.
-
-            `password` - Control4 account password.
-
-            `session` - (Optional) Allows the use of an `aiohttp.ClientSession` object for all network requests. This session will not be closed by the library.
-            If not provided, the library will open and close its own `ClientSession`s as needed.
-        """
-        self.username = username
-        self.password = password
-        self.session = session
-
-    async def __sendAccountAuthRequest(self):
-        """Used internally to retrieve an account bearer token. Returns the entire
-        JSON response from the Control4 auth API.
-        """
-        dataDictionary = {
-            "clientInfo": {
-                "device": {
-                    "deviceName": "pyControl4",
-                    "deviceUUID": "0000000000000000",
-                    "make": "pyControl4",
-                    "model": "pyControl4",
-                    "os": "Android",
-                    "osVersion": "10",
-                },
-                "userInfo": {
-                    "applicationKey": APPLICATION_KEY,
-                    "password": self.password,
-                    "userName": self.username,
-                },
-            }
-        }
-        if self.session is None:
-            async with aiohttp.ClientSession() as session:
-                with async_timeout.timeout(10):
-                    async with session.post(
-                        AUTHENTICATION_ENDPOINT, json=dataDictionary
-                    ) as resp:
-                        await checkResponseForError(await resp.text())
-                        return await resp.text()
-        else:
-            with async_timeout.timeout(10):
-                async with self.session.post(
-                    AUTHENTICATION_ENDPOINT, json=dataDictionary
-                ) as resp:
-                    await checkResponseForError(await resp.text())
-                    return await resp.text()
-
-    async def __sendAccountGetRequest(self, uri):
-        """Used internally to send GET requests to the Control4 API,
-        authenticated with the account bearer token. Returns the entire JSON
-        response from the Control4 auth API.
-
-        Parameters:
-            `uri` - Full URI to send GET request to.
-        """
-        try:
-            headers = {"Authorization": "Bearer {}".format(self.account_bearer_token)}
-        except AttributeError:
-            msg = "The account bearer token is missing - was your username/password correct? "
-            _LOGGER.error(msg)
-            raise
-        if self.session is None:
-            async with aiohttp.ClientSession() as session:
-                with async_timeout.timeout(10):
-                    async with session.get(uri, headers=headers) as resp:
-                        await checkResponseForError(await resp.text())
-                        return await resp.text()
-        else:
-            with async_timeout.timeout(10):
-                async with self.session.get(uri, headers=headers) as resp:
-                    await checkResponseForError(await resp.text())
-                    return await resp.text()
-
-    async def __sendControllerAuthRequest(self, controller_common_name):
-        """Used internally to retrieve an director bearer token. Returns the
-        entire JSON response from the Control4 auth API.
-
-        Parameters:
-            `controller_common_name`: Common name of the controller. See `getAccountControllers()` for details.
-        """
-        try:
-            headers = {"Authorization": "Bearer {}".format(self.account_bearer_token)}
-        except AttributeError:
-            msg = "The account bearer token is missing - was your username/password correct? "
-            _LOGGER.error(msg)
-            raise
-        dataDictionary = {
-            "serviceInfo": {
-                "commonName": controller_common_name,
-                "services": "director",
-            }
-        }
-        if self.session is None:
-            async with aiohttp.ClientSession() as session:
-                with async_timeout.timeout(10):
-                    async with session.post(
-                        CONTROLLER_AUTHORIZATION_ENDPOINT,
-                        headers=headers,
-                        json=dataDictionary,
-                    ) as resp:
-                        await checkResponseForError(await resp.text())
-                        return await resp.text()
-        else:
-            with async_timeout.timeout(10):
-                async with self.session.post(
-                    CONTROLLER_AUTHORIZATION_ENDPOINT,
-                    headers=headers,
-                    json=dataDictionary,
-                ) as resp:
-                    await checkResponseForError(await resp.text())
-                    return await resp.text()
-
-    async def getAccountBearerToken(self):
-        """Gets an account bearer token for making Control4 online API requests."""
-        data = await self.__sendAccountAuthRequest()
-        jsonDictionary = json.loads(data)
-        try:
-            self.account_bearer_token = jsonDictionary["authToken"]["token"]
-            return self.account_bearer_token
-        except KeyError:
-            msg = "Did not recieve an account bearer token. Is your username/password correct? "
-            _LOGGER.error(msg + data)
-            raise
-
-    async def getAccountControllers(self):
-        """Returns a dictionary of the information for all controllers registered to an account.
-
-        Returns:
-            ```
-            {
-                "controllerCommonName": "control4_MODEL_MACADDRESS",
-                "href": "https://apis.control4.com/account/v3/rest/accounts/000000",
-                "name": "Name"
-            }
-            ```
-        """
-        data = await self.__sendAccountGetRequest(GET_CONTROLLERS_ENDPOINT)
-        jsonDictionary = json.loads(data)
-        return jsonDictionary["account"]
-
-    async def getControllerInfo(self, controller_href):
-        """Returns a dictionary of the information of a specific controller.
-
-        Parameters:
-            `controller_href` - The API `href` of the controller (get this from the output of `getAccountControllers()`)
-
-        Returns:
-            ```
-            {
-                'allowsPatching': True,
-                'allowsSupport': False,
-                'blockNotifications': False,
-                'controllerCommonName': 'control4_MODEL_MACADDRESS',
-                'controller': {
-                    'href': 'https://apis.control4.com/account/v3/rest/accounts/000000/controller'
-                },
-                'created': '2017-08-26T18:33:31Z',
-                'dealer': {
-                    'href': 'https://apis.control4.com/account/v3/rest/dealers/12345'
-                },
-                'enabled': True,
-                'hasLoggedIn': True,
-                'href': 'https://apis.control4.com/account/v3/rest/accounts/000000',
-                'id': 000000,
-                'lastCheckIn': '2020-06-13T21:52:34Z',
-                'licenses': {
-                    'href': 'https://apis.control4.com/account/v3/rest/accounts/000000/licenses'
-                },
-                'modified': '2020-06-13T21:52:34Z',
-                'name': 'Name',
-                'provisionDate': '2017-08-26T18:35:11Z',
-                'storage': {
-                    'href': 'https://apis.control4.com/storage/v1/rest/accounts/000000'
-                },
-                'type': 'Consumer',
-                'users': {
-                    'href': 'https://apis.control4.com/account/v3/rest/accounts/000000/users'
-                }
-            }
-            ```
-        """
-        data = await self.__sendAccountGetRequest(controller_href)
-        jsonDictionary = json.loads(data)
-        return jsonDictionary
-
-    async def getControllerOSVersion(self, controller_href):
-        """Returns the OS version of a controller as a string.
-
-        Parameters:
-            `controller_href` - The API `href` of the controller (get this from the output of `getAccountControllers()`)
-        """
-        data = await self.__sendAccountGetRequest(controller_href + "/controller")
-        jsonDictionary = json.loads(data)
-        return jsonDictionary["osVersion"]
-
-    async def getDirectorBearerToken(self, controller_common_name):
-        """Returns a dictionary with a director bearer token for making Control4 Director API requests, and its time valid in seconds (usually 86400 seconds)
-
-        Parameters:
-            `controller_common_name`: Common name of the controller. See `getAccountControllers()` for details.
-        """
-        data = await self.__sendControllerAuthRequest(controller_common_name)
-        jsonDictionary = json.loads(data)
-        return {
-            "token": jsonDictionary["authToken"]["token"],
-            "validSeconds": jsonDictionary["authToken"]["validSeconds"],
-        }
-
@@ -520,22 +279,6 @@

Methods

Gets an account bearer token for making Control4 online API requests.

-
- -Expand source code - -
async def getAccountBearerToken(self):
-    """Gets an account bearer token for making Control4 online API requests."""
-    data = await self.__sendAccountAuthRequest()
-    jsonDictionary = json.loads(data)
-    try:
-        self.account_bearer_token = jsonDictionary["authToken"]["token"]
-        return self.account_bearer_token
-    except KeyError:
-        msg = "Did not recieve an account bearer token. Is your username/password correct? "
-        _LOGGER.error(msg + data)
-        raise
-
async def getAccountControllers(self) @@ -549,26 +292,6 @@

Returns

"name": "Name" }
-
- -Expand source code - -
async def getAccountControllers(self):
-    """Returns a dictionary of the information for all controllers registered to an account.
-
-    Returns:
-        ```
-        {
-            "controllerCommonName": "control4_MODEL_MACADDRESS",
-            "href": "https://apis.control4.com/account/v3/rest/accounts/000000",
-            "name": "Name"
-        }
-        ```
-    """
-    data = await self.__sendAccountGetRequest(GET_CONTROLLERS_ENDPOINT)
-    jsonDictionary = json.loads(data)
-    return jsonDictionary["account"]
-
async def getControllerInfo(self, controller_href) @@ -610,55 +333,6 @@

Returns

} }
-
- -Expand source code - -
async def getControllerInfo(self, controller_href):
-    """Returns a dictionary of the information of a specific controller.
-
-    Parameters:
-        `controller_href` - The API `href` of the controller (get this from the output of `getAccountControllers()`)
-
-    Returns:
-        ```
-        {
-            'allowsPatching': True,
-            'allowsSupport': False,
-            'blockNotifications': False,
-            'controllerCommonName': 'control4_MODEL_MACADDRESS',
-            'controller': {
-                'href': 'https://apis.control4.com/account/v3/rest/accounts/000000/controller'
-            },
-            'created': '2017-08-26T18:33:31Z',
-            'dealer': {
-                'href': 'https://apis.control4.com/account/v3/rest/dealers/12345'
-            },
-            'enabled': True,
-            'hasLoggedIn': True,
-            'href': 'https://apis.control4.com/account/v3/rest/accounts/000000',
-            'id': 000000,
-            'lastCheckIn': '2020-06-13T21:52:34Z',
-            'licenses': {
-                'href': 'https://apis.control4.com/account/v3/rest/accounts/000000/licenses'
-            },
-            'modified': '2020-06-13T21:52:34Z',
-            'name': 'Name',
-            'provisionDate': '2017-08-26T18:35:11Z',
-            'storage': {
-                'href': 'https://apis.control4.com/storage/v1/rest/accounts/000000'
-            },
-            'type': 'Consumer',
-            'users': {
-                'href': 'https://apis.control4.com/account/v3/rest/accounts/000000/users'
-            }
-        }
-        ```
-    """
-    data = await self.__sendAccountGetRequest(controller_href)
-    jsonDictionary = json.loads(data)
-    return jsonDictionary
-
async def getControllerOSVersion(self, controller_href) @@ -667,20 +341,6 @@

Returns

Returns the OS version of a controller as a string.

Parameters

controller_href - The API href of the controller (get this from the output of getAccountControllers())

-
- -Expand source code - -
async def getControllerOSVersion(self, controller_href):
-    """Returns the OS version of a controller as a string.
-
-    Parameters:
-        `controller_href` - The API `href` of the controller (get this from the output of `getAccountControllers()`)
-    """
-    data = await self.__sendAccountGetRequest(controller_href + "/controller")
-    jsonDictionary = json.loads(data)
-    return jsonDictionary["osVersion"]
-
async def getDirectorBearerToken(self, controller_common_name) @@ -689,23 +349,6 @@

Parameters

Returns a dictionary with a director bearer token for making Control4 Director API requests, and its time valid in seconds (usually 86400 seconds)

Parameters

controller_common_name: Common name of the controller. See getAccountControllers() for details.

-
- -Expand source code - -
async def getDirectorBearerToken(self, controller_common_name):
-    """Returns a dictionary with a director bearer token for making Control4 Director API requests, and its time valid in seconds (usually 86400 seconds)
-
-    Parameters:
-        `controller_common_name`: Common name of the controller. See `getAccountControllers()` for details.
-    """
-    data = await self.__sendControllerAuthRequest(controller_common_name)
-    jsonDictionary = json.loads(data)
-    return {
-        "token": jsonDictionary["authToken"]["token"],
-        "validSeconds": jsonDictionary["authToken"]["validSeconds"],
-    }
-
@@ -713,7 +356,6 @@

Parameters

Returns True if contact is triggered (door/window is closed, motion is detected), otherwise returns False.

-
- -Expand source code - -
async def getContactState(self):
-    """Returns `True` if contact is triggered (door/window is closed, motion is detected), otherwise returns `False`."""
-    contact_state = await self.director.getItemVariableValue(
-        self.item_id, "ContactState"
-    )
-    return bool(contact_state)
-
@@ -492,130 +278,42 @@

Methods

Returns True if alarm is triggered, otherwise returns False.

-
- -Expand source code - -
async def getAlarmState(self):
-    """Returns `True` if alarm is triggered, otherwise returns `False`."""
-    alarm_state = await self.director.getItemVariableValue(
-        self.item_id, "ALARM_STATE"
-    )
-    return bool(alarm_state)
-
async def getAlarmType(self)

Returns details about the current alarm type.

-
- -Expand source code - -
async def getAlarmType(self):
-    """Returns details about the current alarm type."""
-    alarm_type = await self.director.getItemVariableValue(
-        self.item_id, "ALARM_TYPE"
-    )
-    return alarm_type
-
async def getArmState(self)

Returns the arm state of the security panel as "DISARMED", "ARMED_HOME", or "ARMED_AWAY".

-
- -Expand source code - -
async def getArmState(self):
-    """Returns the arm state of the security panel as "DISARMED", "ARMED_HOME", or "ARMED_AWAY"."""
-    disarmed = await self.director.getItemVariableValue(
-        self.item_id, "DISARMED_STATE"
-    )
-    armed_home = await self.director.getItemVariableValue(
-        self.item_id, "HOME_STATE"
-    )
-    armed_away = await self.director.getItemVariableValue(
-        self.item_id, "AWAY_STATE"
-    )
-    if disarmed == 1:
-        return "DISARMED"
-    elif armed_home == 1:
-        return "ARMED_HOME"
-    elif armed_away == 1:
-        return "ARMED_AWAY"
-
async def getArmedType(self)

Returns details about the current arm type.

-
- -Expand source code - -
async def getArmedType(self):
-    """Returns details about the current arm type."""
-    armed_type = await self.director.getItemVariableValue(
-        self.item_id, "ARMED_TYPE"
-    )
-    return armed_type
-
async def getDelayTimeRemaining(self)

Returns the remaining exit delay time. Returns 0 if an exit delay is not currently running.

-
- -Expand source code - -
async def getDelayTimeRemaining(self):
-    """Returns the remaining exit delay time. Returns 0 if an exit delay is not currently running."""
-    delay_time_remaining = await self.director.getItemVariableValue(
-        self.item_id, "DELAY_TIME_REMAINING"
-    )
-    return delay_time_remaining
-
async def getDelayTimeTotal(self)

Returns the total exit delay time. Returns 0 if an exit delay is not currently running.

-
- -Expand source code - -
async def getDelayTimeTotal(self):
-    """Returns the total exit delay time. Returns 0 if an exit delay is not currently running."""
-    delay_time_total = await self.director.getItemVariableValue(
-        self.item_id, "DELAY_TIME_TOTAL"
-    )
-    return delay_time_total
-
async def getDisplayText(self)

Returns the display text of the security panel.

-
- -Expand source code - -
async def getDisplayText(self):
-    """Returns the display text of the security panel."""
-    display_text = await self.director.getItemVariableValue(
-        self.item_id, "DISPLAY_TEXT"
-    )
-    return display_text
-
async def getEmergencyTypes(self) @@ -623,82 +321,24 @@

Methods

Returns the available emergency types as a list.

Possible types are "Fire", "Medical", "Panic", and "Police".

-
- -Expand source code - -
async def getEmergencyTypes(self):
-    """Returns the available emergency types as a list.
-
-    Possible types are "Fire", "Medical", "Panic", and "Police".
-    """
-    types_list = []
-
-    data = await self.director.getItemInfo(self.item_id)
-    jsonDictionary = json.loads(data)
-
-    if jsonDictionary[0]["capabilities"]["has_fire"]:
-        types_list.append("Fire")
-    if jsonDictionary[0]["capabilities"]["has_medical"]:
-        types_list.append("Medical")
-    if jsonDictionary[0]["capabilities"]["has_panic"]:
-        types_list.append("Panic")
-    if jsonDictionary[0]["capabilities"]["has_police"]:
-        types_list.append("Police")
-
-    return types_list
-
async def getLastArmFailure(self)

Returns details about the last arm failure.

-
- -Expand source code - -
async def getLastArmFailure(self):
-    """Returns details about the last arm failure."""
-    last_arm_failed = await self.director.getItemVariableValue(
-        self.item_id, "LAST_ARM_FAILED"
-    )
-    return last_arm_failed
-
async def getLastEmergency(self)

Returns details about the last emergency trigger.

-
- -Expand source code - -
async def getLastEmergency(self):
-    """Returns details about the last emergency trigger."""
-    last_emergency = await self.director.getItemVariableValue(
-        self.item_id, "LAST_EMERGENCY"
-    )
-    return last_emergency
-
async def getOpenZoneCount(self)

Returns the number of open/unsecured zones.

-
- -Expand source code - -
async def getOpenZoneCount(self):
-    """Returns the number of open/unsecured zones."""
-    open_zone_count = await self.director.getItemVariableValue(
-        self.item_id, "OPEN_ZONE_COUNT"
-    )
-    return open_zone_count
-
async def getPartitionState(self) @@ -706,37 +346,12 @@

Methods

Returns the partition state of the security panel.

Possible values include "DISARMED_NOT_READY", "DISARMED_READY", "ARMED_HOME", "ARMED_AWAY", "EXIT_DELAY", "ENTRY_DELAY"

-
- -Expand source code - -
async def getPartitionState(self):
-    """Returns the partition state of the security panel.
-
-    Possible values include "DISARMED_NOT_READY", "DISARMED_READY", "ARMED_HOME", "ARMED_AWAY", "EXIT_DELAY", "ENTRY_DELAY"
-    """
-    partition_state = await self.director.getItemVariableValue(
-        self.item_id, "PARTITION_STATE"
-    )
-    return partition_state
-
async def getTroubleText(self)

Returns the trouble display text of the security panel.

-
- -Expand source code - -
async def getTroubleText(self):
-    """Returns the trouble display text of the security panel."""
-    trouble_text = await self.director.getItemVariableValue(
-        self.item_id, "TROUBLE_TEXT"
-    )
-    return trouble_text
-
async def sendKeyPress(self, key) @@ -745,23 +360,6 @@

Methods

Sends a single keypress to the security panel's virtual keypad (if supported).

Parameters

key - Keypress to send. Only one key at a time.

-
- -Expand source code - -
async def sendKeyPress(self, key):
-    """Sends a single keypress to the security panel's virtual keypad (if supported).
-
-    Parameters:
-        `key` - Keypress to send. Only one key at a time.
-    """
-    key = str(key)
-    await self.director.sendPostRequest(
-        "/api/v1/items/{}/commands".format(self.item_id),
-        "KEY_PRESS",
-        {"KeyName": key},
-    )
-
async def setArm(self, usercode, mode: str) @@ -771,25 +369,6 @@

Parameters

Parameters

usercode - PIN/code for arming the system.

mode - Arm mode to use. This depends on what is supported by the security panel itself.

-
- -Expand source code - -
async def setArm(self, usercode, mode: str):
-    """Arms the security panel with the specified mode.
-
-    Parameters:
-        `usercode` - PIN/code for arming the system.
-
-        `mode` - Arm mode to use. This depends on what is supported by the security panel itself.
-    """
-    usercode = str(usercode)
-    await self.director.sendPostRequest(
-        "/api/v1/items/{}/commands".format(self.item_id),
-        "PARTITION_ARM",
-        {"ArmType": mode, "UserCode": usercode},
-    )
-
async def setDisarm(self, usercode) @@ -798,23 +377,6 @@

Parameters

Disarms the security panel.

Parameters

usercode - PIN/code for disarming the system.

-
- -Expand source code - -
async def setDisarm(self, usercode):
-    """Disarms the security panel.
-
-    Parameters:
-        `usercode` - PIN/code for disarming the system.
-    """
-    usercode = str(usercode)
-    await self.director.sendPostRequest(
-        "/api/v1/items/{}/commands".format(self.item_id),
-        "PARTITION_DISARM",
-        {"UserCode": usercode},
-    )
-
async def triggerEmergency(self, usercode, type) @@ -824,25 +386,6 @@

Parameters

Parameters

usercode - PIN/code for disarming the system.

type - Type of emergency: "Fire", "Medical", "Panic", or "Police"

-
- -Expand source code - -
async def triggerEmergency(self, usercode, type):
-    """Triggers an emergency of the specified type.
-
-    Parameters:
-        `usercode` - PIN/code for disarming the system.
-
-        `type` - Type of emergency: "Fire", "Medical", "Panic", or "Police"
-    """
-    usercode = str(usercode)
-    await self.director.sendPostRequest(
-        "/api/v1/items/{}/commands".format(self.item_id),
-        "PARTITION_DISARM",
-        {"UserCode": usercode},
-    )
-
@@ -850,7 +393,6 @@

Parameters

Closes the blind completely.

-
- -Expand source code - -
async def close(self):
-    """Closes the blind completely."""
-    await self.director.sendPostRequest(
-        "/api/v1/items/{}/commands".format(self.item_id),
-        "SET_LEVEL_TARGET:LEVEL_TARGET_CLOSED",
-        {},
-    )
-
async def getBatteryLevel(self)

Returns the battery of a blind. We currently don't know the range or meaning.

-
- -Expand source code - -
async def getBatteryLevel(self):
-    """Returns the battery of a blind. We currently don't know the range or meaning."""
-    value = await self.director.getItemVariableValue(self.item_id, "Battery Level")
-    return int(value)
-
async def getClosing(self) @@ -312,17 +178,6 @@

Methods

Returns an indication of whether the blind is moving in the closed direction as a boolean (True=closing, False=opening). If the blind is stopped, reports the direction it last moved.

-
- -Expand source code - -
async def getClosing(self):
-    """Returns an indication of whether the blind is moving in the closed direction as a boolean
-    (True=closing, False=opening). If the blind is stopped, reports the direction it last moved.
-    """
-    value = await self.director.getItemVariableValue(self.item_id, "Closing")
-    return bool(value)
-
async def getFullyClosed(self) @@ -330,16 +185,6 @@

Methods

Returns an indication of whether the blind is fully closed as a boolean (True=fully closed, False=at least partially open).

-
- -Expand source code - -
async def getFullyClosed(self):
-    """Returns an indication of whether the blind is fully closed as a boolean
-    (True=fully closed, False=at least partially open)."""
-    value = await self.director.getItemVariableValue(self.item_id, "Fully Closed")
-    return bool(value)
-
async def getFullyOpen(self) @@ -347,16 +192,6 @@

Methods

Returns an indication of whether the blind is fully open as a boolean (True=fully open, False=at least partially closed).

-
- -Expand source code - -
async def getFullyOpen(self):
-    """Returns an indication of whether the blind is fully open as a boolean
-    (True=fully open, False=at least partially closed)."""
-    value = await self.director.getItemVariableValue(self.item_id, "Fully Open")
-    return bool(value)
-
async def getLevel(self) @@ -364,17 +199,6 @@

Methods

Returns the level (current position) of a blind as an int 0-100. 0 is fully closed and 100 is fully open.

-
- -Expand source code - -
async def getLevel(self):
-    """Returns the level (current position) of a blind as an int 0-100.
-    0 is fully closed and 100 is fully open.
-    """
-    value = await self.director.getItemVariableValue(self.item_id, "Level")
-    return int(value)
-
async def getOpen(self) @@ -382,16 +206,6 @@

Methods

Returns an indication of whether the blind is open as a boolean (True=open, False=closed). This is true even if the blind is only partially open.

-
- -Expand source code - -
async def getOpen(self):
-    """Returns an indication of whether the blind is open as a boolean (True=open, False=closed).
-    This is true even if the blind is only partially open."""
-    value = await self.director.getItemVariableValue(self.item_id, "Open")
-    return bool(value)
-
async def getOpening(self) @@ -399,17 +213,6 @@

Methods

Returns an indication of whether the blind is moving in the open direction as a boolean (True=opening, False=closing). If the blind is stopped, reports the direction it last moved.

-
- -Expand source code - -
async def getOpening(self):
-    """Returns an indication of whether the blind is moving in the open direction as a boolean
-    (True=opening, False=closing). If the blind is stopped, reports the direction it last moved.
-    """
-    value = await self.director.getItemVariableValue(self.item_id, "Opening")
-    return bool(value)
-
async def getStopped(self) @@ -417,16 +220,6 @@

Methods

Returns an indication of whether the blind is stopped as a boolean (True=stopped, False=moving).

-
- -Expand source code - -
async def getStopped(self):
-    """Returns an indication of whether the blind is stopped as a boolean
-    (True=stopped, False=moving)."""
-    value = await self.director.getItemVariableValue(self.item_id, "Stopped")
-    return bool(value)
-
async def getTargetLevel(self) @@ -435,36 +228,12 @@

Methods

Returns the target level (desired position) of a blind as an int 0-100. The blind will move if this is different from the current level. 0 is fully closed and 100 is fully open.

-
- -Expand source code - -
async def getTargetLevel(self):
-    """Returns the target level (desired position) of a blind as an int 0-100.
-     The blind will move if this is different from the current level.
-    0 is fully closed and 100 is fully open.
-    """
-    value = await self.director.getItemVariableValue(self.item_id, "Target Level")
-    return int(value)
-
async def open(self)

Opens the blind completely.

-
- -Expand source code - -
async def open(self):
-    """Opens the blind completely."""
-    await self.director.sendPostRequest(
-        "/api/v1/items/{}/commands".format(self.item_id),
-        "SET_LEVEL_TARGET:LEVEL_TARGET_OPEN",
-        {},
-    )
-
async def setLevelTarget(self, level) @@ -474,23 +243,6 @@

Methods

Level 0 is fully closed and level 100 is fully open.

Parameters

level - (int) 0-100

-
- -Expand source code - -
async def setLevelTarget(self, level):
-    """Sets the desired level of a blind; it will start moving towards that level.
-    Level 0 is fully closed and level 100 is fully open.
-
-    Parameters:
-        `level` - (int) 0-100
-    """
-    await self.director.sendPostRequest(
-        "/api/v1/items/{}/commands".format(self.item_id),
-        "SET_LEVEL_TARGET",
-        {"LEVEL_TARGET": level},
-    )
-
async def stop(self) @@ -498,37 +250,12 @@

Parameters

Stops the blind if it is moving. Shortly after stopping, the target level will be set to the level the blind had actually reached when it stopped.

-
- -Expand source code - -
async def stop(self):
-    """Stops the blind if it is moving. Shortly after stopping, the target level will be
-    set to the level the blind had actually reached when it stopped."""
-    await self.director.sendPostRequest(
-        "/api/v1/items/{}/commands".format(self.item_id),
-        "STOP",
-        {},
-    )
-
async def toggle(self)

Toggles the blind between open and closed. Has no effect if the blind is partially open.

-
- -Expand source code - -
async def toggle(self):
-    """Toggles the blind between open and closed. Has no effect if the blind is partially open."""
-    await self.director.sendPostRequest(
-        "/api/v1/items/{}/commands".format(self.item_id),
-        "TOGGLE",
-        {},
-    )
-
@@ -536,7 +263,6 @@

Parameters

- \ No newline at end of file + diff --git a/docs/director.html b/docs/director.html index b03b60d..5880dfc 100644 --- a/docs/director.html +++ b/docs/director.html @@ -2,19 +2,22 @@ - - + + pyControl4.director API documentation - - - - - +getting details about items on the Director."> + + + + + - - + +
@@ -25,313 +28,6 @@

Module pyControl4.director

Handles communication with a Control4 Director, and provides functions for getting details about items on the Director.

-
- -Expand source code - -
"""Handles communication with a Control4 Director, and provides functions for
-   getting details about items on the Director.
-"""
-import aiohttp
-import async_timeout
-import json
-
-from .error_handling import checkResponseForError
-
-
-class C4Director:
-    def __init__(
-        self,
-        ip,
-        director_bearer_token,
-        session_no_verify_ssl: aiohttp.ClientSession = None,
-    ):
-        """Creates a Control4 Director object.
-
-        Parameters:
-            `ip` - The IP address of the Control4 Director/Controller.
-
-            `director_bearer_token` - The bearer token used to authenticate
-                                      with the Director.
-                See `pyControl4.account.C4Account.getDirectorBearerToken`
-                for how to get this.
-
-            `session` - (Optional) Allows the use of an
-                        `aiohttp.ClientSession` object
-                        for all network requests. This
-                        session will not be closed by the library.
-                        If not provided, the library will open and
-                        close its own `ClientSession`s as needed.
-        """
-        self.base_url = "https://{}".format(ip)
-        self.headers = {"Authorization": "Bearer {}".format(director_bearer_token)}
-        self.director_bearer_token = director_bearer_token
-        self.session = session_no_verify_ssl
-
-    async def sendGetRequest(self, uri):
-        """Sends a GET request to the specified API URI.
-        Returns the Director's JSON response as a string.
-
-        Parameters:
-            `uri` - The API URI to send the request to. Do not include the IP
-                    address of the Director.
-        """
-        if self.session is None:
-            async with aiohttp.ClientSession(
-                connector=aiohttp.TCPConnector(verify_ssl=False)
-            ) as session:
-                with async_timeout.timeout(10):
-                    async with session.get(
-                        self.base_url + uri, headers=self.headers
-                    ) as resp:
-                        await checkResponseForError(await resp.text())
-                        return await resp.text()
-        else:
-            with async_timeout.timeout(10):
-                async with self.session.get(
-                    self.base_url + uri, headers=self.headers
-                ) as resp:
-                    await checkResponseForError(await resp.text())
-                    return await resp.text()
-
-    async def sendPostRequest(self, uri, command, params, async_variable=True):
-        """Sends a POST request to the specified API URI. Used to send commands
-           to the Director.
-        Returns the Director's JSON response as a string.
-
-        Parameters:
-            `uri` - The API URI to send the request to. Do not include the IP
-                    address of the Director.
-
-            `command` - The Control4 command to send.
-
-            `params` - The parameters of the command, provided as a dictionary.
-        """
-        dataDictionary = {
-            "async": async_variable,
-            "command": command,
-            "tParams": params,
-        }
-        if self.session is None:
-            async with aiohttp.ClientSession(
-                connector=aiohttp.TCPConnector(verify_ssl=False)
-            ) as session:
-                with async_timeout.timeout(10):
-                    async with session.post(
-                        self.base_url + uri, headers=self.headers, json=dataDictionary
-                    ) as resp:
-                        await checkResponseForError(await resp.text())
-                        return await resp.text()
-        else:
-            with async_timeout.timeout(10):
-                async with self.session.post(
-                    self.base_url + uri, headers=self.headers, json=dataDictionary
-                ) as resp:
-                    await checkResponseForError(await resp.text())
-                    return await resp.text()
-
-    async def getAllItemsByCategory(self, category):
-        """Returns a JSON list of items related to a particular category.
-
-        Parameters:
-            `category` - Control4 Category Name: controllers, comfort, lights,
-                         cameras, sensors, audio_video,
-                         motorization, thermostats, motors,
-                         control4_remote_hub,
-                         outlet_wireless_dimmer, voice-scene
-        """
-        return_list = await self.sendGetRequest(
-            "/api/v1/categories/{}".format(category)
-        )
-        return return_list
-
-    async def getAllItemInfo(self):
-        """Returns a JSON list of all the items on the Director."""
-        return await self.sendGetRequest("/api/v1/items")
-
-    async def getItemInfo(self, item_id):
-        """Returns a JSON list of the details of the specified item.
-
-        Parameters:
-            `item_id` - The Control4 item ID.
-        """
-        return await self.sendGetRequest("/api/v1/items/{}".format(item_id))
-
-    async def getItemSetup(self, item_id):
-        """Returns a JSON list of the setup info of the specified item.
-
-        Parameters:
-            `item_id` - The Control4 item ID.
-        """
-        return await self.sendPostRequest(
-            "/api/v1/items/{}/commands".format(item_id), "GET_SETUP", "{}", False
-        )
-
-    async def getItemVariables(self, item_id):
-        """Returns a JSON list of the variables available for the specified item.
-
-        Parameters:
-            `item_id` - The Control4 item ID.
-        """
-        return await self.sendGetRequest("/api/v1/items/{}/variables".format(item_id))
-
-    async def getItemVariableValue(self, item_id, var_name):
-        """Returns the value of the specified variable for the
-        specified item as a string.
-
-        Parameters:
-            `item_id` - The Control4 item ID.
-
-            `var_name` - The Control4 variable name or names.
-        """
-
-        if isinstance(var_name, (tuple, list, set)):
-            var_name = ",".join(var_name)
-
-        data = await self.sendGetRequest(
-            "/api/v1/items/{}/variables?varnames={}".format(item_id, var_name)
-        )
-        if data == "[]":
-            raise ValueError(
-                "Empty response recieved from Director! The variable {} \
-                    doesn't seem to exist for item {}.".format(
-                    var_name, item_id
-                )
-            )
-        jsonDictionary = json.loads(data)
-        return jsonDictionary[0]["value"]
-
-    async def getAllItemVariableValue(self, var_name):
-        """Returns a dictionary with the values of the specified variable
-        for all items that have it.
-
-        Parameters:
-            `var_name` - The Control4 variable name or names.
-        """
-        if isinstance(var_name, (tuple, list, set)):
-            var_name = ",".join(var_name)
-
-        data = await self.sendGetRequest(
-            "/api/v1/items/variables?varnames={}".format(var_name)
-        )
-        if data == "[]":
-            raise ValueError(
-                "Empty response recieved from Director! The variable {} \
-                    doesn't seem to exist for any items.".format(
-                    var_name
-                )
-            )
-        jsonDictionary = json.loads(data)
-        return jsonDictionary
-
-    async def getItemCommands(self, item_id):
-        """Returns a JSON list of the commands available for the specified item.
-
-        Parameters:
-            `item_id` - The Control4 item ID.
-        """
-        return await self.sendGetRequest("/api/v1/items/{}/commands".format(item_id))
-
-    async def getItemNetwork(self, item_id):
-        """Returns a JSON list of the network information for the specified item.
-
-        Parameters:
-            `item_id` - The Control4 item ID.
-        """
-        return await self.sendGetRequest("/api/v1/items/{}/network".format(item_id))
-
-    async def getItemBindings(self, item_id):
-        """Returns a JSON list of the bindings information for the specified item.
-
-        Parameters:
-            `item_id` - The Control4 item ID.
-        """
-        return await self.sendGetRequest("/api/v1/items/{}/bindings".format(item_id))
-
-    async def getUiConfiguration(self):
-        """Returns a dictionary of the JSON Control4 App UI Configuration enumerating rooms and capabilities
-
-        Returns:
-
-            {
-             "experiences": [
-                {
-                 "type": "watch",
-                 "sources": {
-                    "source": [
-                     {
-                      "id": 59,
-                      "type": "HDMI"
-                     },
-                     {
-                      "id": 946,
-                      "type": "HDMI"
-                     },
-                     {
-                      "id": 950,
-                      "type": "HDMI"
-                     },
-                     {
-                      "id": 33,
-                      "type": "VIDEO_SELECTION"
-                     }
-                    ]
-                },
-                 "active": false,
-                 "room_id": 9,
-                 "username": "primaryuser"
-                },
-                {
-                 "type": "listen",
-                 "sources": {
-                    "source": [
-                    {
-                     "id": 298,
-                     "type": "DIGITAL_AUDIO_SERVER",
-                     "name": "My Music"
-                    },
-                    {
-                     "id": 302,
-                     "type": "AUDIO_SELECTION",
-                     "name": "Stations"
-                    },
-                    {
-                     "id": 306,
-                     "type": "DIGITAL_AUDIO_SERVER",
-                     "name": "ShairBridge"
-                    },
-                    {
-                     "id": 937,
-                     "type": "DIGITAL_AUDIO_SERVER",
-                     "name": "Spotify Connect"
-                    },
-                    {
-                     "id": 100002,
-                     "type": "DIGITAL_AUDIO_CLIENT",
-                     "name": "Digital Media"
-                    }
-                   ]
-                },
-                 "active": false,
-                 "room_id": 9,
-                 "username": "primaryuser"
-                },
-                {
-                 "type": "cameras",
-                 "sources": {
-                    "source": [
-                    {
-                     "id": 877,
-                     "type": "Camera"
-                    },
-                    ...
-                }
-                ...
-            }
-        """
-
-        return await self.sendGetRequest("/api/v1/agents/ui_configuration")
-
@@ -664,14 +360,6 @@

Methods

Returns a JSON list of all the items on the Director.

-
- -Expand source code - -
async def getAllItemInfo(self):
-    """Returns a JSON list of all the items on the Director."""
-    return await self.sendGetRequest("/api/v1/items")
-
async def getAllItemVariableValue(self, var_name) @@ -681,33 +369,6 @@

Methods

for all items that have it.

Parameters

var_name - The Control4 variable name or names.

-
- -Expand source code - -
async def getAllItemVariableValue(self, var_name):
-    """Returns a dictionary with the values of the specified variable
-    for all items that have it.
-
-    Parameters:
-        `var_name` - The Control4 variable name or names.
-    """
-    if isinstance(var_name, (tuple, list, set)):
-        var_name = ",".join(var_name)
-
-    data = await self.sendGetRequest(
-        "/api/v1/items/variables?varnames={}".format(var_name)
-    )
-    if data == "[]":
-        raise ValueError(
-            "Empty response recieved from Director! The variable {} \
-                doesn't seem to exist for any items.".format(
-                var_name
-            )
-        )
-    jsonDictionary = json.loads(data)
-    return jsonDictionary
-
async def getAllItemsByCategory(self, category) @@ -720,25 +381,6 @@

Parameters

motorization, thermostats, motors, control4_remote_hub, outlet_wireless_dimmer, voice-scene

-
- -Expand source code - -
async def getAllItemsByCategory(self, category):
-    """Returns a JSON list of items related to a particular category.
-
-    Parameters:
-        `category` - Control4 Category Name: controllers, comfort, lights,
-                     cameras, sensors, audio_video,
-                     motorization, thermostats, motors,
-                     control4_remote_hub,
-                     outlet_wireless_dimmer, voice-scene
-    """
-    return_list = await self.sendGetRequest(
-        "/api/v1/categories/{}".format(category)
-    )
-    return return_list
-
async def getItemBindings(self, item_id) @@ -747,18 +389,6 @@

Parameters

Returns a JSON list of the bindings information for the specified item.

Parameters

item_id - The Control4 item ID.

-
- -Expand source code - -
async def getItemBindings(self, item_id):
-    """Returns a JSON list of the bindings information for the specified item.
-
-    Parameters:
-        `item_id` - The Control4 item ID.
-    """
-    return await self.sendGetRequest("/api/v1/items/{}/bindings".format(item_id))
-
async def getItemCommands(self, item_id) @@ -767,18 +397,6 @@

Parameters

Returns a JSON list of the commands available for the specified item.

Parameters

item_id - The Control4 item ID.

-
- -Expand source code - -
async def getItemCommands(self, item_id):
-    """Returns a JSON list of the commands available for the specified item.
-
-    Parameters:
-        `item_id` - The Control4 item ID.
-    """
-    return await self.sendGetRequest("/api/v1/items/{}/commands".format(item_id))
-
async def getItemInfo(self, item_id) @@ -787,18 +405,6 @@

Parameters

Returns a JSON list of the details of the specified item.

Parameters

item_id - The Control4 item ID.

-
- -Expand source code - -
async def getItemInfo(self, item_id):
-    """Returns a JSON list of the details of the specified item.
-
-    Parameters:
-        `item_id` - The Control4 item ID.
-    """
-    return await self.sendGetRequest("/api/v1/items/{}".format(item_id))
-
async def getItemNetwork(self, item_id) @@ -807,18 +413,6 @@

Parameters

Returns a JSON list of the network information for the specified item.

Parameters

item_id - The Control4 item ID.

-
- -Expand source code - -
async def getItemNetwork(self, item_id):
-    """Returns a JSON list of the network information for the specified item.
-
-    Parameters:
-        `item_id` - The Control4 item ID.
-    """
-    return await self.sendGetRequest("/api/v1/items/{}/network".format(item_id))
-
async def getItemSetup(self, item_id) @@ -827,20 +421,6 @@

Parameters

Returns a JSON list of the setup info of the specified item.

Parameters

item_id - The Control4 item ID.

-
- -Expand source code - -
async def getItemSetup(self, item_id):
-    """Returns a JSON list of the setup info of the specified item.
-
-    Parameters:
-        `item_id` - The Control4 item ID.
-    """
-    return await self.sendPostRequest(
-        "/api/v1/items/{}/commands".format(item_id), "GET_SETUP", "{}", False
-    )
-
async def getItemVariableValue(self, item_id, var_name) @@ -851,36 +431,6 @@

Parameters

Parameters

item_id - The Control4 item ID.

var_name - The Control4 variable name or names.

-
- -Expand source code - -
async def getItemVariableValue(self, item_id, var_name):
-    """Returns the value of the specified variable for the
-    specified item as a string.
-
-    Parameters:
-        `item_id` - The Control4 item ID.
-
-        `var_name` - The Control4 variable name or names.
-    """
-
-    if isinstance(var_name, (tuple, list, set)):
-        var_name = ",".join(var_name)
-
-    data = await self.sendGetRequest(
-        "/api/v1/items/{}/variables?varnames={}".format(item_id, var_name)
-    )
-    if data == "[]":
-        raise ValueError(
-            "Empty response recieved from Director! The variable {} \
-                doesn't seem to exist for item {}.".format(
-                var_name, item_id
-            )
-        )
-    jsonDictionary = json.loads(data)
-    return jsonDictionary[0]["value"]
-
async def getItemVariables(self, item_id) @@ -889,18 +439,6 @@

Parameters

Returns a JSON list of the variables available for the specified item.

Parameters

item_id - The Control4 item ID.

-
- -Expand source code - -
async def getItemVariables(self, item_id):
-    """Returns a JSON list of the variables available for the specified item.
-
-    Parameters:
-        `item_id` - The Control4 item ID.
-    """
-    return await self.sendGetRequest("/api/v1/items/{}/variables".format(item_id))
-
async def getUiConfiguration(self) @@ -983,94 +521,6 @@

Returns

} … }

-
- -Expand source code - -
async def getUiConfiguration(self):
-    """Returns a dictionary of the JSON Control4 App UI Configuration enumerating rooms and capabilities
-
-    Returns:
-
-        {
-         "experiences": [
-            {
-             "type": "watch",
-             "sources": {
-                "source": [
-                 {
-                  "id": 59,
-                  "type": "HDMI"
-                 },
-                 {
-                  "id": 946,
-                  "type": "HDMI"
-                 },
-                 {
-                  "id": 950,
-                  "type": "HDMI"
-                 },
-                 {
-                  "id": 33,
-                  "type": "VIDEO_SELECTION"
-                 }
-                ]
-            },
-             "active": false,
-             "room_id": 9,
-             "username": "primaryuser"
-            },
-            {
-             "type": "listen",
-             "sources": {
-                "source": [
-                {
-                 "id": 298,
-                 "type": "DIGITAL_AUDIO_SERVER",
-                 "name": "My Music"
-                },
-                {
-                 "id": 302,
-                 "type": "AUDIO_SELECTION",
-                 "name": "Stations"
-                },
-                {
-                 "id": 306,
-                 "type": "DIGITAL_AUDIO_SERVER",
-                 "name": "ShairBridge"
-                },
-                {
-                 "id": 937,
-                 "type": "DIGITAL_AUDIO_SERVER",
-                 "name": "Spotify Connect"
-                },
-                {
-                 "id": 100002,
-                 "type": "DIGITAL_AUDIO_CLIENT",
-                 "name": "Digital Media"
-                }
-               ]
-            },
-             "active": false,
-             "room_id": 9,
-             "username": "primaryuser"
-            },
-            {
-             "type": "cameras",
-             "sources": {
-                "source": [
-                {
-                 "id": 877,
-                 "type": "Camera"
-                },
-                ...
-            }
-            ...
-        }
-    """
-
-    return await self.sendGetRequest("/api/v1/agents/ui_configuration")
-
async def sendGetRequest(self, uri) @@ -1081,36 +531,6 @@

Returns

Parameters

uri - The API URI to send the request to. Do not include the IP address of the Director.

-
- -Expand source code - -
async def sendGetRequest(self, uri):
-    """Sends a GET request to the specified API URI.
-    Returns the Director's JSON response as a string.
-
-    Parameters:
-        `uri` - The API URI to send the request to. Do not include the IP
-                address of the Director.
-    """
-    if self.session is None:
-        async with aiohttp.ClientSession(
-            connector=aiohttp.TCPConnector(verify_ssl=False)
-        ) as session:
-            with async_timeout.timeout(10):
-                async with session.get(
-                    self.base_url + uri, headers=self.headers
-                ) as resp:
-                    await checkResponseForError(await resp.text())
-                    return await resp.text()
-    else:
-        with async_timeout.timeout(10):
-            async with self.session.get(
-                self.base_url + uri, headers=self.headers
-            ) as resp:
-                await checkResponseForError(await resp.text())
-                return await resp.text()
-
async def sendPostRequest(self, uri, command, params, async_variable=True) @@ -1124,46 +544,6 @@

Parameters

address of the Director.

command - The Control4 command to send.

params - The parameters of the command, provided as a dictionary.

-
- -Expand source code - -
async def sendPostRequest(self, uri, command, params, async_variable=True):
-    """Sends a POST request to the specified API URI. Used to send commands
-       to the Director.
-    Returns the Director's JSON response as a string.
-
-    Parameters:
-        `uri` - The API URI to send the request to. Do not include the IP
-                address of the Director.
-
-        `command` - The Control4 command to send.
-
-        `params` - The parameters of the command, provided as a dictionary.
-    """
-    dataDictionary = {
-        "async": async_variable,
-        "command": command,
-        "tParams": params,
-    }
-    if self.session is None:
-        async with aiohttp.ClientSession(
-            connector=aiohttp.TCPConnector(verify_ssl=False)
-        ) as session:
-            with async_timeout.timeout(10):
-                async with session.post(
-                    self.base_url + uri, headers=self.headers, json=dataDictionary
-                ) as resp:
-                    await checkResponseForError(await resp.text())
-                    return await resp.text()
-    else:
-        with async_timeout.timeout(10):
-            async with self.session.post(
-                self.base_url + uri, headers=self.headers, json=dataDictionary
-            ) as resp:
-                await checkResponseForError(await resp.text())
-                return await resp.text()
-
@@ -1171,7 +551,6 @@

Parameters