Skip to content

Commit

Permalink
[controller] Fix flake8 warnings (#25311)
Browse files Browse the repository at this point in the history
* [controller] Add to flake8 in workflow and fix python files

* rebase

* Restyled by autopep8

Restyled by isort

Restyled

* Restore .delegate in init interaction_model

* rebase

Restyled by isort

* Fix of the if statement

* Fix use undefined uint8_t

* Add import to __init__

* Fix renamed import ClusterObjects

* Arkq suggested change

* Fix use GeneratedObjects for remove noqa

---------

Co-authored-by: Restyled.io <commits@restyled.io>
Co-authored-by: Arkadiusz Bokowy <a.bokowy@samsung.com>
  • Loading branch information
3 people authored and pull[bot] committed Oct 23, 2023
1 parent d0e85ef commit 9253043
Show file tree
Hide file tree
Showing 31 changed files with 439 additions and 265 deletions.
25 changes: 0 additions & 25 deletions .flake8
Original file line number Diff line number Diff line change
Expand Up @@ -47,31 +47,6 @@ exclude = third_party
scripts/tools/zap_convert_all.py
src/app/ota_image_tool.py
src/app/zap_cluster_list.py
src/controller/python/build-chip-wheel.py
src/controller/python/chip-device-ctrl.py
src/controller/python/chip/CertificateAuthority.py
src/controller/python/chip/ChipBleUtility.py
src/controller/python/chip/ChipBluezMgr.py
src/controller/python/chip/ChipCommissionableNodeCtrl.py
src/controller/python/chip/ChipCoreBluetoothMgr.py
src/controller/python/chip/ChipDeviceCtrl.py
src/controller/python/chip/ChipReplStartup.py
src/controller/python/chip/ChipStack.py
src/controller/python/chip/ChipUtility.py
src/controller/python/chip/FabricAdmin.py
src/controller/python/chip/ble/scan_devices.py
src/controller/python/chip/clusters/Attribute.py
src/controller/python/chip/clusters/ClusterObjects.py
src/controller/python/chip/clusters/Command.py
src/controller/python/chip/clusters/__init__.py
src/controller/python/chip/discovery/__init__.py
src/controller/python/chip/interaction_model/__init__.py
src/controller/python/chip/interaction_model/delegate.py
src/controller/python/chip/internal/commissioner.py
src/controller/python/chip/setup_payload/setup_payload.py
src/controller/python/chip/storage/__init__.py
src/controller/python/chip/tlv/__init__.py
src/controller/python/chip/utils/CommissioningBuildingBlocks.py
src/controller/python/chip/yaml/__init__.py
src/controller/python/chip/yaml/format_converter.py
src/controller/python/chip/yaml/runner.py
Expand Down
1 change: 0 additions & 1 deletion src/controller/python/build-chip-wheel.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@
import shutil

from setuptools import Distribution, setup
from wheel.bdist_wheel import bdist_wheel

parser = argparse.ArgumentParser(
description='build the pip package for chip using chip components generated during the build and python source code')
Expand Down
41 changes: 25 additions & 16 deletions src/controller/python/chip-device-ctrl.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@

import chip.logging
import coloredlogs
from chip import ChipCommissionableNodeCtrl, ChipStack, FabricAdmin, exceptions, native
from chip import ChipCommissionableNodeCtrl, ChipStack, exceptions, native
from chip.setup_payload import SetupPayload
from rich import pretty, print

Expand Down Expand Up @@ -311,7 +311,8 @@ def do_closeble(self, line):
"""

warnings.warn(
"This method is being deprecated. Please use the DeviceController.CloseBLEConnection method directly in the REPL", DeprecationWarning)
"This method is being deprecated. "
"Please use the DeviceController.CloseBLEConnection method directly in the REPL", DeprecationWarning)

args = shlex.split(line)

Expand All @@ -333,7 +334,8 @@ def do_setlogoutput(self, line):
"""

warnings.warn(
"This method is being deprecated. Please use the DeviceController.SetLogFilter method directly in the REPL", DeprecationWarning)
"This method is being deprecated. "
"Please use the DeviceController.SetLogFilter method directly in the REPL", DeprecationWarning)

args = shlex.split(line)

Expand Down Expand Up @@ -382,7 +384,8 @@ def do_setuppayload(self, line):
"""

warnings.warn(
"This method is being deprecated. Please use the SetupPayload function in the chip.setup_payload package directly", DeprecationWarning)
"This method is being deprecated. "
"Please use the SetupPayload function in the chip.setup_payload package directly", DeprecationWarning)

try:
arglist = shlex.split(line)
Expand Down Expand Up @@ -599,7 +602,8 @@ def do_connect(self, line):
"""

