Skip to content

Commit 86877fd

Browse files
Alami-Amineaustina-csa
authored andcommitted
mypy fixes (project-chip#34850)
* Add marker files for matter_idl and matter_yamltests * type-annotations and other mypy fixes * change name of BLE callbacks * integrating comments
1 parent a1b6b40 commit 86877fd

File tree

20 files changed

+74
-61
lines changed

20 files changed

+74
-61
lines changed

scripts/py_matter_idl/BUILD.gn

+3
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,9 @@ pw_python_package("matter_idl") {
3131
# Dependency grammar
3232
"matter_idl/matter_grammar.lark",
3333

34+
#marker file to indicate to mypy that matter_idl is type-annotated
35+
"matter_idl/py.typed",
36+
3437
# Unit test data
3538
"matter_idl/tests/available_tests.yaml",
3639
"matter_idl/tests/inputs/cluster_struct_attribute.matter",

scripts/py_matter_idl/matter_idl/py.typed

Whitespace-only changes.

scripts/py_matter_idl/setup.cfg

+1
Original file line numberDiff line numberDiff line change
@@ -39,3 +39,4 @@ matter_idl =
3939
generators/java/ClusterIDMapping.jinja
4040
generators/java/ClusterReadMapping.jinja
4141
generators/java/ClusterWriteMapping.jinja
42+
py.typed

scripts/py_matter_yamltests/BUILD.gn

+1
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ pw_python_package("matter_yamltests") {
4343
"matter_yamltests/pseudo_clusters/clusters/system_commands.py",
4444
"matter_yamltests/pseudo_clusters/pseudo_cluster.py",
4545
"matter_yamltests/pseudo_clusters/pseudo_clusters.py",
46+
"matter_yamltests/py.typed",
4647
"matter_yamltests/runner.py",
4748
"matter_yamltests/websocket_runner.py",
4849
"matter_yamltests/yaml_loader.py",

scripts/py_matter_yamltests/matter_yamltests/py.typed

Whitespace-only changes.

scripts/py_matter_yamltests/setup.cfg

+4
Original file line numberDiff line numberDiff line change
@@ -25,3 +25,7 @@ install_requires=
2525
diskcache
2626
lark
2727
websockets
28+
29+
[options.package_data]
30+
matter_yamltests =
31+
py.typed

scripts/tests/requirements.txt

+1
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,4 @@ click
33
colorama
44
diskcache
55
websockets
6+
mypy==1.10.1

src/controller/python/chip/CertificateAuthority.py

+4-5
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
import ctypes
2222
import logging
2323
from ctypes import c_void_p
24-
from typing import List
24+
from typing import List, Optional
2525

2626
import chip.exceptions
2727
from chip import ChipStack, FabricAdmin
@@ -92,7 +92,7 @@ def __init__(self, chipStack: ChipStack.ChipStack, caIndex: int, persistentStora
9292
raise ValueError("Encountered error initializing OpCreds adapter")
9393

9494
self._isActive = True
95-
self._activeAdmins = []
95+
self._activeAdmins: List[FabricAdmin.FabricAdmin] = []
9696

9797
def LoadFabricAdminsFromStorage(self):
9898
''' If FabricAdmins had been setup previously, this re-creates them using information from persistent storage.
@@ -221,14 +221,13 @@ def __init__(self, chipStack: ChipStack.ChipStack, persistentStorage: Persistent
221221
persistentStorage: If provided, over-rides the default instance in the provided chipStack
222222
when initializing CertificateAuthority instances.
223223
'''
224-
self._activeCaIndexList = []
225224
self._chipStack = chipStack
226225

227226
if (persistentStorage is None):
228227
persistentStorage = self._chipStack.GetStorageManager()
229228

230229
self._persistentStorage = persistentStorage
231-
self._activeCaList = []
230+
self._activeCaList: List[CertificateAuthority] = []
232231
self._isActive = True
233232

234233
def _AllocateNextCaIndex(self):
@@ -259,7 +258,7 @@ def LoadAuthoritiesFromStorage(self):
259258
ca = self.NewCertificateAuthority(int(caIndex))
260259
ca.LoadFabricAdminsFromStorage()
261260

262-
def NewCertificateAuthority(self, caIndex: int = None, maximizeCertChains: bool = False):
261+
def NewCertificateAuthority(self, caIndex: Optional[int] = None, maximizeCertChains: bool = False):
263262
''' Creates a new CertificateAuthority instance with the provided CA Index and the PersistentStorage
264263
instance previously setup in the constructor.
265264

src/controller/python/chip/ChipBluezMgr.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -33,18 +33,18 @@
3333
import uuid
3434
from ctypes import CFUNCTYPE, PYFUNCTYPE, c_int, c_void_p, cast, pythonapi
3535

36-
import dbus
37-
import dbus.mainloop.glib
38-
import dbus.service
36+
import dbus # type: ignore
37+
import dbus.mainloop.glib # type: ignore
38+
import dbus.service # type: ignore
3939

4040
from .ChipBleBase import ChipBleBase
4141
from .ChipBleUtility import BLE_ERROR_REMOTE_DEVICE_DISCONNECTED, BleDisconnectEvent, ParseServiceData
4242

4343
try:
44-
from gi.repository import GObject
44+
from gi.repository import GObject # type: ignore
4545
except Exception:
4646
logging.exception("Unable to find GObject from gi.repository")
47-
from pgi.repository import GObject
47+
from pgi.repository import GObject # type: ignore
4848

4949
chip_service = uuid.UUID("0000FFF6-0000-1000-8000-00805F9B34FB")
5050
chip_tx = uuid.UUID("18EE2EF5-263D-4559-959F-4F9C429F9D11")

src/controller/python/chip/ChipCommissionableNodeCtrl.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
from __future__ import absolute_import, print_function
2727

2828
from ctypes import CDLL, POINTER, c_void_p, pointer
29+
from typing import Any
2930

3031
from .ChipStack import ChipStack
3132
from .native import PyChipError
@@ -49,7 +50,7 @@ class ChipCommissionableNodeController(object):
4950
def __init__(self, chipStack: ChipStack):
5051
self.commissionableNodeCtrl = None
5152
self._ChipStack = chipStack
52-
self._dmLib = None
53+
self._dmLib: Any = None
5354

5455
self._InitLib()
5556

src/controller/python/chip/ChipStack.py

+6-5
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
import os
3232
from ctypes import CFUNCTYPE, Structure, c_bool, c_char_p, c_uint16, c_uint32, c_void_p, py_object, pythonapi
3333
from threading import Condition, Lock
34+
from typing import Any, Optional
3435

3536
import chip.native
3637
from chip.native import PyChipError
@@ -90,7 +91,7 @@ def __call__(self):
9091
self._cv.notify_all()
9192
pythonapi.Py_DecRef(py_object(self))
9293

93-
def Wait(self, timeoutMs: int = None):
94+
def Wait(self, timeoutMs: Optional[int] = None):
9495
timeout = None
9596
if timeoutMs is not None:
9697
timeout = float(timeoutMs) / 1000
@@ -143,7 +144,7 @@ class ChipStack(object):
143144
def __init__(self, persistentStoragePath: str, enableServerInteractions=True):
144145
builtins.enableDebugMode = False
145146

146-
self._ChipStackLib = None
147+
self._ChipStackLib: Any = None
147148
self._chipDLLPath = None
148149
self.devMgr = None
149150
self._enableServerInteractions = enableServerInteractions
@@ -209,14 +210,14 @@ def Shutdown(self):
209210

210211
delattr(builtins, "chipStack")
211212

212-
def Call(self, callFunct, timeoutMs: int = None):
213+
def Call(self, callFunct, timeoutMs: Optional[int] = None):
213214
'''Run a Python function on CHIP stack, and wait for the response.
214215
This function is a wrapper of PostTaskOnChipThread, which includes some handling of application specific logics.
215216
Calling this function on CHIP on CHIP mainloop thread will cause deadlock.
216217
'''
217218
return self.PostTaskOnChipThread(callFunct).Wait(timeoutMs)
218219

219-
async def CallAsyncWithResult(self, callFunct, timeoutMs: int = None):
220+
async def CallAsyncWithResult(self, callFunct, timeoutMs: Optional[int] = None):
220221
'''Run a Python function on CHIP stack, and wait for the response.
221222
This function will post a task on CHIP mainloop and waits for the call response in a asyncio friendly manner.
222223
'''
@@ -232,7 +233,7 @@ async def CallAsyncWithResult(self, callFunct, timeoutMs: int = None):
232233

233234
return await asyncio.wait_for(callObj.future, timeoutMs / 1000 if timeoutMs else None)
234235

235-
async def CallAsync(self, callFunct, timeoutMs: int = None) -> None:
236+
async def CallAsync(self, callFunct, timeoutMs: Optional[int] = None) -> None:
236237
'''Run a Python function on CHIP stack, and wait for the response.'''
237238
res: PyChipError = await self.CallAsyncWithResult(callFunct, timeoutMs)
238239
res.raise_on_error()

src/controller/python/chip/FabricAdmin.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
from __future__ import annotations
2020

2121
import logging
22-
from typing import List
22+
from typing import List, Optional
2323

2424
from chip import CertificateAuthority, ChipDeviceCtrl
2525
from chip.crypto import p256keypair
@@ -61,9 +61,9 @@ def __init__(self, certificateAuthority: CertificateAuthority.CertificateAuthori
6161
LOGGER.info(f"New FabricAdmin: FabricId: 0x{self._fabricId:016X}, VendorId = 0x{self.vendorId:04X}")
6262

6363
self._isActive = True
64-
self._activeControllers = []
64+
self._activeControllers: List[ChipDeviceCtrl.ChipDeviceController] = []
6565

66-
def NewController(self, nodeId: int = None, paaTrustStorePath: str = "",
66+
def NewController(self, nodeId: Optional[int] = None, paaTrustStorePath: str = "",
6767
useTestCommissioner: bool = False, catTags: List[int] = [], keypair: p256keypair.P256Keypair = None):
6868
''' Create a new chip.ChipDeviceCtrl.ChipDeviceController instance on this fabric.
6969

src/controller/python/chip/ble/scan_devices.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -31,12 +31,12 @@ def ScanFoundCallback(closure, address: str, discriminator: int, vendor: int,
3131

3232

3333
@ScanDoneCallback
34-
def ScanDoneCallback(closure):
34+
def ScanIsDoneCallback(closure):
3535
closure.OnScanComplete()
3636

3737

3838
@ScanErrorCallback
39-
def ScanErrorCallback(closure, errorCode: int):
39+
def ScanHasErrorCallback(closure, errorCode: int):
4040
closure.OnScanError(errorCode)
4141

4242

@@ -106,7 +106,7 @@ def DiscoverSync(timeoutMs: int, adapter=None) -> Generator[DeviceInfo, None, No
106106
scanner = handle.pychip_ble_scanner_start(
107107
ctypes.py_object(receiver),
108108
handle.pychip_ble_adapter_list_get_raw_adapter(nativeList),
109-
timeoutMs, ScanFoundCallback, ScanDoneCallback, ScanErrorCallback)
109+
timeoutMs, ScanFoundCallback, ScanIsDoneCallback, ScanHasErrorCallback)
110110

111111
if scanner == 0:
112112
raise Exception('Failed to start BLE scan')

src/controller/python/chip/clusters/Command.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -382,7 +382,7 @@ async def SendBatchCommands(future: Future, eventLoop, device, commands: List[In
382382
'''
383383
handle = chip.native.GetLibraryHandle()
384384

385-
responseTypes = []
385+
responseTypes: List[Type] = []
386386
pyBatchCommandsData = _BuildPyInvokeRequestData(commands, timedRequestTimeoutMs, responseTypes)
387387

388388
transaction = AsyncBatchCommandsTransaction(future, eventLoop, responseTypes)
@@ -417,7 +417,7 @@ def TestOnlySendBatchCommands(future: Future, eventLoop, device, commands: List[
417417

418418
handle = chip.native.GetLibraryHandle()
419419

420-
responseTypes = []
420+
responseTypes: List[Type] = []
421421
pyBatchCommandsData = _BuildPyInvokeRequestData(commands, timedRequestTimeoutMs,
422422
responseTypes, suppressTimedRequestMessage=suppressTimedRequestMessage)
423423

src/controller/python/chip/commissioning/__init__.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
import dataclasses
2020
import enum
2121
import os
22-
from typing import Set, Tuple, Union
22+
from typing import Optional, Set, Tuple, Union
2323

2424
ROOT_ENDPOINT_ID = 0
2525

@@ -118,8 +118,8 @@ class GetCommissioneeCredentialsResponse:
118118
ipk: bytes
119119
case_admin_node: int
120120
admin_vendor_id: int
121-
node_id: int = None
122-
fabric_id: int = None
121+
node_id: Optional[int] = None
122+
fabric_id: Optional[int] = None
123123

124124

125125
class CredentialProvider:
@@ -137,4 +137,4 @@ async def get_commissionee_credentials(self, request: GetCommissioneeCredentials
137137

138138
class ExampleCredentialProvider:
139139
async def get_commissionee_credentials(self, request: GetCommissioneeCredentialsRequest) -> GetCommissioneeCredentialsResponse:
140-
pass
140+
raise NotImplementedError("This method needs to be implemented.")

src/controller/python/chip/configuration/__init__.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
# limitations under the License.
1515
#
1616

17-
from typing import Optional
17+
from typing import Optional, cast
1818

1919
# Represents the node ID that is to be used when creating device
2020
# controllers/commissioning devices
@@ -45,7 +45,8 @@ def GetLocalNodeId() -> int:
4545
if _local_node_id is None:
4646
SetLocalNodeId(DEFAULT_LOCAL_NODE_ID)
4747

48-
return _local_node_id
48+
# cast is used to tell mypy typechecker that _local_node_id will always be an int from this point onwards
49+
return cast(int, _local_node_id)
4950

5051

5152
def SetCommissionerCAT(cat: int):
@@ -68,4 +69,4 @@ def GetCommissionerCAT() -> int:
6869
if _local_cat is None:
6970
SetCommissionerCAT(DEFAULT_COMMISSIONER_CAT)
7071

71-
return _local_cat
72+
return cast(int, _local_cat)

src/controller/python/chip/discovery/__init__.py

+18-18
Original file line numberDiff line numberDiff line change
@@ -78,24 +78,24 @@ class PendingDiscovery:
7878

7979
@dataclass
8080
class CommissionableNode():
81-
instanceName: str = None
82-
hostName: str = None
83-
port: int = None
84-
longDiscriminator: int = None
85-
vendorId: int = None
86-
productId: int = None
87-
commissioningMode: int = None
88-
deviceType: int = None
89-
deviceName: str = None
90-
pairingInstruction: str = None
91-
pairingHint: int = None
92-
mrpRetryIntervalIdle: int = None
93-
mrpRetryIntervalActive: int = None
94-
mrpRetryActiveThreshold: int = None
95-
supportsTcpClient: bool = None
96-
supportsTcpServer: bool = None
97-
isICDOperatingAsLIT: bool = None
98-
addresses: List[str] = None
81+
instanceName: Optional[str] = None
82+
hostName: Optional[str] = None
83+
port: Optional[int] = None
84+
longDiscriminator: Optional[int] = None
85+
vendorId: Optional[int] = None
86+
productId: Optional[int] = None
87+
commissioningMode: Optional[int] = None
88+
deviceType: Optional[int] = None
89+
deviceName: Optional[str] = None
90+
pairingInstruction: Optional[str] = None
91+
pairingHint: Optional[int] = None
92+
mrpRetryIntervalIdle: Optional[int] = None
93+
mrpRetryIntervalActive: Optional[int] = None
94+
mrpRetryActiveThreshold: Optional[int] = None
95+
supportsTcpClient: Optional[bool] = None
96+
supportsTcpServer: Optional[bool] = None
97+
isICDOperatingAsLIT: Optional[bool] = None
98+
addresses: Optional[List[str]] = None
9999
rotatingId: Optional[str] = None
100100

101101

src/controller/python/chip/internal/thread.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
# Generally thread credentials are assumed to be binary objects, however for
1919
# testing purposes, we expose the internal structure here.
2020

21-
from construct import Byte, Bytes, Int16ul, Int64ul, PaddedString, Struct
21+
from construct import Byte, Bytes, Int16ul, Int64ul, PaddedString, Struct # type: ignore
2222

2323
ThreadNetworkInfo = Struct(
2424
"ActiveTimestamp" / Int64ul,

src/controller/python/chip/storage/__init__.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
import json
2525
import logging
2626
from ctypes import CFUNCTYPE, POINTER, c_bool, c_char, c_char_p, c_uint16, c_void_p, py_object
27-
from typing import Dict
27+
from typing import IO, Dict, Optional
2828

2929
import chip.exceptions
3030
import chip.native
@@ -39,12 +39,12 @@
3939

4040

4141
@_SyncSetKeyValueCbFunct
42-
def _OnSyncSetKeyValueCb(storageObj, key: str, value, size):
42+
def _OnSyncSetKeyValueCb(storageObj, key: bytes, value, size):
4343
storageObj.SetSdkKey(key.decode("utf-8"), ctypes.string_at(value, size))
4444

4545

4646
@_SyncGetKeyValueCbFunct
47-
def _OnSyncGetKeyValueCb(storageObj, key: str, value, size, is_found):
47+
def _OnSyncGetKeyValueCb(storageObj, key: bytes, value, size, is_found):
4848
''' This does not adhere to the API requirements of
4949
PersistentStorageDelegate::SyncGetKeyValue, but that is okay since
5050
the C++ storage binding layer is capable of adapting results from
@@ -94,7 +94,7 @@ class PersistentStorage:
9494
Object must be resident before the Matter stack starts up and last past its shutdown.
9595
'''
9696

97-
def __init__(self, path: str = None, jsonData: Dict = None):
97+
def __init__(self, path: Optional[str] = None, jsonData: Optional[Dict] = None):
9898
''' Initializes the object with either a path to a JSON file that contains the configuration OR
9999
a JSON dictionary that contains an in-memory representation of the configuration.
100100
@@ -118,7 +118,7 @@ def __init__(self, path: str = None, jsonData: Dict = None):
118118

119119
if (self._path):
120120
try:
121-
self._file = open(path, 'r')
121+
self._file: Optional[IO[str]] = open(path, 'r')
122122
self._file.seek(0, 2)
123123
size = self._file.tell()
124124
self._file.seek(0)

0 commit comments

Comments
 (0)