From 163086863b8ecee92e4f614d96bb3722a4e55518 Mon Sep 17 00:00:00 2001 From: Arkadiusz Bokowy Date: Mon, 9 Jan 2023 16:15:00 +0100 Subject: [PATCH] Add isort formatter to restyled configuration (#24148) * Add isort formatter to restyled configuration * Sort Python imports using isort tool This commit also removes unused imports (reported by flake8) in few places. * Restyled by autopep8 * Restyled by isort * Update ZAP template for cluster Objects * Fix E402 suppressions in connection with isort * Fix imports which depend on modified sys path * Fix circular dependency when importing FabricAdmin * Restyled by isort Co-authored-by: Restyled.io --- .isort.cfg | 2 + .restyled.yaml | 11 ++++- build/chip/java/tests/test.py | 2 +- build/config/linux/pkg-config.py | 2 +- .../esp32/components/chip/create_args_gn.py | 2 +- credentials/fetch-paa-certs-from-dcl.py | 15 +++--- .../linux/entitlements/codesign.py | 2 +- .../linux/entitlements/codesign.py | 2 +- examples/chef/chef.py | 9 ++-- examples/chef/create_docker.py | 5 +- .../sample_app_util/test_zap_file_parser.py | 4 +- .../chef/sample_app_util/zap_file_parser.py | 3 +- .../rpc_console/py/chip_rpc/console.py | 17 ++++--- .../entitlements/codesign.py | 2 +- examples/lighting-app/python/lighting.py | 28 ++++------- examples/pigweed-app/mobly_tests/echo_test.py | 7 ++- .../nxp/k32w/k32w0/scripts/detokenizer.py | 9 ++-- .../CHIPCirqueDaemon.py | 11 +++-- .../build/lib/chip_mobly/pigweed_device.py | 4 +- .../mobly/chip_mobly/pigweed_device.py | 4 +- integrations/mobly/hello_world_test.py | 3 +- scripts/build/build/target.py | 4 +- scripts/build/build/targets.py | 14 +++--- scripts/build/build/test_target.py | 6 +-- scripts/build/build_darwin_framework.py | 2 +- scripts/build/builders/bouffalolab.py | 2 +- scripts/build/builders/efr32.py | 2 +- scripts/build/builders/genio.py | 1 - scripts/checkout_submodules.py | 4 +- scripts/codegen.py | 9 ++-- scripts/codepregen.py | 6 +-- scripts/error_table.py | 2 +- scripts/examples/gn_to_cmakelists.py | 4 +- scripts/examples/tests/test.py | 4 +- .../flashing/bouffalolab_firmware_utils.py | 7 ++- scripts/flashing/firmware_utils.py | 2 +- scripts/flashing/qpg_firmware_utils.py | 2 +- scripts/gen_test_driver.py | 2 +- scripts/helpers/bloat_check.py | 7 +-- scripts/helpers/github_fetch_artifacts.py | 3 +- scripts/helpers/upload_release_asset.py | 5 +- scripts/idl_lint.py | 10 ++-- scripts/pregenerate/pregenerators.py | 2 +- scripts/pregenerate/types.py | 1 - .../matter_idl/generators/registry.py | 2 +- .../matter_idl/generators/types.py | 14 +++--- .../matter_idl/lint/lint_rules_parser.py | 16 ++++--- .../py_matter_idl/matter_idl/lint/types.py | 5 +- .../matter_idl/matter_idl_types.py | 6 +-- .../matter_idl/test_generators.py | 15 +++--- .../matter_idl/test_xml_parser.py | 5 +- .../py_matter_idl/matter_idl/xml_parser.py | 14 ++---- .../matter_idl/zapxml/handlers/base.py | 1 + .../matter_idl/zapxml/handlers/context.py | 8 ++-- .../matter_idl/zapxml/handlers/handlers.py | 6 +-- .../matter_yamltests/constraints.py | 2 +- .../matter_yamltests/definitions.py | 4 +- .../matter_yamltests/fixes.py | 2 +- .../matter_yamltests/parser.py | 5 +- scripts/tests/java/base.py | 11 +++-- scripts/tests/java/commissioning_test.py | 7 +-- scripts/tests/java/discover_test.py | 7 +-- scripts/tests/run_java_test.py | 7 +-- scripts/tests/run_test_suite.py | 4 +- scripts/tools/check_includes.py | 2 - scripts/tools/check_includes_config.py | 1 - scripts/tools/check_test_pics.py | 5 +- scripts/tools/check_zcl_file_sync.py | 4 +- scripts/tools/esp32_log_cat.py | 3 +- .../tools/generate_esp32_chip_factory_bin.py | 15 +++--- scripts/tools/memory/block.py | 6 +-- scripts/tools/memory/diffsyms.py | 4 +- scripts/tools/memory/gaps.py | 4 +- scripts/tools/memory/gh_db_load.py | 2 +- scripts/tools/memory/gh_db_query.py | 9 ++-- scripts/tools/memory/gh_report.py | 6 +-- scripts/tools/memory/gh_sizes.py | 4 +- scripts/tools/memory/memdf/collect.py | 10 ++-- .../tools/memory/memdf/collector/bloaty.py | 6 +-- scripts/tools/memory/memdf/collector/csv.py | 6 +-- .../tools/memory/memdf/collector/elftools.py | 8 ++-- .../tools/memory/memdf/collector/readelf.py | 7 +-- scripts/tools/memory/memdf/collector/su.py | 2 - scripts/tools/memory/memdf/collector/util.py | 1 - scripts/tools/memory/memdf/report.py | 10 ++-- scripts/tools/memory/memdf/select.py | 10 ++-- scripts/tools/memory/memdf/sizedb.py | 3 +- scripts/tools/memory/memdf/util/config.py | 5 +- scripts/tools/memory/memdf/util/github.py | 2 - scripts/tools/memory/memdf/util/pretty.py | 1 - scripts/tools/memory/memdf/util/sqlite.py | 2 - scripts/tools/memory/memdf/util/subprocess.py | 1 - scripts/tools/memory/report_summary.py | 4 +- scripts/tools/memory/report_tree.py | 5 +- .../generate_nrfconnect_chip_factory_data.py | 17 +++---- .../nrfconnect_generate_partition.py | 7 +-- .../nxp/generate_nxp_chip_factory_bin.py | 3 +- scripts/tools/silabs/FactoryDataProvider.py | 20 ++++---- scripts/tools/spake2p/spake2p.py | 3 +- scripts/tools/telink/mfg_tool.py | 5 +- scripts/tools/zap/generate.py | 4 +- scripts/tools/zap_convert_all.py | 8 ++-- scripts/tools/zap_regen_all.py | 9 ++-- src/app/ota_image_tool.py | 2 +- .../tests/suites/certification/information.py | 6 +-- src/app/zap_cluster_list.py | 4 +- src/controller/python/build-chip-wheel.py | 5 +- src/controller/python/chip-device-ctrl.py | 37 ++++++--------- src/controller/python/chip-repl.py | 4 +- .../python/chip/CertificateAuthority.py | 26 ++++------- src/controller/python/chip/ChipBleBase.py | 1 + src/controller/python/chip/ChipBleUtility.py | 6 +-- src/controller/python/chip/ChipBluezMgr.py | 25 ++++------ .../python/chip/ChipCommissionableNodeCtrl.py | 5 +- .../python/chip/ChipCoreBluetoothMgr.py | 31 ++++--------- src/controller/python/chip/ChipDeviceCtrl.py | 43 +++++++++-------- src/controller/python/chip/ChipReplStartup.py | 33 ++++++------- src/controller/python/chip/ChipStack.py | 32 ++++++------- src/controller/python/chip/ChipUtility.py | 4 +- src/controller/python/chip/FabricAdmin.py | 39 ++++++++-------- src/controller/python/chip/ble/__init__.py | 2 +- .../python/chip/ble/commissioning/__init__.py | 8 ++-- .../python/chip/ble/get_adapters.py | 3 +- .../python/chip/ble/library_handle.py | 5 +- .../python/chip/ble/scan_devices.py | 5 +- src/controller/python/chip/ble/types.py | 2 +- .../python/chip/clusters/Attribute.py | 25 +++++----- .../python/chip/clusters/ClusterObjects.py | 9 ++-- .../python/chip/clusters/Command.py | 17 +++---- .../python/chip/clusters/Objects.py | 14 ++++-- .../python/chip/clusters/TestObjects.py | 8 ++-- src/controller/python/chip/clusters/Types.py | 1 + .../python/chip/clusters/__init__.py | 5 +- .../python/chip/discovery/__init__.py | 9 ++-- .../python/chip/discovery/library_handle.py | 5 +- src/controller/python/chip/discovery/types.py | 2 +- .../python/chip/interaction_model/__init__.py | 4 +- .../python/chip/interaction_model/delegate.py | 12 ++--- .../python/chip/internal/commissioner.py | 8 ++-- src/controller/python/chip/internal/types.py | 2 +- .../python/chip/logging/__init__.py | 4 +- .../python/chip/logging/library_handle.py | 3 +- src/controller/python/chip/native/__init__.py | 7 +-- src/controller/python/chip/server/types.py | 2 +- .../chip/setup_payload/setup_payload.py | 6 +-- .../python/chip/storage/__init__.py | 16 +++---- src/controller/python/chip/tlv/__init__.py | 3 +- .../chip/utils/CommissioningBuildingBlocks.py | 12 ++--- src/controller/python/chip/utils/__init__.py | 5 ++ src/controller/python/chip/yaml/__init__.py | 1 + .../python/chip/yaml/data_model_lookup.py | 1 + .../python/chip/yaml/format_converter.py | 9 ++-- src/controller/python/chip/yaml/runner.py | 14 +++--- .../templates/python-cluster-Objects-py.zapt | 16 ++++--- .../python/test/test_scripts/base.py | 46 +++++++++---------- .../test/test_scripts/cluster_objects.py | 17 ++++--- .../commissioning_failure_test.py | 9 ++-- .../test/test_scripts/commissioning_test.py | 9 ++-- .../test/test_scripts/failsafe_tests.py | 9 ++-- .../test/test_scripts/mobile-device-test.py | 17 ++++--- .../test_scripts/network_commissioning.py | 9 ++-- .../test_scripts/split_commissioning_test.py | 9 ++-- .../test/unit_tests/test_cluster_objects.py | 3 +- .../test_generated_clusterobjects.py | 6 +-- .../python/test/unit_tests/test_tlv.py | 5 +- src/lib/asn1/gen_asn1oid.py | 4 +- src/lib/support/verhoeff/Verhoeff.py | 5 +- .../pycontroller/build-chip-wheel.py | 6 +-- src/python_testing/TC_DA_1_7.py | 18 ++++---- src/python_testing/TC_RR_1_1.py | 22 ++++----- src/python_testing/TC_SC_3_6.py | 19 ++++---- src/python_testing/TC_TestEventTrigger.py | 7 +-- src/python_testing/hello_test.py | 7 +-- src/python_testing/matter_testing_support.py | 43 ++++++++--------- .../efr32/py/nl_test_runner/nl_test_runner.py | 10 ++-- src/test_driver/esp32/run_qemu_image.py | 7 +-- .../CommissioningFailureOnReportTest.py | 2 +- .../linux-cirque/CommissioningFailureTest.py | 2 +- .../linux-cirque/CommissioningTest.py | 2 +- .../linux-cirque/EchoOverTcpTest.py | 2 +- src/test_driver/linux-cirque/EchoTest.py | 2 +- src/test_driver/linux-cirque/FailsafeTest.py | 2 +- .../linux-cirque/InteractionModelTest.py | 2 +- src/test_driver/linux-cirque/ManualTest.py | 4 +- .../linux-cirque/MobileDeviceTest.py | 2 +- .../linux-cirque/OnOffClusterTest.py | 2 +- .../linux-cirque/SplitCommissioningTest.py | 2 +- .../linux-cirque/helper/CHIPTestBase.py | 6 +-- .../mbed/integration_tests/common/fixtures.py | 7 ++- .../common/pigweed_client.py | 2 +- .../mbed/integration_tests/common/utils.py | 8 ++-- .../lighting-app/test_app.py | 10 ++-- .../integration_tests/lock-app/test_app.py | 10 ++-- .../integration_tests/pigweed-app/test_app.py | 3 +- .../mbed/integration_tests/shell/test_app.py | 10 ++-- .../integration_tests/unit-tests/test_app.py | 3 +- .../integration-tests/common/fixtures.py | 20 ++++---- .../integration-tests/common/fvp_device.py | 2 +- .../common/telnet_connection.py | 3 +- .../integration-tests/common/utils.py | 14 +++--- .../integration-tests/lock-app/test_app.py | 7 ++- .../integration-tests/shell/test_app.py | 11 ++--- .../chip-cert/gen_com_dut_test_vectors.py | 10 ++-- .../chip-cert/gen_op_cert_test_vectors.py | 10 ++-- .../cyw30739_sdk/compress_cgs_data.py | 2 - .../infineon/cyw30739_sdk/gen_ota_image.py | 2 +- .../infineon/cyw30739_sdk/merge_hex.py | 5 +- .../cyw30739_sdk/scripts/gen_ss_cgs.py | 1 - .../ti_simplelink_sdk/oad_merge_tool.py | 1 + third_party/ti_simplelink_sdk/run_oad_tool.py | 4 +- .../ti_simplelink_sdk/run_sysconfig.py | 2 +- 211 files changed, 763 insertions(+), 859 deletions(-) create mode 100644 .isort.cfg mode change 100755 => 100644 scripts/tools/zap_convert_all.py diff --git a/.isort.cfg b/.isort.cfg new file mode 100644 index 00000000000000..38bd3dafddc409 --- /dev/null +++ b/.isort.cfg @@ -0,0 +1,2 @@ +[settings] +line_length = 132 diff --git a/.restyled.yaml b/.restyled.yaml index 75b649d9e4242d..247249683cca2d 100644 --- a/.restyled.yaml +++ b/.restyled.yaml @@ -213,7 +213,7 @@ restylers: - "**/*.sh" - "**/*.bash" - name: autopep8 - image: 'restyled/restyler-autopep8:v1.5.7' + image: 'restyled/restyler-autopep8:v2.0.0' command: - autopep8 - '--in-place' @@ -222,3 +222,12 @@ restylers: - '**/*.py' interpreters: - python + - name: isort + image: 'restyled/restyler-isort:v5.11.2' + command: + - isort + arguments: [] + include: + - '**/*.py' + interpreters: + - python diff --git a/build/chip/java/tests/test.py b/build/chip/java/tests/test.py index 68ca31c5c3c9c3..a67c40079b1a59 100755 --- a/build/chip/java/tests/test.py +++ b/build/chip/java/tests/test.py @@ -18,9 +18,9 @@ import json import os -from os import path import subprocess import unittest +from os import path class JavaBuildTest(unittest.TestCase): diff --git a/build/config/linux/pkg-config.py b/build/config/linux/pkg-config.py index 510a0827054262..664deb766597c1 100755 --- a/build/config/linux/pkg-config.py +++ b/build/config/linux/pkg-config.py @@ -32,9 +32,9 @@ import json import os +import re import subprocess import sys -import re from optparse import OptionParser # This script runs pkg-config, optionally filtering out some results, and diff --git a/config/esp32/components/chip/create_args_gn.py b/config/esp32/components/chip/create_args_gn.py index ddde6aaaba5732..1cb95fb12e761d 100644 --- a/config/esp32/components/chip/create_args_gn.py +++ b/config/esp32/components/chip/create_args_gn.py @@ -19,9 +19,9 @@ # Component makefile for building CHIP within the ESP32 ESP-IDF environment. # +import argparse import json import os -import argparse # Parse the build's compile_commands.json to generate # final args file for CHIP build. diff --git a/credentials/fetch-paa-certs-from-dcl.py b/credentials/fetch-paa-certs-from-dcl.py index 6b49460efdfae4..6499f0e9d21ab5 100644 --- a/credentials/fetch-paa-certs-from-dcl.py +++ b/credentials/fetch-paa-certs-from-dcl.py @@ -21,17 +21,18 @@ # For usage please run:. # python ./credentials/fetch-paa-certs-from-dcl.py --help -from contextlib import nullcontext -import os -import sys -import subprocess import copy +import os import re -from cryptography.hazmat.primitives import serialization -from cryptography import x509 +import subprocess +import sys +from contextlib import nullcontext + import click -from click_option_group import optgroup, RequiredMutuallyExclusiveOptionGroup import requests +from click_option_group import RequiredMutuallyExclusiveOptionGroup, optgroup +from cryptography import x509 +from cryptography.hazmat.primitives import serialization PRODUCTION_NODE_URL = "https://on.dcl.csa-iot.org:26657" PRODUCTION_NODE_URL_REST = "https://on.dcl.csa-iot.org" diff --git a/examples/all-clusters-app/linux/entitlements/codesign.py b/examples/all-clusters-app/linux/entitlements/codesign.py index 2cf51a1cfa5b9e..86a820fcd9884e 100644 --- a/examples/all-clusters-app/linux/entitlements/codesign.py +++ b/examples/all-clusters-app/linux/entitlements/codesign.py @@ -15,8 +15,8 @@ # limitations under the License. import argparse -import subprocess import re +import subprocess def run_command(command): diff --git a/examples/all-clusters-minimal-app/linux/entitlements/codesign.py b/examples/all-clusters-minimal-app/linux/entitlements/codesign.py index 2cf51a1cfa5b9e..86a820fcd9884e 100644 --- a/examples/all-clusters-minimal-app/linux/entitlements/codesign.py +++ b/examples/all-clusters-minimal-app/linux/entitlements/codesign.py @@ -15,8 +15,8 @@ # limitations under the License. import argparse -import subprocess import re +import subprocess def run_command(command): diff --git a/examples/chef/chef.py b/examples/chef/chef.py index f6b3cc385897a9..e8cfe07501ffe4 100755 --- a/examples/chef/chef.py +++ b/examples/chef/chef.py @@ -18,17 +18,16 @@ import json import optparse import os +import re import shutil import sys import tarfile import textwrap from typing import Any, Dict, Sequence -import yaml -import re - import constants import stateful_shell +import yaml from sample_app_util import zap_file_parser TermColors = constants.TermColors @@ -876,14 +875,14 @@ def main() -> int: f"python3 -m chip_rpc.console --device {config['esp32']['TTY']}") elif (options.build_target == "silabs-thread"): if (sys.platform == "linux") or (sys.platform == "linux2"): - if(config['silabs-thread']['TTY'] is None): + if (config['silabs-thread']['TTY'] is None): flush_print( 'The path for the serial enumeration for silabs-thread is not set. Make sure silabs-thread.TTY is set on your config.yaml file') exit(1) shell.run_cmd( f"python3 -m chip_rpc.console --device {config['silabs-thread']['TTY']} -b 115200") elif sys.platform == "darwin": - if(config['silabs-thread']['CU'] is None): + if (config['silabs-thread']['CU'] is None): flush_print( 'The path for the serial enumeration for silabs-thread is not set. Make sure silabs-thread.CU is set on your config.yaml file') exit(1) diff --git a/examples/chef/create_docker.py b/examples/chef/create_docker.py index 688f782f041e4c..bc80b612537cf8 100755 --- a/examples/chef/create_docker.py +++ b/examples/chef/create_docker.py @@ -14,10 +14,11 @@ # See the License for the specific language governing permissions and # limitations under the License. -import os import argparse -import tarfile +import os import shutil +import tarfile + import docker client = docker.from_env() diff --git a/examples/chef/sample_app_util/test_zap_file_parser.py b/examples/chef/sample_app_util/test_zap_file_parser.py index a49345ad128eb1..5ef9fbdb8d721c 100644 --- a/examples/chef/sample_app_util/test_zap_file_parser.py +++ b/examples/chef/sample_app_util/test_zap_file_parser.py @@ -9,14 +9,14 @@ import tempfile import unittest +import zap_file_parser + try: import yaml except ImportError: print("Missing yaml library. Install with:\npip install pyyaml") exit(1) -import zap_file_parser - _HERE = os.path.abspath(os.path.dirname(__file__)) _TEST_FILE = os.path.join(_HERE, "test_files", "sample_zap_file.zap") diff --git a/examples/chef/sample_app_util/zap_file_parser.py b/examples/chef/sample_app_util/zap_file_parser.py index 66a09c0c70e27a..fddc5c9e8efcd2 100644 --- a/examples/chef/sample_app_util/zap_file_parser.py +++ b/examples/chef/sample_app_util/zap_file_parser.py @@ -29,13 +29,12 @@ available. - Add support for .matter files. """ -import copy import base64 +import copy import hashlib import json import os import re - from typing import Dict, List, Literal, Optional, Sequence, TypedDict, Union try: diff --git a/examples/common/pigweed/rpc_console/py/chip_rpc/console.py b/examples/common/pigweed/rpc_console/py/chip_rpc/console.py index c74b6617396e59..7df7214808f47c 100644 --- a/examples/common/pigweed/rpc_console/py/chip_rpc/console.py +++ b/examples/common/pigweed/rpc_console/py/chip_rpc/console.py @@ -37,32 +37,31 @@ """ import argparse -from typing import Callable -from collections import namedtuple -from inspect import cleandoc import logging import re import socket -from concurrent.futures import ThreadPoolExecutor import sys import threading -from typing import Any, BinaryIO, Collection +from collections import namedtuple +from concurrent.futures import ThreadPoolExecutor +from inspect import cleandoc +from typing import Any, BinaryIO, Callable, Collection +import pw_cli.log from chip_rpc.plugins.device_toolbar import DeviceToolbar from chip_rpc.plugins.helper_scripts import HelperScripts -import pw_cli.log from pw_console import PwConsoleEmbed from pw_console.__main__ import create_temp_log_file from pw_console.pyserial_wrapper import SerialWithLogging from pw_hdlc.rpc import HdlcRpcClient, default_channels from pw_rpc import callback_client from pw_rpc.console_tools.console import ClientInfo, flattened_rpc_completions - -from pw_tokenizer.database import LoadTokenDatabases -from pw_tokenizer.detokenize import Detokenizer, detokenize_base64 from pw_tokenizer import tokens +from pw_tokenizer.database import LoadTokenDatabases +from pw_tokenizer.detokenize import Detokenizer # Protos +# isort: off from attributes_service import attributes_service_pb2 from button_service import button_service_pb2 from descriptor_service import descriptor_service_pb2 diff --git a/examples/darwin-framework-tool/entitlements/codesign.py b/examples/darwin-framework-tool/entitlements/codesign.py index bc7cb56b81cb0b..f3ec9802223d22 100644 --- a/examples/darwin-framework-tool/entitlements/codesign.py +++ b/examples/darwin-framework-tool/entitlements/codesign.py @@ -15,8 +15,8 @@ # limitations under the License. import argparse -import subprocess import re +import subprocess def run_command(command): diff --git a/examples/lighting-app/python/lighting.py b/examples/lighting-app/python/lighting.py index a10fbbddf14e35..148f2296c9848f 100644 --- a/examples/lighting-app/python/lighting.py +++ b/examples/lighting-app/python/lighting.py @@ -14,30 +14,20 @@ # limitations under the License. # -from chip.server import ( - GetLibraryHandle, - NativeLibraryHandleMethodArguments, - PostAttributeChangeCallback, -) - -from chip.exceptions import ChipStackError - -from ctypes import CFUNCTYPE, c_char_p, c_int32, c_uint8 - -import sys +import asyncio import os - -import textwrap import string - -from cmd import Cmd - -import asyncio +import sys +import textwrap import threading +from cmd import Cmd +from ctypes import CFUNCTYPE, c_char_p, c_int32, c_uint8 -from dali.driver.hid import tridonic -from dali.gear.general import RecallMaxLevel, Off, DAPC +from chip.exceptions import ChipStackError +from chip.server import GetLibraryHandle, NativeLibraryHandleMethodArguments, PostAttributeChangeCallback from dali.address import Broadcast, Short +from dali.driver.hid import tridonic +from dali.gear.general import DAPC, Off, RecallMaxLevel dali_loop = None dev = None diff --git a/examples/pigweed-app/mobly_tests/echo_test.py b/examples/pigweed-app/mobly_tests/echo_test.py index 179987f60f5dd9..071a555934f87d 100644 --- a/examples/pigweed-app/mobly_tests/echo_test.py +++ b/examples/pigweed-app/mobly_tests/echo_test.py @@ -12,12 +12,11 @@ # See the License for the specific language governing permissions and # limitations under the License. -from chip_mobly import pigweed_device -from mobly import asserts -from mobly import base_test -from mobly import test_runner import time +from chip_mobly import pigweed_device +from mobly import asserts, base_test, test_runner + class PigweedEchoTest(base_test.BaseTestClass): def setup_class(self): diff --git a/examples/platform/nxp/k32w/k32w0/scripts/detokenizer.py b/examples/platform/nxp/k32w/k32w0/scripts/detokenizer.py index d2dbfa49c7ff5a..4ad1436a71fc8b 100644 --- a/examples/platform/nxp/k32w/k32w0/scripts/detokenizer.py +++ b/examples/platform/nxp/k32w/k32w0/scripts/detokenizer.py @@ -1,8 +1,9 @@ import argparse -import sys import os -import serial +import sys + import pw_tokenizer +import serial def parse_args(): @@ -75,8 +76,8 @@ def decode_serial(serialport, outfile, database): if input: try: - while(True): - if(input.in_waiting > 0): + while (True): + if (input.in_waiting > 0): # read line from serial port and ascii decode line = input.readline().decode('ascii').strip() # find token start and detokenize diff --git a/integrations/docker/ci-only-images/chip-cirque-device-base/CHIPCirqueDaemon.py b/integrations/docker/ci-only-images/chip-cirque-device-base/CHIPCirqueDaemon.py index dc9b47a78281dd..a24403cdfe1c7e 100755 --- a/integrations/docker/ci-only-images/chip-cirque-device-base/CHIPCirqueDaemon.py +++ b/integrations/docker/ci-only-images/chip-cirque-device-base/CHIPCirqueDaemon.py @@ -14,15 +14,16 @@ # See the License for the specific language governing permissions and # limitations under the License. -import sys -import subprocess import logging +import subprocess +import sys import time -import click -from pathlib import Path from dataclasses import dataclass from enum import Enum -from multiprocessing.connection import Listener, Client +from multiprocessing.connection import Client, Listener +from pathlib import Path + +import click log = logging.getLogger() log.setLevel(logging.DEBUG) diff --git a/integrations/mobly/build/lib/chip_mobly/pigweed_device.py b/integrations/mobly/build/lib/chip_mobly/pigweed_device.py index 0edd75a6a5105e..5a5300fc3f8905 100644 --- a/integrations/mobly/build/lib/chip_mobly/pigweed_device.py +++ b/integrations/mobly/build/lib/chip_mobly/pigweed_device.py @@ -12,11 +12,11 @@ # See the License for the specific language governing permissions and # limitations under the License. +import importlib import os from pathlib import Path -import serial # type: ignore -import importlib +import serial # type: ignore from pw_hdlc.rpc import HdlcRpcClient # Point the script to the .proto file with our RPC services. diff --git a/integrations/mobly/chip_mobly/pigweed_device.py b/integrations/mobly/chip_mobly/pigweed_device.py index debfc6d519b00b..31daae9e908e64 100644 --- a/integrations/mobly/chip_mobly/pigweed_device.py +++ b/integrations/mobly/chip_mobly/pigweed_device.py @@ -12,11 +12,11 @@ # See the License for the specific language governing permissions and # limitations under the License. +import importlib import os from pathlib import Path -import serial # type: ignore -import importlib +import serial # type: ignore from pw_hdlc.rpc import HdlcRpcClient, default_channels # Point the script to the .proto file with our RPC services. diff --git a/integrations/mobly/hello_world_test.py b/integrations/mobly/hello_world_test.py index 6fdfcbca1fc931..ff2abe03de25b5 100755 --- a/integrations/mobly/hello_world_test.py +++ b/integrations/mobly/hello_world_test.py @@ -14,8 +14,7 @@ from chip_mobly import pigweed_device from mobly import asserts # type: ignore -from mobly import base_test -from mobly import test_runner +from mobly import base_test, test_runner class HelloWorldTest(base_test.BaseTestClass): diff --git a/scripts/build/build/target.py b/scripts/build/build/target.py index 8d281906d633d2..63c278a233cb57 100644 --- a/scripts/build/build/target.py +++ b/scripts/build/build/target.py @@ -42,13 +42,11 @@ import logging import os import re - from dataclasses import dataclass -from typing import Any, Dict, List, Iterable, Optional +from typing import Any, Dict, Iterable, List, Optional from builders.builder import BuilderOptions - report_rejected_parts = True diff --git a/scripts/build/build/targets.py b/scripts/build/build/targets.py index bd7dc36231c699..ef8d863e727d4e 100755 --- a/scripts/build/build/targets.py +++ b/scripts/build/build/targets.py @@ -15,29 +15,29 @@ import os import re from itertools import combinations -from typing import List, Any, Optional - -from .target import BuildTarget, TargetPart +from typing import Any, List, Optional from builders.ameba import AmebaApp, AmebaBoard, AmebaBuilder from builders.android import AndroidApp, AndroidBoard, AndroidBuilder +from builders.bouffalolab import BouffalolabApp, BouffalolabBoard, BouffalolabBuilder from builders.cc13x2x7_26x2x7 import cc13x2x7_26x2x7App, cc13x2x7_26x2x7Builder from builders.cyw30739 import Cyw30739App, Cyw30739Board, Cyw30739Builder from builders.efr32 import Efr32App, Efr32Board, Efr32Builder from builders.esp32 import Esp32App, Esp32Board, Esp32Builder +from builders.genio import GenioApp, GenioBuilder from builders.host import HostApp, HostBoard, HostBuilder, HostCryptoLibrary +from builders.imx import IMXApp, IMXBuilder from builders.infineon import InfineonApp, InfineonBoard, InfineonBuilder from builders.k32w import K32WApp, K32WBuilder from builders.mbed import MbedApp, MbedBoard, MbedBuilder, MbedProfile from builders.mw320 import MW320App, MW320Builder from builders.nrf import NrfApp, NrfBoard, NrfConnectBuilder +from builders.openiotsdk import OpenIotSdkApp, OpenIotSdkBuilder from builders.qpg import QpgApp, QpgBoard, QpgBuilder from builders.telink import TelinkApp, TelinkBoard, TelinkBuilder from builders.tizen import TizenApp, TizenBoard, TizenBuilder -from builders.bouffalolab import BouffalolabApp, BouffalolabBoard, BouffalolabBuilder -from builders.imx import IMXApp, IMXBuilder -from builders.genio import GenioApp, GenioBuilder -from builders.openiotsdk import OpenIotSdkApp, OpenIotSdkBuilder + +from .target import BuildTarget, TargetPart def BuildHostTestRunnerTarget(): diff --git a/scripts/build/build/test_target.py b/scripts/build/build/test_target.py index 02ded283e96e91..2ade0e3b657b6b 100755 --- a/scripts/build/build/test_target.py +++ b/scripts/build/build/test_target.py @@ -13,12 +13,12 @@ # See the License for the specific language governing permissions and # limitations under the License. -import unittest -import sys import os +import sys +import unittest sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) -from build.target import BuildTarget, TargetPart # noqa: E402 +from build.target import BuildTarget, TargetPart # noqa: E402 isort:skip class FakeBuilder: diff --git a/scripts/build/build_darwin_framework.py b/scripts/build/build_darwin_framework.py index 7d638bdd2c708e..f0964a57627bdb 100644 --- a/scripts/build/build_darwin_framework.py +++ b/scripts/build/build_darwin_framework.py @@ -14,8 +14,8 @@ # limitations under the License. import argparse import os -from subprocess import PIPE, Popen import platform +from subprocess import PIPE, Popen def run_command(command): diff --git a/scripts/build/builders/bouffalolab.py b/scripts/build/builders/bouffalolab.py index 52e1e4e01e90d3..707c4e11ae886d 100644 --- a/scripts/build/builders/bouffalolab.py +++ b/scripts/build/builders/bouffalolab.py @@ -12,9 +12,9 @@ # See the License for the specific language governing permissions and # limitations under the License. +import logging import os import platform -import logging from enum import Enum, auto from .gn import GnBuilder diff --git a/scripts/build/builders/efr32.py b/scripts/build/builders/efr32.py index f7c84dcd6d7299..412726aa6a708c 100644 --- a/scripts/build/builders/efr32.py +++ b/scripts/build/builders/efr32.py @@ -13,9 +13,9 @@ # limitations under the License. import os -from enum import Enum, auto import shlex import subprocess +from enum import Enum, auto from .gn import GnBuilder diff --git a/scripts/build/builders/genio.py b/scripts/build/builders/genio.py index ce099a2504919e..56ba33f7b705ff 100755 --- a/scripts/build/builders/genio.py +++ b/scripts/build/builders/genio.py @@ -1,5 +1,4 @@ import os - from enum import Enum, auto from .gn import GnBuilder diff --git a/scripts/checkout_submodules.py b/scripts/checkout_submodules.py index c5967949b9cd3a..858fc7cbf17509 100755 --- a/scripts/checkout_submodules.py +++ b/scripts/checkout_submodules.py @@ -16,11 +16,11 @@ # import argparse -from collections import namedtuple import configparser import logging -import subprocess import os +import subprocess +from collections import namedtuple CHIP_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) diff --git a/scripts/codegen.py b/scripts/codegen.py index 5d824be7bfebf8..8f6b73badf6fa0 100755 --- a/scripts/codegen.py +++ b/scripts/codegen.py @@ -13,24 +13,25 @@ # See the License for the specific language governing permissions and # limitations under the License. -import click import logging -import enum import sys +import click + try: import coloredlogs _has_coloredlogs = True -except: +except ImportError: _has_coloredlogs = False try: from matter_idl.matter_idl_parser import CreateParser -except: +except ImportError: import os sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), 'py_matter_idl'))) from matter_idl.matter_idl_parser import CreateParser +# isort: off from matter_idl.generators import FileSystemGeneratorStorage, GeneratorStorage from matter_idl.generators.registry import CodeGenerator, GENERATORS diff --git a/scripts/codepregen.py b/scripts/codepregen.py index 13ca9a60d972c7..2464e7c122106a 100755 --- a/scripts/codepregen.py +++ b/scripts/codepregen.py @@ -14,14 +14,14 @@ # See the License for the specific language governing permissions and # limitations under the License. -import click +import enum +import itertools import logging import multiprocessing -import itertools -import enum import os import sys +import click try: from pregenerate import FindPregenerationTargets diff --git a/scripts/error_table.py b/scripts/error_table.py index 46096e84a03afd..c8e5c1040affe9 100644 --- a/scripts/error_table.py +++ b/scripts/error_table.py @@ -26,8 +26,8 @@ import re from dataclasses import dataclass from enum import IntEnum -from pathlib import Path from operator import attrgetter +from pathlib import Path from xml.etree.ElementInclude import include diff --git a/scripts/examples/gn_to_cmakelists.py b/scripts/examples/gn_to_cmakelists.py index 7449cf57fdaf6a..3525fce49606b1 100755 --- a/scripts/examples/gn_to_cmakelists.py +++ b/scripts/examples/gn_to_cmakelists.py @@ -33,11 +33,11 @@ # -import itertools import functools +import itertools import json -import posixpath import os +import posixpath import string import sys diff --git a/scripts/examples/tests/test.py b/scripts/examples/tests/test.py index 0f0a3320d0c104..2430e27ccd854e 100644 --- a/scripts/examples/tests/test.py +++ b/scripts/examples/tests/test.py @@ -14,15 +14,15 @@ # See the License for the specific language governing permissions and # limitations under the License. -import coloredlogs import difflib import logging import os import subprocess import sys - from typing import List +import coloredlogs + SCRIPT_ROOT = os.path.dirname(__file__) diff --git a/scripts/flashing/bouffalolab_firmware_utils.py b/scripts/flashing/bouffalolab_firmware_utils.py index 9bbccde7621265..c968c90f2f839c 100644 --- a/scripts/flashing/bouffalolab_firmware_utils.py +++ b/scripts/flashing/bouffalolab_firmware_utils.py @@ -13,15 +13,14 @@ # See the License for the specific language governing permissions and # limitations under the License. -import re -import sys import os import pathlib -import firmware_utils +import re +import sys import bflb_iot_tool import bflb_iot_tool.__main__ - +import firmware_utils # Additional options that can be use to configure an `Flasher` # object (as dictionary keys) and/or passed as command line options. diff --git a/scripts/flashing/firmware_utils.py b/scripts/flashing/firmware_utils.py index 8e26dfca1d29c4..6087360c0614ac 100644 --- a/scripts/flashing/firmware_utils.py +++ b/scripts/flashing/firmware_utils.py @@ -15,10 +15,10 @@ """Utitilies to flash or erase a device.""" import argparse -import pathlib import errno import locale import os +import pathlib import stat import subprocess import sys diff --git a/scripts/flashing/qpg_firmware_utils.py b/scripts/flashing/qpg_firmware_utils.py index 525a931c35fb80..036e82fc83dd8a 100644 --- a/scripts/flashing/qpg_firmware_utils.py +++ b/scripts/flashing/qpg_firmware_utils.py @@ -29,9 +29,9 @@ --application FILE Flash an image through drag and drop """ -import sys import os import shutil +import sys import firmware_utils diff --git a/scripts/gen_test_driver.py b/scripts/gen_test_driver.py index d38868b6505faa..9ef28a833f1c57 100644 --- a/scripts/gen_test_driver.py +++ b/scripts/gen_test_driver.py @@ -16,8 +16,8 @@ # limitations under the License. import optparse -import sys import re +import sys TEMPLATE_PREFIX = '''/* * diff --git a/scripts/helpers/bloat_check.py b/scripts/helpers/bloat_check.py index def289280ac3ae..798df246b78554 100755 --- a/scripts/helpers/bloat_check.py +++ b/scripts/helpers/bloat_check.py @@ -17,11 +17,8 @@ # import argparse -import coloredlogs import csv import datetime -import github -import github_fetch_artifacts import io import logging import os @@ -31,6 +28,10 @@ import traceback import zipfile +import coloredlogs +import github +import github_fetch_artifacts + LOG_KEEP_DAYS = 3 BINARY_KEEP_DAYS = 30 diff --git a/scripts/helpers/github_fetch_artifacts.py b/scripts/helpers/github_fetch_artifacts.py index 101a404ccff8d7..8a050e06047daf 100644 --- a/scripts/helpers/github_fetch_artifacts.py +++ b/scripts/helpers/github_fetch_artifacts.py @@ -16,8 +16,9 @@ # limitations under the License. # -import github import logging + +import github import requests # Artifacts can be fetched using: diff --git a/scripts/helpers/upload_release_asset.py b/scripts/helpers/upload_release_asset.py index 2430356425e80b..21e28f39db8ed7 100755 --- a/scripts/helpers/upload_release_asset.py +++ b/scripts/helpers/upload_release_asset.py @@ -17,11 +17,12 @@ # import argparse -import coloredlogs import logging +import os import tarfile + +import coloredlogs import github -import os class BundleBuilder: diff --git a/scripts/idl_lint.py b/scripts/idl_lint.py index a9271afbd73fc0..e7217c9567dfb1 100755 --- a/scripts/idl_lint.py +++ b/scripts/idl_lint.py @@ -13,23 +13,23 @@ # See the License for the specific language governing permissions and # limitations under the License. -import click -import coloredlogs -import enum import logging import os import sys -from typing import List, Optional +import click +import coloredlogs try: from matter_idl import matter_idl_parser -except: +except ImportError: sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), 'py_matter_idl'))) from matter_idl import matter_idl_parser +# isort: off import matter_idl.lint + # Supported log levels, mapping string values required for argument # parsing into logging constants __LOG_LEVELS__ = { diff --git a/scripts/pregenerate/pregenerators.py b/scripts/pregenerate/pregenerators.py index 3d6658dd3bb7b1..c3b05b3bdda354 100644 --- a/scripts/pregenerate/pregenerators.py +++ b/scripts/pregenerate/pregenerators.py @@ -17,7 +17,7 @@ import shlex import subprocess -from .types import InputIdlFile, IdlFileType +from .types import IdlFileType, InputIdlFile CODEGEN_PY_PATH = os.path.join(os.path.dirname(__file__), '..', 'codegen.py') diff --git a/scripts/pregenerate/types.py b/scripts/pregenerate/types.py index 3d8c0bca3034d8..7f7d601e09a3e8 100644 --- a/scripts/pregenerate/types.py +++ b/scripts/pregenerate/types.py @@ -13,7 +13,6 @@ # limitations under the License. import os - from dataclasses import dataclass from enum import Enum, auto diff --git a/scripts/py_matter_idl/matter_idl/generators/registry.py b/scripts/py_matter_idl/matter_idl/generators/registry.py index 5510d3976dc623..bc6d0b972952c9 100644 --- a/scripts/py_matter_idl/matter_idl/generators/registry.py +++ b/scripts/py_matter_idl/matter_idl/generators/registry.py @@ -14,9 +14,9 @@ import enum -from matter_idl.generators.java import JavaGenerator from matter_idl.generators.bridge import BridgeGenerator from matter_idl.generators.cpp.application import CppApplicationGenerator +from matter_idl.generators.java import JavaGenerator class CodeGenerator(enum.Enum): diff --git a/scripts/py_matter_idl/matter_idl/generators/types.py b/scripts/py_matter_idl/matter_idl/generators/types.py index dd7705dc7070f9..5d1930808e3b48 100644 --- a/scripts/py_matter_idl/matter_idl/generators/types.py +++ b/scripts/py_matter_idl/matter_idl/generators/types.py @@ -12,14 +12,12 @@ # See the License for the specific language governing permissions and # limitations under the License. -import logging import enum +from dataclasses import dataclass +from typing import List, Optional, Union -from matter_idl.matter_idl_types import DataType from matter_idl import matter_idl_types # to explicitly say 'Enum' - -from typing import Union, List, Optional -from dataclasses import dataclass +from matter_idl.matter_idl_types import DataType def ToPowerOfTwo(bits: int) -> int: @@ -104,7 +102,7 @@ def bits(self): class IdlEnumType: """ An enumeration type. Enumerations are constants with an underlying - base type that is an interger. + base type that is an interger. """ idl_name: str base_type: BasicInteger @@ -145,9 +143,9 @@ class IdlItemType(enum.Enum): @dataclass class IdlType: """ - A type defined within the IDL. + A type defined within the IDL. - IDLs would generally only define structures as all other types are + IDLs would generally only define structures as all other types are described in other things like enums/bitmaps/basic types etc. However since IDL parsing is not yet codegen just syntactically, we allow diff --git a/scripts/py_matter_idl/matter_idl/lint/lint_rules_parser.py b/scripts/py_matter_idl/matter_idl/lint/lint_rules_parser.py index 18bbb473b7871c..c03a0aa6806168 100755 --- a/scripts/py_matter_idl/matter_idl/lint/lint_rules_parser.py +++ b/scripts/py_matter_idl/matter_idl/lint/lint_rules_parser.py @@ -2,23 +2,25 @@ import logging import os +import traceback import xml.etree.ElementTree - from dataclasses import dataclass, field -from typing import List, Optional, Mapping -from lark import Lark -from lark.visitors import Transformer, v_args, Discard +from typing import List, Mapping, Optional + import stringcase -import traceback +from lark import Lark +from lark.visitors import Discard, Transformer, v_args try: - from .types import RequiredAttributesRule, AttributeRequirement, ClusterRequirement, RequiredCommandsRule, ClusterCommandRequirement + from .types import (AttributeRequirement, ClusterCommandRequirement, ClusterRequirement, RequiredAttributesRule, + RequiredCommandsRule) except: import sys sys.path.append(os.path.join(os.path.abspath( os.path.dirname(__file__)), "..", "..")) - from matter_idl.lint.types import RequiredAttributesRule, AttributeRequirement, ClusterRequirement, RequiredCommandsRule, ClusterCommandRequirement + from matter_idl.lint.types import (AttributeRequirement, ClusterCommandRequirement, ClusterRequirement, RequiredAttributesRule, + RequiredCommandsRule) def parseNumberString(n): diff --git a/scripts/py_matter_idl/matter_idl/lint/types.py b/scripts/py_matter_idl/matter_idl/lint/types.py index 8ee6a805ec4d4e..7814b83d373b97 100644 --- a/scripts/py_matter_idl/matter_idl/lint/types.py +++ b/scripts/py_matter_idl/matter_idl/lint/types.py @@ -12,10 +12,11 @@ # See the License for the specific language governing permissions and # limitations under the License. -from matter_idl.matter_idl_types import Idl, ParseMetaData, ClusterSide from abc import ABC, abstractmethod -from typing import List, Optional from dataclasses import dataclass, field +from typing import List, Optional + +from matter_idl.matter_idl_types import ClusterSide, Idl, ParseMetaData @dataclass diff --git a/scripts/py_matter_idl/matter_idl/matter_idl_types.py b/scripts/py_matter_idl/matter_idl/matter_idl_types.py index 0971867ab3c82a..68559439e079a9 100644 --- a/scripts/py_matter_idl/matter_idl/matter_idl_types.py +++ b/scripts/py_matter_idl/matter_idl/matter_idl_types.py @@ -1,8 +1,8 @@ import enum -from lark.tree import Meta - from dataclasses import dataclass, field -from typing import List, Set, Optional, Union +from typing import List, Optional, Set, Union + +from lark.tree import Meta # Information about parsing location for specific items diff --git a/scripts/py_matter_idl/matter_idl/test_generators.py b/scripts/py_matter_idl/matter_idl/test_generators.py index 9fb21aecf565dd..a5fbcb4a17f0b4 100755 --- a/scripts/py_matter_idl/matter_idl/test_generators.py +++ b/scripts/py_matter_idl/matter_idl/test_generators.py @@ -16,26 +16,25 @@ import os import unittest -import yaml -import logging -from typing import List from dataclasses import dataclass, field +from typing import List + +import yaml try: from matter_idl.matter_idl_parser import CreateParser -except: +except ImportError: import sys sys.path.append(os.path.abspath( os.path.join(os.path.dirname(__file__), '..'))) from matter_idl.matter_idl_parser import CreateParser -from matter_idl.matter_idl_types import Idl -from matter_idl.generators.java import JavaGenerator +from matter_idl.generators import GeneratorStorage from matter_idl.generators.bridge import BridgeGenerator from matter_idl.generators.cpp.application import CppApplicationGenerator -from matter_idl.generators import GeneratorStorage - +from matter_idl.generators.java import JavaGenerator +from matter_idl.matter_idl_types import Idl TESTS_DIR = os.path.join(os.path.dirname(__file__), "tests") REGENERATE_GOLDEN_IMAGES = False diff --git a/scripts/py_matter_idl/matter_idl/test_xml_parser.py b/scripts/py_matter_idl/matter_idl/test_xml_parser.py index e8645cb0f4043d..5d8d53201b2723 100755 --- a/scripts/py_matter_idl/matter_idl/test_xml_parser.py +++ b/scripts/py_matter_idl/matter_idl/test_xml_parser.py @@ -13,10 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. -import unittest import io - -from typing import Optional, Union, List +import unittest +from typing import List, Optional, Union try: from matter_idl.matter_idl_types import * diff --git a/scripts/py_matter_idl/matter_idl/xml_parser.py b/scripts/py_matter_idl/matter_idl/xml_parser.py index 5ef145ee377462..bae5cdf47a5b50 100755 --- a/scripts/py_matter_idl/matter_idl/xml_parser.py +++ b/scripts/py_matter_idl/matter_idl/xml_parser.py @@ -14,30 +14,26 @@ # See the License for the specific language governing permissions and # limitations under the License. -import enum import logging import os -import xml.sax -import xml.sax.handler try: - from matter_idl.matter_idl_types import Idl -except: + from matter_idl.zapxml import ParseSource, ParseXmls +except ImportError: import sys sys.path.append(os.path.abspath( os.path.join(os.path.dirname(__file__), '..'))) - from matter_idl.matter_idl_types import Idl - -from matter_idl.zapxml import ParseSource, ParseXmls + from matter_idl.zapxml import ParseSource, ParseXmls if __name__ == '__main__': # This Parser is generally not intended to be run as a stand-alone binary. # The ability to run is for debug and to print out the parsed AST. + import pprint + import click import coloredlogs - import pprint # Supported log levels, mapping string values required for argument # parsing into logging constants diff --git a/scripts/py_matter_idl/matter_idl/zapxml/handlers/base.py b/scripts/py_matter_idl/matter_idl/zapxml/handlers/base.py index bb2ca95566a4ae..ac17363d3fa6ae 100644 --- a/scripts/py_matter_idl/matter_idl/zapxml/handlers/base.py +++ b/scripts/py_matter_idl/matter_idl/zapxml/handlers/base.py @@ -13,6 +13,7 @@ # limitations under the License. import enum + from .context import Context diff --git a/scripts/py_matter_idl/matter_idl/zapxml/handlers/context.py b/scripts/py_matter_idl/matter_idl/zapxml/handlers/context.py index b8fd748dfdcfd2..c4f4f4094fbcc8 100644 --- a/scripts/py_matter_idl/matter_idl/zapxml/handlers/context.py +++ b/scripts/py_matter_idl/matter_idl/zapxml/handlers/context.py @@ -14,9 +14,9 @@ import logging import xml.sax.xmlreader +from typing import List, Optional -from matter_idl.matter_idl_types import Idl, ParseMetaData, Attribute -from typing import Optional, List +from matter_idl.matter_idl_types import Attribute, Idl, ParseMetaData class IdlPostProcessor: @@ -59,13 +59,13 @@ def __repr__(self): class Context: """ - Contains a processing state during XML reading. + Contains a processing state during XML reading. The purpose of this is to allow elements to interact with each other, share data and defer processing. Usage: - - globally shared data: + - globally shared data: > locator: parsing location, for error reporting > path: current ProcessingPath for any logging of where we are located - shared data: diff --git a/scripts/py_matter_idl/matter_idl/zapxml/handlers/handlers.py b/scripts/py_matter_idl/matter_idl/zapxml/handlers/handlers.py index f1396627247a36..bc94ff052bcfa6 100644 --- a/scripts/py_matter_idl/matter_idl/zapxml/handlers/handlers.py +++ b/scripts/py_matter_idl/matter_idl/zapxml/handlers/handlers.py @@ -13,13 +13,13 @@ # limitations under the License. import logging +from typing import List, Optional, Union from matter_idl.matter_idl_types import * -from typing import Optional, Union, List +from .base import BaseHandler, HandledDepth from .context import Context, IdlPostProcessor -from .parsing import ParseInt, AttrsToAccessPrivilege, AttrsToAttribute -from .base import HandledDepth, BaseHandler +from .parsing import AttrsToAccessPrivilege, AttrsToAttribute, ParseInt class ClusterNameHandler(BaseHandler): diff --git a/scripts/py_matter_yamltests/matter_yamltests/constraints.py b/scripts/py_matter_yamltests/matter_yamltests/constraints.py index 0da769fb321d83..6f28476df0751b 100644 --- a/scripts/py_matter_yamltests/matter_yamltests/constraints.py +++ b/scripts/py_matter_yamltests/matter_yamltests/constraints.py @@ -15,8 +15,8 @@ # limitations under the License. # -from abc import ABC, abstractmethod import string +from abc import ABC, abstractmethod class ConstraintParseError(Exception): diff --git a/scripts/py_matter_yamltests/matter_yamltests/definitions.py b/scripts/py_matter_yamltests/matter_yamltests/definitions.py index f4b39b134e3f1a..98599072f3c9a2 100644 --- a/scripts/py_matter_yamltests/matter_yamltests/definitions.py +++ b/scripts/py_matter_yamltests/matter_yamltests/definitions.py @@ -13,11 +13,11 @@ # See the License for the specific language governing permissions and # limitations under the License. -from typing import List import enum +from typing import List -from matter_idl.zapxml import ParseSource, ParseXmls from matter_idl.matter_idl_types import * +from matter_idl.zapxml import ParseSource, ParseXmls class _ItemType(enum.Enum): diff --git a/scripts/py_matter_yamltests/matter_yamltests/fixes.py b/scripts/py_matter_yamltests/matter_yamltests/fixes.py index 676739d5ae3f6b..b0a3f428895f0d 100644 --- a/scripts/py_matter_yamltests/matter_yamltests/fixes.py +++ b/scripts/py_matter_yamltests/matter_yamltests/fixes.py @@ -13,8 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. -import re import binascii +import re '''Fixes certain value formats known to exist in YAML tests diff --git a/scripts/py_matter_yamltests/matter_yamltests/parser.py b/scripts/py_matter_yamltests/matter_yamltests/parser.py index 329d17cf124856..d58d56e3c43bd8 100644 --- a/scripts/py_matter_yamltests/matter_yamltests/parser.py +++ b/scripts/py_matter_yamltests/matter_yamltests/parser.py @@ -14,11 +14,12 @@ # limitations under the License. import copy -import yaml from enum import Enum -from .constraints import get_constraints +import yaml + from . import fixes +from .constraints import get_constraints _TESTS_SECTION = [ 'name', diff --git a/scripts/tests/java/base.py b/scripts/tests/java/base.py index 1417db0a7e981a..ce0e04bbccceb7 100755 --- a/scripts/tests/java/base.py +++ b/scripts/tests/java/base.py @@ -17,17 +17,18 @@ # limitations under the License. # +import asyncio +import datetime # Commissioning test. import logging import os -import sys import queue -import datetime -import asyncio +import subprocess +import sys import threading -import typing import time -import subprocess +import typing + from colorama import Fore, Style diff --git a/scripts/tests/java/commissioning_test.py b/scripts/tests/java/commissioning_test.py index 3985c08b9a5383..dc9b7bb550817c 100755 --- a/scripts/tests/java/commissioning_test.py +++ b/scripts/tests/java/commissioning_test.py @@ -17,15 +17,16 @@ # limitations under the License. # +import argparse +import asyncio import logging import os -import sys -import asyncio import queue import subprocess +import sys import threading import typing -import argparse + from colorama import Fore, Style from java.base import DumpProgramOutputToQueue diff --git a/scripts/tests/java/discover_test.py b/scripts/tests/java/discover_test.py index 81d493fba8750e..80c18d6c30e301 100755 --- a/scripts/tests/java/discover_test.py +++ b/scripts/tests/java/discover_test.py @@ -17,15 +17,16 @@ # limitations under the License. # +import argparse +import asyncio import logging import os -import sys -import asyncio import queue import subprocess +import sys import threading import typing -import argparse + from colorama import Fore, Style from java.base import DumpProgramOutputToQueue diff --git a/scripts/tests/run_java_test.py b/scripts/tests/run_java_test.py index 060355f8b93a26..12d7f7c7b6c3cf 100755 --- a/scripts/tests/run_java_test.py +++ b/scripts/tests/run_java_test.py @@ -14,8 +14,6 @@ # See the License for the specific language governing permissions and # limitations under the License. -import click -import coloredlogs import logging import os import pathlib @@ -26,10 +24,13 @@ import signal import subprocess import sys + +import click +import coloredlogs +from colorama import Fore, Style from java.base import DumpProgramOutputToQueue from java.commissioning_test import CommissioningTest from java.discover_test import DiscoverTest -from colorama import Fore, Style @click.command() diff --git a/scripts/tests/run_test_suite.py b/scripts/tests/run_test_suite.py index 1aac9d5ad9a442..e6c46fa1068bf4 100755 --- a/scripts/tests/run_test_suite.py +++ b/scripts/tests/run_test_suite.py @@ -22,14 +22,12 @@ from dataclasses import dataclass from pathlib import Path +import chiptest import click import coloredlogs - -import chiptest from chiptest.accessories import AppsRegister from chiptest.glob_matcher import GlobMatcher - DEFAULT_CHIP_ROOT = os.path.abspath( os.path.join(os.path.dirname(__file__), '..', '..')) diff --git a/scripts/tools/check_includes.py b/scripts/tools/check_includes.py index 02f63582fd76fd..40f8e757eb6d69 100644 --- a/scripts/tools/check_includes.py +++ b/scripts/tools/check_includes.py @@ -24,12 +24,10 @@ import re import sys - from typing import Iterable, Pattern import check_includes_config as config - # The input comes from `grep -n` and has the form # filename:line:include-directive # diff --git a/scripts/tools/check_includes_config.py b/scripts/tools/check_includes_config.py index cbf0b405c720dd..ac237e415deedb 100644 --- a/scripts/tools/check_includes_config.py +++ b/scripts/tools/check_includes_config.py @@ -18,7 +18,6 @@ from typing import Dict, Set - # IGNORE lists source files that are not checked at all. # # Each entry is a string giving a Python regular expression, diff --git a/scripts/tools/check_test_pics.py b/scripts/tools/check_test_pics.py index facc3dc4478001..11ccab7b756ab8 100755 --- a/scripts/tools/check_test_pics.py +++ b/scripts/tools/check_test_pics.py @@ -20,9 +20,10 @@ definition YAML file. """ -import yaml -import sys import re +import sys + +import yaml value_regexp = re.compile("=.*") diff --git a/scripts/tools/check_zcl_file_sync.py b/scripts/tools/check_zcl_file_sync.py index 19d4b75128308d..4a68415a96bca4 100755 --- a/scripts/tools/check_zcl_file_sync.py +++ b/scripts/tools/check_zcl_file_sync.py @@ -23,10 +23,10 @@ Ensure that the two fies are in sync EXCEPT the extension. """ +import difflib import json -import sys import os -import difflib +import sys def main(): diff --git a/scripts/tools/esp32_log_cat.py b/scripts/tools/esp32_log_cat.py index c8bafd1652e4f5..3ac7905b52c8ce 100755 --- a/scripts/tools/esp32_log_cat.py +++ b/scripts/tools/esp32_log_cat.py @@ -27,8 +27,9 @@ # import argparse -import coloredlogs import logging + +import coloredlogs import serial diff --git a/scripts/tools/generate_esp32_chip_factory_bin.py b/scripts/tools/generate_esp32_chip_factory_bin.py index 988178b62bbc85..997d95848a65ce 100755 --- a/scripts/tools/generate_esp32_chip_factory_bin.py +++ b/scripts/tools/generate_esp32_chip_factory_bin.py @@ -16,22 +16,23 @@ # limitations under the License. # -import os -import sys -import shutil +import argparse import base64 +import enum import logging -import argparse +import os +import shutil import subprocess -import cryptography.x509 +import sys from types import SimpleNamespace -import enum + +import cryptography.x509 from bitarray import bitarray from bitarray.util import ba2int CHIP_TOPDIR = os.path.dirname(os.path.realpath(__file__))[:-len(os.path.join('scripts', 'tools'))] sys.path.insert(0, os.path.join(CHIP_TOPDIR, 'scripts', 'tools', 'spake2p')) -from spake2p import generate_verifier # noqa: E402 +from spake2p import generate_verifier # noqa: E402 isort:skip if os.getenv('IDF_PATH'): sys.path.insert(0, os.path.join(os.getenv('IDF_PATH'), diff --git a/scripts/tools/memory/block.py b/scripts/tools/memory/block.py index 74fe6fafa50cca..15b7308781d45b 100755 --- a/scripts/tools/memory/block.py +++ b/scripts/tools/memory/block.py @@ -19,20 +19,16 @@ import logging import sys - from typing import Optional, Pattern -import pandas as pd # type: ignore - import memdf.collect import memdf.name import memdf.report import memdf.select import memdf.util.config - +import pandas as pd # type: ignore from memdf import Config, ConfigDescription - BLOCKLIST_CONFIG: ConfigDescription = { 'symbol.block': { 'help': 'Block symbol', diff --git a/scripts/tools/memory/diffsyms.py b/scripts/tools/memory/diffsyms.py index 70d1e78dfa4fa0..589747a37253c3 100755 --- a/scripts/tools/memory/diffsyms.py +++ b/scripts/tools/memory/diffsyms.py @@ -18,12 +18,10 @@ import sys -import pandas as pd - import memdf.collect import memdf.report import memdf.select - +import pandas as pd from memdf import Config, ConfigDescription, SymbolDF CONFIG: ConfigDescription = { diff --git a/scripts/tools/memory/gaps.py b/scripts/tools/memory/gaps.py index 21db90650144d4..50ce2d1c07ee00 100755 --- a/scripts/tools/memory/gaps.py +++ b/scripts/tools/memory/gaps.py @@ -18,12 +18,10 @@ import sys -from elftools.elf.elffile import ELFFile # type: ignore - import memdf.collect import memdf.report import memdf.select - +from elftools.elf.elffile import ELFFile # type: ignore from memdf import Config, ConfigDescription CONFIG: ConfigDescription = { diff --git a/scripts/tools/memory/gh_db_load.py b/scripts/tools/memory/gh_db_load.py index 9cb69bea5c2b7e..5bc04f2022ada7 100755 --- a/scripts/tools/memory/gh_db_load.py +++ b/scripts/tools/memory/gh_db_load.py @@ -24,8 +24,8 @@ import memdf.util.config import memdf.util.markdown import memdf.util.sqlite -from memdf.util.github import Gh from memdf import Config, ConfigDescription +from memdf.util.github import Gh GITHUB_CONFIG: ConfigDescription = { Config.group_def('github'): { diff --git a/scripts/tools/memory/gh_db_query.py b/scripts/tools/memory/gh_db_query.py index e42262e567ba7f..ff989e1c2b41a8 100755 --- a/scripts/tools/memory/gh_db_query.py +++ b/scripts/tools/memory/gh_db_query.py @@ -19,17 +19,14 @@ import datetime import logging import sys - -from typing import cast, Dict, List, Mapping, Optional, Tuple - -import pandas as pd # type: ignore +from typing import Dict, List, Mapping, Optional, Tuple, cast import memdf.report import memdf.util.config import memdf.util.sqlite -from memdf.sizedb import SizeDatabase +import pandas as pd # type: ignore from memdf import Config - +from memdf.sizedb import SizeDatabase QUERY_CONFIG = { Config.group_map('query'): { diff --git a/scripts/tools/memory/gh_report.py b/scripts/tools/memory/gh_report.py index 608fe9c5edbf9a..0e949134b1f5db 100755 --- a/scripts/tools/memory/gh_report.py +++ b/scripts/tools/memory/gh_report.py @@ -20,19 +20,17 @@ import logging import re import sys - from typing import Dict import fastcore # type: ignore -import pandas as pd # type: ignore - import memdf.report import memdf.sizedb import memdf.util.config import memdf.util.markdown import memdf.util.sqlite -from memdf.util.github import Gh +import pandas as pd # type: ignore from memdf import Config, ConfigDescription +from memdf.util.github import Gh DB_CONFIG: ConfigDescription = { Config.group_def('database'): { diff --git a/scripts/tools/memory/gh_sizes.py b/scripts/tools/memory/gh_sizes.py index 6e11cf9b7e770f..88c3291f99cb96 100755 --- a/scripts/tools/memory/gh_sizes.py +++ b/scripts/tools/memory/gh_sizes.py @@ -73,13 +73,11 @@ import pathlib import sys -import numpy as np # type: ignore - import memdf.collect import memdf.report import memdf.select import memdf.util - +import numpy as np # type: ignore from memdf import Config, ConfigDescription, DFs, SectionDF, SegmentDF PLATFORM_CONFIG_DIR = pathlib.Path('scripts/tools/memory/platform') diff --git a/scripts/tools/memory/memdf/collect.py b/scripts/tools/memory/memdf/collect.py index 0575b967fe4dd7..18cd0048669b37 100644 --- a/scripts/tools/memory/memdf/collect.py +++ b/scripts/tools/memory/memdf/collect.py @@ -16,12 +16,8 @@ """Collect information from various sources into Memory Map DataFrames.""" import bisect - from typing import Callable, Dict, List, Mapping, Optional, Sequence, Tuple -from elftools.elf.constants import SH_FLAGS # type: ignore -import pandas as pd # type: ignore - import memdf.collector.bloaty import memdf.collector.csv import memdf.collector.elftools @@ -30,9 +26,9 @@ import memdf.name import memdf.select import memdf.util.config - -from memdf import (Config, ConfigDescription, DF, DFs, SymbolDF, SectionDF, - ExtentDF) +import pandas as pd # type: ignore +from elftools.elf.constants import SH_FLAGS # type: ignore +from memdf import DF, Config, ConfigDescription, DFs, ExtentDF, SectionDF, SymbolDF from memdf.collector.util import simplify_source PREFIX_CONFIG: ConfigDescription = { diff --git a/scripts/tools/memory/memdf/collector/bloaty.py b/scripts/tools/memory/memdf/collector/bloaty.py index 6e86486d898624..d3caeb3bd6cb2e 100644 --- a/scripts/tools/memory/memdf/collector/bloaty.py +++ b/scripts/tools/memory/memdf/collector/bloaty.py @@ -18,12 +18,10 @@ import io import os -import pandas as pd # type: ignore - import memdf.util.subprocess - -from memdf.collector.util import simplify_source +import pandas as pd # type: ignore from memdf import Config, ConfigDescription, DFs, SymbolDF +from memdf.collector.util import simplify_source CONFIG: ConfigDescription = { 'tool.bloaty': { diff --git a/scripts/tools/memory/memdf/collector/csv.py b/scripts/tools/memory/memdf/collector/csv.py index fa2b7a25f10271..9d2fe0098da370 100644 --- a/scripts/tools/memory/memdf/collector/csv.py +++ b/scripts/tools/memory/memdf/collector/csv.py @@ -15,12 +15,10 @@ # """Collect memory information from csv files.""" -import pandas as pd # type: ignore - import memdf.name - -from memdf.util.config import Config, ConfigDescription +import pandas as pd # type: ignore from memdf.df import DFs +from memdf.util.config import Config, ConfigDescription CONFIG: ConfigDescription = {} diff --git a/scripts/tools/memory/memdf/collector/elftools.py b/scripts/tools/memory/memdf/collector/elftools.py index 84f4e16ba7ab19..8aac38fba3f6a1 100644 --- a/scripts/tools/memory/memdf/collector/elftools.py +++ b/scripts/tools/memory/memdf/collector/elftools.py @@ -17,16 +17,14 @@ import pathlib -from elftools.elf.elffile import ELFFile # type: ignore +import elftools.elf.constants # type: ignore import elftools.elf.descriptions # type: ignore import elftools.elf.sections # type: ignore -import elftools.elf.constants # type: ignore - import memdf.name - +from elftools.elf.elffile import ELFFile # type: ignore from memdf.collector.util import simplify_source +from memdf.df import DFs, SectionDF, SegmentDF, SymbolDF from memdf.util.config import Config, ConfigDescription -from memdf.df import DFs, SegmentDF, SectionDF, SymbolDF CONFIG: ConfigDescription = {} diff --git a/scripts/tools/memory/memdf/collector/readelf.py b/scripts/tools/memory/memdf/collector/readelf.py index e66baffc2da191..d2b1aaa32b1307 100644 --- a/scripts/tools/memory/memdf/collector/readelf.py +++ b/scripts/tools/memory/memdf/collector/readelf.py @@ -17,18 +17,15 @@ import io import re - from typing import Dict, List import elftools.elf.constants # type: ignore -import pandas as pd # type: ignore - import memdf.name import memdf.util.subprocess - +import pandas as pd # type: ignore from memdf.collector.util import simplify_source +from memdf.df import DFs, SectionDF, SegmentDF, SymbolDF, SymbolSourceDF from memdf.util.config import Config, ConfigDescription -from memdf.df import DFs, SegmentDF, SectionDF, SymbolDF, SymbolSourceDF NM_CONFIG: ConfigDescription = { 'tool.nm': { diff --git a/scripts/tools/memory/memdf/collector/su.py b/scripts/tools/memory/memdf/collector/su.py index fc0afff45832f0..cb84e3d55816ef 100644 --- a/scripts/tools/memory/memdf/collector/su.py +++ b/scripts/tools/memory/memdf/collector/su.py @@ -18,11 +18,9 @@ import os import os.path import re - from typing import IO import pandas as pd # type: ignore - from memdf.df import DFs, StackDF from memdf.util.config import Config, ConfigDescription diff --git a/scripts/tools/memory/memdf/collector/util.py b/scripts/tools/memory/memdf/collector/util.py index bfa3fad4fac940..f5d597af81c176 100644 --- a/scripts/tools/memory/memdf/collector/util.py +++ b/scripts/tools/memory/memdf/collector/util.py @@ -17,7 +17,6 @@ import os import re - from typing import Optional diff --git a/scripts/tools/memory/memdf/report.py b/scripts/tools/memory/memdf/report.py index bda23163842bd8..a7c8c92bceed4f 100644 --- a/scripts/tools/memory/memdf/report.py +++ b/scripts/tools/memory/memdf/report.py @@ -20,18 +20,14 @@ import json import pathlib import sys - -from typing import (Any, Callable, Dict, List, Mapping, IO, Optional, Protocol, - Sequence, Union) +from typing import IO, Any, Callable, Dict, List, Mapping, Optional, Protocol, Sequence, Union import cxxfilt # type: ignore -import pandas as pd # type: ignore - import memdf.df import memdf.select import memdf.util.pretty - -from memdf import Config, ConfigDescription, DF, DFs +import pandas as pd # type: ignore +from memdf import DF, Config, ConfigDescription, DFs from memdf.util.config import ParseSizeAction REPORT_DEMANGLE_CONFIG: ConfigDescription = { diff --git a/scripts/tools/memory/memdf/select.py b/scripts/tools/memory/memdf/select.py index 251b1be5642c9a..3cb1b38339d308 100644 --- a/scripts/tools/memory/memdf/select.py +++ b/scripts/tools/memory/memdf/select.py @@ -15,15 +15,13 @@ # """Data frame selection utilities.""" -import numpy as np # type: ignore +from typing import Mapping, Optional import memdf.name -import memdf.util.pretty import memdf.util.config - -from memdf import Config, ConfigDescription, DF - -from typing import Mapping, Optional +import memdf.util.pretty +import numpy as np # type: ignore +from memdf import DF, Config, ConfigDescription def split_size(config: Config, key: str) -> None: diff --git a/scripts/tools/memory/memdf/sizedb.py b/scripts/tools/memory/memdf/sizedb.py index 7e59caedd042e6..a0704b41cd7abf 100644 --- a/scripts/tools/memory/memdf/sizedb.py +++ b/scripts/tools/memory/memdf/sizedb.py @@ -20,9 +20,8 @@ import logging import sqlite3 import zipfile - from pathlib import Path -from typing import Dict, IO, Iterable, List, Optional, Union +from typing import IO, Dict, Iterable, List, Optional, Union import memdf.util.sqlite diff --git a/scripts/tools/memory/memdf/util/config.py b/scripts/tools/memory/memdf/util/config.py index f8294ad8b037a5..fc159db924c1fa 100644 --- a/scripts/tools/memory/memdf/util/config.py +++ b/scripts/tools/memory/memdf/util/config.py @@ -19,12 +19,9 @@ import ast import logging import re - -from typing import (Any, Dict, List, Mapping, MutableMapping, Optional, - Pattern, Sequence, Tuple, Union) +from typing import Any, Dict, List, Mapping, MutableMapping, Optional, Pattern, Sequence, Tuple, Union import humanfriendly # type: ignore - import memdf.util.nd as nd import memdf.util.pretty diff --git a/scripts/tools/memory/memdf/util/github.py b/scripts/tools/memory/memdf/util/github.py index bcd14c597701a2..53c59316507466 100644 --- a/scripts/tools/memory/memdf/util/github.py +++ b/scripts/tools/memory/memdf/util/github.py @@ -18,13 +18,11 @@ import itertools import logging import os - from typing import Iterable, Mapping, Optional import dateutil # type: ignore import dateutil.parser # type: ignore import ghapi.all # type: ignore - from memdf import Config, ConfigDescription diff --git a/scripts/tools/memory/memdf/util/pretty.py b/scripts/tools/memory/memdf/util/pretty.py index 3de71e86ec382d..ed0cd23d79142c 100644 --- a/scripts/tools/memory/memdf/util/pretty.py +++ b/scripts/tools/memory/memdf/util/pretty.py @@ -17,7 +17,6 @@ import logging import pprint - from typing import Any diff --git a/scripts/tools/memory/memdf/util/sqlite.py b/scripts/tools/memory/memdf/util/sqlite.py index c0d825ac98f860..64c32e033e7ceb 100644 --- a/scripts/tools/memory/memdf/util/sqlite.py +++ b/scripts/tools/memory/memdf/util/sqlite.py @@ -17,11 +17,9 @@ """Wrapper and utility functions around sqlite3""" import sqlite3 - from typing import List, Optional import pandas as pd # type: ignore - from memdf import Config, ConfigDescription CONFIG: ConfigDescription = { diff --git a/scripts/tools/memory/memdf/util/subprocess.py b/scripts/tools/memory/memdf/util/subprocess.py index 7d88a77db5bcd8..8901d19b0cef56 100644 --- a/scripts/tools/memory/memdf/util/subprocess.py +++ b/scripts/tools/memory/memdf/util/subprocess.py @@ -17,7 +17,6 @@ import logging import subprocess - from typing import List from memdf.util.config import Config diff --git a/scripts/tools/memory/report_summary.py b/scripts/tools/memory/report_summary.py index 3b21f6a88bb8ea..88ba23c2a37550 100755 --- a/scripts/tools/memory/report_summary.py +++ b/scripts/tools/memory/report_summary.py @@ -28,12 +28,10 @@ import sys -import numpy # type: ignore - import memdf.collect import memdf.report import memdf.select - +import numpy # type: ignore from memdf import Config, DFs, SymbolDF diff --git a/scripts/tools/memory/report_tree.py b/scripts/tools/memory/report_tree.py index 5b3114cc6f6c55..efdeef3c4cffc8 100755 --- a/scripts/tools/memory/report_tree.py +++ b/scripts/tools/memory/report_tree.py @@ -25,16 +25,13 @@ import os import sys - -from typing import (Dict, Sequence, Optional) +from typing import Dict, Optional, Sequence import anytree # type: ignore - import memdf.collect import memdf.name import memdf.report import memdf.select - from memdf import Config, DFs, SymbolDF diff --git a/scripts/tools/nrfconnect/generate_nrfconnect_chip_factory_data.py b/scripts/tools/nrfconnect/generate_nrfconnect_chip_factory_data.py index ff4f64e3d82b25..4eafc7b68f7cc8 100644 --- a/scripts/tools/nrfconnect/generate_nrfconnect_chip_factory_data.py +++ b/scripts/tools/nrfconnect/generate_nrfconnect_chip_factory_data.py @@ -15,16 +15,17 @@ # limitations under the License. # -from os.path import exists -import os -import sys +import argparse +import base64 import json +import logging as log +import os import secrets -import argparse import subprocess -import logging as log -import base64 +import sys from collections import namedtuple +from os.path import exists + from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.serialization import load_der_private_key @@ -342,7 +343,7 @@ def generate_json(self): def _add_entry(self, name: str, value: any): """ Add single entry to list of tuples ("key", "value") """ - if(isinstance(value, bytes) or isinstance(value, bytearray)): + if (isinstance(value, bytes) or isinstance(value, bytearray)): value = HEX_PREFIX + value.hex() if value or (isinstance(value, int) and value == 0): log.debug("Adding entry '{}' with size {} and type {}".format(name, sys.getsizeof(value), type(value))) @@ -487,7 +488,7 @@ def base64_str(s): return base64.b64decode(s) log.basicConfig(format='[%(levelname)s] %(message)s', level=log.INFO) # check if json file already exist - if(exists(args.output) and not args.overwrite): + if (exists(args.output) and not args.overwrite): log.error("Output file: {} already exist, to create a new one add argument '--overwrite'. By default overwriting is disabled".format(args.output)) return diff --git a/scripts/tools/nrfconnect/nrfconnect_generate_partition.py b/scripts/tools/nrfconnect/nrfconnect_generate_partition.py index bb267406427a6d..d3da44ab4dc1c5 100644 --- a/scripts/tools/nrfconnect/nrfconnect_generate_partition.py +++ b/scripts/tools/nrfconnect/nrfconnect_generate_partition.py @@ -15,13 +15,14 @@ # limitations under the License. # -import codecs -import sys -from intelhex import IntelHex import argparse +import codecs import json import logging as log +import sys + import cbor2 as cbor +from intelhex import IntelHex HEX_PREFIX = "hex:" diff --git a/scripts/tools/nxp/generate_nxp_chip_factory_bin.py b/scripts/tools/nxp/generate_nxp_chip_factory_bin.py index 17b8b388d21855..0db2f2ced7f8e2 100755 --- a/scripts/tools/nxp/generate_nxp_chip_factory_bin.py +++ b/scripts/tools/nxp/generate_nxp_chip_factory_bin.py @@ -17,10 +17,11 @@ # import argparse -import subprocess import base64 import logging import os +import subprocess + from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.serialization import load_der_private_key diff --git a/scripts/tools/silabs/FactoryDataProvider.py b/scripts/tools/silabs/FactoryDataProvider.py index fbd45aef2c8976..76daf33ffa7796 100644 --- a/scripts/tools/silabs/FactoryDataProvider.py +++ b/scripts/tools/silabs/FactoryDataProvider.py @@ -14,13 +14,13 @@ # limitations under the License. # -import subprocess -import sys import argparse -import struct import base64 import datetime import os +import struct +import subprocess +import sys class FactoryDataWriter: @@ -141,24 +141,24 @@ def __init__(self, arguments) -> None: self._args = arguments if self._args.rotating_id: - assert(len(bytearray.fromhex(self._args.rotating_id)) == kUniqueIDLength), "Provide a 16 bytes rotating id" + assert (len(bytearray.fromhex(self._args.rotating_id)) == kUniqueIDLength), "Provide a 16 bytes rotating id" if self._args.product_name: - assert(len(self._args.product_name) <= kMaxProductNameLength), "Product name exceeds the size limit" + assert (len(self._args.product_name) <= kMaxProductNameLength), "Product name exceeds the size limit" if self._args.vendor_name: - assert(len(self._args.vendor_name) <= kMaxVendorNameLength), "Vendor name exceeds the size limit" + assert (len(self._args.vendor_name) <= kMaxVendorNameLength), "Vendor name exceeds the size limit" if self._args.hw_version_str: - assert(len(self._args.hw_version_str) <= kMaxHardwareVersionStringLength), "Hardware version string exceeds the size limit" + assert (len(self._args.hw_version_str) <= kMaxHardwareVersionStringLength), "Hardware version string exceeds the size limit" if self._args.serial_number: - assert(len(self._args.serial_number) <= kMaxSerialNumberLength), "Serial number exceeds the size limit" + assert (len(self._args.serial_number) <= kMaxSerialNumberLength), "Serial number exceeds the size limit" if self._args.manufacturing_date: try: datetime.datetime.strptime(self._args.manufacturing_date, '%Y-%m-%d') except ValueError: raise ValueError("Incorrect manufacturing data format, should be YYYY-MM-DD") if self._args.commissioning_flow: - assert(self._args.commissioning_flow <= 3), "Invalid commissioning flow value" + assert (self._args.commissioning_flow <= 3), "Invalid commissioning flow value" if self._args.rendezvous_flag: - assert(self._args.rendezvous_flag <= 7), "Invalid rendez-vous flag value" + assert (self._args.rendezvous_flag <= 7), "Invalid rendez-vous flag value" if self._args.gen_spake2p_path: self._args.spake2_verifier = self.generate_spake2p_verifier() diff --git a/scripts/tools/spake2p/spake2p.py b/scripts/tools/spake2p/spake2p.py index 2b654680824645..5ad10dd6cd75ca 100755 --- a/scripts/tools/spake2p/spake2p.py +++ b/scripts/tools/spake2p/spake2p.py @@ -19,10 +19,11 @@ import argparse import base64 -from ecdsa.curves import NIST256p import hashlib import struct +from ecdsa.curves import NIST256p + # Forbidden passcodes as listed in the "5.1.7.1. Invalid Passcodes" section of the Matter spec INVALID_PASSCODES = [00000000, 11111111, diff --git a/scripts/tools/telink/mfg_tool.py b/scripts/tools/telink/mfg_tool.py index fc3f1eb596d27c..5aef079534d316 100644 --- a/scripts/tools/telink/mfg_tool.py +++ b/scripts/tools/telink/mfg_tool.py @@ -20,16 +20,17 @@ import binascii import csv import json +import logging as logger import os import random import shutil import subprocess -import logging as logger import sys + +import cbor2 as cbor import cryptography.hazmat.backends import cryptography.x509 import pyqrcode -import cbor2 as cbor from intelhex import IntelHex TOOLS = { diff --git a/scripts/tools/zap/generate.py b/scripts/tools/zap/generate.py index 30f60aa8127d21..a777bf5865747d 100755 --- a/scripts/tools/zap/generate.py +++ b/scripts/tools/zap/generate.py @@ -18,12 +18,12 @@ import argparse import json import os -from pathlib import Path -import tempfile import subprocess import sys +import tempfile import urllib.request from dataclasses import dataclass +from pathlib import Path @dataclass diff --git a/scripts/tools/zap_convert_all.py b/scripts/tools/zap_convert_all.py old mode 100755 new mode 100644 index a626a97efc74fb..2f5f7e1ee4f23c --- a/scripts/tools/zap_convert_all.py +++ b/scripts/tools/zap_convert_all.py @@ -15,12 +15,12 @@ # limitations under the License. # -import os -from pathlib import Path -import sys -import subprocess import argparse import multiprocessing +import os +import subprocess +import sys +from pathlib import Path CHIP_ROOT_DIR = os.path.realpath( os.path.join(os.path.dirname(__file__), '../..')) diff --git a/scripts/tools/zap_regen_all.py b/scripts/tools/zap_regen_all.py index e9483084c56019..0cd072a878c644 100755 --- a/scripts/tools/zap_regen_all.py +++ b/scripts/tools/zap_regen_all.py @@ -16,14 +16,13 @@ # import argparse -import os -from pathlib import Path -import sys -import subprocess import logging import multiprocessing - +import os +import subprocess +import sys from dataclasses import dataclass +from pathlib import Path CHIP_ROOT_DIR = os.path.realpath( os.path.join(os.path.dirname(__file__), '../..')) diff --git a/src/app/ota_image_tool.py b/src/app/ota_image_tool.py index 6ff27ab91e6533..c666c229ca6ca2 100755 --- a/src/app/ota_image_tool.py +++ b/src/app/ota_image_tool.py @@ -38,7 +38,7 @@ sys.path.insert(0, os.path.join( os.path.dirname(__file__), '../controller/python')) -from chip.tlv import TLVReader, TLVWriter, uint # noqa: E402 +from chip.tlv import TLVReader, TLVWriter, uint # noqa: E402 isort:skip HEADER_MAGIC = 0x1BEEF11E FIXED_HEADER_FORMAT = ' int: class ChipDeviceController(): activeList = set() - def __init__(self, opCredsContext: ctypes.c_void_p, fabricId: int, nodeId: int, adminVendorId: int, catTags: typing.List[int] = [], paaTrustStorePath: str = "", useTestCommissioner: bool = False, fabricAdmin: FabricAdmin = None, name: str = None): + def __init__(self, opCredsContext: ctypes.c_void_p, fabricId: int, nodeId: int, adminVendorId: int, + catTags: typing.List[int] = [], paaTrustStorePath: str = "", useTestCommissioner: bool = False, + fabricAdmin: FabricAdmin.FabricAdmin = None, name: str = None): self.state = DCState.NOT_INITIALIZED self.devCtrl = None self._ChipStack = builtins.chipStack @@ -295,7 +300,7 @@ def HandlePASEEstablishmentComplete(err: PyChipError): ChipDeviceController.activeList.add(self) @property - def fabricAdmin(self) -> FabricAdmin: + def fabricAdmin(self) -> FabricAdmin.FabricAdmin: return self._fabricAdmin @property diff --git a/src/controller/python/chip/ChipReplStartup.py b/src/controller/python/chip/ChipReplStartup.py index 940089ccd8698e..98dc963e2824ec 100644 --- a/src/controller/python/chip/ChipReplStartup.py +++ b/src/controller/python/chip/ChipReplStartup.py @@ -1,22 +1,17 @@ -from rich import print -from rich.pretty import pprint -from rich import pretty -from rich import inspect -from rich.console import Console -import logging -from chip import ChipDeviceCtrl -import chip.clusters as Clusters -from chip.ChipStack import * -import coloredlogs -import chip.logging import argparse +import atexit import builtins -import chip.FabricAdmin +import logging + import chip.CertificateAuthority -import chip.native import chip.discovery -from chip.utils import CommissioningBuildingBlocks -import atexit +import chip.FabricAdmin +import chip.logging +import chip.native +import coloredlogs +from chip.ChipStack import * +from rich import inspect, pretty +from rich.console import Console _fabricAdmins = None @@ -33,14 +28,14 @@ def ReplInit(debug): console.rule('Matter REPL') console.print(''' [bold blue] - + Welcome to the Matter Python REPL! - + For help, please type [/][bold green]matterhelp()[/][bold blue] - + To get more information on a particular object/class, you can pass that into [bold green]matterhelp()[/][bold blue] as well. - + ''') console.rule() diff --git a/src/controller/python/chip/ChipStack.py b/src/controller/python/chip/ChipStack.py index fabf43e4110c5e..4154a92ec1460a 100644 --- a/src/controller/python/chip/ChipStack.py +++ b/src/controller/python/chip/ChipStack.py @@ -24,31 +24,27 @@ """Chip Stack interface """ -from __future__ import absolute_import -from __future__ import print_function -import sys +from __future__ import absolute_import, print_function + +import builtins +import logging import os +import sys import time -import glob -import platform -import logging -from threading import Lock, Event, Condition from ctypes import * -from .ChipUtility import ChipUtility -from .storage import * -from .exceptions import * -import builtins - -from .interaction_model import InteractionModelError, delegate as im -from .clusters import Command as ClusterCommand -from .clusters import Attribute as ClusterAttribute -from .clusters import ClusterObjects as ClusterObjects -from .clusters import Objects as GeneratedObjects -from .clusters.CHIPClusters import * +from threading import Condition, Event, Lock import chip.native from chip.native import PyChipError +from .ChipUtility import ChipUtility +from .clusters import Attribute as ClusterAttribute +from .clusters import Command as ClusterCommand +from .clusters.CHIPClusters import * +from .exceptions import * +from .interaction_model import delegate as im +from .storage import * + __all__ = [ "DeviceStatusStruct", "ChipStackException", diff --git a/src/controller/python/chip/ChipUtility.py b/src/controller/python/chip/ChipUtility.py index 5f34984f904a0f..08ffa6a1225df5 100644 --- a/src/controller/python/chip/ChipUtility.py +++ b/src/controller/python/chip/ChipUtility.py @@ -21,8 +21,8 @@ # This file is utility for Chip # -from __future__ import absolute_import -from __future__ import print_function +from __future__ import absolute_import, print_function + import binascii from ctypes import * diff --git a/src/controller/python/chip/FabricAdmin.py b/src/controller/python/chip/FabricAdmin.py index 97a729035f811e..fbd4bc2165d11f 100644 --- a/src/controller/python/chip/FabricAdmin.py +++ b/src/controller/python/chip/FabricAdmin.py @@ -18,20 +18,12 @@ # Needed to use types in type hints before they are fully defined. from __future__ import annotations -import ctypes -from dataclasses import dataclass, field -from typing import * -from ctypes import * -from rich.pretty import pprint -import json import logging -import builtins -import base64 -import chip.exceptions -from chip import ChipDeviceCtrl -import copy -from .storage import PersistentStorage -from chip.CertificateAuthority import CertificateAuthority +from ctypes import * +from typing import * + +from chip import CertificateAuthority, ChipDeviceCtrl +from chip.native import GetLibraryHandle class FabricAdmin: @@ -40,13 +32,13 @@ class FabricAdmin: ''' @classmethod def _Handle(cls): - return chip.native.GetLibraryHandle() + return GetLibraryHandle() @classmethod def logger(cls): return logging.getLogger('FabricAdmin') - def __init__(self, certificateAuthority: CertificateAuthority, vendorId: int, fabricId: int = 1): + def __init__(self, certificateAuthority: CertificateAuthority.CertificateAuthority, vendorId: int, fabricId: int = 1): ''' Initializes the object. certificateAuthority: CertificateAuthority instance that will be used to vend NOCs for both @@ -54,7 +46,7 @@ def __init__(self, certificateAuthority: CertificateAuthority, vendorId: int, fa vendorId: Valid operational Vendor ID associated with this fabric. fabricId: Fabric ID to be associated with this fabric. ''' - self._handle = chip.native.GetLibraryHandle() + self._handle = GetLibraryHandle() if (vendorId is None or vendorId == 0): raise ValueError( @@ -87,7 +79,7 @@ def NewController(self, nodeId: int = None, paaTrustStorePath: str = "", useTest useTestCommissioner: If a test commmisioner is to be created. catTags: A list of 32-bit CAT tags that will added to the NOC generated for this controller. ''' - if (not(self._isActive)): + if (not (self._isActive)): raise RuntimeError( f"FabricAdmin object was previously shutdown and is no longer valid!") @@ -104,8 +96,15 @@ def NewController(self, nodeId: int = None, paaTrustStorePath: str = "", useTest self.logger().warning( f"Allocating new controller with CaIndex: {self._certificateAuthority.caIndex}, FabricId: 0x{self._fabricId:016X}, NodeId: 0x{nodeId:016X}, CatTags: {catTags}") - controller = ChipDeviceCtrl.ChipDeviceController(opCredsContext=self._certificateAuthority.GetOpCredsContext(), fabricId=self._fabricId, nodeId=nodeId, - adminVendorId=self._vendorId, paaTrustStorePath=paaTrustStorePath, useTestCommissioner=useTestCommissioner, fabricAdmin=self, catTags=catTags) + controller = ChipDeviceCtrl.ChipDeviceController( + opCredsContext=self._certificateAuthority.GetOpCredsContext(), + fabricId=self._fabricId, + nodeId=nodeId, + adminVendorId=self._vendorId, + paaTrustStorePath=paaTrustStorePath, + useTestCommissioner=useTestCommissioner, + fabricAdmin=self, + catTags=catTags) self._activeControllers.append(controller) return controller @@ -137,5 +136,5 @@ def caIndex(self) -> int: return self._certificateAuthority.caIndex @property - def certificateAuthority(self) -> CertificateAuthority: + def certificateAuthority(self) -> CertificateAuthority.CertificateAuthority: return self._certificateAuthority diff --git a/src/controller/python/chip/ble/__init__.py b/src/controller/python/chip/ble/__init__.py index 5e64b26a9b37ba..9ec88b6441435e 100644 --- a/src/controller/python/chip/ble/__init__.py +++ b/src/controller/python/chip/ble/__init__.py @@ -11,8 +11,8 @@ # limitations under the License. """BLE-related functionality within CHIP""" -from chip.ble.scan_devices import DiscoverAsync, DiscoverSync from chip.ble.get_adapters import GetAdapters +from chip.ble.scan_devices import DiscoverAsync, DiscoverSync __all__ = [ 'GetAdapters', diff --git a/src/controller/python/chip/ble/commissioning/__init__.py b/src/controller/python/chip/ble/commissioning/__init__.py index 05b31f1e1c4812..fff81bd8775a2d 100644 --- a/src/controller/python/chip/ble/commissioning/__init__.py +++ b/src/controller/python/chip/ble/commissioning/__init__.py @@ -13,12 +13,14 @@ # See the License for the specific language governing permissions and # limitations under the License. # + +from dataclasses import dataclass +from enum import Enum +from queue import Queue from typing import Optional + from chip.internal import GetCommissioner from chip.internal.commissioner import PairingState -from queue import Queue -from dataclasses import dataclass -from enum import Enum TEST_NODE_ID = 11223344 diff --git a/src/controller/python/chip/ble/get_adapters.py b/src/controller/python/chip/ble/get_adapters.py index 0f3be727806559..eaff4698b76a0c 100644 --- a/src/controller/python/chip/ble/get_adapters.py +++ b/src/controller/python/chip/ble/get_adapters.py @@ -1,5 +1,6 @@ -from typing import List from dataclasses import dataclass +from typing import List + from chip.ble.library_handle import _GetBleLibraryHandle diff --git a/src/controller/python/chip/ble/library_handle.py b/src/controller/python/chip/ble/library_handle.py index d2469716adb3b5..52f83d65b180b8 100644 --- a/src/controller/python/chip/ble/library_handle.py +++ b/src/controller/python/chip/ble/library_handle.py @@ -14,9 +14,10 @@ # limitations under the License. # -import chip.native import ctypes -from ctypes import c_bool, c_void_p, c_char_p, c_uint32, py_object +from ctypes import c_bool, c_char_p, c_uint32, c_void_p, py_object + +import chip.native from chip.ble.types import DeviceScannedCallback, ScanDoneCallback diff --git a/src/controller/python/chip/ble/scan_devices.py b/src/controller/python/chip/ble/scan_devices.py index 78784e007a9e9c..700f39b7e1de62 100644 --- a/src/controller/python/chip/ble/scan_devices.py +++ b/src/controller/python/chip/ble/scan_devices.py @@ -15,10 +15,11 @@ # import ctypes -from typing import Generator from dataclasses import dataclass -from chip.ble.library_handle import _GetBleLibraryHandle from queue import Queue +from typing import Generator + +from chip.ble.library_handle import _GetBleLibraryHandle from chip.ble.types import DeviceScannedCallback, ScanDoneCallback diff --git a/src/controller/python/chip/ble/types.py b/src/controller/python/chip/ble/types.py index e1e667608e7f39..b56a2e5670b012 100644 --- a/src/controller/python/chip/ble/types.py +++ b/src/controller/python/chip/ble/types.py @@ -14,7 +14,7 @@ # limitations under the License. # -from ctypes import CFUNCTYPE, py_object, c_char_p, c_uint16 +from ctypes import CFUNCTYPE, c_char_p, c_uint16, py_object DeviceScannedCallback = CFUNCTYPE(None, py_object, c_char_p, c_uint16, c_uint16, c_uint16) diff --git a/src/controller/python/chip/clusters/Attribute.py b/src/controller/python/chip/clusters/Attribute.py index 68499a5b9484fa..d83ad04cdb0169 100644 --- a/src/controller/python/chip/clusters/Attribute.py +++ b/src/controller/python/chip/clusters/Attribute.py @@ -17,27 +17,26 @@ # Needed to use types in type hints before they are fully defined. from __future__ import annotations -from asyncio import events -from asyncio.futures import Future +import builtins import ctypes +import inspect +import logging +import sys +from asyncio.futures import Future +from ctypes import CFUNCTYPE, c_size_t, c_uint8, c_uint16, c_uint32, c_uint64, c_void_p, py_object from dataclasses import dataclass, field -from typing import Tuple, Type, Union, List, Any, Callable, Dict, Set, Optional -from ctypes import CFUNCTYPE, c_char_p, c_size_t, c_void_p, c_uint64, c_uint32, c_uint16, c_uint8, py_object, c_uint64 -import construct -from rich.pretty import pprint +from enum import Enum, unique +from typing import Any, Callable, Dict, List, Optional, Union -from .ClusterObjects import Cluster, ClusterAttributeDescriptor, ClusterEvent import chip.exceptions import chip.interaction_model import chip.tlv +import construct from chip.native import PyChipError -from enum import Enum, unique -import inspect -import sys -import logging -import threading -import builtins +from rich.pretty import pprint + +from .ClusterObjects import Cluster, ClusterAttributeDescriptor, ClusterEvent @unique diff --git a/src/controller/python/chip/clusters/ClusterObjects.py b/src/controller/python/chip/clusters/ClusterObjects.py index c3af537dae12c6..13f35f240ae3cb 100644 --- a/src/controller/python/chip/clusters/ClusterObjects.py +++ b/src/controller/python/chip/clusters/ClusterObjects.py @@ -15,11 +15,12 @@ # limitations under the License. # -from dataclasses import dataclass, asdict, field, make_dataclass -from typing import ClassVar, List, Dict, Any, Mapping, Type, Union, ClassVar import enum import typing -from chip import tlv, ChipUtility +from dataclasses import asdict, dataclass, field, make_dataclass +from typing import Any, ClassVar, Dict, List, Mapping, Union + +from chip import ChipUtility, tlv from chip.clusters.Types import Nullable, NullValue from dacite import from_dict @@ -31,7 +32,7 @@ def GetUnionUnderlyingType(typeToCheck, matchingType=None): If that is 'None' (not to be confused with NoneType), then it will retrieve the 'real' type behind the union, i.e not Nullable && not None ''' - if (not(typing.get_origin(typeToCheck) == typing.Union)): + if (not (typing.get_origin(typeToCheck) == typing.Union)): return None for t in typing.get_args(typeToCheck): diff --git a/src/controller/python/chip/clusters/Command.py b/src/controller/python/chip/clusters/Command.py index 83026866e1b0e7..0bc8fc473ffd91 100644 --- a/src/controller/python/chip/clusters/Command.py +++ b/src/controller/python/chip/clusters/Command.py @@ -15,24 +15,21 @@ # limitations under the License. # -from asyncio.futures import Future +import builtins import ctypes +import inspect +import logging +import sys +from asyncio.futures import Future +from ctypes import CFUNCTYPE, c_char_p, c_size_t, c_uint8, c_uint16, c_uint32, c_void_p, py_object from dataclasses import dataclass from typing import Type -from ctypes import CFUNCTYPE, c_char_p, c_size_t, c_void_p, c_uint32, c_uint16, c_uint8, py_object - -from construct.core import ValidationError -from .ClusterObjects import ClusterCommand import chip.exceptions import chip.interaction_model from chip.native import PyChipError -import inspect -import sys -import builtins -import logging - +from .ClusterObjects import ClusterCommand logger = logging.getLogger('chip.cluster.Command') logger.setLevel(logging.ERROR) diff --git a/src/controller/python/chip/clusters/Objects.py b/src/controller/python/chip/clusters/Objects.py index dc59a90dc3045e..07594ef887e438 100644 --- a/src/controller/python/chip/clusters/Objects.py +++ b/src/controller/python/chip/clusters/Objects.py @@ -20,18 +20,22 @@ ''' # This file contains generated struct, enum, command definition. -# Users are not expected to import this file, instead, users can use import chip.clusters, which will import all symbols from this file and can get a readable, pretty naming like clusters.OnOff.commands.OnCommand +# Users are not expected to import this file, instead, users can use import chip.clusters, +# which will import all symbols from this file and can get a readable, pretty naming like +# clusters.OnOff.commands.OnCommand -from dataclasses import dataclass, field import typing +from dataclasses import dataclass, field from enum import IntEnum -from chip import ChipUtility -from chip.tlv import uint, float32 +from chip import ChipUtility +from chip.tlv import float32, uint -from .ClusterObjects import ClusterObject, ClusterObjectDescriptor, ClusterObjectFieldDescriptor, ClusterCommand, ClusterAttributeDescriptor, Cluster, ClusterEvent +from .ClusterObjects import (Cluster, ClusterAttributeDescriptor, ClusterCommand, ClusterEvent, ClusterObject, + ClusterObjectDescriptor, ClusterObjectFieldDescriptor) from .Types import Nullable, NullValue + @dataclass class Identify(Cluster): id: typing.ClassVar[int] = 0x0003 diff --git a/src/controller/python/chip/clusters/TestObjects.py b/src/controller/python/chip/clusters/TestObjects.py index 0ff413e74569bc..6e9f5bd8c0af36 100644 --- a/src/controller/python/chip/clusters/TestObjects.py +++ b/src/controller/python/chip/clusters/TestObjects.py @@ -16,12 +16,14 @@ # -from dataclasses import dataclass import typing -from .ClusterObjects import ClusterObjectDescriptor, ClusterCommand -from chip import ChipUtility +from dataclasses import dataclass from enum import IntEnum +from chip import ChipUtility + +from .ClusterObjects import ClusterCommand, ClusterObjectDescriptor + @dataclass class OnOff: diff --git a/src/controller/python/chip/clusters/Types.py b/src/controller/python/chip/clusters/Types.py index 2c5ac1652976d9..2359705010ec49 100644 --- a/src/controller/python/chip/clusters/Types.py +++ b/src/controller/python/chip/clusters/Types.py @@ -15,6 +15,7 @@ # limitations under the License. # + class Nullable(): def __repr__(self): return 'Null' diff --git a/src/controller/python/chip/clusters/__init__.py b/src/controller/python/chip/clusters/__init__.py index dee5aa9d605a23..32369c56d4fd68 100644 --- a/src/controller/python/chip/clusters/__init__.py +++ b/src/controller/python/chip/clusters/__init__.py @@ -21,7 +21,6 @@ # """Provides Python APIs for CHIP.""" -from . import Command -from . import Attribute + +from . import Attribute, CHIPClusters, Command from .Objects import * -from . import CHIPClusters diff --git a/src/controller/python/chip/discovery/__init__.py b/src/controller/python/chip/discovery/__init__.py index d41325f5ff5a8d..b18467933f97fa 100644 --- a/src/controller/python/chip/discovery/__init__.py +++ b/src/controller/python/chip/discovery/__init__.py @@ -14,16 +14,15 @@ # limitations under the License. # +import enum import logging -import time import threading -import enum - +import time from dataclasses import dataclass -from typing import List, Dict, Set, Callable +from typing import Callable, List, Set from chip.discovery.library_handle import _GetDiscoveryLibraryHandle -from chip.discovery.types import DiscoverSuccessCallback_t, DiscoverFailureCallback_t +from chip.discovery.types import DiscoverFailureCallback_t, DiscoverSuccessCallback_t from chip.native import PyChipError diff --git a/src/controller/python/chip/discovery/library_handle.py b/src/controller/python/chip/discovery/library_handle.py index 19ad5e8954181c..5eb79ba32d291e 100644 --- a/src/controller/python/chip/discovery/library_handle.py +++ b/src/controller/python/chip/discovery/library_handle.py @@ -14,9 +14,10 @@ # limitations under the License. # -import chip.native import ctypes -from chip.discovery.types import DiscoverSuccessCallback_t, DiscoverFailureCallback_t + +import chip.native +from chip.discovery.types import DiscoverFailureCallback_t, DiscoverSuccessCallback_t from chip.native import PyChipError diff --git a/src/controller/python/chip/discovery/types.py b/src/controller/python/chip/discovery/types.py index 34868b804f1bfc..00308f179259f8 100644 --- a/src/controller/python/chip/discovery/types.py +++ b/src/controller/python/chip/discovery/types.py @@ -15,8 +15,8 @@ # from ctypes import CFUNCTYPE, c_char_p, c_uint16, c_uint32, c_uint64 -from chip.native import PyChipError +from chip.native import PyChipError DiscoverSuccessCallback_t = CFUNCTYPE( None, # void return diff --git a/src/controller/python/chip/interaction_model/__init__.py b/src/controller/python/chip/interaction_model/__init__.py index 58ba600e3667e4..1b9fc2177e242e 100644 --- a/src/controller/python/chip/interaction_model/__init__.py +++ b/src/controller/python/chip/interaction_model/__init__.py @@ -21,11 +21,13 @@ # """Provides Python APIs for CHIP.""" + import enum -from .delegate import AttributePath, AttributePathIBstruct, EventPath, EventPathIBstruct, DataVersionFilterIBstruct from chip.exceptions import ChipStackException +from .delegate import AttributePath, AttributePathIBstruct, DataVersionFilterIBstruct, EventPath, EventPathIBstruct + __all__ = ["Status", "InteractionModelError"] diff --git a/src/controller/python/chip/interaction_model/delegate.py b/src/controller/python/chip/interaction_model/delegate.py index 4909a10fc341eb..f5aa54c89dbef7 100644 --- a/src/controller/python/chip/interaction_model/delegate.py +++ b/src/controller/python/chip/interaction_model/delegate.py @@ -14,17 +14,17 @@ limitations under the License. ''' -from abc import abstractmethod -from construct import Struct, Int64ul, Int32ul, Int16ul, Int8ul -from ctypes import CFUNCTYPE, c_void_p, c_uint32, c_uint64, c_uint8, c_uint16, c_ssize_t import ctypes -import chip.native import threading -import chip.tlv -import chip.exceptions import typing +from ctypes import CFUNCTYPE, c_uint8, c_uint32, c_uint64, c_void_p from dataclasses import dataclass +import chip.exceptions +import chip.native +import chip.tlv +from construct import Int8ul, Int16ul, Int32ul, Int64ul, Struct + # The type should match CommandStatus in interaction_model/Delegate.h # CommandStatus should not contain padding IMCommandStatus = Struct( diff --git a/src/controller/python/chip/internal/commissioner.py b/src/controller/python/chip/internal/commissioner.py index 46766faeb374c9..b5cfa62555dd32 100644 --- a/src/controller/python/chip/internal/commissioner.py +++ b/src/controller/python/chip/internal/commissioner.py @@ -13,13 +13,13 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from chip.configuration import GetLocalNodeId -from chip.configuration import GetCommissionerCAT -from chip.native import NativeLibraryHandleMethodArguments, GetLibraryHandle +import ctypes from enum import Enum from typing import Optional + +from chip.configuration import GetCommissionerCAT, GetLocalNodeId from chip.internal.types import NetworkCredentialsRequested, OperationalCredentialsRequested, PairingComplete -import ctypes +from chip.native import GetLibraryHandle, NativeLibraryHandleMethodArguments # Not using c_void_p directly is IMPORTANT. Python auto-casts c_void_p # to intergers and this can cause 32/64 bit issues. diff --git a/src/controller/python/chip/internal/types.py b/src/controller/python/chip/internal/types.py index 27596e0d2e0455..190456969b2006 100644 --- a/src/controller/python/chip/internal/types.py +++ b/src/controller/python/chip/internal/types.py @@ -14,7 +14,7 @@ # limitations under the License. # -from ctypes import CFUNCTYPE, c_void_p, c_size_t, c_uint32 +from ctypes import CFUNCTYPE, c_size_t, c_uint32, c_void_p # General callback of 'network credentials requested. No python-data # is available as the underlying callback is used internally diff --git a/src/controller/python/chip/logging/__init__.py b/src/controller/python/chip/logging/__init__.py index 5228fdd90e5444..980c33ac92482d 100644 --- a/src/controller/python/chip/logging/__init__.py +++ b/src/controller/python/chip/logging/__init__.py @@ -14,10 +14,10 @@ # limitations under the License. # -from chip.logging.library_handle import _GetLoggingLibraryHandle -from chip.logging.types import LogRedirectCallback_t import logging +from chip.logging.library_handle import _GetLoggingLibraryHandle +from chip.logging.types import LogRedirectCallback_t # Defines match support/logging/Constants.h (LogCategory enum) ERROR_CATEGORY_NONE = 0 diff --git a/src/controller/python/chip/logging/library_handle.py b/src/controller/python/chip/logging/library_handle.py index 0ed77f64d89978..ae34f502fd1093 100644 --- a/src/controller/python/chip/logging/library_handle.py +++ b/src/controller/python/chip/logging/library_handle.py @@ -14,8 +14,9 @@ # limitations under the License. # -import chip.native import ctypes + +import chip.native from chip.logging.types import LogRedirectCallback_t diff --git a/src/controller/python/chip/native/__init__.py b/src/controller/python/chip/native/__init__.py index 1810c18c62f69d..e83821242bf583 100644 --- a/src/controller/python/chip/native/__init__.py +++ b/src/controller/python/chip/native/__init__.py @@ -1,11 +1,12 @@ import ctypes +import enum import glob import os import platform -import construct -import chip.exceptions import typing -import enum + +import chip.exceptions +import construct NATIVE_LIBRARY_BASE_NAME = "_ChipDeviceCtrl.so" diff --git a/src/controller/python/chip/server/types.py b/src/controller/python/chip/server/types.py index ec5c13d462ff7e..3df693d1049861 100644 --- a/src/controller/python/chip/server/types.py +++ b/src/controller/python/chip/server/types.py @@ -1,4 +1,4 @@ -from ctypes import CFUNCTYPE, py_object, c_char_p, c_uint8, c_uint16 +from ctypes import CFUNCTYPE, c_char_p, c_uint8, c_uint16 PostAttributeChangeCallback = CFUNCTYPE( None, diff --git a/src/controller/python/chip/setup_payload/setup_payload.py b/src/controller/python/chip/setup_payload/setup_payload.py index 63dad272ed0cab..fd3d8e1db036b7 100644 --- a/src/controller/python/chip/setup_payload/setup_payload.py +++ b/src/controller/python/chip/setup_payload/setup_payload.py @@ -14,11 +14,11 @@ # limitations under the License. # -from chip.native import GetLibraryHandle, NativeLibraryHandleMethodArguments -from chip.exceptions import ChipStackError - from ctypes import CFUNCTYPE, c_char_p, c_int32, c_uint8 +from chip.exceptions import ChipStackError +from chip.native import GetLibraryHandle, NativeLibraryHandleMethodArguments + class SetupPayload: # AttributeVisitor: void(const char* name, const char* value) diff --git a/src/controller/python/chip/storage/__init__.py b/src/controller/python/chip/storage/__init__.py index 926b7e12855849..07fdb1f6615dff 100644 --- a/src/controller/python/chip/storage/__init__.py +++ b/src/controller/python/chip/storage/__init__.py @@ -18,18 +18,16 @@ # Needed to use types in type hints before they are fully defined. from __future__ import annotations +import base64 +import copy import ctypes -from dataclasses import dataclass, field -from typing import * -from ctypes import * -from rich.pretty import pprint import json import logging -import base64 +from ctypes import * +from typing import Dict + import chip.exceptions -import copy import chip.native -import builtins _SyncSetKeyValueCbFunct = CFUNCTYPE( None, py_object, c_char_p, POINTER(c_char), c_uint16) @@ -194,7 +192,7 @@ def SetReplKey(self, key: str, value): raise ValueError("Invalid Key") if (value is None): - del(self._jsonData['repl-config'][key]) + del (self._jsonData['repl-config'][key]) else: self._jsonData['repl-config'][key] = value @@ -238,7 +236,7 @@ def DeleteSdkKey(self, key: str): ''' self.logger().info(f"DeleteSdkKey: {key}") - del(self._jsonData['sdk-config'][key]) + del (self._jsonData['sdk-config'][key]) self.Commit() def Shutdown(self): diff --git a/src/controller/python/chip/tlv/__init__.py b/src/controller/python/chip/tlv/__init__.py index 5665c5e2a4f46b..6b22fbb8536299 100644 --- a/src/controller/python/chip/tlv/__init__.py +++ b/src/controller/python/chip/tlv/__init__.py @@ -25,8 +25,7 @@ # -from __future__ import absolute_import -from __future__ import print_function +from __future__ import absolute_import, print_function import struct from collections import OrderedDict diff --git a/src/controller/python/chip/utils/CommissioningBuildingBlocks.py b/src/controller/python/chip/utils/CommissioningBuildingBlocks.py index d68b32bf013f1e..ae0fbc395e7da4 100644 --- a/src/controller/python/chip/utils/CommissioningBuildingBlocks.py +++ b/src/controller/python/chip/utils/CommissioningBuildingBlocks.py @@ -15,18 +15,16 @@ # limitations under the License. # -import asyncio import logging import os +import typing import chip.clusters as Clusters -import chip.tlv -from chip.clusters import OperationalCredentials as opCreds -from chip.clusters import GeneralCommissioning as generalCommissioning -from chip.FabricAdmin import FabricAdmin as FabricAdmin -import typing 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.FabricAdmin import FabricAdmin as FabricAdmin _UINT16_MAX = 65535 @@ -91,7 +89,7 @@ async def GrantPrivilege(adminCtrl: ChipDeviceController, grantedCtrl: ChipDevic break # Step 3: If there isn't an existing entry to add to, make a new one. - if (not(addedPrivilege)): + 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!") diff --git a/src/controller/python/chip/utils/__init__.py b/src/controller/python/chip/utils/__init__.py index 198b3b6d575898..7cedcb67655385 100644 --- a/src/controller/python/chip/utils/__init__.py +++ b/src/controller/python/chip/utils/__init__.py @@ -21,4 +21,9 @@ # """Provides commissioning building blocks Python APIs for CHIP.""" + from . import CommissioningBuildingBlocks + +__all__ = [ + 'CommissioningBuildingBlocks', +] diff --git a/src/controller/python/chip/yaml/__init__.py b/src/controller/python/chip/yaml/__init__.py index 08850e21feea48..e099964280b22d 100644 --- a/src/controller/python/chip/yaml/__init__.py +++ b/src/controller/python/chip/yaml/__init__.py @@ -20,4 +20,5 @@ # Provides Python APIs for Matter. """Provides yaml parser Python APIs for Matter.""" + from . import runner diff --git a/src/controller/python/chip/yaml/data_model_lookup.py b/src/controller/python/chip/yaml/data_model_lookup.py index 215ac8fcbd9380..afabeb15278ace 100644 --- a/src/controller/python/chip/yaml/data_model_lookup.py +++ b/src/controller/python/chip/yaml/data_model_lookup.py @@ -16,6 +16,7 @@ # from abc import ABC, abstractmethod + import chip.clusters as Clusters diff --git a/src/controller/python/chip/yaml/format_converter.py b/src/controller/python/chip/yaml/format_converter.py index ce2edfdc6af4eb..3f740d7e1d0e1e 100644 --- a/src/controller/python/chip/yaml/format_converter.py +++ b/src/controller/python/chip/yaml/format_converter.py @@ -15,10 +15,11 @@ # limitations under the License. # +import enum import typing + from chip.clusters.Types import Nullable, NullValue -from chip.tlv import uint, float32 -import enum +from chip.tlv import float32, uint from chip.yaml.errors import ValidationError @@ -165,10 +166,10 @@ def convert_to_data_model_type(field_value, field_type): return_field_value[field_descriptor.Label] = convert_to_data_model_type( field_value[item], field_descriptor.Type) return return_field_value - elif(type(field_value) is float): + elif (type(field_value) is float): return float32(field_value) # list represents a data model list - elif(type(field_value) is list): + elif (type(field_value) is list): list_element_type = typing.get_args(field_type)[0] # The field type passed in is the type of the list element and not list[T]. diff --git a/src/controller/python/chip/yaml/runner.py b/src/controller/python/chip/yaml/runner.py index f55d6ccb2efce7..c901c0ee748204 100644 --- a/src/controller/python/chip/yaml/runner.py +++ b/src/controller/python/chip/yaml/runner.py @@ -15,18 +15,20 @@ # limitations under the License. # +import asyncio as asyncio +import logging from abc import ABC, abstractmethod from dataclasses import dataclass -from chip import ChipDeviceCtrl from enum import Enum -import stringcase + import chip.interaction_model -import asyncio as asyncio -import logging -from chip.yaml.errors import ParsingError, UnexpectedParsingError +import chip.yaml.format_converter as Converter +import stringcase +from chip import ChipDeviceCtrl from chip.clusters.Attribute import AttributeStatus, ValueDecodeFailure +from chip.yaml.errors import ParsingError, UnexpectedParsingError + from .data_model_lookup import * -import chip.yaml.format_converter as Converter logger = logging.getLogger('YamlParser') diff --git a/src/controller/python/templates/python-cluster-Objects-py.zapt b/src/controller/python/templates/python-cluster-Objects-py.zapt index 5695721c7100c6..59cf38258fc15f 100644 --- a/src/controller/python/templates/python-cluster-Objects-py.zapt +++ b/src/controller/python/templates/python-cluster-Objects-py.zapt @@ -3,18 +3,22 @@ ''' # This file contains generated struct, enum, command definition. -# Users are not expected to import this file, instead, users can use import chip.clusters, which will import all symbols from this file and can get a readable, pretty naming like clusters.OnOff.commands.OnCommand +# Users are not expected to import this file, instead, users can use import chip.clusters, +# which will import all symbols from this file and can get a readable, pretty naming like +# clusters.OnOff.commands.OnCommand -from dataclasses import dataclass, field import typing +from dataclasses import dataclass, field from enum import IntEnum -from chip import ChipUtility -from chip.tlv import uint, float32 +from chip import ChipUtility +from chip.tlv import float32, uint -from .ClusterObjects import ClusterObject, ClusterObjectDescriptor, ClusterObjectFieldDescriptor, ClusterCommand, ClusterAttributeDescriptor, Cluster, ClusterEvent +from .ClusterObjects import (Cluster, ClusterAttributeDescriptor, ClusterCommand, ClusterEvent, ClusterObject, + ClusterObjectDescriptor, ClusterObjectFieldDescriptor) from .Types import Nullable, NullValue + {{#zcl_clusters}} @dataclass class {{asUpperCamelCase name}}(Cluster): @@ -88,7 +92,7 @@ class {{asUpperCamelCase name}}(Cluster): is_client: typing.ClassVar[bool] = False {{else}} is_client: typing.ClassVar[bool] = True -{{/if}} +{{/if}} {{~#if responseName}} response_type: typing.ClassVar[str] = '{{asUpperCamelCase responseName}}' diff --git a/src/controller/python/test/test_scripts/base.py b/src/controller/python/test/test_scripts/base.py index 9995492c26c135..5cefae37631d2a 100644 --- a/src/controller/python/test/test_scripts/base.py +++ b/src/controller/python/test/test_scripts/base.py @@ -16,32 +16,30 @@ # import asyncio -from dataclasses import dataclass -from inspect import Attribute +import copy +import ctypes +import faulthandler import inspect -from typing import Any -import typing -from chip import ChipDeviceCtrl -from chip import ChipCommissionableNodeCtrl -import chip.interaction_model as IM -import threading +import logging import os +import secrets import sys -import logging +import threading import time -import ctypes +from dataclasses import dataclass +from inspect import Attribute +from typing import Any + +import chip.CertificateAuthority import chip.clusters as Clusters import chip.clusters.Attribute as Attribute -from chip.utils import CommissioningBuildingBlocks -from chip.ChipStack import * -import chip.native -import chip.FabricAdmin -import chip.CertificateAuthority import chip.discovery -import copy -import secrets -import faulthandler -import ipdb +import chip.FabricAdmin +import chip.interaction_model as IM +import chip.native +from chip import ChipDeviceCtrl +from chip.ChipStack import * +from chip.utils import CommissioningBuildingBlocks logger = logging.getLogger('PythonMatterControllerTEST') logger.setLevel(logging.INFO) @@ -395,7 +393,7 @@ async def TestControllerCATValues(self, nodeid: int): # Read out an attribute using the new controller. It has no privileges, so this should fail with an UnsupportedAccess error. res = await newControllers[0].ReadAttribute(nodeid=nodeid, attributes=[(0, Clusters.AccessControl.Attributes.Acl)]) - if(res[0][Clusters.AccessControl][Clusters.AccessControl.Attributes.Acl].Reason.status != IM.Status.UnsupportedAccess): + if (res[0][Clusters.AccessControl][Clusters.AccessControl.Attributes.Acl].Reason.status != IM.Status.UnsupportedAccess): self.logger.error(f"1: Received data instead of an error:{res}") return False @@ -426,7 +424,7 @@ async def TestMultiControllerFabric(self, nodeid: int): # Read out the ACL list from one of the newly minted controllers which has no access. This should return an IM error. # res = await newControllers[0].ReadAttribute(nodeid=nodeid, attributes=[(0, Clusters.AccessControl.Attributes.Acl)]) - if(res[0][Clusters.AccessControl][Clusters.AccessControl.Attributes.Acl].Reason.status != IM.Status.UnsupportedAccess): + if (res[0][Clusters.AccessControl][Clusters.AccessControl.Attributes.Acl].Reason.status != IM.Status.UnsupportedAccess): self.logger.error(f"1: Received data instead of an error:{res}") return False @@ -444,7 +442,7 @@ async def TestMultiControllerFabric(self, nodeid: int): # under-neath. # res = await newControllers[0].ReadAttribute(nodeid=nodeid, attributes=[(0, Clusters.AccessControl.Attributes.Acl)]) - if(res[0][Clusters.AccessControl][Clusters.AccessControl.Attributes.Acl].Reason.status != IM.Status.UnsupportedAccess): + if (res[0][Clusters.AccessControl][Clusters.AccessControl.Attributes.Acl].Reason.status != IM.Status.UnsupportedAccess): self.logger.error(f"3: Received data instead of an error:{res}") return False @@ -471,7 +469,7 @@ async def TestMultiControllerFabric(self, nodeid: int): # await CommissioningBuildingBlocks.GrantPrivilege(adminCtrl=self.devCtrl, grantedCtrl=newControllers[1], privilege=Clusters.AccessControl.Enums.AccessControlEntryPrivilegeEnum.kView, targetNodeId=nodeid) res = await newControllers[1].ReadAttribute(nodeid=nodeid, attributes=[(0, Clusters.AccessControl.Attributes.Acl)]) - if(res[0][Clusters.AccessControl][Clusters.AccessControl.Attributes.Acl].Reason.status != IM.Status.UnsupportedAccess): + if (res[0][Clusters.AccessControl][Clusters.AccessControl.Attributes.Acl].Reason.status != IM.Status.UnsupportedAccess): self.logger.error(f"6: Received data5 instead of an error:{res}") return False @@ -919,7 +917,7 @@ async def OnResubscriptionSucceeded(transaction): subscription.OverrideLivenessTimeoutMs(100) async with cv: - if (not(resubAttempted) or not(resubSucceeded)): + if (not (resubAttempted) or not (resubSucceeded)): res = await asyncio.wait_for(cv.wait(), 3) if not res: self.logger.error("Timed out waiting for resubscription to succeed") diff --git a/src/controller/python/test/test_scripts/cluster_objects.py b/src/controller/python/test/test_scripts/cluster_objects.py index f5f3b5b85af7e2..eadcc413a1462a 100644 --- a/src/controller/python/test/test_scripts/cluster_objects.py +++ b/src/controller/python/test/test_scripts/cluster_objects.py @@ -15,17 +15,16 @@ # limitations under the License. # +import asyncio +import logging import pprint + +import base import chip.clusters as Clusters import chip.exceptions -import logging -from chip.clusters.Attribute import AttributePath, AttributeReadResult, AttributeStatus, ValueDecodeFailure, TypedAttributePath, SubscriptionTransaction, DataVersion import chip.interaction_model -import asyncio -import time -import sys - -import base +from chip.clusters.Attribute import (AttributePath, AttributeStatus, DataVersion, SubscriptionTransaction, TypedAttributePath, + ValueDecodeFailure) logger = logging.getLogger('PythonMatterControllerTEST') logger.setLevel(logging.INFO) @@ -143,9 +142,9 @@ async def TestWriteRequest(cls, devCtrl): ]) expectedRes = [ AttributeStatus(Path=AttributePath(EndpointId=0, ClusterId=40, - AttributeId=5), Status=chip.interaction_model.Status.Success), + AttributeId=5), Status=chip.interaction_model.Status.Success), AttributeStatus(Path=AttributePath(EndpointId=0, ClusterId=40, - AttributeId=6), Status=chip.interaction_model.Status.ConstraintError) + AttributeId=6), Status=chip.interaction_model.Status.ConstraintError) ] logger.info(f"Received WriteResponse: {res}") diff --git a/src/controller/python/test/test_scripts/commissioning_failure_test.py b/src/controller/python/test/test_scripts/commissioning_failure_test.py index 1437c646c14f15..8b9edbfee514d1 100755 --- a/src/controller/python/test/test_scripts/commissioning_failure_test.py +++ b/src/controller/python/test/test_scripts/commissioning_failure_test.py @@ -18,15 +18,14 @@ # # Commissioning test. + import os import sys from optparse import OptionParser -from base import TestFail, TestTimeout, BaseTestHelper, FailIfNot, logger -from cluster_objects import NODE_ID, ClusterObjectTests -from network_commissioning import NetworkCommissioningTests -import asyncio -# The thread network dataset tlv for testing, splited into T-L-V. +from base import BaseTestHelper, FailIfNot, TestFail, TestTimeout, logger + +# The thread network dataset tlv for testing, splitted into T-L-V. TEST_THREAD_NETWORK_DATASET_TLV = "0e080000000000010000" + \ "000300000c" + \ diff --git a/src/controller/python/test/test_scripts/commissioning_test.py b/src/controller/python/test/test_scripts/commissioning_test.py index 0e62b953718ba1..ca3ac311983d6d 100755 --- a/src/controller/python/test/test_scripts/commissioning_test.py +++ b/src/controller/python/test/test_scripts/commissioning_test.py @@ -18,15 +18,14 @@ # # Commissioning test. + import os import sys from optparse import OptionParser -from base import TestFail, TestTimeout, BaseTestHelper, FailIfNot, logger -from cluster_objects import NODE_ID, ClusterObjectTests -from network_commissioning import NetworkCommissioningTests -import asyncio -# The thread network dataset tlv for testing, splited into T-L-V. +from base import BaseTestHelper, FailIfNot, TestFail, TestTimeout, logger + +# The thread network dataset tlv for testing, splitted into T-L-V. TEST_THREAD_NETWORK_DATASET_TLV = "0e080000000000010000" + \ "000300000c" + \ diff --git a/src/controller/python/test/test_scripts/failsafe_tests.py b/src/controller/python/test/test_scripts/failsafe_tests.py index 7d2ee73d6efdcd..4b3838430ca213 100755 --- a/src/controller/python/test/test_scripts/failsafe_tests.py +++ b/src/controller/python/test/test_scripts/failsafe_tests.py @@ -18,15 +18,14 @@ # # Commissioning test. + import os import sys from optparse import OptionParser -from base import TestFail, TestTimeout, BaseTestHelper, FailIfNot, logger -from cluster_objects import NODE_ID, ClusterObjectTests -from network_commissioning import NetworkCommissioningTests -import asyncio -# The thread network dataset tlv for testing, splited into T-L-V. +from base import BaseTestHelper, FailIfNot, TestFail, TestTimeout, logger + +# The thread network dataset tlv for testing, splitted into T-L-V. TEST_THREAD_NETWORK_DATASET_TLV = "0e080000000000010000" + \ "000300000c" + \ diff --git a/src/controller/python/test/test_scripts/mobile-device-test.py b/src/controller/python/test/test_scripts/mobile-device-test.py index 4f63e8aadefb1e..e602194f29efbf 100755 --- a/src/controller/python/test/test_scripts/mobile-device-test.py +++ b/src/controller/python/test/test_scripts/mobile-device-test.py @@ -18,20 +18,19 @@ # # Commissioning test. -from logging import disable + +import asyncio import os -import sys + +import base +import chip.logging import click import coloredlogs -import chip.logging -import logging -from base import TestFail, TestTimeout, BaseTestHelper, FailIfNot, logger, TestIsEnabled, SetTestSet -import base -from cluster_objects import NODE_ID, ClusterObjectTests +from base import BaseTestHelper, FailIfNot, SetTestSet, TestFail, TestTimeout, logger +from cluster_objects import ClusterObjectTests from network_commissioning import NetworkCommissioningTests -import asyncio -# The thread network dataset tlv for testing, splited into T-L-V. +# The thread network dataset tlv for testing, splitted into T-L-V. TEST_THREAD_NETWORK_DATASET_TLV = "0e080000000000010000" + \ "000300000c" + \ diff --git a/src/controller/python/test/test_scripts/network_commissioning.py b/src/controller/python/test/test_scripts/network_commissioning.py index ca1d5573a13611..64c5510c4e9624 100644 --- a/src/controller/python/test/test_scripts/network_commissioning.py +++ b/src/controller/python/test/test_scripts/network_commissioning.py @@ -15,15 +15,14 @@ # limitations under the License. # -import chip.clusters as Clusters -import logging -from chip.clusters.Attribute import AttributePath, AttributeReadResult, AttributeStatus, ValueDecodeFailure -from chip.clusters.Types import NullValue -import chip.interaction_model import asyncio +import logging import random import base +import chip.clusters as Clusters +import chip.interaction_model +from chip.clusters.Types import NullValue logger = logging.getLogger('NetworkCommissioning') logger.setLevel(logging.INFO) diff --git a/src/controller/python/test/test_scripts/split_commissioning_test.py b/src/controller/python/test/test_scripts/split_commissioning_test.py index 1652231b4ea222..47fedb3aadee8f 100755 --- a/src/controller/python/test/test_scripts/split_commissioning_test.py +++ b/src/controller/python/test/test_scripts/split_commissioning_test.py @@ -18,15 +18,14 @@ # # Commissioning test. + import os import sys from optparse import OptionParser -from base import TestFail, TestTimeout, BaseTestHelper, FailIfNot, logger -from cluster_objects import NODE_ID, ClusterObjectTests -from network_commissioning import NetworkCommissioningTests -import asyncio -# The thread network dataset tlv for testing, splited into T-L-V. +from base import BaseTestHelper, FailIfNot, TestFail, TestTimeout, logger + +# The thread network dataset tlv for testing, splitted into T-L-V. TEST_THREAD_NETWORK_DATASET_TLV = "0e080000000000010000" + \ "000300000c" + \ diff --git a/src/controller/python/test/unit_tests/test_cluster_objects.py b/src/controller/python/test/unit_tests/test_cluster_objects.py index b687cca0036223..926bc0f32d1b99 100644 --- a/src/controller/python/test/unit_tests/test_cluster_objects.py +++ b/src/controller/python/test/unit_tests/test_cluster_objects.py @@ -1,11 +1,10 @@ import typing import unittest - from dataclasses import dataclass +import chip.ChipUtility from chip.clusters import ClusterObjects from chip.tlv import TLVReader, TLVWriter, uint -import chip.ChipUtility ''' This file contains tests for checking if the cluster object can generate correct TLV data. diff --git a/src/controller/python/test/unit_tests/test_generated_clusterobjects.py b/src/controller/python/test/unit_tests/test_generated_clusterobjects.py index 2c415345436254..cdcc8bffa1a4ac 100644 --- a/src/controller/python/test/unit_tests/test_generated_clusterobjects.py +++ b/src/controller/python/test/unit_tests/test_generated_clusterobjects.py @@ -1,10 +1,8 @@ import unittest + import chip.clusters as Clusters +from chip.clusters.Types import NullValue from rich.pretty import pprint -from rich.console import Console -from chip.clusters.Types import Nullable, NullValue -import logging -from rich.logging import RichHandler ''' This file contains tests for validating the generated cluster objects by running encoding and decoding diff --git a/src/controller/python/test/unit_tests/test_tlv.py b/src/controller/python/test/unit_tests/test_tlv.py index 901197b4ea4742..ad37b53c190a69 100644 --- a/src/controller/python/test/unit_tests/test_tlv.py +++ b/src/controller/python/test/unit_tests/test_tlv.py @@ -15,12 +15,11 @@ # limitations under the License. # +import unittest -from chip.tlv import TLVWriter, TLVReader +from chip.tlv import TLVReader, TLVWriter from chip.tlv import uint as tlvUint -import unittest - class TestTLVWriter(unittest.TestCase): def _getEncoded(self, val, tag=None): diff --git a/src/lib/asn1/gen_asn1oid.py b/src/lib/asn1/gen_asn1oid.py index e4c9943b68d2c2..020cc49a1624f1 100755 --- a/src/lib/asn1/gen_asn1oid.py +++ b/src/lib/asn1/gen_asn1oid.py @@ -26,8 +26,8 @@ # TLV encodings (notably the Matter Certificate object). # -from __future__ import absolute_import -from __future__ import print_function +from __future__ import absolute_import, print_function + import optparse import sys diff --git a/src/lib/support/verhoeff/Verhoeff.py b/src/lib/support/verhoeff/Verhoeff.py index caa5fe8b43c9e8..ff986cbf240ce3 100755 --- a/src/lib/support/verhoeff/Verhoeff.py +++ b/src/lib/support/verhoeff/Verhoeff.py @@ -25,9 +25,10 @@ # a given base. # -from __future__ import absolute_import -from __future__ import print_function +from __future__ import absolute_import, print_function + import sys + from six.moves import range __all__ = ['ComputeCheckChar', 'VerifyCheckChar', diff --git a/src/pybindings/pycontroller/build-chip-wheel.py b/src/pybindings/pycontroller/build-chip-wheel.py index d1de5922443b2b..bf5b130bd0afaa 100644 --- a/src/pybindings/pycontroller/build-chip-wheel.py +++ b/src/pybindings/pycontroller/build-chip-wheel.py @@ -22,16 +22,16 @@ # from __future__ import absolute_import -from datetime import datetime -from setuptools import setup -from wheel.bdist_wheel import bdist_wheel import argparse import json import os import platform import shutil +from datetime import datetime +from setuptools import 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/python_testing/TC_DA_1_7.py b/src/python_testing/TC_DA_1_7.py index d36aa4e241eddc..b16faccbd339bc 100644 --- a/src/python_testing/TC_DA_1_7.py +++ b/src/python_testing/TC_DA_1_7.py @@ -15,20 +15,20 @@ # limitations under the License. # -from matter_testing_support import MatterBaseTest, default_matter_test_main, async_test_body -from matter_testing_support import hex_from_bytes, bytes_from_hex -from chip.interaction_model import Status -import chip.clusters as Clusters import logging -from mobly import asserts -from pathlib import Path from glob import glob -from cryptography.x509 import load_der_x509_certificate, SubjectKeyIdentifier, AuthorityKeyIdentifier, Certificate +from pathlib import Path +from typing import Optional + +import chip.clusters as Clusters +from chip.interaction_model import Status from cryptography.exceptions import InvalidSignature from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import ec -from cryptography.hazmat.primitives.serialization import PublicFormat, Encoding -from typing import Optional +from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat +from cryptography.x509 import AuthorityKeyIdentifier, Certificate, SubjectKeyIdentifier, load_der_x509_certificate +from matter_testing_support import MatterBaseTest, async_test_body, bytes_from_hex, default_matter_test_main, hex_from_bytes +from mobly import asserts FORBIDDEN_AKID = [ bytes_from_hex("78:5C:E7:05:B8:6B:8F:4E:6F:C7:93:AA:60:CB:43:EA:69:68:82:D5"), diff --git a/src/python_testing/TC_RR_1_1.py b/src/python_testing/TC_RR_1_1.py index 85ffaba8d221ad..c9704416f6d2a7 100644 --- a/src/python_testing/TC_RR_1_1.py +++ b/src/python_testing/TC_RR_1_1.py @@ -15,22 +15,22 @@ # limitations under the License. # -from matter_testing_support import MatterBaseTest, default_matter_test_main, async_test_body -import chip.clusters as Clusters -import chip.FabricAdmin -import chip.CertificateAuthority +import asyncio import logging -from mobly import asserts -from chip.utils import CommissioningBuildingBlocks -from chip.clusters.Attribute import TypedAttributePath, SubscriptionTransaction, AttributeStatus -from chip.interaction_model import Status as StatusEnum import queue -import asyncio +import random +import time from binascii import hexlify from threading import Event -import time -import random +import chip.CertificateAuthority +import chip.clusters as Clusters +import chip.FabricAdmin +from chip.clusters.Attribute import AttributeStatus, SubscriptionTransaction, TypedAttributePath +from chip.interaction_model import Status as StatusEnum +from chip.utils import CommissioningBuildingBlocks +from matter_testing_support import MatterBaseTest, async_test_body, default_matter_test_main +from mobly import asserts from TC_SC_3_6 import AttributeChangeAccumulator, ResubscriptionCatcher # TODO: Overall, we need to add validation that session IDs have not changed throughout to be agnostic diff --git a/src/python_testing/TC_SC_3_6.py b/src/python_testing/TC_SC_3_6.py index 363db9118e1cb3..55d34baffee24b 100644 --- a/src/python_testing/TC_SC_3_6.py +++ b/src/python_testing/TC_SC_3_6.py @@ -15,18 +15,19 @@ # limitations under the License. # -from matter_testing_support import MatterBaseTest, default_matter_test_main, async_test_body -import chip.clusters as Clusters -import chip.FabricAdmin -import chip.CertificateAuthority +import asyncio import logging -from mobly import asserts -from chip.utils import CommissioningBuildingBlocks -from chip.clusters.Attribute import TypedAttributePath, SubscriptionTransaction import queue -import asyncio -from threading import Event import time +from threading import Event + +import chip.CertificateAuthority +import chip.clusters as Clusters +import chip.FabricAdmin +from chip.clusters.Attribute import SubscriptionTransaction, TypedAttributePath +from chip.utils import CommissioningBuildingBlocks +from matter_testing_support import MatterBaseTest, async_test_body, default_matter_test_main +from mobly import asserts # TODO: Overall, we need to add validation that session IDs have not changed throughout to be agnostic # to some internal behavior assumptions of the SDK we are making relative to the write to diff --git a/src/python_testing/TC_TestEventTrigger.py b/src/python_testing/TC_TestEventTrigger.py index 8834417e41d847..495baa72aae7d0 100644 --- a/src/python_testing/TC_TestEventTrigger.py +++ b/src/python_testing/TC_TestEventTrigger.py @@ -15,11 +15,12 @@ # limitations under the License. # +import logging from imaplib import Commands -from matter_testing_support import MatterBaseTest, default_matter_test_main, async_test_body -from chip.interaction_model import Status, InteractionModelError + import chip.clusters as Clusters -import logging +from chip.interaction_model import InteractionModelError, Status +from matter_testing_support import MatterBaseTest, async_test_body, default_matter_test_main from mobly import asserts # Assumes `--enable-key 000102030405060708090a0b0c0d0e0f` on Linux app command line, or a DUT diff --git a/src/python_testing/hello_test.py b/src/python_testing/hello_test.py index 57255112fd20c4..70d4bbf97ddcd8 100644 --- a/src/python_testing/hello_test.py +++ b/src/python_testing/hello_test.py @@ -15,10 +15,11 @@ # limitations under the License. # -from matter_testing_support import MatterBaseTest, default_matter_test_main, async_test_body -from chip.interaction_model import Status -import chip.clusters as Clusters import logging + +import chip.clusters as Clusters +from chip.interaction_model import Status +from matter_testing_support import MatterBaseTest, async_test_body, default_matter_test_main from mobly import asserts diff --git a/src/python_testing/matter_testing_support.py b/src/python_testing/matter_testing_support.py index e558d5389ba2da..3b3555a9a8a5d0 100644 --- a/src/python_testing/matter_testing_support.py +++ b/src/python_testing/matter_testing_support.py @@ -16,34 +16,31 @@ # import argparse -from binascii import unhexlify, hexlify -import logging -from chip import ChipDeviceCtrl -import chip.clusters as Clusters -from chip.ChipStack import * -from chip.storage import PersistentStorage -import chip.logging -import chip.native -import chip.FabricAdmin -import chip.CertificateAuthority -from chip.utils import CommissioningBuildingBlocks +import asyncio import builtins -from typing import Optional, List, Tuple -from dataclasses import dataclass, field -from dataclasses import asdict as dataclass_asdict -import re +import json +import logging import os -import sys import pathlib -import json +import re +import sys import uuid -import asyncio +from binascii import hexlify, unhexlify +from dataclasses import asdict as dataclass_asdict +from dataclasses import dataclass, field +from typing import List, Optional, Tuple -from mobly import base_test -from mobly.config_parser import TestRunConfig, ENV_MOBLY_LOGPATH -from mobly import logger -from mobly import signals -from mobly import utils +import chip.CertificateAuthority +import chip.clusters as Clusters +import chip.FabricAdmin +import chip.logging +import chip.native +from chip import ChipDeviceCtrl +from chip.ChipStack import * +from chip.storage import PersistentStorage +from chip.utils import CommissioningBuildingBlocks +from mobly import base_test, logger, signals, utils +from mobly.config_parser import ENV_MOBLY_LOGPATH, TestRunConfig from mobly.test_runner import TestRunner # TODO: Add utility to commission a device if needed diff --git a/src/test_driver/efr32/py/nl_test_runner/nl_test_runner.py b/src/test_driver/efr32/py/nl_test_runner/nl_test_runner.py index 492fc3fa8ecf22..01c124bb6bf2d9 100644 --- a/src/test_driver/efr32/py/nl_test_runner/nl_test_runner.py +++ b/src/test_driver/efr32/py/nl_test_runner/nl_test_runner.py @@ -17,16 +17,16 @@ import argparse import logging -from pw_hdlc.rpc import HdlcRpcClient, default_channels, write_to_file -from pw_status import Status -import serial # type: ignore import subprocess import sys import time from typing import Any +import serial # type: ignore +from pw_hdlc.rpc import HdlcRpcClient, default_channels, write_to_file + # RPC Protos -from nl_test_service import nl_test_pb2 +from nl_test_service import nl_test_pb2 # isort:skip PW_LOG = logging.getLogger(__name__) @@ -103,7 +103,7 @@ def on_error_callback(call_object, error): colors.HEADER + streamed_data.test_suite_start.suite_name) + colors.ENDC) if streamed_data.HasField("test_case_run"): print("\t{}: {}".format(streamed_data.test_case_run.test_case_name, - FAIL_STRING if streamed_data.test_case_run.failed else PASS_STRING)) + FAIL_STRING if streamed_data.test_case_run.failed else PASS_STRING)) if streamed_data.HasField("test_suite_tests_run_summary"): total_run += streamed_data.test_suite_tests_run_summary.total_count total_failed += streamed_data.test_suite_tests_run_summary.failed_count diff --git a/src/test_driver/esp32/run_qemu_image.py b/src/test_driver/esp32/run_qemu_image.py index 698649fc64c5d7..6d684c95ce7df1 100755 --- a/src/test_driver/esp32/run_qemu_image.py +++ b/src/test_driver/esp32/run_qemu_image.py @@ -13,13 +13,14 @@ # See the License for the specific language governing permissions and # limitations under the License. -import coloredlogs -import click import logging import os import re -import sys import subprocess +import sys + +import click +import coloredlogs # Supported log levels, mapping string values required for argument # parsing into logging constants diff --git a/src/test_driver/linux-cirque/CommissioningFailureOnReportTest.py b/src/test_driver/linux-cirque/CommissioningFailureOnReportTest.py index bca82e7795a8e1..4f657235af1a53 100755 --- a/src/test_driver/linux-cirque/CommissioningFailureOnReportTest.py +++ b/src/test_driver/linux-cirque/CommissioningFailureOnReportTest.py @@ -18,8 +18,8 @@ import logging import os import pprint -import time import sys +import time from helper.CHIPTestBase import CHIPVirtualHome diff --git a/src/test_driver/linux-cirque/CommissioningFailureTest.py b/src/test_driver/linux-cirque/CommissioningFailureTest.py index b625c8eb268ed3..8cabb4deba54cc 100755 --- a/src/test_driver/linux-cirque/CommissioningFailureTest.py +++ b/src/test_driver/linux-cirque/CommissioningFailureTest.py @@ -18,8 +18,8 @@ import logging import os import pprint -import time import sys +import time from helper.CHIPTestBase import CHIPVirtualHome diff --git a/src/test_driver/linux-cirque/CommissioningTest.py b/src/test_driver/linux-cirque/CommissioningTest.py index 09a1f017300a02..b2c3a654deb505 100755 --- a/src/test_driver/linux-cirque/CommissioningTest.py +++ b/src/test_driver/linux-cirque/CommissioningTest.py @@ -18,8 +18,8 @@ import logging import os import pprint -import time import sys +import time from helper.CHIPTestBase import CHIPVirtualHome diff --git a/src/test_driver/linux-cirque/EchoOverTcpTest.py b/src/test_driver/linux-cirque/EchoOverTcpTest.py index 853e2cb9749bd0..5cb0c0b1c7a111 100755 --- a/src/test_driver/linux-cirque/EchoOverTcpTest.py +++ b/src/test_driver/linux-cirque/EchoOverTcpTest.py @@ -17,8 +17,8 @@ import logging import os -import time import sys +import time from helper.CHIPTestBase import CHIPVirtualHome diff --git a/src/test_driver/linux-cirque/EchoTest.py b/src/test_driver/linux-cirque/EchoTest.py index 91464046f3f9b8..4f13027958591a 100755 --- a/src/test_driver/linux-cirque/EchoTest.py +++ b/src/test_driver/linux-cirque/EchoTest.py @@ -17,8 +17,8 @@ import logging import os -import time import sys +import time from helper.CHIPTestBase import CHIPVirtualHome diff --git a/src/test_driver/linux-cirque/FailsafeTest.py b/src/test_driver/linux-cirque/FailsafeTest.py index adde541957c9ca..dbcddda426849e 100755 --- a/src/test_driver/linux-cirque/FailsafeTest.py +++ b/src/test_driver/linux-cirque/FailsafeTest.py @@ -18,8 +18,8 @@ import logging import os import pprint -import time import sys +import time from helper.CHIPTestBase import CHIPVirtualHome diff --git a/src/test_driver/linux-cirque/InteractionModelTest.py b/src/test_driver/linux-cirque/InteractionModelTest.py index fb1b8d275444e4..fe0848d1bc76f1 100755 --- a/src/test_driver/linux-cirque/InteractionModelTest.py +++ b/src/test_driver/linux-cirque/InteractionModelTest.py @@ -17,8 +17,8 @@ import logging import os -import time import sys +import time from helper.CHIPTestBase import CHIPVirtualHome diff --git a/src/test_driver/linux-cirque/ManualTest.py b/src/test_driver/linux-cirque/ManualTest.py index 36602c0b9898ee..0032df00b8ff2f 100755 --- a/src/test_driver/linux-cirque/ManualTest.py +++ b/src/test_driver/linux-cirque/ManualTest.py @@ -15,11 +15,11 @@ limitations under the License. """ +import json import logging import os -import time import sys -import json +import time from optparse import OptionParser, OptionValueError from helper.CHIPTestBase import CHIPVirtualHome diff --git a/src/test_driver/linux-cirque/MobileDeviceTest.py b/src/test_driver/linux-cirque/MobileDeviceTest.py index fc461441034551..bb7a9a4f69b525 100755 --- a/src/test_driver/linux-cirque/MobileDeviceTest.py +++ b/src/test_driver/linux-cirque/MobileDeviceTest.py @@ -18,8 +18,8 @@ import logging import os import pprint -import time import sys +import time from helper.CHIPTestBase import CHIPVirtualHome diff --git a/src/test_driver/linux-cirque/OnOffClusterTest.py b/src/test_driver/linux-cirque/OnOffClusterTest.py index 53f34a96bf3df1..701bd80dfaea81 100755 --- a/src/test_driver/linux-cirque/OnOffClusterTest.py +++ b/src/test_driver/linux-cirque/OnOffClusterTest.py @@ -17,8 +17,8 @@ import logging import os -import time import sys +import time from helper.CHIPTestBase import CHIPVirtualHome diff --git a/src/test_driver/linux-cirque/SplitCommissioningTest.py b/src/test_driver/linux-cirque/SplitCommissioningTest.py index 24d00e372ec1da..623e4355dee79d 100755 --- a/src/test_driver/linux-cirque/SplitCommissioningTest.py +++ b/src/test_driver/linux-cirque/SplitCommissioningTest.py @@ -18,8 +18,8 @@ import logging import os import pprint -import time import sys +import time from helper.CHIPTestBase import CHIPVirtualHome diff --git a/src/test_driver/linux-cirque/helper/CHIPTestBase.py b/src/test_driver/linux-cirque/helper/CHIPTestBase.py index 415d12acda36fa..957c9187aa465f 100644 --- a/src/test_driver/linux-cirque/helper/CHIPTestBase.py +++ b/src/test_driver/linux-cirque/helper/CHIPTestBase.py @@ -20,15 +20,15 @@ import logging import os import re -from typing import Union, List - -import requests import sys import time import traceback from enum import IntEnum +from typing import List, Union from urllib.parse import urljoin +import requests + class TestResult(IntEnum): OK = 0 diff --git a/src/test_driver/mbed/integration_tests/common/fixtures.py b/src/test_driver/mbed/integration_tests/common/fixtures.py index 32f943c98a5a6f..78b05cafd432d7 100644 --- a/src/test_driver/mbed/integration_tests/common/fixtures.py +++ b/src/test_driver/mbed/integration_tests/common/fixtures.py @@ -13,18 +13,17 @@ # See the License for the specific language governing permissions and # limitations under the License. -from typing import List, Optional, Any, Mapping +import logging +from time import sleep +from typing import Any, List, Mapping, Optional import mbed_lstools import pytest -from time import sleep from .device import Device - from .serial_connection import SerialConnection from .serial_device import SerialDevice -import logging log = logging.getLogger(__name__) diff --git a/src/test_driver/mbed/integration_tests/common/pigweed_client.py b/src/test_driver/mbed/integration_tests/common/pigweed_client.py index eb5c4b992e6209..6a770d3417e845 100644 --- a/src/test_driver/mbed/integration_tests/common/pigweed_client.py +++ b/src/test_driver/mbed/integration_tests/common/pigweed_client.py @@ -13,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. +import importlib import os from pathlib import Path -import importlib from pw_hdlc.rpc import HdlcRpcClient, default_channels diff --git a/src/test_driver/mbed/integration_tests/common/utils.py b/src/test_driver/mbed/integration_tests/common/utils.py index 438ab89c55912b..02529d430586f4 100644 --- a/src/test_driver/mbed/integration_tests/common/utils.py +++ b/src/test_driver/mbed/integration_tests/common/utils.py @@ -14,22 +14,22 @@ # limitations under the License. -import sys +import logging import os import platform import random -import shlex import re +import shlex +import sys -from chip.setup_payload import SetupPayload from chip import exceptions +from chip.setup_payload import SetupPayload if platform.system() == 'Darwin': from chip.ChipCoreBluetoothMgr import CoreBluetoothManager as BleManager elif sys.platform.startswith('linux'): from chip.ChipBluezMgr import BluezManager as BleManager -import logging log = logging.getLogger(__name__) diff --git a/src/test_driver/mbed/integration_tests/lighting-app/test_app.py b/src/test_driver/mbed/integration_tests/lighting-app/test_app.py index 27099d3ade10e2..6e4608e2f20b92 100644 --- a/src/test_driver/mbed/integration_tests/lighting-app/test_app.py +++ b/src/test_driver/mbed/integration_tests/lighting-app/test_app.py @@ -13,20 +13,18 @@ # See the License for the specific language governing permissions and # limitations under the License. -import pytest +import logging from time import sleep +import pytest +from button_service import button_service_pb2 from chip import ChipDeviceCtrl - -from common.utils import * - from common.pigweed_client import PigweedClient +from common.utils import * from device_service import device_service_pb2 -from button_service import button_service_pb2 from lighting_service import lighting_service_pb2 from pw_status import Status -import logging log = logging.getLogger(__name__) BLE_DEVICE_NAME = "MBED-lighting" diff --git a/src/test_driver/mbed/integration_tests/lock-app/test_app.py b/src/test_driver/mbed/integration_tests/lock-app/test_app.py index 2fca2b5356f735..e22d92c9bf3f58 100644 --- a/src/test_driver/mbed/integration_tests/lock-app/test_app.py +++ b/src/test_driver/mbed/integration_tests/lock-app/test_app.py @@ -13,20 +13,18 @@ # See the License for the specific language governing permissions and # limitations under the License. -import pytest +import logging from time import sleep +import pytest +from button_service import button_service_pb2 from chip import ChipDeviceCtrl - -from common.utils import * - from common.pigweed_client import PigweedClient +from common.utils import * from device_service import device_service_pb2 -from button_service import button_service_pb2 from locking_service import locking_service_pb2 from pw_status import Status -import logging log = logging.getLogger(__name__) BLE_DEVICE_NAME = "MBED-lock" diff --git a/src/test_driver/mbed/integration_tests/pigweed-app/test_app.py b/src/test_driver/mbed/integration_tests/pigweed-app/test_app.py index ad6ee4f9a142fe..04f5aa92e49d55 100644 --- a/src/test_driver/mbed/integration_tests/pigweed-app/test_app.py +++ b/src/test_driver/mbed/integration_tests/pigweed-app/test_app.py @@ -14,9 +14,8 @@ # limitations under the License. import pytest -from echo_service import echo_pb2 - from common.pigweed_client import PigweedClient +from echo_service import echo_pb2 RPC_PROTOS = [echo_pb2] PW_ECHO_TEST_MESSAGE = "Test_message" diff --git a/src/test_driver/mbed/integration_tests/shell/test_app.py b/src/test_driver/mbed/integration_tests/shell/test_app.py index 6dcc37a89775a3..1a6b9b153e0809 100644 --- a/src/test_driver/mbed/integration_tests/shell/test_app.py +++ b/src/test_driver/mbed/integration_tests/shell/test_app.py @@ -13,16 +13,16 @@ # See the License for the specific language governing permissions and # limitations under the License. -import pytest +import logging import re -from packaging import version from time import sleep +import pytest +from chip import ChipDeviceCtrl, exceptions from chip.setup_payload import SetupPayload -from chip import exceptions -from chip import ChipDeviceCtrl from common.utils import * -import logging +from packaging import version + log = logging.getLogger(__name__) BLE_DEVICE_NAME = "MBED-shell" diff --git a/src/test_driver/mbed/integration_tests/unit-tests/test_app.py b/src/test_driver/mbed/integration_tests/unit-tests/test_app.py index 04f81ae7320f4e..9f9290756498e3 100644 --- a/src/test_driver/mbed/integration_tests/unit-tests/test_app.py +++ b/src/test_driver/mbed/integration_tests/unit-tests/test_app.py @@ -13,9 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. -import pytest import re +import pytest + def test_unit_tests(device): device.reset(duration=1) diff --git a/src/test_driver/openiotsdk/integration-tests/common/fixtures.py b/src/test_driver/openiotsdk/integration-tests/common/fixtures.py index 2613b196567c00..510512ed0c1f01 100644 --- a/src/test_driver/openiotsdk/integration-tests/common/fixtures.py +++ b/src/test_driver/openiotsdk/integration-tests/common/fixtures.py @@ -15,23 +15,21 @@ # limitations under the License. # -import pytest +import logging import os import pathlib -from time import sleep import shutil +from time import sleep -from .telnet_connection import TelnetConnection -from .fvp_device import FvpDevice - -from chip import exceptions - -from chip import ChipDeviceCtrl -from chip.ChipStack import * -import chip.native import chip.CertificateAuthority +import chip.native +import pytest +from chip import ChipDeviceCtrl, exceptions +from chip.ChipStack import * + +from .fvp_device import FvpDevice +from .telnet_connection import TelnetConnection -import logging log = logging.getLogger(__name__) diff --git a/src/test_driver/openiotsdk/integration-tests/common/fvp_device.py b/src/test_driver/openiotsdk/integration-tests/common/fvp_device.py index 3255e6a42eaf48..4431b868cb3280 100644 --- a/src/test_driver/openiotsdk/integration-tests/common/fvp_device.py +++ b/src/test_driver/openiotsdk/integration-tests/common/fvp_device.py @@ -16,9 +16,9 @@ # import logging -import threading import os import subprocess +import threading from time import sleep from .device import Device diff --git a/src/test_driver/openiotsdk/integration-tests/common/telnet_connection.py b/src/test_driver/openiotsdk/integration-tests/common/telnet_connection.py index b5367ed5747387..66a509e2627e6b 100644 --- a/src/test_driver/openiotsdk/integration-tests/common/telnet_connection.py +++ b/src/test_driver/openiotsdk/integration-tests/common/telnet_connection.py @@ -14,10 +14,9 @@ # limitations under the License. import logging -from time import sleep import re - from telnetlib import Telnet +from time import sleep log = logging.getLogger(__name__) diff --git a/src/test_driver/openiotsdk/integration-tests/common/utils.py b/src/test_driver/openiotsdk/integration-tests/common/utils.py index 04d463d8558d38..69cbd4282cbc19 100644 --- a/src/test_driver/openiotsdk/integration-tests/common/utils.py +++ b/src/test_driver/openiotsdk/integration-tests/common/utils.py @@ -15,21 +15,19 @@ # limitations under the License. # +import asyncio +import ctypes +import logging import os import random -import shlex import re -import ctypes -import asyncio +import shlex from time import sleep -from chip.setup_payload import SetupPayload -from chip import exceptions - +from chip import discovery, exceptions from chip.clusters import Objects as GeneratedObjects -from chip import discovery +from chip.setup_payload import SetupPayload -import logging log = logging.getLogger(__name__) IP_ADDRESS_BUFFER_LEN = 100 diff --git a/src/test_driver/openiotsdk/integration-tests/lock-app/test_app.py b/src/test_driver/openiotsdk/integration-tests/lock-app/test_app.py index d89d26dc32d698..cadd7eab4b116d 100644 --- a/src/test_driver/openiotsdk/integration-tests/lock-app/test_app.py +++ b/src/test_driver/openiotsdk/integration-tests/lock-app/test_app.py @@ -15,14 +15,13 @@ # limitations under the License. # -import pytest +import logging from time import sleep -from common.utils import * - +import pytest from chip.clusters.Objects import DoorLock +from common.utils import * -import logging log = logging.getLogger(__name__) diff --git a/src/test_driver/openiotsdk/integration-tests/shell/test_app.py b/src/test_driver/openiotsdk/integration-tests/shell/test_app.py index 72cd8d0166c50f..192257bceb0c3d 100644 --- a/src/test_driver/openiotsdk/integration-tests/shell/test_app.py +++ b/src/test_driver/openiotsdk/integration-tests/shell/test_app.py @@ -13,18 +13,17 @@ # See the License for the specific language governing permissions and # limitations under the License. -import pytest +import logging import re -from packaging import version from time import sleep -from chip.setup_payload import SetupPayload -from chip import exceptions import chip.native - +import pytest +from chip import exceptions +from chip.setup_payload import SetupPayload from common.utils import * +from packaging import version -import logging log = logging.getLogger(__name__) diff --git a/src/tools/chip-cert/gen_com_dut_test_vectors.py b/src/tools/chip-cert/gen_com_dut_test_vectors.py index 96a8e88e6006bb..bdbc7ca4cdd8ab 100755 --- a/src/tools/chip-cert/gen_com_dut_test_vectors.py +++ b/src/tools/chip-cert/gen_com_dut_test_vectors.py @@ -1,17 +1,17 @@ #!/usr/bin/env python import argparse +import glob import json import os +import os.path import subprocess import sys -import typing -import cryptography.x509 -import os.path -import glob -from binascii import hexlify, unhexlify +from binascii import hexlify from enum import Enum +import cryptography.x509 + VID_NOT_PRESENT = 0xFFFF PID_NOT_PRESENT = 0x0000 diff --git a/src/tools/chip-cert/gen_op_cert_test_vectors.py b/src/tools/chip-cert/gen_op_cert_test_vectors.py index 4a737abad0dbb7..d1a074f1bed234 100755 --- a/src/tools/chip-cert/gen_op_cert_test_vectors.py +++ b/src/tools/chip-cert/gen_op_cert_test_vectors.py @@ -1,17 +1,13 @@ #!/usr/bin/env python import argparse -import json import os +import os.path import subprocess import sys -import typing -import cryptography.x509 -import os.path -import glob -from binascii import hexlify, unhexlify from enum import Enum -from dacs import copyrightNotice, bytes_from_hex, make_c_array, make_array_header, open_outfile + +from dacs import copyrightNotice, make_array_header, make_c_array class CertType(Enum): diff --git a/third_party/infineon/cyw30739_sdk/compress_cgs_data.py b/third_party/infineon/cyw30739_sdk/compress_cgs_data.py index c159f61746f8f4..803415316db4e7 100644 --- a/third_party/infineon/cyw30739_sdk/compress_cgs_data.py +++ b/third_party/infineon/cyw30739_sdk/compress_cgs_data.py @@ -29,10 +29,8 @@ import re import subprocess import sys - from collections import namedtuple - Item = namedtuple('Item', 'line type nested_data') Entry = namedtuple('Entry', 'items name remark') CommentedBytes = namedtuple('CommentedBytes', 'items data') diff --git a/third_party/infineon/cyw30739_sdk/gen_ota_image.py b/third_party/infineon/cyw30739_sdk/gen_ota_image.py index aa7755287525bf..edd51c6bef7b4a 100644 --- a/third_party/infineon/cyw30739_sdk/gen_ota_image.py +++ b/third_party/infineon/cyw30739_sdk/gen_ota_image.py @@ -27,9 +27,9 @@ import subprocess import sys import zlib +from struct import pack, pack_into from intelhex import IntelHex -from struct import pack, pack_into def main(): diff --git a/third_party/infineon/cyw30739_sdk/merge_hex.py b/third_party/infineon/cyw30739_sdk/merge_hex.py index 387b741a00d2e9..ed9c034c4c8020 100644 --- a/third_party/infineon/cyw30739_sdk/merge_hex.py +++ b/third_party/infineon/cyw30739_sdk/merge_hex.py @@ -24,13 +24,12 @@ import os import pathlib import re -import sys import zlib +from collections import OrderedDict +from struct import pack, unpack import leb128 -from collections import OrderedDict from intelhex import IntelHex -from struct import pack, unpack THREAD_FACTORY_KEY_BASE = 0x2000 MATTER_FACTORY_KEY_BASE = 0x2100 diff --git a/third_party/infineon/cyw30739_sdk/scripts/gen_ss_cgs.py b/third_party/infineon/cyw30739_sdk/scripts/gen_ss_cgs.py index 41758d0c9becc3..aaf1ef4f7f410e 100644 --- a/third_party/infineon/cyw30739_sdk/scripts/gen_ss_cgs.py +++ b/third_party/infineon/cyw30739_sdk/scripts/gen_ss_cgs.py @@ -25,7 +25,6 @@ import os import pathlib import sys - from collections import OrderedDict THREAD_FACTORY_KEY_BASE = 0x2000 diff --git a/third_party/ti_simplelink_sdk/oad_merge_tool.py b/third_party/ti_simplelink_sdk/oad_merge_tool.py index 262732619014b3..c603a2fe445b58 100644 --- a/third_party/ti_simplelink_sdk/oad_merge_tool.py +++ b/third_party/ti_simplelink_sdk/oad_merge_tool.py @@ -23,6 +23,7 @@ """ import sys + import intelhex oad_bin_file = sys.argv[1] diff --git a/third_party/ti_simplelink_sdk/run_oad_tool.py b/third_party/ti_simplelink_sdk/run_oad_tool.py index 8d1e227efe97fc..3f7335f2768fbf 100644 --- a/third_party/ti_simplelink_sdk/run_oad_tool.py +++ b/third_party/ti_simplelink_sdk/run_oad_tool.py @@ -11,9 +11,9 @@ """ import os -import sys import subprocess -import json +import sys + import intelhex # The extension is probably not necessary diff --git a/third_party/ti_simplelink_sdk/run_sysconfig.py b/third_party/ti_simplelink_sdk/run_sysconfig.py index 97ea0ea2d51b9a..c394b59f68fa64 100644 --- a/third_party/ti_simplelink_sdk/run_sysconfig.py +++ b/third_party/ti_simplelink_sdk/run_sysconfig.py @@ -11,8 +11,8 @@ SysConfig cmd line. """ -import sys import subprocess +import sys # Select OS specific helper script if sys.platform.startswith('linux'):