warnings.warn(
"This method is being deprecated. Please use the DeviceController.[ConnectBLE|CommissionIP] methods directly in the REPL", DeprecationWarning)
"This method is being deprecated. "
"Please use the DeviceController.[ConnectBLE|CommissionIP] methods directly in the REPL", DeprecationWarning)

try:
args = shlex.split(line)
Expand Down Expand Up @@ -661,7 +665,7 @@ def do_closesession(self, line):
self.devCtrl.CloseSession(args.nodeid)
except exceptions.ChipStackException as ex:
print(str(ex))
except:
except Exception:
self.do_help("close-session")

def do_resolve(self, line):
Expand Down Expand Up @@ -782,7 +786,7 @@ def do_discover(self, line):
print('exception')
print(str(ex))
return
except:
except Exception:
self.do_help("discover")
return

Expand Down Expand Up @@ -826,7 +830,7 @@ def do_zcl(self, line):
args[2]), int(args[3]), int(args[4]), FormatZCLArguments(args[5:], command), blocking=True)
if err != 0:
print("Failed to receive command response: {}".format(res))
elif res != None:
elif res is not None:
print("Received command status response:")
print(res)
else:
Expand Down Expand Up @@ -858,10 +862,11 @@ def do_zclread(self, line):
elif len(args) == 5:
if args[0] not in all_attrs:
raise exceptions.UnknownCluster(args[0])
self.replHint = f"await devCtrl.ReadAttribute({int(args[2])}, [({int(args[3])}, Clusters.{args[0]}.Attributes.{args[1]})])"
self.replHint = (f"await devCtrl.ReadAttribute({int(args[2])}, [({int(args[3])}, "
f"Clusters.{args[0]}.Attributes.{args[1]})])")
res = self.devCtrl.ZCLReadAttribute(args[0], args[1], int(
args[2]), int(args[3]), int(args[4]))
if res != None:
if res is not None:
print(repr(res))
else:
self.do_help("zclread")
Expand Down Expand Up @@ -893,7 +898,9 @@ def do_zclwrite(self, line):
raise exceptions.UnknownCluster(args[0])
attribute_type = all_attrs.get(args[0], {}).get(
args[1], {}).get("type", None)
self.replHint = f"await devCtrl.WriteAttribute({int(args[2])}, [({int(args[3])}, Clusters.{args[0]}.Attributes.{args[1]}(value={repr(ParseValueWithType(args[5], attribute_type))}))])"
self.replHint = (
f"await devCtrl.WriteAttribute({int(args[2])}, [({int(args[3])}, "
f"Clusters.{args[0]}.Attributes.{args[1]}(value={repr(ParseValueWithType(args[5], attribute_type))}))])")
res = self.devCtrl.ZCLWriteAttribute(args[0], args[1], int(
args[2]), int(args[3]), int(args[4]), ParseValueWithType(args[5], attribute_type))
print(repr(res))
Expand Down Expand Up @@ -930,7 +937,8 @@ def do_zclsubscribe(self, line):
raise exceptions.UnknownCluster(args[0])
res = self.devCtrl.ZCLSubscribeAttribute(args[0], args[1], int(
args[2]), int(args[3]), int(args[4]), int(args[5]))
self.replHint = f"sub = await devCtrl.ReadAttribute({int(args[2])}, [({int(args[3])}, Clusters.{args[0]}.Attributes.{args[1]})], reportInterval=({int(args[4])}, {int(args[5])}))"
self.replHint = (f"sub = await devCtrl.ReadAttribute({int(args[2])}, [({int(args[3])}, "
f"Clusters.{args[0]}.Attributes.{args[1]})], reportInterval=({int(args[4])}, {int(args[5])}))")
print(res.GetAllValues())
print(f"Subscription Established: {res}")
elif len(args) == 2 and args[0] == '-shutdown':
Expand Down Expand Up @@ -1013,15 +1021,16 @@ def do_opencommissioningwindow(self, line):
print("Invalid option specified!")
raise ValueError("Invalid option specified")

self.replHint = f"devCtrl.OpenCommissioningWindow(nodeid={int(arglist[0])}, timeout={args.timeout}, iteration={args.iteration}, discriminator={args.discriminator}, option={args.option})"
self.replHint = (f"devCtrl.OpenCommissioningWindow(nodeid={int(arglist[0])}, timeout={args.timeout}, "
f"iteration={args.iteration}, discriminator={args.discriminator}, option={args.option})")

self.devCtrl.OpenCommissioningWindow(
int(arglist[0]), args.timeout, args.iteration, args.discriminator, args.option)

except exceptions.ChipStackException as ex:
print(str(ex))
return
except:
except Exception:
self.do_help("open-commissioning-window")
return

Expand All @@ -1041,7 +1050,7 @@ def do_getfabricid(self, line):
compressed_fabricid = self.devCtrl.GetCompressedFabricId()
raw_fabricid = self.devCtrl.fabricId

