From 2378450abad2746e1ec7f355949323c6265d6e40 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Damian=20Michalak-Szmaci=C5=84ski?= Date: Wed, 5 Jul 2023 23:08:29 +0200 Subject: [PATCH] [controller] Fix flake8 warnings (#25311) * [controller] Add to flake8 in workflow and fix python files * rebase * Restyled by autopep8 Restyled by isort Restyled * Restore .delegate in init interaction_model * rebase Restyled by isort * Fix of the if statement * Fix use undefined uint8_t * Add import to __init__ * Fix renamed import ClusterObjects * Arkq suggested change * Fix use GeneratedObjects for remove noqa --------- Co-authored-by: Restyled.io Co-authored-by: Arkadiusz Bokowy --- .flake8 | 25 --- src/controller/python/build-chip-wheel.py | 1 - src/controller/python/chip-device-ctrl.py | 41 +++-- .../python/chip/CertificateAuthority.py | 29 ++-- src/controller/python/chip/ChipBleUtility.py | 6 +- src/controller/python/chip/ChipBluezMgr.py | 67 +++++---- .../python/chip/ChipCommissionableNodeCtrl.py | 7 +- .../python/chip/ChipCoreBluetoothMgr.py | 8 +- src/controller/python/chip/ChipDeviceCtrl.py | 142 +++++++++++------- src/controller/python/chip/ChipReplStartup.py | 13 +- src/controller/python/chip/ChipStack.py | 15 +- src/controller/python/chip/ChipUtility.py | 4 +- src/controller/python/chip/FabricAdmin.py | 15 +- .../python/chip/ble/scan_devices.py | 2 +- .../python/chip/clusters/Attribute.py | 99 ++++++++---- .../python/chip/clusters/ClusterObjects.py | 35 +++-- .../python/chip/clusters/Command.py | 2 +- .../python/chip/clusters/__init__.py | 68 ++++++++- .../python/chip/discovery/__init__.py | 2 +- .../python/chip/interaction_model/__init__.py | 3 +- .../python/chip/interaction_model/delegate.py | 6 +- .../python/chip/internal/commissioner.py | 6 +- .../chip/setup_payload/setup_payload.py | 4 +- .../python/chip/storage/__init__.py | 12 +- src/controller/python/chip/tlv/__init__.py | 9 +- .../chip/utils/CommissioningBuildingBlocks.py | 58 +++++-- src/controller/python/chip/yaml/__init__.py | 2 + .../python/chip/yaml/format_converter.py | 7 +- src/controller/python/chip/yaml/runner.py | 12 +- .../pycontroller/build-chip-wheel.py | 1 - .../pycontroller/pychip/__init__.py | 3 + 31 files changed, 439 insertions(+), 265 deletions(-) diff --git a/.flake8 b/.flake8 index 599ac08c7b63a3..c53238a9262656 100644 --- a/.flake8 +++ b/.flake8 @@ -47,31 +47,6 @@ exclude = third_party scripts/tools/zap_convert_all.py src/app/ota_image_tool.py src/app/zap_cluster_list.py - src/controller/python/build-chip-wheel.py - src/controller/python/chip-device-ctrl.py - src/controller/python/chip/CertificateAuthority.py - src/controller/python/chip/ChipBleUtility.py - src/controller/python/chip/ChipBluezMgr.py - src/controller/python/chip/ChipCommissionableNodeCtrl.py - src/controller/python/chip/ChipCoreBluetoothMgr.py - src/controller/python/chip/ChipDeviceCtrl.py - src/controller/python/chip/ChipReplStartup.py - src/controller/python/chip/ChipStack.py - src/controller/python/chip/ChipUtility.py - src/controller/python/chip/FabricAdmin.py - src/controller/python/chip/ble/scan_devices.py - src/controller/python/chip/clusters/Attribute.py - src/controller/python/chip/clusters/ClusterObjects.py - src/controller/python/chip/clusters/Command.py - src/controller/python/chip/clusters/__init__.py - src/controller/python/chip/discovery/__init__.py - src/controller/python/chip/interaction_model/__init__.py - src/controller/python/chip/interaction_model/delegate.py - src/controller/python/chip/internal/commissioner.py - src/controller/python/chip/setup_payload/setup_payload.py - src/controller/python/chip/storage/__init__.py - src/controller/python/chip/tlv/__init__.py - src/controller/python/chip/utils/CommissioningBuildingBlocks.py src/controller/python/chip/yaml/__init__.py src/controller/python/chip/yaml/format_converter.py src/controller/python/chip/yaml/runner.py diff --git a/src/controller/python/build-chip-wheel.py b/src/controller/python/build-chip-wheel.py index 9fb2a9dedab491..7b21215bdcd8e2 100644 --- a/src/controller/python/build-chip-wheel.py +++ b/src/controller/python/build-chip-wheel.py @@ -29,7 +29,6 @@ import shutil from setuptools import Distribution, setup -from wheel.bdist_wheel import bdist_wheel parser = argparse.ArgumentParser( description='build the pip package for chip using chip components generated during the build and python source code') diff --git a/src/controller/python/chip-device-ctrl.py b/src/controller/python/chip-device-ctrl.py index e9022910e80667..469fb2c49fdfc8 100755 --- a/src/controller/python/chip-device-ctrl.py +++ b/src/controller/python/chip-device-ctrl.py @@ -44,7 +44,7 @@ import chip.logging import coloredlogs -from chip import ChipCommissionableNodeCtrl, ChipStack, FabricAdmin, exceptions, native +from chip import ChipCommissionableNodeCtrl, ChipStack, exceptions, native from chip.setup_payload import SetupPayload from rich import pretty, print @@ -311,7 +311,8 @@ def do_closeble(self, line): """ warnings.warn( - "This method is being deprecated. Please use the DeviceController.CloseBLEConnection method directly in the REPL", DeprecationWarning) + "This method is being deprecated. " + "Please use the DeviceController.CloseBLEConnection method directly in the REPL", DeprecationWarning) args = shlex.split(line) @@ -333,7 +334,8 @@ def do_setlogoutput(self, line): """ warnings.warn( - "This method is being deprecated. Please use the DeviceController.SetLogFilter method directly in the REPL", DeprecationWarning) + "This method is being deprecated. " + "Please use the DeviceController.SetLogFilter method directly in the REPL", DeprecationWarning) args = shlex.split(line) @@ -382,7 +384,8 @@ def do_setuppayload(self, line): """ warnings.warn( - "This method is being deprecated. Please use the SetupPayload function in the chip.setup_payload package directly", DeprecationWarning) + "This method is being deprecated. " + "Please use the SetupPayload function in the chip.setup_payload package directly", DeprecationWarning) try: arglist = shlex.split(line) @@ -599,7 +602,8 @@ def do_connect(self, line): """ warnings.warn( - "This method is being deprecated. Please use the DeviceController.[ConnectBLE|CommissionIP] methods directly in the REPL", DeprecationWarning) + "This method is being deprecated. " + "Please use the DeviceController.[ConnectBLE|CommissionIP] methods directly in the REPL", DeprecationWarning) try: args = shlex.split(line) @@ -661,7 +665,7 @@ def do_closesession(self, line): self.devCtrl.CloseSession(args.nodeid) except exceptions.ChipStackException as ex: print(str(ex)) - except: + except Exception: self.do_help("close-session") def do_resolve(self, line): @@ -782,7 +786,7 @@ def do_discover(self, line): print('exception') print(str(ex)) return - except: + except Exception: self.do_help("discover") return @@ -826,7 +830,7 @@ def do_zcl(self, line): args[2]), int(args[3]), int(args[4]), FormatZCLArguments(args[5:], command), blocking=True) if err != 0: print("Failed to receive command response: {}".format(res)) - elif res != None: + elif res is not None: print("Received command status response:") print(res) else: @@ -858,10 +862,11 @@ def do_zclread(self, line): elif len(args) == 5: if args[0] not in all_attrs: raise exceptions.UnknownCluster(args[0]) - self.replHint = f"await devCtrl.ReadAttribute({int(args[2])}, [({int(args[3])}, Clusters.{args[0]}.Attributes.{args[1]})])" + self.replHint = (f"await devCtrl.ReadAttribute({int(args[2])}, [({int(args[3])}, " + f"Clusters.{args[0]}.Attributes.{args[1]})])") res = self.devCtrl.ZCLReadAttribute(args[0], args[1], int( args[2]), int(args[3]), int(args[4])) - if res != None: + if res is not None: print(repr(res)) else: self.do_help("zclread") @@ -893,7 +898,9 @@ def do_zclwrite(self, line): raise exceptions.UnknownCluster(args[0]) attribute_type = all_attrs.get(args[0], {}).get( args[1], {}).get("type", None) - self.replHint = f"await devCtrl.WriteAttribute({int(args[2])}, [({int(args[3])}, Clusters.{args[0]}.Attributes.{args[1]}(value={repr(ParseValueWithType(args[5], attribute_type))}))])" + self.replHint = ( + f"await devCtrl.WriteAttribute({int(args[2])}, [({int(args[3])}, " + f"Clusters.{args[0]}.Attributes.{args[1]}(value={repr(ParseValueWithType(args[5], attribute_type))}))])") res = self.devCtrl.ZCLWriteAttribute(args[0], args[1], int( args[2]), int(args[3]), int(args[4]), ParseValueWithType(args[5], attribute_type)) print(repr(res)) @@ -930,7 +937,8 @@ def do_zclsubscribe(self, line): raise exceptions.UnknownCluster(args[0]) res = self.devCtrl.ZCLSubscribeAttribute(args[0], args[1], int( args[2]), int(args[3]), int(args[4]), int(args[5])) - self.replHint = f"sub = await devCtrl.ReadAttribute({int(args[2])}, [({int(args[3])}, Clusters.{args[0]}.Attributes.{args[1]})], reportInterval=({int(args[4])}, {int(args[5])}))" + self.replHint = (f"sub = await devCtrl.ReadAttribute({int(args[2])}, [({int(args[3])}, " + f"Clusters.{args[0]}.Attributes.{args[1]})], reportInterval=({int(args[4])}, {int(args[5])}))") print(res.GetAllValues()) print(f"Subscription Established: {res}") elif len(args) == 2 and args[0] == '-shutdown': @@ -1013,7 +1021,8 @@ def do_opencommissioningwindow(self, line): print("Invalid option specified!") raise ValueError("Invalid option specified") - self.replHint = f"devCtrl.OpenCommissioningWindow(nodeid={int(arglist[0])}, timeout={args.timeout}, iteration={args.iteration}, discriminator={args.discriminator}, option={args.option})" + self.replHint = (f"devCtrl.OpenCommissioningWindow(nodeid={int(arglist[0])}, timeout={args.timeout}, " + f"iteration={args.iteration}, discriminator={args.discriminator}, option={args.option})") self.devCtrl.OpenCommissioningWindow( int(arglist[0]), args.timeout, args.iteration, args.discriminator, args.option) @@ -1021,7 +1030,7 @@ def do_opencommissioningwindow(self, line): except exceptions.ChipStackException as ex: print(str(ex)) return - except: + except Exception: self.do_help("open-commissioning-window") return @@ -1041,7 +1050,7 @@ def do_getfabricid(self, line): compressed_fabricid = self.devCtrl.GetCompressedFabricId() raw_fabricid = self.devCtrl.fabricId - self.replHint = f"devCtrl.GetCompressedFabricId(), devCtrl.fabricId" + self.replHint = "devCtrl.GetCompressedFabricId(), devCtrl.fabricId" except exceptions.ChipStackException as ex: print("An exception occurred during reading FabricID:") print(str(ex)) @@ -1146,7 +1155,7 @@ def main(): else: try: adapterId = int(options.bluetoothAdapter[3:]) - except: + except ValueError: print( "Invalid bluetooth adapter: {}, adapter name looks like hci0, hci1 etc.") sys.exit(-1) diff --git a/src/controller/python/chip/CertificateAuthority.py b/src/controller/python/chip/CertificateAuthority.py index 084c028ee060a9..bce921cfb785bf 100644 --- a/src/controller/python/chip/CertificateAuthority.py +++ b/src/controller/python/chip/CertificateAuthority.py @@ -20,8 +20,8 @@ import ctypes import logging -from ctypes import * -from typing import * +from ctypes import c_void_p +from typing import List import chip.exceptions from chip import ChipStack, FabricAdmin @@ -30,18 +30,20 @@ class CertificateAuthority: - ''' This represents an operational Root Certificate Authority (CA) with a root key key pair with associated public key (i.e "Root PK") . This manages - a set of FabricAdmin objects, each administering a fabric identified by a unique FabricId scoped to it. + ''' This represents an operational Root Certificate Authority (CA) with a root key key pair with associated + public key (i.e "Root PK") . This manages a set of FabricAdmin objects, each administering a fabric identified + by a unique FabricId scoped to it. - Each CertificateAuthority instance is tied to a 'CA index' that is used to look-up the list of fabrics already setup previously - in the provided PersistentStorage object. + Each CertificateAuthority instance is tied to a 'CA index' that is used to look-up the list of fabrics already setup + previously in the provided PersistentStorage object. >> C++ Binding Details - Each CertificateAuthority instance is associated with a single instance of the OperationalCredentialsAdapter. This adapter instance implements - the OperationalCredentialsDelegate and is meant to provide a Python adapter to the functions in that delegate. It relies on the in-built - ExampleOperationalCredentialsIssuer to then generate certificate material for the CA. This instance also uses the 'CA index' to - store/look-up the associated credential material from the provided PersistentStorage object. + Each CertificateAuthority instance is associated with a single instance of the OperationalCredentialsAdapter. + This adapter instance implements the OperationalCredentialsDelegate and is meant to provide a Python adapter to the + functions in that delegate. It relies on the in-built ExampleOperationalCredentialsIssuer to then generate certificate + material for the CA. This instance also uses the 'CA index' to store/look-up the associated credential material from + the provided PersistentStorage object. ''' @classmethod def _Handle(cls): @@ -57,7 +59,8 @@ def __init__(self, chipStack: ChipStack.ChipStack, caIndex: int, persistentStora Arguments: chipStack: A reference to a chip.ChipStack object. - caIndex: An index used to look-up details about stored credential material and fabrics from persistent storage. + caIndex: An index used to look-up details about stored credential material and fabrics + from persistent storage. persistentStorage: An optional reference to a PersistentStorage object. If one is provided, it will pick that over the default PersistentStorage object retrieved from the chipStack. ''' @@ -121,10 +124,10 @@ def NewFabricAdmin(self, vendorId: int, fabricId: int): ''' if (not (self._isActive)): raise RuntimeError( - f"CertificateAuthority object was previously shutdown and is no longer valid!") + "CertificateAuthority object was previously shutdown and is no longer valid!") if (vendorId is None or fabricId is None): - raise ValueError(f"Invalid values for fabricId and vendorId") + raise ValueError("Invalid values for fabricId and vendorId") for existingAdmin in self._activeAdmins: if (existingAdmin.fabricId == fabricId): diff --git a/src/controller/python/chip/ChipBleUtility.py b/src/controller/python/chip/ChipBleUtility.py index 6d09dd1ae2b470..410475042bcdae 100644 --- a/src/controller/python/chip/ChipBleUtility.py +++ b/src/controller/python/chip/ChipBleUtility.py @@ -24,7 +24,7 @@ from __future__ import absolute_import, print_function -from ctypes import * +from ctypes import Structure, c_bool, c_int32, c_uint16, c_void_p from .ChipUtility import ChipUtility @@ -62,7 +62,7 @@ def VoidPtrToUUIDString(ptr, len): + ptr[20:] ) ptr = str(ptr) - except Exception as ex: + except Exception: print("ERROR: failed to convert void * to UUID") ptr = None @@ -319,7 +319,7 @@ def fromBleRxEvent(cls, bleRxEvent): bleRxEventStruct.Buffer = ChipUtility.ByteArrayToVoidPtr( bleRxEvent.Buffer) bleRxEventStruct.Length = ( - len(bleRxEvent.Buffer) if (bleRxEvent.Buffer != None) else 0 + len(bleRxEvent.Buffer) if (bleRxEvent.Buffer is not None) else 0 ) return bleRxEventStruct diff --git a/src/controller/python/chip/ChipBluezMgr.py b/src/controller/python/chip/ChipBluezMgr.py index 33926b47b0e006..e480750b600af8 100644 --- a/src/controller/python/chip/ChipBluezMgr.py +++ b/src/controller/python/chip/ChipBluezMgr.py @@ -31,7 +31,7 @@ import time import traceback import uuid -from ctypes import * +from ctypes import CFUNCTYPE, PYFUNCTYPE, c_int, c_void_p, cast, pythonapi import dbus import dbus.mainloop.glib @@ -42,7 +42,7 @@ try: from gi.repository import GObject -except Exception as ex: +except Exception: logging.exception("Unable to find GObject from gi.repository") from pgi.repository import GObject @@ -180,7 +180,7 @@ def adapter_bg_scan(self, enable): except dbus.exceptions.DBusException as ex: self.adapter_event.clear() self.logger.debug(str(ex)) - except Exception as ex: + except Exception: self.logger.debug(traceback.format_exc()) @property @@ -191,7 +191,7 @@ def Address(self): except dbus.exceptions.DBusException as ex: self.logger.debug(str(ex)) return None - except Exception as ex: + except Exception: self.logger.debug(traceback.format_exc()) return None @@ -202,7 +202,7 @@ def UUIDs(self): except dbus.exceptions.DBusException as ex: self.logger.debug(str(ex)) return None - except Exception as ex: + except Exception: self.logger.debug(traceback.format_exc()) return None @@ -211,7 +211,7 @@ def SetDiscoveryFilter(self, dict): self.adapter.SetDiscoveryFilter(dict) except dbus.exceptions.DBusException as ex: self.logger.debug(str(ex)) - except Exception as ex: + except Exception: self.logger.debug(traceback.format_exc()) @property @@ -223,7 +223,7 @@ def Discovering(self): except dbus.exceptions.DBusException as ex: self.logger.debug(str(ex)) return False - except Exception as ex: + except Exception: self.logger.debug(traceback.format_exc()) return False @@ -236,7 +236,7 @@ def DiscoverableTimeout(self, timeoutSec): except dbus.exceptions.DBusException as ex: self.logger.debug(str(ex)) return False - except Exception as ex: + except Exception: self.logger.debug(traceback.format_exc()) return False @@ -248,7 +248,7 @@ def Powered(self, enable): except dbus.exceptions.DBusException as ex: self.logger.debug(str(ex)) return False - except Exception as ex: + except Exception: self.logger.debug(traceback.format_exc()) return False @@ -285,7 +285,7 @@ def clear_adapter(self): if device.Connected: device.device_bg_connect(False) self.adapter.RemoveDevice(device.device.object_path) - except Exception as ex: + except Exception: pass @@ -393,7 +393,7 @@ def device_bg_connect(self, enable): except dbus.exceptions.DBusException as ex: self.device_event.clear() self.logger.info(str(ex)) - except Exception as ex: + except Exception: self.logger.debug(traceback.format_exc()) def service_discover(self, gatt_dic): @@ -420,7 +420,7 @@ def service_discover(self, gatt_dic): except dbus.exceptions.DBusException as ex: self.logger.debug(str(ex)) return None - except Exception as ex: + except Exception: self.logger.debug(traceback.format_exc()) return None @@ -439,7 +439,7 @@ def uuids(self): except dbus.exceptions.DBusException as ex: self.logger.debug(str(ex)) return None - except Exception as ex: + except Exception: self.logger.debug(traceback.format_exc()) return None @@ -450,7 +450,7 @@ def Address(self): except dbus.exceptions.DBusException as ex: self.logger.debug(str(ex)) return None - except Exception as ex: + except Exception: self.logger.debug(traceback.format_exc()) return None @@ -462,7 +462,7 @@ def Name(self): except dbus.exceptions.DBusException as ex: self.logger.debug(str(ex)) return None - except Exception as ex: + except Exception: self.logger.debug(traceback.format_exc()) return None @@ -474,7 +474,7 @@ def Connected(self): except dbus.exceptions.DBusException as ex: self.logger.debug(str(ex)) return False - except Exception as ex: + except Exception: self.logger.debug(traceback.format_exc()) return False @@ -485,7 +485,7 @@ def TxPower(self): except dbus.exceptions.DBusException as ex: self.logger.debug(str(ex)) return None - except Exception as ex: + except Exception: self.logger.debug(traceback.format_exc()) return None @@ -497,7 +497,7 @@ def RSSI(self): except dbus.exceptions.DBusException as ex: self.logger.debug(str(ex)) return None - except Exception as ex: + except Exception: self.logger.debug(traceback.format_exc()) return None @@ -508,7 +508,7 @@ def Adapter(self): except dbus.exceptions.DBusException as ex: self.logger.debug(str(ex)) return None - except Exception as ex: + except Exception: self.logger.debug(traceback.format_exc()) return None @@ -519,7 +519,7 @@ def ServiceData(self): except dbus.exceptions.DBusException as ex: self.logger.debug(str(ex)) return None - except Exception as ex: + except Exception: self.logger.debug(traceback.format_exc()) return None @@ -532,7 +532,7 @@ def ServicesResolved(self): except dbus.exceptions.DBusException as ex: self.logger.debug(str(ex)) return False - except Exception as ex: + except Exception: self.logger.debug(traceback.format_exc()) return False @@ -569,7 +569,7 @@ def uuid(self): except dbus.exceptions.DBusException as ex: self.logger.debug(str(ex)) return None - except Exception as ex: + except Exception: self.logger.debug(traceback.format_exc()) return None @@ -582,7 +582,7 @@ def Primary(self): except dbus.exceptions.DBusException as ex: self.logger.debug(str(ex)) return False - except Exception as ex: + except Exception: self.logger.debug(traceback.format_exc()) return False @@ -594,7 +594,7 @@ def Device(self): except dbus.exceptions.DBusException as ex: self.logger.debug(str(ex)) return None - except Exception as ex: + except Exception: self.logger.debug(traceback.format_exc()) return None @@ -619,7 +619,7 @@ def find_characteristic(self, uuid): except dbus.exceptions.DBusException as ex: self.logger.debug(str(ex)) return None - except Exception as ex: + except Exception: self.logger.debug(traceback.format_exc()) return None @@ -707,7 +707,7 @@ def WriteValue(self, value, options, reply_handler, error_handler, timeout): ) except dbus.exceptions.DBusException as ex: self.logger.debug(str(ex)) - except Exception as ex: + except Exception: self.logger.debug(traceback.format_exc()) @property @@ -723,7 +723,7 @@ def uuid(self): except dbus.exceptions.DBusException as ex: self.logger.debug(str(ex)) return None - except Exception as ex: + except Exception: self.logger.debug(traceback.format_exc()) return None @@ -740,7 +740,7 @@ def StartNotify(self, cbfunct, reply_handler, error_handler, timeout): ) except dbus.exceptions.DBusException as ex: self.logger.debug(str(ex)) - except Exception as ex: + except Exception: self.logger.debug(traceback.format_exc()) def StopNotify(self, reply_handler, error_handler, timeout): @@ -755,7 +755,7 @@ def StopNotify(self, reply_handler, error_handler, timeout): self.received = None except dbus.exceptions.DBusException as ex: self.logger.debug(str(ex)) - except Exception as ex: + except Exception: self.logger.debug(traceback.format_exc()) @property @@ -768,7 +768,7 @@ def Notifying(self): except dbus.exceptions.DBusException as ex: self.logger.debug(str(ex)) return False - except Exception as ex: + except Exception: self.logger.debug(traceback.format_exc()) return False @@ -858,7 +858,8 @@ def get_adapter_by_addr(self, identifier): return adapters[0] if len(adapters) > 0: for adapter in adapters: - if str(adapter.Address).upper() == str(identifier).upper() or "/org/bluez/{}".format(identifier) == str(adapter.path): + if (str(adapter.Address).upper() == str(identifier).upper() or + "/org/bluez/{}".format(identifier) == str(adapter.path)): return adapter self.logger.info( "adapter %s cannot be found, expect the ble mac address" % ( @@ -889,7 +890,7 @@ def running_thread(self, target, kwargs): while not self.Gmainloop or not self.Gmainloop.is_running(): time.sleep(0.00001) target(**kwargs) - except Exception as err: + except Exception: traceback.print_exc() finally: self.Gmainloop.quit() @@ -924,7 +925,7 @@ def dump_scan_result(self, device): self.logger.info("{0:<16}= {1}".format("Address", device.Address)) devIdInfo = self.get_peripheral_devIdInfo(device) - if devIdInfo != None: + if devIdInfo is not None: self.logger.info("{0:<16}= {1}".format( "Pairing State", devIdInfo.pairingState)) self.logger.info("{0:<16}= {1}".format( diff --git a/src/controller/python/chip/ChipCommissionableNodeCtrl.py b/src/controller/python/chip/ChipCommissionableNodeCtrl.py index 70ecf00f4b2856..f487ffd5edf7f7 100644 --- a/src/controller/python/chip/ChipCommissionableNodeCtrl.py +++ b/src/controller/python/chip/ChipCommissionableNodeCtrl.py @@ -25,10 +25,9 @@ from __future__ import absolute_import, print_function -from ctypes import * +from ctypes import CDLL, POINTER, c_void_p, pointer -from .ChipStack import * -from .exceptions import * +from .ChipStack import ChipStack from .native import PyChipError __all__ = ["ChipCommissionableNodeController"] @@ -62,7 +61,7 @@ def __init__(self, chipStack: ChipStack): self._ChipStack.commissionableNodeCtrl = commissionableNodeCtrl def __del__(self): - if self.commissionableNodeCtrl != None: + if self.commissionableNodeCtrl is not None: self._dmLib.pychip_CommissionableNodeController_DeleteController( self.commissionableNodeCtrl) self.commissionableNodeCtrl = None diff --git a/src/controller/python/chip/ChipCoreBluetoothMgr.py b/src/controller/python/chip/ChipCoreBluetoothMgr.py index 5b744671394615..3f792a5a4d2425 100644 --- a/src/controller/python/chip/ChipCoreBluetoothMgr.py +++ b/src/controller/python/chip/ChipCoreBluetoothMgr.py @@ -27,10 +27,10 @@ import logging import queue import time -from ctypes import * +from ctypes import CFUNCTYPE, PYFUNCTYPE, c_int, c_void_p, cast, pointer, pythonapi import objc -from Foundation import * +from Foundation import CBUUID, CBCentralManager, NSDefaultRunLoopMode, NSRunLoop from .ChipBleBase import ChipBleBase from .ChipBleUtility import (BLE_ERROR_REMOTE_DEVICE_DISCONNECTED, BLE_SUBSCRIBE_OPERATION_SUBSCRIBE, @@ -47,7 +47,7 @@ u"/System/Library/Frameworks/IOBluetooth.framework/Versions/A/Frameworks/CoreBluetooth.framework" ), ) -except Exception as ex: +except Exception: objc.loadBundle( "CoreBluetooth", globals(), @@ -86,7 +86,7 @@ def _VoidPtrToCBUUID(ptr, len): + ptr[20:] ) ptr = CBUUID.UUIDWithString_(ptr) - except Exception as ex: + except Exception: print("ERROR: failed to convert void * to CBUUID") ptr = None diff --git a/src/controller/python/chip/ChipDeviceCtrl.py b/src/controller/python/chip/ChipDeviceCtrl.py index 401a356d7556ca..4e4f7752d2d580 100644 --- a/src/controller/python/chip/ChipDeviceCtrl.py +++ b/src/controller/python/chip/ChipDeviceCtrl.py @@ -37,7 +37,8 @@ import threading import time import typing -from ctypes import * +from ctypes import (CDLL, CFUNCTYPE, POINTER, byref, c_bool, c_char, c_char_p, c_int, c_size_t, c_uint8, c_uint16, c_uint32, + c_uint64, c_void_p, create_string_buffer, pointer, py_object, resize, string_at) from dataclasses import dataclass import dacite @@ -45,14 +46,13 @@ from . import FabricAdmin from . import clusters as Clusters from . import discovery -from .ChipStack import * from .clusters import Attribute as ClusterAttribute from .clusters import ClusterObjects as ClusterObjects from .clusters import Command as ClusterCommand from .clusters import Objects as GeneratedObjects -from .clusters.CHIPClusters import * +from .clusters.CHIPClusters import ChipClusters from .crypto import p256keypair -from .exceptions import * +from .exceptions import UnknownAttribute, UnknownCommand from .interaction_model import InteractionModelError from .interaction_model import delegate as im from .native import PyChipError @@ -549,7 +549,8 @@ def DiscoverCommissionableNodes(self, filterType: discovery.FilterType = discove discovery.FilterType.COMMISSIONER discovery.FilterType.COMPRESSED_FABRIC_ID - This function will always return a list of CommissionableDevice. When stopOnFirst is set, this function will return when at least one device is discovered or on timeout. + This function will always return a list of CommissionableDevice. When stopOnFirst is set, + this function will return when at least one device is discovered or on timeout. ''' self.CheckIsActive() @@ -767,9 +768,9 @@ def DeviceAvailableCallback(device, err): def ComputeRoundTripTimeout(self, nodeid, upperLayerProcessingTimeoutMs: int = 0): ''' Returns a computed timeout value based on the round-trip time it takes for the peer at the other end of the session to - receive a message, process it and send it back. This is computed based on the session type, the type of transport, sleepy - characteristics of the target and a caller-provided value for the time it takes to process a message at the upper layer on - the target For group sessions. + receive a message, process it and send it back. This is computed based on the session type, the type of transport, + sleepy characteristics of the target and a caller-provided value for the time it takes to process a message + at the upper layer on the target For group sessions. This will result in a session being established if one wasn't already. ''' @@ -778,15 +779,17 @@ def ComputeRoundTripTimeout(self, nodeid, upperLayerProcessingTimeoutMs: int = 0 device.deviceProxy, upperLayerProcessingTimeoutMs)) return res - async def SendCommand(self, nodeid: int, endpoint: int, payload: ClusterObjects.ClusterCommand, responseType=None, timedRequestTimeoutMs: typing.Union[None, int] = None, interactionTimeoutMs: typing.Union[None, int] = None, busyWaitMs: typing.Union[None, int] = None): + async def SendCommand(self, nodeid: int, endpoint: int, payload: ClusterObjects.ClusterCommand, responseType=None, + timedRequestTimeoutMs: typing.Union[None, int] = None, + interactionTimeoutMs: typing.Union[None, int] = None, busyWaitMs: typing.Union[None, int] = 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. + 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. timedWriteTimeoutMs: Timeout for a timed invoke request. Omit or set to 'None' to indicate a non-timed request. - interactionTimeoutMs: Overall timeout for the interaction. Omit or set to 'None' to have the SDK automatically compute the right - timeout value based on transport characteristics as well as the responsiveness of the target. + interactionTimeoutMs: Overall timeout for the interaction. Omit or set to 'None' to have the SDK automatically compute the + right timeout value based on transport characteristics as well as the responsiveness of the target. ''' self.CheckIsActive() @@ -799,12 +802,14 @@ async def SendCommand(self, nodeid: int, endpoint: int, payload: ClusterObjects. EndpointId=endpoint, ClusterId=payload.cluster_id, CommandId=payload.command_id, - ), payload, timedRequestTimeoutMs=timedRequestTimeoutMs, interactionTimeoutMs=interactionTimeoutMs, busyWaitMs=busyWaitMs).raise_on_error() + ), payload, timedRequestTimeoutMs=timedRequestTimeoutMs, + interactionTimeoutMs=interactionTimeoutMs, busyWaitMs=busyWaitMs).raise_on_error() return await future def SendGroupCommand(self, groupid: int, payload: ClusterObjects.ClusterCommand, busyWaitMs: typing.Union[None, int] = None): ''' - Send a group cluster-object encapsulated command to a group_id and get returned a future that can be awaited upon to get confirmation command was sent. + Send a group cluster-object encapsulated command to a group_id and get returned a future + that can be awaited upon to get confirmation command was sent. ''' self.CheckIsActive() @@ -814,18 +819,22 @@ def SendGroupCommand(self, groupid: int, payload: ClusterObjects.ClusterCommand, # None is the expected return for sending group commands. return None - async def WriteAttribute(self, nodeid: int, attributes: typing.List[typing.Tuple[int, ClusterObjects.ClusterAttributeDescriptor, int]], timedRequestTimeoutMs: typing.Union[None, int] = None, interactionTimeoutMs: typing.Union[None, int] = None, busyWaitMs: typing.Union[None, int] = None): + async def WriteAttribute(self, nodeid: int, + attributes: typing.List[typing.Tuple[int, ClusterObjects.ClusterAttributeDescriptor, int]], + timedRequestTimeoutMs: typing.Union[None, int] = None, + interactionTimeoutMs: typing.Union[None, int] = None, busyWaitMs: typing.Union[None, int] = None): ''' Write a list of attributes on a target node. nodeId: Target's Node ID timedWriteTimeoutMs: Timeout for a timed write request. Omit or set to 'None' to indicate a non-timed request. attributes: A list of tuples of type (endpoint, cluster-object): - interactionTimeoutMs: Overall timeout for the interaction. Omit or set to 'None' to have the SDK automatically compute the right - timeout value based on transport characteristics as well as the responsiveness of the target. + interactionTimeoutMs: Overall timeout for the interaction. Omit or set to 'None' to have the SDK automatically compute the + right timeout value based on transport characteristics as well as the responsiveness of the target. E.g - (1, Clusters.UnitTesting.Attributes.XYZAttribute('hello')) -- Write 'hello' to the XYZ attribute on the test cluster to endpoint 1 + (1, Clusters.UnitTesting.Attributes.XYZAttribute('hello')) -- Write 'hello' + to the XYZ attribute on the test cluster to endpoint 1 ''' self.CheckIsActive() @@ -844,7 +853,8 @@ async def WriteAttribute(self, nodeid: int, attributes: typing.List[typing.Tuple v[0], v[1], v[2], 1, v[1].value)) ClusterAttribute.WriteAttributes( - future, eventLoop, device.deviceProxy, attrs, timedRequestTimeoutMs=timedRequestTimeoutMs, interactionTimeoutMs=interactionTimeoutMs, busyWaitMs=busyWaitMs).raise_on_error() + future, eventLoop, device.deviceProxy, attrs, timedRequestTimeoutMs=timedRequestTimeoutMs, + interactionTimeoutMs=interactionTimeoutMs, busyWaitMs=busyWaitMs).raise_on_error() return await future def WriteGroupAttribute( @@ -989,21 +999,24 @@ async def Read(self, nodeid: int, attributes: typing.List[typing.Union[ typing.Tuple[int, typing.Type[ClusterObjects.Cluster]], # Concrete path typing.Tuple[int, typing.Type[ClusterObjects.ClusterAttributeDescriptor]] - ]] = None, dataVersionFilters: typing.List[typing.Tuple[int, typing.Type[ClusterObjects.Cluster], int]] = None, events: typing.List[typing.Union[ - None, # Empty tuple, all wildcard - typing.Tuple[str, int], # all wildcard with urgency set - typing.Tuple[int, int], # Endpoint, - # Wildcard endpoint, Cluster id present - typing.Tuple[typing.Type[ClusterObjects.Cluster], int], - # Wildcard endpoint, Cluster + Event present - typing.Tuple[typing.Type[ClusterObjects.ClusterEvent], int], - # Wildcard event id - typing.Tuple[int, typing.Type[ClusterObjects.Cluster], int], - # Concrete path - typing.Tuple[int, - typing.Type[ClusterObjects.ClusterEvent], int] ]] = None, - eventNumberFilter: typing.Optional[int] = None, returnClusterObject: bool = False, reportInterval: typing.Tuple[int, int] = None, fabricFiltered: bool = True, keepSubscriptions: bool = False): + dataVersionFilters: typing.List[typing.Tuple[int, typing.Type[ClusterObjects.Cluster], int]] = None, events: typing.List[ + typing.Union[ + None, # Empty tuple, all wildcard + typing.Tuple[str, int], # all wildcard with urgency set + typing.Tuple[int, int], # Endpoint, + # Wildcard endpoint, Cluster id present + typing.Tuple[typing.Type[ClusterObjects.Cluster], int], + # Wildcard endpoint, Cluster + Event present + typing.Tuple[typing.Type[ClusterObjects.ClusterEvent], int], + # Wildcard event id + typing.Tuple[int, typing.Type[ClusterObjects.Cluster], int], + # Concrete path + typing.Tuple[int, typing.Type[ClusterObjects.ClusterEvent], int] + ]] = None, + eventNumberFilter: typing.Optional[int] = None, + returnClusterObject: bool = False, reportInterval: typing.Tuple[int, int] = None, + fabricFiltered: bool = True, keepSubscriptions: bool = False): ''' Read a list of attributes and/or events from a target node @@ -1026,12 +1039,15 @@ async def Read(self, nodeid: int, attributes: typing.List[typing.Union[ dataVersionFilters: A list of tuples of (endpoint, cluster, data version). events: A list of tuples of varying types depending on the type of read being requested: - (endpoint, Clusters.ClusterA.EventA, urgent): Endpoint = specific, Cluster = specific, Event = specific, Urgent = True/False - (endpoint, Clusters.ClusterA, urgent): Endpoint = specific, Cluster = specific, Event = *, Urgent = True/False - (Clusters.ClusterA.EventA, urgent): Endpoint = *, Cluster = specific, Event = specific, Urgent = True/False + (endpoint, Clusters.ClusterA.EventA, urgent): Endpoint = specific, + Cluster = specific, Event = specific, Urgent = True/False + (endpoint, Clusters.ClusterA, urgent): Endpoint = specific, + Cluster = specific, Event = *, Urgent = True/False + (Clusters.ClusterA.EventA, urgent): Endpoint = *, + Cluster = specific, Event = specific, Urgent = True/False endpoint: Endpoint = specific, Cluster = *, Event = *, Urgent = True/False - Clusters.ClusterA: Endpoint = *, Cluster = specific, Event = *, Urgent = True/False - '*' or (): Endpoint = *, Cluster = *, Event = *, Urgent = True/False + Clusters.ClusterA: Endpoint = *, Cluster = specific, Event = *, Urgent = True/False + '*' or (): Endpoint = *, Cluster = *, Event = *, Urgent = True/False eventNumberFilter: Optional minimum event number filter. @@ -1054,8 +1070,13 @@ async def Read(self, nodeid: int, attributes: typing.List[typing.Union[ eventPaths = [self._parseEventPathTuple( v) for v in events] if events else None - ClusterAttribute.Read(future=future, eventLoop=eventLoop, device=device.deviceProxy, devCtrl=self, attributes=attributePaths, dataVersionFilters=clusterDataVersionFilters, events=eventPaths, eventNumberFilter=eventNumberFilter, returnClusterObject=returnClusterObject, - subscriptionParameters=ClusterAttribute.SubscriptionParameters(reportInterval[0], reportInterval[1]) if reportInterval else None, fabricFiltered=fabricFiltered, keepSubscriptions=keepSubscriptions).raise_on_error() + ClusterAttribute.Read(future=future, eventLoop=eventLoop, device=device.deviceProxy, devCtrl=self, + attributes=attributePaths, dataVersionFilters=clusterDataVersionFilters, events=eventPaths, + eventNumberFilter=eventNumberFilter, returnClusterObject=returnClusterObject, + subscriptionParameters=ClusterAttribute.SubscriptionParameters( + reportInterval[0], reportInterval[1]) if reportInterval else None, + fabricFiltered=fabricFiltered, + keepSubscriptions=keepSubscriptions).raise_on_error() return await future async def ReadAttribute(self, nodeid: int, attributes: typing.List[typing.Union[ @@ -1069,7 +1090,10 @@ async def ReadAttribute(self, nodeid: int, attributes: typing.List[typing.Union[ typing.Tuple[int, typing.Type[ClusterObjects.Cluster]], # Concrete path typing.Tuple[int, typing.Type[ClusterObjects.ClusterAttributeDescriptor]] - ]], dataVersionFilters: typing.List[typing.Tuple[int, typing.Type[ClusterObjects.Cluster], int]] = None, returnClusterObject: bool = False, reportInterval: typing.Tuple[int, int] = None, fabricFiltered: bool = True, keepSubscriptions: bool = False): + ]], dataVersionFilters: typing.List[typing.Tuple[int, typing.Type[ClusterObjects.Cluster], int]] = None, + returnClusterObject: bool = False, + reportInterval: typing.Tuple[int, int] = None, + fabricFiltered: bool = True, keepSubscriptions: bool = False): ''' Read a list of attributes from a target node, this is a wrapper of DeviceController.Read() @@ -1095,7 +1119,13 @@ async def ReadAttribute(self, nodeid: int, attributes: typing.List[typing.Union[ reportInterval: A tuple of two int-s for (MinIntervalFloor, MaxIntervalCeiling). Used by establishing subscriptions. When not provided, a read request will be sent. ''' - res = await self.Read(nodeid, attributes=attributes, dataVersionFilters=dataVersionFilters, returnClusterObject=returnClusterObject, reportInterval=reportInterval, fabricFiltered=fabricFiltered, keepSubscriptions=keepSubscriptions) + res = await self.Read(nodeid, + attributes=attributes, + dataVersionFilters=dataVersionFilters, + returnClusterObject=returnClusterObject, + reportInterval=reportInterval, + fabricFiltered=fabricFiltered, + keepSubscriptions=keepSubscriptions) if isinstance(res, ClusterAttribute.SubscriptionTransaction): return res else: @@ -1113,18 +1143,24 @@ async def ReadEvent(self, nodeid: int, events: typing.List[typing.Union[ typing.Tuple[int, typing.Type[ClusterObjects.Cluster], int], # Concrete path typing.Tuple[int, typing.Type[ClusterObjects.ClusterEvent], int] - ]], eventNumberFilter: typing.Optional[int] = None, fabricFiltered: bool = True, reportInterval: typing.Tuple[int, int] = None, keepSubscriptions: bool = False): + ]], eventNumberFilter: typing.Optional[int] = None, + fabricFiltered: bool = True, + reportInterval: typing.Tuple[int, int] = None, + keepSubscriptions: bool = False): ''' Read a list of events from a target node, this is a wrapper of DeviceController.Read() nodeId: Target's Node ID events: A list of tuples of varying types depending on the type of read being requested: - (endpoint, Clusters.ClusterA.EventA, urgent): Endpoint = specific, Cluster = specific, Event = specific, Urgent = True/False - (endpoint, Clusters.ClusterA, urgent): Endpoint = specific, Cluster = specific, Event = *, Urgent = True/False - (Clusters.ClusterA.EventA, urgent): Endpoint = *, Cluster = specific, Event = specific, Urgent = True/False + (endpoint, Clusters.ClusterA.EventA, urgent): Endpoint = specific, + Cluster = specific, Event = specific, Urgent = True/False + (endpoint, Clusters.ClusterA, urgent): Endpoint = specific, + Cluster = specific, Event = *, Urgent = True/False + (Clusters.ClusterA.EventA, urgent): Endpoint = *, + Cluster = specific, Event = specific, Urgent = True/False endpoint: Endpoint = specific, Cluster = *, Event = *, Urgent = True/False - Clusters.ClusterA: Endpoint = *, Cluster = specific, Event = *, Urgent = True/False - '*' or (): Endpoint = *, Cluster = *, Event = *, Urgent = True/False + Clusters.ClusterA: Endpoint = *, Cluster = specific, Event = *, Urgent = True/False + '*' or (): Endpoint = *, Cluster = *, Event = *, Urgent = True/False The cluster and events specified above are to be selected from the generated cluster objects. @@ -1137,7 +1173,8 @@ async def ReadEvent(self, nodeid: int, events: typing.List[typing.Union[ reportInterval: A tuple of two int-s for (MinIntervalFloor, MaxIntervalCeiling). Used by establishing subscriptions. When not provided, a read request will be sent. ''' - res = await self.Read(nodeid=nodeid, events=events, eventNumberFilter=eventNumberFilter, fabricFiltered=fabricFiltered, reportInterval=reportInterval, keepSubscriptions=keepSubscriptions) + res = await self.Read(nodeid=nodeid, events=events, eventNumberFilter=eventNumberFilter, + fabricFiltered=fabricFiltered, reportInterval=reportInterval, keepSubscriptions=keepSubscriptions) if isinstance(res, ClusterAttribute.SubscriptionTransaction): return res else: @@ -1162,8 +1199,7 @@ def ZCLSend(self, cluster, command, nodeid, endpoint, groupid, args, blocking=Fa def ZCLReadAttribute(self, cluster, attribute, nodeid, endpoint, groupid, blocking=True): self.CheckIsActive() - req = None - clusterType = eval(f"GeneratedObjects.{cluster}") + clusterType = getattr(GeneratedObjects, cluster) try: attributeType = eval( diff --git a/src/controller/python/chip/ChipReplStartup.py b/src/controller/python/chip/ChipReplStartup.py index 98dc963e2824ec..850d85eb90ffed 100644 --- a/src/controller/python/chip/ChipReplStartup.py +++ b/src/controller/python/chip/ChipReplStartup.py @@ -9,7 +9,7 @@ import chip.logging import chip.native import coloredlogs -from chip.ChipStack import * +from chip.ChipStack import ChipStack from rich import inspect, pretty from rich.console import Console @@ -81,7 +81,10 @@ def mattersetdebug(enableDebugMode: bool = True): parser = argparse.ArgumentParser() parser.add_argument( - "-p", "--storagepath", help="Path to persistent storage configuration file (default: /tmp/repl-storage.json)", action="store", default="/tmp/repl-storage.json") + "-p", "--storagepath", + help="Path to persistent storage configuration file (default: /tmp/repl-storage.json)", + action="store", + default="/tmp/repl-storage.json") parser.add_argument( "-d", "--debug", help="Set default logging level to debug.", action="store_true") args = parser.parse_args() @@ -113,7 +116,9 @@ def mattersetdebug(enableDebugMode: bool = True): console.print( '''\t[red]certificateAuthorityManager[blue]:\tManages a list of CertificateAuthority instances. \t[red]caList[blue]:\t\t\t\tThe list of CertificateAuthority instances. -\t[red]caList\[n]\[m][blue]:\t\t\tA specific FabricAdmin object at index m for the nth CertificateAuthority instance.''') +\t[red]caList[n][m][blue]:\t\t\tA specific FabricAdmin object at index m for the nth CertificateAuthority instance.''') console.print( - f'\n\n[blue]Default CHIP Device Controller (NodeId: {devCtrl.nodeId}): has been initialized to manage [bold red]caList[0].adminList[0][blue] (FabricId = {caList[0].adminList[0].fabricId}), and is available as [bold red]devCtrl') + f'\n\n[blue]Default CHIP Device Controller (NodeId: {devCtrl.nodeId}): ' + f'has been initialized to manage [bold red]caList[0].adminList[0][blue] (FabricId = {caList[0].adminList[0].fabricId}), ' + 'and is available as [bold red]devCtrl') diff --git a/src/controller/python/chip/ChipStack.py b/src/controller/python/chip/ChipStack.py index ad217249937fc6..d64fa347faecf1 100644 --- a/src/controller/python/chip/ChipStack.py +++ b/src/controller/python/chip/ChipStack.py @@ -31,7 +31,8 @@ import os import sys import time -from ctypes import * +from ctypes import (CFUNCTYPE, POINTER, Structure, c_bool, c_char_p, c_int64, c_uint8, c_uint16, c_uint32, c_ulong, c_void_p, + py_object, pythonapi) from threading import Condition, Event, Lock import chip.native @@ -40,10 +41,9 @@ from .ChipUtility import ChipUtility from .clusters import Attribute as ClusterAttribute from .clusters import Command as ClusterCommand -from .clusters.CHIPClusters import * -from .exceptions import * +from .exceptions import ChipStackError, ChipStackException, DeviceError from .interaction_model import delegate as im -from .storage import * +from .storage import PersistentStorage __all__ = [ "DeviceStatusStruct", @@ -174,7 +174,8 @@ def Wait(self, timeoutMs: int = None): @_singleton class ChipStack(object): - def __init__(self, persistentStoragePath: str, installDefaultLogHandler=True, bluetoothAdapter=None, enableServerInteractions=True): + def __init__(self, persistentStoragePath: str, installDefaultLogHandler=True, + bluetoothAdapter=None, enableServerInteractions=True): builtins.enableDebugMode = False self.networkLock = Lock() @@ -362,7 +363,7 @@ def Call(self, callFunct, timeoutMs: int = None): with self.networkLock: res = self.PostTaskOnChipThread(callFunct).Wait(timeoutMs) self.completeEvent.set() - if res == 0 and self.callbackRes != None: + if res == 0 and self.callbackRes is not None: return self.callbackRes return res @@ -417,7 +418,7 @@ def ErrorToException(self, err, devStatusPtr=None): devStatus.SysErrorCode if ( devStatus.SysErrorCode != 0) else None ) - if sysErrorCode != None: + if sysErrorCode is not None: msg = msg + " (system err %d)" % (sysErrorCode) return DeviceError( devStatus.ProfileId, devStatus.StatusCode, sysErrorCode, msg diff --git a/src/controller/python/chip/ChipUtility.py b/src/controller/python/chip/ChipUtility.py index 08ffa6a1225df5..95a2da333a3f39 100644 --- a/src/controller/python/chip/ChipUtility.py +++ b/src/controller/python/chip/ChipUtility.py @@ -24,7 +24,7 @@ from __future__ import absolute_import, print_function import binascii -from ctypes import * +from ctypes import c_byte, c_void_p, cast, memmove class ChipUtility(object): @@ -42,7 +42,7 @@ def VoidPtrToByteArray(ptr, len): @staticmethod def ByteArrayToVoidPtr(array): - if array != None: + if array is not None: if not (isinstance(array, bytes) or isinstance(array, bytearray)): raise TypeError("Array must be an str or a bytearray") return cast((c_byte * len(array)).from_buffer_copy(array), c_void_p) diff --git a/src/controller/python/chip/FabricAdmin.py b/src/controller/python/chip/FabricAdmin.py index 873344d540a4ae..fc20327e628bcc 100644 --- a/src/controller/python/chip/FabricAdmin.py +++ b/src/controller/python/chip/FabricAdmin.py @@ -19,8 +19,7 @@ from __future__ import annotations import logging -from ctypes import * -from typing import * +from typing import List from chip import CertificateAuthority, ChipDeviceCtrl from chip.crypto import p256keypair @@ -66,15 +65,16 @@ def __init__(self, certificateAuthority: CertificateAuthority.CertificateAuthori self._isActive = True self._activeControllers = [] - def NewController(self, nodeId: int = None, paaTrustStorePath: str = "", useTestCommissioner: bool = False, catTags: List[int] = [], keypair: p256keypair.P256Keypair = None): + def NewController(self, nodeId: int = None, paaTrustStorePath: str = "", + useTestCommissioner: bool = False, catTags: List[int] = [], keypair: p256keypair.P256Keypair = None): ''' Create a new chip.ChipDeviceCtrl.ChipDeviceController instance on this fabric. When vending ChipDeviceController instances on a given fabric, each controller instance is associated with a unique fabric index local to the running process. In the underlying FabricTable, each FabricInfo instance can be treated as unique identities that can collide on the same logical fabric. - nodeId: NodeID to be assigned to the controller. Automatically allocates one starting from 112233 if one - is not provided. + nodeId: NodeID to be assigned to the controller. Automatically allocates one starting from 112233 if one + is not provided. paaTrustStorePath: Path to the PAA trust store. If one isn't provided, a suitable default is selected. useTestCommissioner: If a test commmisioner is to be created. @@ -82,7 +82,7 @@ def NewController(self, nodeId: int = None, paaTrustStorePath: str = "", useTest ''' if (not (self._isActive)): raise RuntimeError( - f"FabricAdmin object was previously shutdown and is no longer valid!") + "FabricAdmin object was previously shutdown and is no longer valid!") nodeIdList = [controller.nodeId for controller in self._activeControllers if controller.isActive] if (nodeId is None): @@ -95,7 +95,8 @@ def NewController(self, nodeId: int = None, paaTrustStorePath: str = "", useTest raise RuntimeError(f"Provided NodeId {nodeId} collides with an existing controller instance!") self.logger().warning( - f"Allocating new controller with CaIndex: {self._certificateAuthority.caIndex}, FabricId: 0x{self._fabricId:016X}, NodeId: 0x{nodeId:016X}, CatTags: {catTags}") + f"Allocating new controller with CaIndex: {self._certificateAuthority.caIndex}, " + f"FabricId: 0x{self._fabricId:016X}, NodeId: 0x{nodeId:016X}, CatTags: {catTags}") controller = ChipDeviceCtrl.ChipDeviceController( opCredsContext=self._certificateAuthority.GetOpCredsContext(), diff --git a/src/controller/python/chip/ble/scan_devices.py b/src/controller/python/chip/ble/scan_devices.py index 5422afb7cbb88b..5e9ee24dadd1c4 100644 --- a/src/controller/python/chip/ble/scan_devices.py +++ b/src/controller/python/chip/ble/scan_devices.py @@ -130,7 +130,7 @@ def ScanError(self, errorCode): def DiscoverSync(timeoutMs: int, adapter=None) -> Generator[DeviceInfo, None, None]: - """Discover BLE devices over the specified period of time. + """Discover BLE devices over the specified period of time. NOTE: devices are not guaranteed to be unique. New entries are returned as soon as the underlying BLE manager detects changes. diff --git a/src/controller/python/chip/clusters/Attribute.py b/src/controller/python/chip/clusters/Attribute.py index 382279bccaf15f..6f2b52ff179ca3 100644 --- a/src/controller/python/chip/clusters/Attribute.py +++ b/src/controller/python/chip/clusters/Attribute.py @@ -29,6 +29,7 @@ from enum import Enum, unique from typing import Any, Callable, Dict, List, Optional, Tuple, Union +import chip import chip.exceptions import chip.interaction_model import chip.tlv @@ -149,11 +150,11 @@ def __init__(self, ClusterType: Cluster = None, AttributeType: ClusterAttributeD raise KeyError(f"No Schema found for Attribute {Path}") # Next, let's figure out the label. - for field in self.ClusterType.descriptor.Fields: - if (field.Tag != self.AttributeType.attribute_id): + for c_field in self.ClusterType.descriptor.Fields: + if (c_field.Tag != self.AttributeType.attribute_id): continue - self.AttributeName = field.Label + self.AttributeName = c_field.Label if (self.AttributeName is None): raise KeyError(f"Unable to resolve name for Attribute {Path}") @@ -212,7 +213,8 @@ class EventHeader: Timestamp: int = None TimestampType: EventTimestampType = None - def __init__(self, EndpointId: int = None, ClusterId: int = None, EventId: int = None, EventNumber=None, Priority=None, Timestamp=None, TimestampType=None): + def __init__(self, EndpointId: int = None, ClusterId: int = None, + EventId: int = None, EventNumber=None, Priority=None, Timestamp=None, TimestampType=None): self.EndpointId = EndpointId self.ClusterId = ClusterId self.EventId = EventId @@ -222,7 +224,8 @@ def __init__(self, EndpointId: int = None, ClusterId: int = None, EventId: int = self.TimestampType = TimestampType def __str__(self) -> str: - return f"{self.EndpointId}/{self.ClusterId}/{self.EventId}/{self.EventNumber}/{self.Priority}/{self.Timestamp}/{self.TimestampType}" + return (f"{self.EndpointId}/{self.ClusterId}/{self.EventId}/" + f"{self.EventNumber}/{self.Priority}/{self.Timestamp}/{self.TimestampType}") @dataclass @@ -291,8 +294,9 @@ class EventReadResult(EventStatus): def _BuildAttributeIndex(): ''' Build internal attribute index for locating the corresponding cluster object by path in the future. - We do this because this operation will take a long time when there are lots of attributes, it takes about 300ms for a single query. - This is acceptable during init, but unacceptable when the server returns lots of attributes at the same time. + We do this because this operation will take a long time when there are lots of attributes, + it takes about 300ms for a single query. + This is acceptable during init, but unacceptable when the server returns lots of attributes at the same time. ''' for clusterName, obj in inspect.getmembers(sys.modules['chip.clusters.Objects']): if ('chip.clusters.Objects' in str(obj)) and inspect.isclass(obj): @@ -375,7 +379,8 @@ def UpdateTLV(self, path: AttributePath, dataVersion: int, data: Union[bytes, V if (path.ClusterId not in endpointCache): endpointCache[path.ClusterId] = {} - # All attributes from the same cluster instance should have the same dataVersion, so we can set the dataVersion of the cluster to the dataVersion with a random attribute. + # All attributes from the same cluster instance should have the same dataVersion, + # so we can set the dataVersion of the cluster to the dataVersion with a random attribute. endpointVersion[path.ClusterId] = dataVersion clusterCache = endpointCache[path.ClusterId] @@ -388,14 +393,18 @@ def UpdateCachedData(self, changedPathSet: set[AttributePath]): ''' This converts the raw TLV data into a cluster object format. Two formats are available: - 1. Attribute-View (returnClusterObject=False): Dict[EndpointId, Dict[ClusterObjectType, Dict[AttributeObjectType, Dict[AttributeValue, DataVersion]]]] + 1. Attribute-View (returnClusterObject=False): Dict[EndpointId, + Dict[ClusterObjectType, + Dict[AttributeObjectType, Dict[AttributeValue, DataVersion]]]] 2. Cluster-View (returnClusterObject=True): Dict[EndpointId, Dict[ClusterObjectType, ClusterValue]] - In the attribute-view, only attributes that match the original path criteria are present in the dictionary. The attribute values can - either be the actual data for the attribute, or a ValueDecodeFailure in the case of non-success IM status codes, or other errors encountered during decode. + In the attribute-view, only attributes that match the original path criteria are present in the dictionary. + The attribute values can either be the actual data for the attribute, or a ValueDecodeFailure in the case of + non-success IM status codes, or other errors encountered during decode. In the cluster-view, a cluster object that corresponds to all attributes on a given cluster instance is returned, - regardless of the subset of attributes read. For attributes not returned in the report, defaults are used. If a cluster cannot be decoded, + regardless of the subset of attributes read. For attributes not returned in the report, + defaults are used. If a cluster cannot be decoded, instead of a cluster object value, a ValueDecodeFailure shall be present. ''' @@ -554,7 +563,8 @@ def Callback(transaction: SubscriptionTransaction) def SetAttributeUpdateCallback(self, callback: Callable[[TypedAttributePath, SubscriptionTransaction], None]): ''' - Sets the callback function for the attribute value change event, accepts a Callable accepts an attribute path and the cached data. + Sets the callback function for the attribute value change event, + accepts a Callable accepts an attribute path and the cached data. ''' if callback is not None: self._onAttributeChangeCb = callback @@ -565,7 +575,8 @@ def SetEventUpdateCallback(self, callback: Callable[[EventReadResult, Subscripti def SetErrorCallback(self, callback: Callable[[int, SubscriptionTransaction], None]): ''' - Sets the callback function in case a subscription error occured, accepts a Callable accepts an error code and the cached data. + Sets the callback function in case a subscription error occured, + accepts a Callable accepts an error code and the cached data. ''' if callback is not None: self._onErrorCb = callback @@ -604,7 +615,8 @@ def __repr__(self): return f'' -async def DefaultResubscriptionAttemptedCallback(transaction: SubscriptionTransaction, terminationError, nextResubscribeIntervalMsec): +async def DefaultResubscriptionAttemptedCallback(transaction: SubscriptionTransaction, + terminationError, nextResubscribeIntervalMsec): print(f"Previous subscription failed with Error: {terminationError} - re-subscribing in {nextResubscribeIntervalMsec}ms...") @@ -626,7 +638,7 @@ def DefaultEventChangeCallback(data: EventReadResult, transaction: SubscriptionT def DefaultErrorCallback(chipError: int, transaction: SubscriptionTransaction): - print("Error during Subscription: Chip Stack Error %d".format(chipError)) + print(f"Error during Subscription: Chip Stack Error {chipError}") def _BuildEventIndex(): @@ -683,7 +695,7 @@ def handleAttributeData(self, path: AttributePathWithListIndex, dataVersion: int imStatus = status try: imStatus = chip.interaction_model.Status(status) - except: + except chip.exceptions.ChipStackException: pass if (imStatus != chip.interaction_model.Status.Success): @@ -716,7 +728,8 @@ def handleEventData(self, header: EventHeader, path: EventPath, data: bytes, sta eventValue = eventType.FromTLV(data) except Exception as ex: logging.error( - f"Error convering TLV to Cluster Object for path: Endpoint = {path.EndpointId}/Cluster = {path.ClusterId}/Event = {path.EventId}") + f"Error convering TLV to Cluster Object for path: Endpoint = {path.EndpointId}/" + f"Cluster = {path.ClusterId}/Event = {path.EventId}") logging.error( f"Failed Cluster Object: {str(eventType)}") logging.error(ex) @@ -765,7 +778,8 @@ def handleResubscriptionAttempted(self, terminationCause: PyChipError, nextResub self._subscription_handler, terminationCause.code, nextResubscribeIntervalMsec)) else: self._event_loop.call_soon_threadsafe( - self._subscription_handler._onResubscriptionAttemptedCb, self._subscription_handler, terminationCause.code, nextResubscribeIntervalMsec) + self._subscription_handler._onResubscriptionAttemptedCb, + self._subscription_handler, terminationCause.code, nextResubscribeIntervalMsec) def _handleReportBegin(self): pass @@ -833,7 +847,7 @@ def handleResponse(self, path: AttributePath, status: int): try: imStatus = chip.interaction_model.Status(status) self._resultData.append(AttributeWriteResult(Path=path, Status=imStatus)) - except: + except chip.exceptions.ChipStackException: self._resultData.append(AttributeWriteResult(Path=path, Status=status)) def handleError(self, chipError: PyChipError): @@ -889,7 +903,8 @@ def _OnReadAttributeDataCallback(closure, dataVersion: int, endpoint: int, clust @_OnReadEventDataCallbackFunct -def _OnReadEventDataCallback(closure, endpoint: int, cluster: int, event: c_uint64, number: int, priority: int, timestamp: int, timestampType: int, data, len, status): +def _OnReadEventDataCallback(closure, endpoint: int, cluster: int, event: c_uint64, + number: int, priority: int, timestamp: int, timestampType: int, data, len, status): dataBytes = ctypes.string_at(data, len) path = EventPath(ClusterId=cluster, EventId=event) @@ -955,7 +970,9 @@ def _OnWriteDoneCallback(closure): closure.handleDone() -def WriteAttributes(future: Future, eventLoop, device, attributes: List[AttributeWriteRequest], timedRequestTimeoutMs: Union[None, int] = None, interactionTimeoutMs: Union[None, int] = None, busyWaitMs: Union[None, int] = None) -> PyChipError: +def WriteAttributes(future: Future, eventLoop, device, + attributes: List[AttributeWriteRequest], timedRequestTimeoutMs: Union[None, int] = None, + interactionTimeoutMs: Union[None, int] = None, busyWaitMs: Union[None, int] = None) -> PyChipError: handle = chip.native.GetLibraryHandle() writeargs = [] @@ -1026,7 +1043,11 @@ def WriteGroupAttributes(groupId: int, devCtrl: c_void_p, attributes: List[Attri ) -def Read(future: Future, eventLoop, device, devCtrl, attributes: List[AttributePath] = None, dataVersionFilters: List[DataVersionFilter] = None, events: List[EventPath] = None, eventNumberFilter: Optional[int] = None, returnClusterObject: bool = True, subscriptionParameters: SubscriptionParameters = None, fabricFiltered: bool = True, keepSubscriptions: bool = False) -> PyChipError: +def Read(future: Future, eventLoop, device, devCtrl, + attributes: List[AttributePath] = None, dataVersionFilters: List[DataVersionFilter] = None, + events: List[EventPath] = None, eventNumberFilter: Optional[int] = None, returnClusterObject: bool = True, + subscriptionParameters: SubscriptionParameters = None, + fabricFiltered: bool = True, keepSubscriptions: bool = False) -> PyChipError: if (not attributes) and dataVersionFilters: raise ValueError( "Must provide valid attribute list when data version filters is not null") @@ -1058,17 +1079,17 @@ def Read(future: Future, eventLoop, device, devCtrl, attributes: List[AttributeP filter.EndpointId = f.EndpointId else: raise ValueError( - f"DataVersionFilter must provide EndpointId.") + "DataVersionFilter must provide EndpointId.") if f.ClusterId is not None: filter.ClusterId = f.ClusterId else: raise ValueError( - f"DataVersionFilter must provide ClusterId.") + "DataVersionFilter must provide ClusterId.") if f.DataVersion is not None: filter.DataVersion = f.DataVersion else: raise ValueError( - f"DataVersionFilter must provide DataVersion.") + "DataVersionFilter must provide DataVersion.") filter = chip.interaction_model.DataVersionFilterIBstruct.build( filter) readargs.append(ctypes.c_char_p(filter)) @@ -1127,12 +1148,23 @@ def Read(future: Future, eventLoop, device, devCtrl, attributes: List[AttributeP return res -def ReadAttributes(future: Future, eventLoop, device, devCtrl, attributes: List[AttributePath], dataVersionFilters: List[DataVersionFilter] = None, returnClusterObject: bool = True, subscriptionParameters: SubscriptionParameters = None, fabricFiltered: bool = True) -> int: - return Read(future=future, eventLoop=eventLoop, device=device, devCtrl=devCtrl, attributes=attributes, dataVersionFilters=dataVersionFilters, events=None, returnClusterObject=returnClusterObject, subscriptionParameters=subscriptionParameters, fabricFiltered=fabricFiltered) +def ReadAttributes(future: Future, eventLoop, device, devCtrl, + attributes: List[AttributePath], dataVersionFilters: List[DataVersionFilter] = None, + returnClusterObject: bool = True, + subscriptionParameters: SubscriptionParameters = None, fabricFiltered: bool = True) -> int: + return Read(future=future, eventLoop=eventLoop, device=device, + devCtrl=devCtrl, attributes=attributes, dataVersionFilters=dataVersionFilters, + events=None, returnClusterObject=returnClusterObject, + subscriptionParameters=subscriptionParameters, fabricFiltered=fabricFiltered) -def ReadEvents(future: Future, eventLoop, device, devCtrl, events: List[EventPath], eventNumberFilter=None, returnClusterObject: bool = True, subscriptionParameters: SubscriptionParameters = None, fabricFiltered: bool = True) -> int: - return Read(future=future, eventLoop=eventLoop, device=device, devCtrl=devCtrl, attributes=None, dataVersionFilters=None, events=events, eventNumberFilter=eventNumberFilter, returnClusterObject=returnClusterObject, subscriptionParameters=subscriptionParameters, fabricFiltered=fabricFiltered) +def ReadEvents(future: Future, eventLoop, device, devCtrl, + events: List[EventPath], eventNumberFilter=None, returnClusterObject: bool = True, + subscriptionParameters: SubscriptionParameters = None, fabricFiltered: bool = True) -> int: + return Read(future=future, eventLoop=eventLoop, device=device, devCtrl=devCtrl, attributes=None, + dataVersionFilters=None, events=events, eventNumberFilter=eventNumberFilter, + returnClusterObject=returnClusterObject, + subscriptionParameters=subscriptionParameters, fabricFiltered=fabricFiltered) def Init(): @@ -1161,13 +1193,16 @@ def Init(): _OnWriteResponseCallbackFunct, _OnWriteErrorCallbackFunct, _OnWriteDoneCallbackFunct]) handle.pychip_ReadClient_Read.restype = PyChipError setter.Set('pychip_ReadClient_InitCallbacks', None, [ - _OnReadAttributeDataCallbackFunct, _OnReadEventDataCallbackFunct, _OnSubscriptionEstablishedCallbackFunct, _OnResubscriptionAttemptedCallbackFunct, _OnReadErrorCallbackFunct, _OnReadDoneCallbackFunct, + _OnReadAttributeDataCallbackFunct, _OnReadEventDataCallbackFunct, + _OnSubscriptionEstablishedCallbackFunct, _OnResubscriptionAttemptedCallbackFunct, + _OnReadErrorCallbackFunct, _OnReadDoneCallbackFunct, _OnReportBeginCallbackFunct, _OnReportEndCallbackFunct]) handle.pychip_WriteClient_InitCallbacks( _OnWriteResponseCallback, _OnWriteErrorCallback, _OnWriteDoneCallback) handle.pychip_ReadClient_InitCallbacks( - _OnReadAttributeDataCallback, _OnReadEventDataCallback, _OnSubscriptionEstablishedCallback, _OnResubscriptionAttemptedCallback, _OnReadErrorCallback, _OnReadDoneCallback, + _OnReadAttributeDataCallback, _OnReadEventDataCallback, + _OnSubscriptionEstablishedCallback, _OnResubscriptionAttemptedCallback, _OnReadErrorCallback, _OnReadDoneCallback, _OnReportBeginCallback, _OnReportEndCallback) _BuildAttributeIndex() diff --git a/src/controller/python/chip/clusters/ClusterObjects.py b/src/controller/python/chip/clusters/ClusterObjects.py index 99893c4b186579..7496099a301e91 100644 --- a/src/controller/python/chip/clusters/ClusterObjects.py +++ b/src/controller/python/chip/clusters/ClusterObjects.py @@ -37,7 +37,10 @@ def GetUnionUnderlyingType(typeToCheck, matchingType=None): for t in typing.get_args(typeToCheck): if (matchingType is None): - if (t != type(None) and t != Nullable): + # Comparison below explicitly not using 'isinstance' as that doesn't do what we want. + # type_none is simple hack for Flake8 E721 + type_none = type(None) + if (t != type_none and t != Nullable): return t else: if (t == matchingType): @@ -50,7 +53,7 @@ def GetUnionUnderlyingType(typeToCheck, matchingType=None): class ClusterObjectFieldDescriptor: Label: str = '' Tag: int = None - Type: Type = None + Type: type = None def _PutSingleElementToTLV(self, tag, val, elementType, writer: tlv.TLVWriter, debugPath: str = '?'): if issubclass(elementType, ClusterObject): @@ -111,15 +114,15 @@ class ClusterObjectDescriptor: Fields: List[ClusterObjectFieldDescriptor] def GetFieldByTag(self, tag: int) -> ClusterObjectFieldDescriptor: - for field in self.Fields: - if field.Tag == tag: - return field + for _field in self.Fields: + if _field.Tag == tag: + return _field return None def GetFieldByLabel(self, label: str) -> ClusterObjectFieldDescriptor: - for field in self.Fields: - if field.Label == label: - return field + for _field in self.Fields: + if _field.Label == label: + return _field return None def _ConvertNonArray(self, debugPath: str, elementType, value: Any) -> Any: @@ -176,10 +179,9 @@ def TLVToDict(self, tlvBuf: bytes) -> Dict[str, Any]: def DictToTLVWithWriter(self, debugPath: str, tag, data: Mapping, writer: tlv.TLVWriter): writer.startStructure(tag) - for field in self.Fields: - val = data.get(field.Label, None) - field.PutFieldToTLV(field.Tag, val, writer, - debugPath + f'.{field.Label}') + for _field in self.Fields: + val = data.get(_field.Label, None) + _field.PutFieldToTLV(_field.Tag, val, writer, debugPath + f'.{_field.Label}') writer.endContainer() def DictToTLV(self, data: dict) -> bytes: @@ -268,9 +270,11 @@ class ClusterAttributeDescriptor: ''' The ClusterAttributeDescriptor is used for holding an attribute's metadata like its cluster id, attribute id and its type. - Users should not initialize an object based on this class. Instead, users should pass the subclass objects to tell some methods what they want. + Users should not initialize an object based on this class. Instead, users should pass + the subclass objects to tell some methods what they want. - The implementation of this functions is quite tricky, it will create a cluster object on-the-fly, and use it for actual encode / decode routine to save lines of code. + The implementation of this functions is quite tricky, it will create a cluster object on-the-fly, + and use it for actual encode / decode routine to save lines of code. ''' def __init_subclass__(cls, *args, **kwargs) -> None: @@ -297,7 +301,8 @@ def ToTLV(cls, tag: Union[int, None], value): @classmethod def FromTLV(cls, tlvBuffer: bytes): obj_class = cls._cluster_object - return obj_class.FromDict(obj_class.descriptor.TagDictToLabelDict('', {0: tlv.TLVReader(tlvBuffer).get().get('Any', {})})).Value + return obj_class.FromDict( + obj_class.descriptor.TagDictToLabelDict('', {0: tlv.TLVReader(tlvBuffer).get().get('Any', {})})).Value @classmethod def FromTagDictOrRawValue(cls, val: Any): diff --git a/src/controller/python/chip/clusters/Command.py b/src/controller/python/chip/clusters/Command.py index 5ce2f4c620db4a..203c92aeb49744 100644 --- a/src/controller/python/chip/clusters/Command.py +++ b/src/controller/python/chip/clusters/Command.py @@ -107,7 +107,7 @@ def _handleError(self, imError: Status, chipError: PyChipError, exception: Excep try: self._future.set_exception( chip.interaction_model.InteractionModelError(chip.interaction_model.Status(imError.IMStatus), imError.ClusterStatus)) - except Exception as e2: + except Exception: logger.exception("Failed to map interaction model status received: %s. Remapping to Failure." % imError) self._future.set_exception(chip.interaction_model.InteractionModelError( chip.interaction_model.Status.Failure, imError.ClusterStatus)) diff --git a/src/controller/python/chip/clusters/__init__.py b/src/controller/python/chip/clusters/__init__.py index 32369c56d4fd68..f1f357d308ca6c 100644 --- a/src/controller/python/chip/clusters/__init__.py +++ b/src/controller/python/chip/clusters/__init__.py @@ -23,4 +23,70 @@ """Provides Python APIs for CHIP.""" from . import Attribute, CHIPClusters, Command -from .Objects import * +from .Objects import (AccessControl, AccountLogin, Actions, ActivatedCarbonFilterMonitoring, AdministratorCommissioning, AirQuality, + ApplicationBasic, ApplicationLauncher, AudioOutput, BallastConfiguration, BarrierControl, BasicInformation, + BinaryInputBasic, Binding, BooleanState, BridgedDeviceBasicInformation, BromateConcentrationMeasurement, + BromodichloromethaneConcentrationMeasurement, BromoformConcentrationMeasurement, + CarbonDioxideConcentrationMeasurement, CarbonMonoxideConcentrationMeasurement, CeramicFilterMonitoring, + Channel, ChloraminesConcentrationMeasurement, ChlorineConcentrationMeasurement, + ChlorodibromomethaneConcentrationMeasurement, ChloroformConcentrationMeasurement, ColorControl, + ContentLauncher, CopperConcentrationMeasurement, Descriptor, DiagnosticLogs, DishwasherAlarm, DishwasherMode, + DissolvedOxygenConcentrationMeasurement, DoorLock, ElectricalMeasurement, ElectrostaticFilterMonitoring, + EthernetNetworkDiagnostics, EthyleneConcentrationMeasurement, EthyleneOxideConcentrationMeasurement, + FanControl, FaultInjection, FecalColiformEColiConcentrationMeasurement, FixedLabel, FlowMeasurement, + FluorideConcentrationMeasurement, FormaldehydeConcentrationMeasurement, FuelTankMonitoring, + GeneralCommissioning, GeneralDiagnostics, GroupKeyManagement, Groups, HaloaceticAcidsConcentrationMeasurement, + HepaFilterMonitoring, HydrogenConcentrationMeasurement, HydrogenSulfideConcentrationMeasurement, + IcdManagement, Identify, IlluminanceMeasurement, InkCartridgeMonitoring, IonizingFilterMonitoring, + KeypadInput, LaundryWasherControls, LaundryWasherMode, LeadConcentrationMeasurement, LevelControl, + LocalizationConfiguration, LowPower, ManganeseConcentrationMeasurement, MediaInput, MediaPlayback, ModeSelect, + NetworkCommissioning, NitricOxideConcentrationMeasurement, NitrogenDioxideConcentrationMeasurement, + OccupancySensing, OnOff, OnOffSwitchConfiguration, OperationalCredentials, OperationalState, + OtaSoftwareUpdateProvider, OtaSoftwareUpdateRequestor, OxygenConcentrationMeasurement, + OzoneConcentrationMeasurement, OzoneFilterMonitoring, Pm1ConcentrationMeasurement, + Pm10ConcentrationMeasurement, Pm25ConcentrationMeasurement, PowerSource, PowerSourceConfiguration, + PressureMeasurement, ProxyConfiguration, ProxyDiscovery, ProxyValid, PulseWidthModulation, + PumpConfigurationAndControl, RadonConcentrationMeasurement, RefrigeratorAlarm, + RefrigeratorAndTemperatureControlledCabinetMode, RelativeHumidityMeasurement, RvcCleanMode, + RvcOperationalState, RvcRunMode, Scenes, SmokeCoAlarm, SodiumConcentrationMeasurement, SoftwareDiagnostics, + SulfateConcentrationMeasurement, SulfurDioxideConcentrationMeasurement, Switch, TargetNavigator, + TemperatureControl, TemperatureMeasurement, Thermostat, ThermostatUserInterfaceConfiguration, + ThreadNetworkDiagnostics, TimeFormatLocalization, TimeSynchronization, TonerCartridgeMonitoring, + TotalColiformBacteriaConcentrationMeasurement, TotalTrihalomethanesConcentrationMeasurement, + TotalVolatileOrganicCompoundsConcentrationMeasurement, TurbidityConcentrationMeasurement, UnitLocalization, + UnitTesting, UserLabel, UvFilterMonitoring, WakeOnLan, WaterTankMonitoring, WiFiNetworkDiagnostics, + WindowCovering, ZeoliteFilterMonitoring) + +__all__ = [Attribute, CHIPClusters, Command, AccessControl, AccountLogin, Actions, ActivatedCarbonFilterMonitoring, AdministratorCommissioning, AirQuality, + ApplicationBasic, ApplicationLauncher, AudioOutput, BallastConfiguration, BarrierControl, BasicInformation, + BinaryInputBasic, Binding, BooleanState, BridgedDeviceBasicInformation, BromateConcentrationMeasurement, + BromodichloromethaneConcentrationMeasurement, BromoformConcentrationMeasurement, + CarbonDioxideConcentrationMeasurement, CarbonMonoxideConcentrationMeasurement, CeramicFilterMonitoring, + Channel, ChloraminesConcentrationMeasurement, ChlorineConcentrationMeasurement, + ChlorodibromomethaneConcentrationMeasurement, ChloroformConcentrationMeasurement, ColorControl, + ContentLauncher, CopperConcentrationMeasurement, Descriptor, DiagnosticLogs, DishwasherAlarm, DishwasherMode, + DissolvedOxygenConcentrationMeasurement, DoorLock, ElectricalMeasurement, ElectrostaticFilterMonitoring, + EthernetNetworkDiagnostics, EthyleneConcentrationMeasurement, EthyleneOxideConcentrationMeasurement, + FanControl, FaultInjection, FecalColiformEColiConcentrationMeasurement, FixedLabel, FlowMeasurement, + FluorideConcentrationMeasurement, FormaldehydeConcentrationMeasurement, FuelTankMonitoring, + GeneralCommissioning, GeneralDiagnostics, GroupKeyManagement, Groups, HaloaceticAcidsConcentrationMeasurement, + HepaFilterMonitoring, HydrogenConcentrationMeasurement, HydrogenSulfideConcentrationMeasurement, + IcdManagement, Identify, IlluminanceMeasurement, InkCartridgeMonitoring, IonizingFilterMonitoring, + KeypadInput, LaundryWasherControls, LaundryWasherMode, LeadConcentrationMeasurement, LevelControl, + LocalizationConfiguration, LowPower, ManganeseConcentrationMeasurement, MediaInput, MediaPlayback, ModeSelect, + NetworkCommissioning, NitricOxideConcentrationMeasurement, NitrogenDioxideConcentrationMeasurement, + OccupancySensing, OnOff, OnOffSwitchConfiguration, OperationalCredentials, OperationalState, + OtaSoftwareUpdateProvider, OtaSoftwareUpdateRequestor, OxygenConcentrationMeasurement, + OzoneConcentrationMeasurement, OzoneFilterMonitoring, Pm1ConcentrationMeasurement, + Pm10ConcentrationMeasurement, Pm25ConcentrationMeasurement, PowerSource, PowerSourceConfiguration, + PressureMeasurement, ProxyConfiguration, ProxyDiscovery, ProxyValid, PulseWidthModulation, + PumpConfigurationAndControl, RadonConcentrationMeasurement, RefrigeratorAlarm, + RefrigeratorAndTemperatureControlledCabinetMode, RelativeHumidityMeasurement, RvcCleanMode, + RvcOperationalState, RvcRunMode, Scenes, SmokeCoAlarm, SodiumConcentrationMeasurement, SoftwareDiagnostics, + SulfateConcentrationMeasurement, SulfurDioxideConcentrationMeasurement, Switch, TargetNavigator, + TemperatureControl, TemperatureMeasurement, Thermostat, ThermostatUserInterfaceConfiguration, + ThreadNetworkDiagnostics, TimeFormatLocalization, TimeSynchronization, TonerCartridgeMonitoring, + TotalColiformBacteriaConcentrationMeasurement, TotalTrihalomethanesConcentrationMeasurement, + TotalVolatileOrganicCompoundsConcentrationMeasurement, TurbidityConcentrationMeasurement, UnitLocalization, + UnitTesting, UserLabel, UvFilterMonitoring, WakeOnLan, WaterTankMonitoring, WiFiNetworkDiagnostics, + WindowCovering, ZeoliteFilterMonitoring] diff --git a/src/controller/python/chip/discovery/__init__.py b/src/controller/python/chip/discovery/__init__.py index e6a03466090c1c..bfc79577b75169 100644 --- a/src/controller/python/chip/discovery/__init__.py +++ b/src/controller/python/chip/discovery/__init__.py @@ -142,7 +142,7 @@ def ResolutionThread(self): if self.NeedsCallback(item): try: item.callback(item.result) - except: + except Exception: logging.exception("Node discovery callback failed") else: updatedDiscoveries.append(item) diff --git a/src/controller/python/chip/interaction_model/__init__.py b/src/controller/python/chip/interaction_model/__init__.py index a2c9e1479397fa..bd064f2df87d34 100644 --- a/src/controller/python/chip/interaction_model/__init__.py +++ b/src/controller/python/chip/interaction_model/__init__.py @@ -28,7 +28,8 @@ from .delegate import AttributePath, AttributePathIBstruct, DataVersionFilterIBstruct, EventPath, EventPathIBstruct -__all__ = ["Status", "InteractionModelError"] +__all__ = ["AttributePath", "AttributePathIBstruct", "DataVersionFilterIBstruct", + "EventPath", "EventPathIBstruct", "Status", "InteractionModelError"] # defined src/controller/python/chip/interaction_model/Delegate.h diff --git a/src/controller/python/chip/interaction_model/delegate.py b/src/controller/python/chip/interaction_model/delegate.py index 4c52cabf1a767a..f5037ec44cf9f4 100644 --- a/src/controller/python/chip/interaction_model/delegate.py +++ b/src/controller/python/chip/interaction_model/delegate.py @@ -109,7 +109,8 @@ class AttributeWriteResult: # typedef void (*PythonInteractionModelDelegate_OnCommandResponseStatusCodeReceivedFunct)(uint64_t commandSenderPtr, # void * commandStatusBuf); -# typedef void (*PythonInteractionModelDelegate_OnCommandResponseProtocolErrorFunct)(uint64_t commandSenderPtr, uint8_t commandIndex); +# typedef void (*PythonInteractionModelDelegate_OnCommandResponseProtocolErrorFunct)(uint64_t commandSenderPtr, +# uint8_t commandIndex); # typedef void (*PythonInteractionModelDelegate_OnCommandResponseFunct)(uint64_t commandSenderPtr, uint32_t error); _OnCommandResponseStatusCodeReceivedFunct = CFUNCTYPE( None, c_uint64, c_void_p, c_uint32) @@ -183,7 +184,8 @@ def _OnWriteResponseStatus(IMAttributeWriteResult, IMAttributeWriteResultLen): appId = status["AppIdentifier"] if appId < 256: - # For all attribute write requests using CHIPCluster API, appId is filled by CHIPDevice, and should be smaller than 256 (UINT8_MAX). + # For all attribute write requests using CHIPCluster API, appId is filled by CHIPDevice, + # and should be smaller than 256 (UINT8_MAX). appId = DEFAULT_ATTRIBUTEWRITE_APPID with _writeStatusDictLock: diff --git a/src/controller/python/chip/internal/commissioner.py b/src/controller/python/chip/internal/commissioner.py index b5cfa62555dd32..c20043cf6ad3df 100644 --- a/src/controller/python/chip/internal/commissioner.py +++ b/src/controller/python/chip/internal/commissioner.py @@ -50,7 +50,7 @@ def OnPairingComplete(err: int): class PairingState(Enum): - """States throughout a pairing flow. + """States throughout a pairing flow. Devices generally go through: initialized -> pairing -> netcreds -> opcreds -> done (initialized) @@ -68,7 +68,7 @@ class Commissioner: The commissioner is a DeviceController that supports pairing. Since the device - controller supports multiple devices, this class is expected to be used + controller supports multiple devices, this class is expected to be used as a singleton """ @@ -108,7 +108,7 @@ def _SetNativeCallSignatues(handle: ctypes.CDLL): setter.Set('pychip_internal_Commissioner_Unpair', ctypes.c_uint32, [Commissioner_p, ctypes.c_uint64]) setter.Set('pychip_internal_Commissioner_BleConnectForPairing', - ctypes.c_uint32, [Commissioner_p, ctypes.c_uint64, ctypes.c_uint32, cctypes._uint16]) + ctypes.c_uint32, [Commissioner_p, ctypes.c_uint64, ctypes.c_uint32, ctypes.c_uint16]) setter.Set('pychip_internal_PairingDelegate_SetPairingCompleteCallback', None, [ PairingComplete]) diff --git a/src/controller/python/chip/setup_payload/setup_payload.py b/src/controller/python/chip/setup_payload/setup_payload.py index ea5f786fa6140d..c6a6b6a690e423 100644 --- a/src/controller/python/chip/setup_payload/setup_payload.py +++ b/src/controller/python/chip/setup_payload/setup_payload.py @@ -14,7 +14,7 @@ # limitations under the License. # -from ctypes import CFUNCTYPE, c_char_p, c_int32, c_uint8 +from ctypes import CFUNCTYPE, c_char_p, c_int32, c_uint8, c_uint16, c_uint32 from typing import Optional from chip.exceptions import ChipStackError @@ -117,7 +117,7 @@ def __InitNativeFunctions(self, chipLib): [c_char_p, SetupPayload.AttributeVisitor, SetupPayload.VendorAttributeVisitor]) setter.Set("pychip_SetupPayload_PrintOnboardingCodes", c_int32, - [c_uint32, c_uint16, c_uint16, c_uint16, uint8_t, uint8_t, uint8_t]) + [c_uint32, c_uint16, c_uint16, c_uint16, c_uint8, c_uint8, c_uint8]) # Getters from parsed contents. # Prefer using the methods below to access setup payload information once parse. diff --git a/src/controller/python/chip/storage/__init__.py b/src/controller/python/chip/storage/__init__.py index 07fdb1f6615dff..385efca6be1c8c 100644 --- a/src/controller/python/chip/storage/__init__.py +++ b/src/controller/python/chip/storage/__init__.py @@ -23,7 +23,7 @@ import ctypes import json import logging -from ctypes import * +from ctypes import CFUNCTYPE, POINTER, c_bool, c_char, c_char_p, c_uint16, c_void_p, py_object from typing import Dict import chip.exceptions @@ -111,7 +111,7 @@ def __init__(self, path: str = None, jsonData: Dict = None): if (path is not None): self.logger().warn(f"Initializing persistent storage from file: {path}") else: - self.logger().warn(f"Initializing persistent storage from dict") + self.logger().warn("Initializing persistent storage from dict") self._handle = chip.native.GetLibraryHandle() self._isActive = True @@ -138,11 +138,11 @@ def __init__(self, path: str = None, jsonData: Dict = None): self._jsonData = jsonData if ('sdk-config' not in self._jsonData): - logging.warn(f"No valid SDK configuration present - clearing out configuration") + logging.warn("No valid SDK configuration present - clearing out configuration") self._jsonData['sdk-config'] = {} if ('repl-config' not in self._jsonData): - logging.warn(f"No valid REPL configuration present - clearing out configuration") + logging.warn("No valid REPL configuration present - clearing out configuration") self._jsonData['repl-config'] = {} # Clear out the file so that calling 'Commit' will re-open the file at that time in write mode. @@ -150,7 +150,9 @@ def __init__(self, path: str = None, jsonData: Dict = None): self._handle.pychip_Storage_InitializeStorageAdapter.restype = c_void_p self._handle.pychip_Storage_InitializeStorageAdapter.argtypes = [ctypes.py_object, - _SyncSetKeyValueCbFunct, _SyncGetKeyValueCbFunct, _SyncDeleteKeyValueCbFunct] + _SyncSetKeyValueCbFunct, + _SyncGetKeyValueCbFunct, + _SyncDeleteKeyValueCbFunct] self._closure = self._handle.pychip_Storage_InitializeStorageAdapter(ctypes.py_object( self), _OnSyncSetKeyValueCb, _OnSyncGetKeyValueCb, _OnSyncDeleteKeyValueCb) diff --git a/src/controller/python/chip/tlv/__init__.py b/src/controller/python/chip/tlv/__init__.py index a29704f5343ebd..d24569618fb008 100644 --- a/src/controller/python/chip/tlv/__init__.py +++ b/src/controller/python/chip/tlv/__init__.py @@ -116,7 +116,8 @@ class uint(int): ''' - NewType will not return a class until Python 3.10, as Python 3.10 is not widely used, we still need to construct a class so it can work as a type. + NewType will not return a class until Python 3.10, as Python 3.10 is not widely used, + we still need to construct a class so it can work as a type. ''' def __init__(self, val: int): @@ -386,7 +387,7 @@ def _encodeControlAndTag(self, type, tag, lenOfLenOrVal=0): raise ValueError("Invalid object given for TLV tag") if tagNum < 0 or tagNum > UINT32_MAX: raise ValueError("TLV tag number out of range") - if profile != None: + if profile is not None: if not isinstance(profile, int): raise ValueError("Invalid object given for TLV profile id") if profile < 0 or profile > UINT32_MAX: @@ -656,7 +657,7 @@ def _decodeVal(self, tlv, decoding): ) try: decoding["value"] = str(val, "utf-8") - except Exception as ex: + except Exception: decoding["value"] = val self._bytesRead += decoding["strDataLen"] elif "Byte String" in decoding["type"]: @@ -673,7 +674,7 @@ def _decodeVal(self, tlv, decoding): def _get(self, tlv, decodings, out): endOfEncoding = False - while len(tlv[self._bytesRead:]) > 0 and endOfEncoding == False: + while len(tlv[self._bytesRead:]) > 0 and endOfEncoding is False: decoding = {} self._decodeControlAndTag(tlv, decoding) self._decodeStrLength(tlv, decoding) diff --git a/src/controller/python/chip/utils/CommissioningBuildingBlocks.py b/src/controller/python/chip/utils/CommissioningBuildingBlocks.py index c85866003c7207..bfff0ef0545fc2 100644 --- a/src/controller/python/chip/utils/CommissioningBuildingBlocks.py +++ b/src/controller/python/chip/utils/CommissioningBuildingBlocks.py @@ -23,7 +23,7 @@ from chip.ChipDeviceCtrl import ChipDeviceController as ChipDeviceController from chip.clusters import GeneralCommissioning as generalCommissioning from chip.clusters import OperationalCredentials as opCreds -from chip.clusters.Types import * +from chip.clusters.Types import NullValue from chip.FabricAdmin import FabricAdmin as FabricAdmin _UINT16_MAX = 65535 @@ -41,19 +41,24 @@ async def _IsNodeInFabricList(devCtrl, nodeId): return False -async def GrantPrivilege(adminCtrl: ChipDeviceController, grantedCtrl: ChipDeviceController, privilege: Clusters.AccessControl.Enums.AccessControlEntryPrivilegeEnum, targetNodeId: int, targetCatTags: typing.List[int] = []): - ''' Given an existing controller with admin privileges over a target node, grants the specified privilege to the new ChipDeviceController instance to the entire Node. This is achieved +async def GrantPrivilege(adminCtrl: ChipDeviceController, grantedCtrl: ChipDeviceController, + privilege: Clusters.AccessControl.Enums.AccessControlEntryPrivilegeEnum, + targetNodeId: int, targetCatTags: typing.List[int] = []): + ''' Given an existing controller with admin privileges over a target node, grants the specified privilege + to the new ChipDeviceController instance to the entire Node. This is achieved by updating the ACL entries on the target. - This will automatically take care of working within the minimas of the target as well as doing an efficient read-modify-write operation that takes - into consideration the existing entries on the target and minimizing the total number of ACL entries written per fabric. + This will automatically take care of working within the minimas of the target as well as doing an efficient + read-modify-write operation that takes into consideration the existing entries on the target and minimizing + the total number of ACL entries written per fabric. Args: adminCtrl: ChipDeviceController instance with admin privileges over the target node grantedCtrl: ChipDeviceController instance that is being granted the new privilege. privilege: Privilege to grant to the granted controller. If None, no privilege is granted. targetNodeId: Target node to which the controller is granted privilege. - targetCatTag: Target 32-bit CAT tag that is granted privilege. If provided, this will be used in the subject list instead of the nodeid of that of grantedCtrl. + targetCatTag: Target 32-bit CAT tag that is granted privilege. + If provided, this will be used in the subject list instead of the nodeid of that of grantedCtrl. ''' data = await adminCtrl.ReadAttribute(targetNodeId, [(Clusters.AccessControl.Attributes.Acl)]) if 0 not in data: @@ -92,10 +97,14 @@ async def GrantPrivilege(adminCtrl: ChipDeviceController, grantedCtrl: ChipDevic if (not (addedPrivilege)): if len(currentAcls) >= 3: raise ValueError( - f"Cannot add another ACL entry to grant privilege to existing count of {currentAcls} ACLs -- will exceed minimas!") + f"Cannot add another ACL entry to grant privilege to existing count of {currentAcls} " + "ACLs -- will exceed minimas!") - currentAcls.append(Clusters.AccessControl.Structs.AccessControlEntryStruct(privilege=privilege, authMode=Clusters.AccessControl.Enums.AccessControlEntryAuthModeEnum.kCase, - subjects=targetSubjects)) + currentAcls.append(Clusters.AccessControl.Structs.AccessControlEntryStruct( + privilege=privilege, + authMode=Clusters.AccessControl.Enums.AccessControlEntryAuthModeEnum.kCase, + subjects=targetSubjects + )) # Step 4: Prune ACLs which have empty subjects. currentAcls = [acl for acl in currentAcls if acl.subjects != NullValue and len(acl.subjects) != 0] @@ -104,16 +113,23 @@ async def GrantPrivilege(adminCtrl: ChipDeviceController, grantedCtrl: ChipDevic await adminCtrl.WriteAttribute(targetNodeId, [(0, Clusters.AccessControl.Attributes.Acl(currentAcls))]) -async def CreateControllersOnFabric(fabricAdmin: FabricAdmin, adminDevCtrl: ChipDeviceController, controllerNodeIds: typing.List[int], privilege: Clusters.AccessControl.Enums.AccessControlEntryPrivilegeEnum, targetNodeId: int, catTags: typing.List[int] = []) -> typing.List[ChipDeviceController]: +async def CreateControllersOnFabric(fabricAdmin: FabricAdmin, + adminDevCtrl: ChipDeviceController, + controllerNodeIds: typing.List[int], + privilege: Clusters.AccessControl.Enums.AccessControlEntryPrivilegeEnum, + targetNodeId: int, + catTags: typing.List[int] = []) -> typing.List[ChipDeviceController]: ''' Create new ChipDeviceController instances on a given fabric with a specific privilege on a target node. Args: fabricAdmin: A FabricAdmin object that is capable of vending new controller instances on a fabric. - adminDevCtrl: An existing ChipDeviceController instance that already has admin privileges on the target node. + adminDevCtrl: An existing ChipDeviceController instance that already has admin privileges + on the target node. controllerNodeIds: List of desired nodeIds for the controllers. privilege: The specific ACL privilege to grant to the newly minted controllers. targetNodeId: The Node ID of the target. - catTags: CAT Tags to include in the NOC of controller, as well as when setting up the ACLs on the target. + catTags: CAT Tags to include in the NOC of controller, as well as when setting + up the ACLs on the target. ''' controllerList = [] @@ -148,13 +164,20 @@ async def AddNOCForNewFabricFromExisting(commissionerDevCtrl, newFabricDevCtrl, csrForAddNOC = await commissionerDevCtrl.SendCommand(existingNodeId, 0, opCreds.Commands.CSRRequest(CSRNonce=os.urandom(32))) chainForAddNOC = newFabricDevCtrl.IssueNOCChain(csrForAddNOC, newNodeId) - if chainForAddNOC.rcacBytes is None or chainForAddNOC.icacBytes is None or chainForAddNOC.nocBytes is None or chainForAddNOC.ipkBytes is None: + if (chainForAddNOC.rcacBytes is None or + chainForAddNOC.icacBytes is None or + chainForAddNOC.nocBytes is None or chainForAddNOC.ipkBytes is None): # Expiring the failsafe timer in an attempt to clean up. await commissionerDevCtrl.SendCommand(existingNodeId, 0, generalCommissioning.Commands.ArmFailSafe(0)) return False await commissionerDevCtrl.SendCommand(existingNodeId, 0, opCreds.Commands.AddTrustedRootCertificate(chainForAddNOC.rcacBytes)) - resp = await commissionerDevCtrl.SendCommand(existingNodeId, 0, opCreds.Commands.AddNOC(chainForAddNOC.nocBytes, chainForAddNOC.icacBytes, chainForAddNOC.ipkBytes, newFabricDevCtrl.nodeId, 0xFFF1)) + resp = await commissionerDevCtrl.SendCommand(existingNodeId, + 0, + opCreds.Commands.AddNOC(chainForAddNOC.nocBytes, + chainForAddNOC.icacBytes, + chainForAddNOC.ipkBytes, + newFabricDevCtrl.nodeId, 0xFFF1)) if resp.statusCode is not opCreds.Enums.NodeOperationalCertStatusEnum.kOk: # Expiring the failsafe timer in an attempt to clean up. await commissionerDevCtrl.SendCommand(existingNodeId, 0, generalCommissioning.Commands.ArmFailSafe(0)) @@ -194,11 +217,14 @@ async def UpdateNOC(devCtrl, existingNodeId, newNodeId): csrForUpdateNOC = await devCtrl.SendCommand( existingNodeId, 0, opCreds.Commands.CSRRequest(CSRNonce=os.urandom(32), isForUpdateNOC=True)) chainForUpdateNOC = devCtrl.IssueNOCChain(csrForUpdateNOC, newNodeId) - if chainForUpdateNOC.rcacBytes is None or chainForUpdateNOC.icacBytes is None or chainForUpdateNOC.nocBytes is None or chainForUpdateNOC.ipkBytes is None: + if (chainForUpdateNOC.rcacBytes is None or + chainForUpdateNOC.icacBytes is None or + chainForUpdateNOC.nocBytes is None or chainForUpdateNOC.ipkBytes is None): await devCtrl.SendCommand(existingNodeId, 0, generalCommissioning.Commands.ArmFailSafe(0)) return False - resp = await devCtrl.SendCommand(existingNodeId, 0, opCreds.Commands.UpdateNOC(chainForUpdateNOC.nocBytes, chainForUpdateNOC.icacBytes)) + resp = await devCtrl.SendCommand(existingNodeId, 0, opCreds.Commands.UpdateNOC(chainForUpdateNOC.nocBytes, + chainForUpdateNOC.icacBytes)) if resp.statusCode is not opCreds.Enums.NodeOperationalCertStatusEnum.kOk: # Expiring the failsafe timer in an attempt to clean up. await devCtrl.SendCommand(existingNodeId, 0, generalCommissioning.Commands.ArmFailSafe(0)) diff --git a/src/controller/python/chip/yaml/__init__.py b/src/controller/python/chip/yaml/__init__.py index e099964280b22d..7f312912b6664a 100644 --- a/src/controller/python/chip/yaml/__init__.py +++ b/src/controller/python/chip/yaml/__init__.py @@ -22,3 +22,5 @@ """Provides yaml parser Python APIs for Matter.""" from . import runner + +__all__ = [runner] diff --git a/src/controller/python/chip/yaml/format_converter.py b/src/controller/python/chip/yaml/format_converter.py index 551e1e398ef85b..eefe61f172ee15 100644 --- a/src/controller/python/chip/yaml/format_converter.py +++ b/src/controller/python/chip/yaml/format_converter.py @@ -15,7 +15,6 @@ # limitations under the License. # -import enum import typing from dataclasses import dataclass @@ -157,7 +156,9 @@ def convert_to_data_model_type(field_value, field_type): for t in typing.get_args(field_type): # Comparison below explicitly not using 'isinstance' as that doesn't do what we want. - if t != Nullable and t != type(None): + # type_none is simple hack for Flake8 E721 + type_none = type(None) + if t != Nullable and t != type_none: underlying_field_type = t break @@ -178,7 +179,7 @@ def convert_to_data_model_type(field_value, field_type): field_descriptor = next( x for x in field_descriptors.Fields if x.Label.lower() == item.lower()) - except StopIteration as exc: + except StopIteration: raise ValidationError( f'Did not find field "{item}" in {str(field_type)}') from None diff --git a/src/controller/python/chip/yaml/runner.py b/src/controller/python/chip/yaml/runner.py index 2e21f5eefd7d02..8553af31eeb6e1 100644 --- a/src/controller/python/chip/yaml/runner.py +++ b/src/controller/python/chip/yaml/runner.py @@ -25,16 +25,18 @@ import chip.yaml.format_converter as Converter import stringcase from chip.ChipDeviceCtrl import ChipDeviceController, discovery +from chip.clusters import ClusterObjects from chip.clusters.Attribute import (AttributeStatus, EventReadResult, SubscriptionTransaction, TypedAttributePath, ValueDecodeFailure) from chip.exceptions import ChipStackError +from chip.yaml.data_model_lookup import DataModelLookup from chip.yaml.errors import ActionCreationError, UnexpectedActionCreationError from matter_yamltests.pseudo_clusters.clusters.delay_commands import DelayCommands from matter_yamltests.pseudo_clusters.clusters.log_commands import LogCommands from matter_yamltests.pseudo_clusters.clusters.system_commands import SystemCommands from matter_yamltests.pseudo_clusters.pseudo_clusters import PseudoClusters -from .data_model_lookup import * +from .data_model_lookup import PreDefinedDataModelLookup _PSEUDO_CLUSTERS = PseudoClusters([DelayCommands(), LogCommands(), SystemCommands()]) logger = logging.getLogger('YamlParser') @@ -369,7 +371,7 @@ async def run_action(self, dev_ctrl: ChipDeviceController) -> _ActionResult: class AttributeChangeAccumulator: - def __init__(self, name: str, expected_attribute: Clusters.ClusterAttributeDescriptor, + def __init__(self, name: str, expected_attribute: ClusterObjects.ClusterAttributeDescriptor, output_queue: queue.SimpleQueue): self._name = name self._expected_attribute = expected_attribute @@ -556,7 +558,7 @@ def __init__(self, test_step, cluster: str, context: _ExecutionContext): args = test_step.arguments['values'] if len(args) != 1: - raise UnexpectedActionCreationError(f'WriteAttribute is trying to write multiple values') + raise UnexpectedActionCreationError('WriteAttribute is trying to write multiple values') request_data_as_dict = args[0] try: # TODO this is an ugly hack @@ -614,11 +616,11 @@ def __init__(self, test_step, context: _ExecutionContext): queue_name = stringcase.pascalcase(test_step.event) else: raise UnexpectedActionCreationError( - f'WaitForReport needs to wait on either attribute or event, neither were provided') + 'WaitForReport needs to wait on either attribute or event, neither were provided') self._output_queue = context.subscription_callback_result_queue.get(queue_name, None) if self._output_queue is None: - raise UnexpectedActionCreationError(f'Could not find output queue') + raise UnexpectedActionCreationError('Could not find output queue') async def run_action(self, dev_ctrl: ChipDeviceController) -> _ActionResult: try: diff --git a/src/pybindings/pycontroller/build-chip-wheel.py b/src/pybindings/pycontroller/build-chip-wheel.py index bf5b130bd0afaa..a61b591d5c5368 100644 --- a/src/pybindings/pycontroller/build-chip-wheel.py +++ b/src/pybindings/pycontroller/build-chip-wheel.py @@ -28,7 +28,6 @@ import os import platform import shutil -from datetime import datetime from setuptools import setup from wheel.bdist_wheel import bdist_wheel diff --git a/src/pybindings/pycontroller/pychip/__init__.py b/src/pybindings/pycontroller/pychip/__init__.py index 59fe478151e825..c2020be2dc7a4f 100644 --- a/src/pybindings/pycontroller/pychip/__init__.py +++ b/src/pybindings/pycontroller/pychip/__init__.py @@ -1 +1,4 @@ + from .PyChip import chip + +__all__ = [chip]