Skip to content

Commit 7c0d57d

Browse files
committed
more mypy fixes
1 parent 2b1dd69 commit 7c0d57d

File tree

5 files changed

+64
-61
lines changed

5 files changed

+64
-61
lines changed

src/controller/python/chip/ChipDeviceCtrl.py

+26-27
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@
4242
from ctypes import (CDLL, CFUNCTYPE, POINTER, Structure, byref, c_bool, c_char, c_char_p, c_int, c_int32, c_size_t, c_uint8,
4343
c_uint16, c_uint32, c_uint64, c_void_p, create_string_buffer, pointer, py_object, resize, string_at)
4444
from dataclasses import dataclass
45+
from typing import Optional
4546

4647
import dacite # type: ignore
4748

@@ -267,7 +268,7 @@ class CommissioningContext(CallbackContext):
267268
This context also resets commissioning related device controller state.
268269
"""
269270

270-
def __init__(self, devCtrl: ChipDeviceController, lock: asyncio.Lock) -> None:
271+
def __init__(self, devCtrl: ChipDeviceControllerBase, lock: asyncio.Lock) -> None:
271272
super().__init__(lock)
272273
self._devCtrl = devCtrl
273274

@@ -388,12 +389,12 @@ def attestationChallenge(self) -> bytes:
388389

389390

390391
class ChipDeviceControllerBase():
391-
activeList = set()
392+
activeList: typing.Set = set()
392393

393394
def __init__(self, name: str = ''):
394395
self.devCtrl = None
395396
self._ChipStack = builtins.chipStack
396-
self._dmLib = None
397+
self._dmLib: typing.Any = None
397398

398399
self._InitLib()
399400

@@ -553,10 +554,6 @@ def _enablePairingCompleteCallback(self, value: bool):
553554
self._dmLib.pychip_ScriptDevicePairingDelegate_SetExpectingPairingComplete(
554555
self.pairingDelegate, value)
555556

556-
@property
557-
def fabricAdmin(self) -> FabricAdmin.FabricAdmin:
558-
return self._fabricAdmin
559-
560557
@property
561558
def nodeId(self) -> int:
562559
return self._nodeId
@@ -595,7 +592,7 @@ def Shutdown(self):
595592
ChipDeviceController.activeList.remove(self)
596593
self._isActive = False
597594

598-
def ShutdownAll():
595+
def ShutdownAll(self):
599596
''' Shut down all active controllers and reclaim any used resources.
600597
'''
601598
#
@@ -766,7 +763,7 @@ def GetAddressAndPort(self, nodeid):
766763

767764
return (address.value.decode(), port.value) if error == 0 else None
768765

769-
async def DiscoverCommissionableNodes(self, filterType: discovery.FilterType = discovery.FilterType.NONE, filter: typing.Any = None,
766+
async def DiscoverCommissionableNodes(self, filterType: discovery.FilterType = discovery.FilterType.NONE, filter: Optional[typing.Any] = None,
770767
stopOnFirst: bool = False, timeoutSecond: int = 5) -> typing.Union[None, CommissionableNode, typing.List[CommissionableNode]]:
771768
''' Discover commissionable nodes via DNS-SD with specified filters.
772769
Supported filters are:
@@ -928,7 +925,7 @@ def GetClusterHandler(self):
928925

929926
return self._Cluster
930927

931-
async def FindOrEstablishPASESession(self, setupCode: str, nodeid: int, timeoutMs: int = None) -> typing.Optional[DeviceProxyWrapper]:
928+
async def FindOrEstablishPASESession(self, setupCode: str, nodeid: int, timeoutMs: Optional[int] = None) -> typing.Optional[DeviceProxyWrapper]:
932929
''' Returns CommissioneeDeviceProxy if we can find or establish a PASE connection to the specified device'''
933930
self.CheckIsActive()
934931
returnDevice = c_void_p(None)
@@ -944,7 +941,9 @@ async def FindOrEstablishPASESession(self, setupCode: str, nodeid: int, timeoutM
944941
if res.is_success:
945942
return DeviceProxyWrapper(returnDevice, DeviceProxyWrapper.DeviceProxyType.COMMISSIONEE, self._dmLib)
946943

947-
def GetConnectedDeviceSync(self, nodeid, allowPASE=True, timeoutMs: int = None):
944+
return None
945+
946+
def GetConnectedDeviceSync(self, nodeid, allowPASE=True, timeoutMs: Optional[int] = None):
948947
''' Gets an OperationalDeviceProxy or CommissioneeDeviceProxy for the specified Node.
949948
950949
nodeId: Target's Node ID
@@ -956,8 +955,8 @@ def GetConnectedDeviceSync(self, nodeid, allowPASE=True, timeoutMs: int = None):
956955
'''
957956
self.CheckIsActive()
958957

959-
returnDevice = c_void_p(None)
960-
returnErr = None
958+
returnDevice: ctypes.c_void_p = c_void_p(None)
959+
returnErr: typing.Any = None
961960
deviceAvailableCV = threading.Condition()
962961

963962
if allowPASE:
@@ -1014,7 +1013,7 @@ async def WaitForActive(self, nodeid, *, timeoutSeconds=30.0, stayActiveDuration
10141013
await WaitForCheckIn(ScopedNodeId(nodeid, self._fabricIndex), timeoutSeconds=timeoutSeconds)
10151014
return await self.SendCommand(nodeid, 0, Clusters.IcdManagement.Commands.StayActiveRequest(stayActiveDuration=stayActiveDurationMs))
10161015

1017-
async def GetConnectedDevice(self, nodeid, allowPASE: bool = True, timeoutMs: int = None):
1016+
async def GetConnectedDevice(self, nodeid, allowPASE: bool = True, timeoutMs: Optional[int] = None):
10181017
''' Gets an OperationalDeviceProxy or CommissioneeDeviceProxy for the specified Node.
10191018
10201019
nodeId: Target's Node ID
@@ -1412,7 +1411,7 @@ def _parseEventPathTuple(self, pathTuple: typing.Union[
14121411
else:
14131412
raise ValueError("Unsupported Attribute Path")
14141413

1415-
async def Read(self, nodeid: int, attributes: typing.List[typing.Union[
1414+
async def Read(self, nodeid: int, attributes: Optional[typing.List[typing.Union[
14161415
None, # Empty tuple, all wildcard
14171416
typing.Tuple[int], # Endpoint
14181417
# Wildcard endpoint, Cluster id present
@@ -1423,9 +1422,9 @@ async def Read(self, nodeid: int, attributes: typing.List[typing.Union[
14231422
typing.Tuple[int, typing.Type[ClusterObjects.Cluster]],
14241423
# Concrete path
14251424
typing.Tuple[int, typing.Type[ClusterObjects.ClusterAttributeDescriptor]]
1426-
]] = None,
1427-
dataVersionFilters: typing.List[typing.Tuple[int, typing.Type[ClusterObjects.Cluster], int]] = None, events: typing.List[
1428-
typing.Union[
1425+
]]] = None,
1426+
dataVersionFilters: Optional[typing.List[typing.Tuple[int, typing.Type[ClusterObjects.Cluster], int]]] = None, events: Optional[typing.List[
1427+
typing.Union[
14291428
None, # Empty tuple, all wildcard
14301429
typing.Tuple[str, int], # all wildcard with urgency set
14311430
typing.Tuple[int, int], # Endpoint,
@@ -1437,9 +1436,9 @@ async def Read(self, nodeid: int, attributes: typing.List[typing.Union[
14371436
typing.Tuple[int, typing.Type[ClusterObjects.Cluster], int],
14381437
# Concrete path
14391438
typing.Tuple[int, typing.Type[ClusterObjects.ClusterEvent], int]
1440-
]] = None,
1439+
]]] = None,
14411440
eventNumberFilter: typing.Optional[int] = None,
1442-
returnClusterObject: bool = False, reportInterval: typing.Tuple[int, int] = None,
1441+
returnClusterObject: bool = False, reportInterval: Optional[typing.Tuple[int, int]] = None,
14431442
fabricFiltered: bool = True, keepSubscriptions: bool = False, autoResubscribe: bool = True):
14441443
'''
14451444
Read a list of attributes and/or events from a target node
@@ -1528,9 +1527,9 @@ async def ReadAttribute(self, nodeid: int, attributes: typing.List[typing.Union[
15281527
typing.Tuple[int, typing.Type[ClusterObjects.Cluster]],
15291528
# Concrete path
15301529
typing.Tuple[int, typing.Type[ClusterObjects.ClusterAttributeDescriptor]]
1531-
]], dataVersionFilters: typing.List[typing.Tuple[int, typing.Type[ClusterObjects.Cluster], int]] = None,
1530+
]], dataVersionFilters: Optional[typing.List[typing.Tuple[int, typing.Type[ClusterObjects.Cluster], int]]] = None,
15321531
returnClusterObject: bool = False,
1533-
reportInterval: typing.Tuple[int, int] = None,
1532+
reportInterval: Optional[typing.Tuple[int, int]] = None,
15341533
fabricFiltered: bool = True, keepSubscriptions: bool = False, autoResubscribe: bool = True):
15351534
'''
15361535
Read a list of attributes from a target node, this is a wrapper of DeviceController.Read()
@@ -1611,7 +1610,7 @@ async def ReadEvent(self, nodeid: int, events: typing.List[typing.Union[
16111610
typing.Tuple[int, typing.Type[ClusterObjects.ClusterEvent], int]
16121611
]], eventNumberFilter: typing.Optional[int] = None,
16131612
fabricFiltered: bool = True,
1614-
reportInterval: typing.Tuple[int, int] = None,
1613+
reportInterval: Optional[typing.Tuple[int, int]] = None,
16151614
keepSubscriptions: bool = False,
16161615
autoResubscribe: bool = True):
16171616
'''
@@ -1928,7 +1927,7 @@ class ChipDeviceController(ChipDeviceControllerBase):
19281927
'''
19291928

19301929
def __init__(self, opCredsContext: ctypes.c_void_p, fabricId: int, nodeId: int, adminVendorId: int, catTags: typing.List[int] = [
1931-
], paaTrustStorePath: str = "", useTestCommissioner: bool = False, fabricAdmin: FabricAdmin = None, name: str = None, keypair: p256keypair.P256Keypair = None):
1930+
], paaTrustStorePath: str = "", useTestCommissioner: bool = False, fabricAdmin: Optional[FabricAdmin] = None, name: Optional[str] = None, keypair: Optional[p256keypair.P256Keypair] = None):
19321931
super().__init__(
19331932
name or
19341933
f"caIndex({fabricAdmin.caIndex:x})/fabricId(0x{fabricId:016X})/nodeId(0x{nodeId:016X})"
@@ -1971,7 +1970,7 @@ def caIndex(self) -> int:
19711970
return self._caIndex
19721971

19731972
@property
1974-
def fabricAdmin(self) -> FabricAdmin:
1973+
def fabricAdmin(self) -> FabricAdmin.FabricAdmin:
19751974
return self._fabricAdmin
19761975

19771976
async def Commission(self, nodeid) -> int:
@@ -2114,7 +2113,7 @@ def GetFabricCheckResult(self) -> int:
21142113
return self._fabricCheckNodeId
21152114

21162115
async def CommissionOnNetwork(self, nodeId: int, setupPinCode: int,
2117-
filterType: DiscoveryFilterType = DiscoveryFilterType.NONE, filter: typing.Any = None,
2116+
filterType: DiscoveryFilterType = DiscoveryFilterType.NONE, filter: Optional[typing.Any] = None,
21182117
discoveryTimeoutMsec: int = 30000) -> int:
21192118
'''
21202119
Does the routine for OnNetworkCommissioning, with a filter for mDNS discovery.
@@ -2217,7 +2216,7 @@ class BareChipDeviceController(ChipDeviceControllerBase):
22172216
'''
22182217

22192218
def __init__(self, operationalKey: p256keypair.P256Keypair, noc: bytes,
2220-
icac: typing.Union[bytes, None], rcac: bytes, ipk: typing.Union[bytes, None], adminVendorId: int, name: str = None):
2219+
icac: typing.Union[bytes, None], rcac: bytes, ipk: typing.Union[bytes, None], adminVendorId: int, name: Optional[str] = None):
22212220
'''Creates a controller without AutoCommissioner.
22222221
22232222
The allocated controller uses the noc, icac, rcac and ipk instead of the default,

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

+19-19
Original file line numberDiff line numberDiff line change
@@ -58,9 +58,9 @@ class EventPriority(Enum):
5858

5959
@dataclass(frozen=True)
6060
class AttributePath:
61-
EndpointId: int = int()
62-
ClusterId: int = int()
63-
AttributeId: int = int()
61+
EndpointId: Optional[int] = None
62+
ClusterId: Optional[int] = None
63+
AttributeId: Optional[int] = None
6464

6565
@staticmethod
6666
def from_cluster(EndpointId: int, Cluster: Cluster) -> AttributePath:
@@ -80,12 +80,12 @@ def __str__(self) -> str:
8080

8181
@dataclass(frozen=True)
8282
class DataVersionFilter:
83-
EndpointId: int = None
84-
ClusterId: int = None
85-
DataVersion: int = None
83+
EndpointId: Optional[int] = None
84+
ClusterId: Optional[int] = None
85+
DataVersion: Optional[int] = None
8686

8787
@staticmethod
88-
def from_cluster(EndpointId: int, Cluster: Cluster, DataVersion: int = None) -> AttributePath:
88+
def from_cluster(EndpointId: int, Cluster: Cluster, DataVersion: Optional[int] = None) -> AttributePath:
8989
if Cluster is None:
9090
raise ValueError("Cluster cannot be None")
9191
return DataVersionFilter(EndpointId=EndpointId, ClusterId=Cluster.id, DataVersion=DataVersion)
@@ -104,8 +104,8 @@ class TypedAttributePath:
104104
AttributeName: str = None
105105
Path: AttributePath = None
106106

107-
def __init__(self, ClusterType: Cluster = None, AttributeType: ClusterAttributeDescriptor = None,
108-
Path: AttributePath = None):
107+
def __init__(self, ClusterType: Optional[Cluster] = None, AttributeType: Optional[ClusterAttributeDescriptor] = None,
108+
Path: Optional[AttributePath] = None):
109109
''' Only one of either ClusterType and AttributeType OR Path may be provided.
110110
'''
111111

@@ -156,13 +156,13 @@ class EventPath:
156156
Urgent: int = None
157157

158158
@staticmethod
159-
def from_cluster(EndpointId: int, Cluster: Cluster, EventId: int = None, Urgent: int = None) -> "EventPath":
159+
def from_cluster(EndpointId: int, Cluster: Cluster, EventId: Optional[int] = None, Urgent: Optional[int] = None) -> "EventPath":
160160
if Cluster is None:
161161
raise ValueError("Cluster cannot be None")
162162
return EventPath(EndpointId=EndpointId, ClusterId=Cluster.id, EventId=EventId, Urgent=Urgent)
163163

164164
@staticmethod
165-
def from_event(EndpointId: int, Event: ClusterEvent, Urgent: int = None) -> "EventPath":
165+
def from_event(EndpointId: int, Event: ClusterEvent, Urgent: Optional[int] = None) -> "EventPath":
166166
if Event is None:
167167
raise ValueError("Event cannot be None")
168168
return EventPath(EndpointId=EndpointId, ClusterId=Event.cluster_id, EventId=Event.event_id, Urgent=Urgent)
@@ -181,8 +181,8 @@ class EventHeader:
181181
Timestamp: int = None
182182
TimestampType: EventTimestampType = None
183183

184-
def __init__(self, EndpointId: int = None, ClusterId: int = None,
185-
EventId: int = None, EventNumber=None, Priority=None, Timestamp=None, TimestampType=None):
184+
def __init__(self, EndpointId: Optional[int] = None, ClusterId: Optional[int] = None,
185+
EventId: Optional[int] = None, EventNumber=None, Priority=None, Timestamp=None, TimestampType=None):
186186
self.EndpointId = EndpointId
187187
self.ClusterId = ClusterId
188188
self.EventId = EventId
@@ -1044,9 +1044,9 @@ def WriteGroupAttributes(groupId: int, devCtrl: c_void_p, attributes: List[Attri
10441044

10451045

10461046
def Read(future: Future, eventLoop, device, devCtrl,
1047-
attributes: List[AttributePath] = None, dataVersionFilters: List[DataVersionFilter] = None,
1048-
events: List[EventPath] = None, eventNumberFilter: Optional[int] = None, returnClusterObject: bool = True,
1049-
subscriptionParameters: SubscriptionParameters = None,
1047+
attributes: Optional[List[AttributePath]] = None, dataVersionFilters: Optional[List[DataVersionFilter]] = None,
1048+
events: Optional[List[EventPath]] = None, eventNumberFilter: Optional[int] = None, returnClusterObject: bool = True,
1049+
subscriptionParameters: Optional[SubscriptionParameters] = None,
10501050
fabricFiltered: bool = True, keepSubscriptions: bool = False, autoResubscribe: bool = True) -> PyChipError:
10511051
if (not attributes) and dataVersionFilters:
10521052
raise ValueError(
@@ -1164,9 +1164,9 @@ def Read(future: Future, eventLoop, device, devCtrl,
11641164

11651165

11661166
def ReadAttributes(future: Future, eventLoop, device, devCtrl,
1167-
attributes: List[AttributePath], dataVersionFilters: List[DataVersionFilter] = None,
1167+
attributes: List[AttributePath], dataVersionFilters: Optional[List[DataVersionFilter]] = None,
11681168
returnClusterObject: bool = True,
1169-
subscriptionParameters: SubscriptionParameters = None, fabricFiltered: bool = True) -> int:
1169+
subscriptionParameters: Optional[SubscriptionParameters] = None, fabricFiltered: bool = True) -> int:
11701170
return Read(future=future, eventLoop=eventLoop, device=device,
11711171
devCtrl=devCtrl, attributes=attributes, dataVersionFilters=dataVersionFilters,
11721172
events=None, returnClusterObject=returnClusterObject,
@@ -1175,7 +1175,7 @@ def ReadAttributes(future: Future, eventLoop, device, devCtrl,
11751175

11761176
def ReadEvents(future: Future, eventLoop, device, devCtrl,
11771177
events: List[EventPath], eventNumberFilter=None, returnClusterObject: bool = True,
1178-
subscriptionParameters: SubscriptionParameters = None, fabricFiltered: bool = True) -> int:
1178+
subscriptionParameters: Optional[SubscriptionParameters] = None, fabricFiltered: bool = True) -> int:
11791179
return Read(future=future, eventLoop=eventLoop, device=device, devCtrl=devCtrl, attributes=None,
11801180
dataVersionFilters=None, events=events, eventNumberFilter=eventNumberFilter,
11811181
returnClusterObject=returnClusterObject,

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

+5-5
Original file line numberDiff line numberDiff line change
@@ -175,7 +175,7 @@ def TagDictToLabelDict(self, debugPath: str, tlvData: Dict[int, Any]) -> Dict[st
175175

176176
def TLVToDict(self, tlvBuf: bytes) -> Dict[str, Any]:
177177
tlvData = tlv.TLVReader(tlvBuf).get().get('Any', {})
178-
return self.TagDictToLabelDict([], tlvData)
178+
return self.TagDictToLabelDict('', tlvData)
179179

180180
def DictToTLVWithWriter(self, debugPath: str, tag, data: Mapping, writer: tlv.TLVWriter):
181181
writer.startStructure(tag)
@@ -210,11 +210,11 @@ def descriptor(cls):
210210

211211
# The below dictionaries will be filled dynamically
212212
# and are used for quick lookup/mapping from cluster/attribute id to the correct class
213-
ALL_CLUSTERS = {}
214-
ALL_ATTRIBUTES = {}
213+
ALL_CLUSTERS: typing.Dict = {}
214+
ALL_ATTRIBUTES: typing.Dict = {}
215215
# These need to be separate because there can be overlap in command ids for commands and responses.
216-
ALL_ACCEPTED_COMMANDS = {}
217-
ALL_GENERATED_COMMANDS = {}
216+
ALL_ACCEPTED_COMMANDS: typing.Dict = {}
217+
ALL_GENERATED_COMMANDS: typing.Dict = {}
218218

219219

220220
class ClusterCommand(ClusterObject):

src/controller/python/chip/crypto/p256keypair.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,8 @@
1717

1818
import abc
1919
import hashlib
20-
from ctypes import (CFUNCTYPE, POINTER, c_bool, c_char, c_size_t, c_uint8, c_uint32, c_void_p, cast, memmove, pointer, py_object,
21-
string_at)
20+
from ctypes import (CFUNCTYPE, POINTER, _Pointer, c_bool, c_char, c_size_t, c_uint8, c_uint32, c_void_p, cast, memmove, pointer,
21+
py_object, string_at)
2222
from typing import TYPE_CHECKING
2323

2424
from chip import native
@@ -30,7 +30,7 @@ class pointer_fix:
3030
@classmethod
3131
def __class_getitem__(cls, item):
3232
return POINTER(item)
33-
pointer = pointer_fix
33+
_Pointer = pointer_fix
3434

3535

3636
_pychip_P256Keypair_ECDSA_sign_msg_func = CFUNCTYPE(
@@ -43,15 +43,15 @@ def __class_getitem__(cls, item):
4343

4444

4545
@ _pychip_P256Keypair_ECDSA_sign_msg_func
46-
def _pychip_ECDSA_sign_msg(self_: 'P256Keypair', message_buf: pointer[c_uint8], message_size: int, signature_buf: pointer[c_uint8], signature_buf_size: pointer[c_size_t]) -> bool:
46+
def _pychip_ECDSA_sign_msg(self_: 'P256Keypair', message_buf: _Pointer[c_uint8], message_size: int, signature_buf: _Pointer[c_uint8], signature_buf_size: _Pointer[c_size_t]) -> bool:
4747
res = self_.ECDSA_sign_msg(string_at(message_buf, message_size)[:])
4848
memmove(signature_buf, res, len(res))
4949
signature_buf_size.contents.value = len(res)
5050
return True
5151

5252

5353
@ _pychip_P256Keypair_ECDH_derive_secret_func
54-
def _pychip_ECDH_derive_secret(self_: 'P256Keypair', remote_pubkey: pointer[c_uint8], out_secret_buf: pointer[c_uint8], out_secret_buf_size: pointer[c_uint32]) -> bool:
54+
def _pychip_ECDH_derive_secret(self_: 'P256Keypair', remote_pubkey: _Pointer[c_uint8], out_secret_buf: _Pointer[c_uint8], out_secret_buf_size: _Pointer[c_uint32]) -> bool:
5555
res = self_.ECDH_derive_secret(
5656
string_at(remote_pubkey, P256_PUBLIC_KEY_LENGTH)[:])
5757
memmove(out_secret_buf, res, len(res))

0 commit comments

Comments
 (0)