self.replHint = f"devCtrl.GetCompressedFabricId(), devCtrl.fabricId"
self.replHint = "devCtrl.GetCompressedFabricId(), devCtrl.fabricId"
except exceptions.ChipStackException as ex:
print("An exception occurred during reading FabricID:")
print(str(ex))
Expand Down Expand Up @@ -1146,7 +1155,7 @@ def main():
else:
try:
adapterId = int(options.bluetoothAdapter[3:])
except:
except ValueError:
print(
"Invalid bluetooth adapter: {}, adapter name looks like hci0, hci1 etc.")
sys.exit(-1)
Expand Down
29 changes: 16 additions & 13 deletions src/controller/python/chip/CertificateAuthority.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@

import ctypes
import logging
from ctypes import *
from typing import *
from ctypes import c_void_p
from typing import List

import chip.exceptions
from chip import ChipStack, FabricAdmin
Expand All @@ -30,18 +30,20 @@


class CertificateAuthority:
''' This represents an operational Root Certificate Authority (CA) with a root key key pair with associated public key (i.e "Root PK") . This manages
a set of FabricAdmin objects, each administering a fabric identified by a unique FabricId scoped to it.
''' This represents an operational Root Certificate Authority (CA) with a root key key pair with associated
public key (i.e "Root PK") . This manages a set of FabricAdmin objects, each administering a fabric identified
by a unique FabricId scoped to it.
Each CertificateAuthority instance is tied to a 'CA index' that is used to look-up the list of fabrics already setup previously
in the provided PersistentStorage object.
Each CertificateAuthority instance is tied to a 'CA index' that is used to look-up the list of fabrics already setup
previously in the provided PersistentStorage object.
>> C++ Binding Details
Each CertificateAuthority instance is associated with a single instance of the OperationalCredentialsAdapter. This adapter instance implements
the OperationalCredentialsDelegate and is meant to provide a Python adapter to the functions in that delegate. It relies on the in-built
ExampleOperationalCredentialsIssuer to then generate certificate material for the CA. This instance also uses the 'CA index' to
store/look-up the associated credential material from the provided PersistentStorage object.
Each CertificateAuthority instance is associated with a single instance of the OperationalCredentialsAdapter.
This adapter instance implements the OperationalCredentialsDelegate and is meant to provide a Python adapter to the
functions in that delegate. It relies on the in-built ExampleOperationalCredentialsIssuer to then generate certificate
material for the CA. This instance also uses the 'CA index' to store/look-up the associated credential material from
the provided PersistentStorage object.
'''
@classmethod
def _Handle(cls):
Expand All @@ -57,7 +59,8 @@ def __init__(self, chipStack: ChipStack.ChipStack, caIndex: int, persistentStora
Arguments:
chipStack: A reference to a chip.ChipStack object.
caIndex: An index used to look-up details about stored credential material and fabrics from persistent storage.
caIndex: An index used to look-up details about stored credential material and fabrics
from persistent storage.
persistentStorage: An optional reference to a PersistentStorage object. If one is provided, it will pick that over
the default PersistentStorage object retrieved from the chipStack.
'''
Expand Down Expand Up @@ -121,10 +124,10 @@ def NewFabricAdmin(self, vendorId: int, fabricId: int):
'''
if (not (self._isActive)):
raise RuntimeError(
f"CertificateAuthority object was previously shutdown and is no longer valid!")
"CertificateAuthority object was previously shutdown and is no longer valid!")

if (vendorId is None or fabricId is None):
raise ValueError(f"Invalid values for fabricId and vendorId")
raise ValueError("Invalid values for fabricId and vendorId")

for existingAdmin in self._activeAdmins:
if (existingAdmin.fabricId == fabricId):
Expand Down
6 changes: 3 additions & 3 deletions src/controller/python/chip/ChipBleUtility.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@

from __future__ import absolute_import, print_function

from ctypes import *
from ctypes import Structure, c_bool, c_int32, c_uint16, c_void_p

from .ChipUtility import ChipUtility

Expand Down Expand Up @@ -62,7 +62,7 @@ def VoidPtrToUUIDString(ptr, len):
+ ptr[20:]
)
ptr = str(ptr)
except Exception as ex:
except Exception:
print("ERROR: failed to convert void * to UUID")
ptr = None

Expand Down Expand Up @@ -319,7 +319,7 @@ def fromBleRxEvent(cls, bleRxEvent):
bleRxEventStruct.Buffer = ChipUtility.ByteArrayToVoidPtr(
bleRxEvent.Buffer)
bleRxEventStruct.Length = (
len(bleRxEvent.Buffer) if (bleRxEvent.Buffer != None) else 0
len(bleRxEvent.Buffer) if (bleRxEvent.Buffer is not None) else 0
)
return bleRxEventStruct

Expand Down
Loading

0 comments on commit 9253043

Please sign in to comment.