Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Auto-Deduce Invoke Response Type #10933

Merged
merged 6 commits into from
Oct 27, 2021
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/controller/python/chip/ChipDeviceCtrl.py
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,12 @@ def DeviceAvailableCallback(device, err):
return returnDevice

async def SendCommand(self, nodeid: int, endpoint: int, payload: ClusterObjects.ClusterCommand, responseType=None):
'''
Send a cluster-object encapsulated command to a node and get returned a future that can be awaited upon to receive the response.
If a valid responseType is passed in, that will be used to deserialize the object. If not, the type will be automatically deduced
from the metadata received over the wire.
'''

eventLoop = asyncio.get_running_loop()
future = eventLoop.create_future()

Expand Down
59 changes: 49 additions & 10 deletions src/controller/python/chip/clusters/Command.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,13 @@
from typing import Type
from ctypes import CFUNCTYPE, c_char_p, c_size_t, c_void_p, c_uint32, c_uint16, py_object


from .ClusterObjects import ClusterCommand
import chip.exceptions
import chip.interaction_model

import inspect
import sys


@dataclass
class CommandPath:
Expand All @@ -34,25 +36,54 @@ class CommandPath:
CommandId: int


def FindCommandClusterObject(isClientSideCommand: bool, path: CommandPath):
''' Locates the right generated cluster object given a set of parameters.

isClientSideCommand: True if it is a client-to-server command, else False.
path: A CommandPath that describes the endpoint, cluster and ID of the command.

Returns the type of the cluster object if one is found. Otherwise, returns None.
'''
for clusterName, obj in inspect.getmembers(sys.modules['chip.clusters.Objects']):
andy31415 marked this conversation as resolved.
Show resolved Hide resolved
if ('chip.clusters.Objects' in str(obj)) and inspect.isclass(obj):
for objName, subclass in inspect.getmembers(obj):
if inspect.isclass(subclass) and (('Commands') in str(subclass)):
for commandName, command in inspect.getmembers(subclass):
if inspect.isclass(command):
for name, field in inspect.getmembers(command):
if ('__dataclass_fields__' in name):
if (field['cluster_id'].default == path.ClusterId) and (field['command_id'].default == path.CommandId) and (field['is_client'].default == isClientSideCommand):
return eval('chip.clusters.Objects.' + clusterName + '.Commands.' + commandName)
return None


class AsyncCommandTransaction:
def __init__(self, future: Future, eventLoop, expectType: Type):
self._event_loop = eventLoop
self._future = future
self._expect_type = expectType

def _handleResponse(self, response: bytes):
if self._expect_type:
try:
self._future.set_result(self._expect_type.FromTLV(response))
except Exception as ex:
self._handleError(
chip.interaction_model.Status.Failure, 0, ex)
else:
def _handleResponse(self, path: CommandPath, response: bytes):
if (len(response) == 0):
self._future.set_result(None)
else:
# If a type hasn't been assigned, let's auto-deduce it.
if (self._expect_type == None):
self._expect_type = FindCommandClusterObject(False, path)

if self._expect_type:
try:
self._future.set_result(
self._expect_type.FromTLV(response))
except Exception as ex:
self._handleError(
chip.interaction_model.Status.Failure, 0, ex)
else:
self._future.set_result(None)

def handleResponse(self, path: CommandPath, response: bytes):
self._event_loop.call_soon_threadsafe(
self._handleResponse, response)
self._handleResponse, path, response)

def _handleError(self, imError: int, chipError: int, exception: Exception):
if exception:
Expand All @@ -68,6 +99,7 @@ def _handleError(self, imError: int, chipError: int, exception: Exception):
except:
self._future.set_exception(chip.interaction_model.InteractionModelError(
chip.interaction_model.Status.Failure))
pass

def handleError(self, imError: int, chipError: int):
self._event_loop.call_soon_threadsafe(
Expand Down Expand Up @@ -100,6 +132,13 @@ def _OnCommandSenderDoneCallback(closure):


def SendCommand(future: Future, eventLoop, responseType: Type, device, commandPath: CommandPath, payload: ClusterCommand) -> int:
''' Send a cluster-object encapsulated command to a device and does the following:
- On receipt of a successful data response, returns the cluster-object equivalent through the provided future.
- None (on a successful response containing no data)
- Raises an exception if any errors are encountered.

If no response type is provided above, the type will be automatically deduced.
'''
if (responseType is not None) and (not issubclass(responseType, ClusterCommand)):
raise ValueError("responseType must be a ClusterCommand or None")

Expand Down
Loading