nwo
stringlengths
6
76
sha
stringlengths
40
40
path
stringlengths
5
118
language
stringclasses
1 value
identifier
stringlengths
1
89
parameters
stringlengths
2
5.4k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
51.1k
docstring
stringlengths
1
17.6k
docstring_summary
stringlengths
0
7.02k
docstring_tokens
sequence
function
stringlengths
30
51.1k
function_tokens
sequence
url
stringlengths
85
218
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/group.py
python
GroupCluster.from_id
(cls, group_endpoint, cluster_id: int)
Instantiate from ZCL cluster by cluster id.
Instantiate from ZCL cluster by cluster id.
[ "Instantiate", "from", "ZCL", "cluster", "by", "cluster", "id", "." ]
def from_id(cls, group_endpoint, cluster_id: int): """Instantiate from ZCL cluster by cluster id.""" if cluster_id in cls._registry: return cls._registry[cluster_id](group_endpoint, is_server=True) group_endpoint.debug( "0x%04x cluster id is not supported for group requests", cluster_id ) raise KeyError("Unsupported 0x{:04x} cluster id for groups".format(cluster_id))
[ "def", "from_id", "(", "cls", ",", "group_endpoint", ",", "cluster_id", ":", "int", ")", ":", "if", "cluster_id", "in", "cls", ".", "_registry", ":", "return", "cls", ".", "_registry", "[", "cluster_id", "]", "(", "group_endpoint", ",", "is_server", "=", "True", ")", "group_endpoint", ".", "debug", "(", "\"0x%04x cluster id is not supported for group requests\"", ",", "cluster_id", ")", "raise", "KeyError", "(", "\"Unsupported 0x{:04x} cluster id for groups\"", ".", "format", "(", "cluster_id", ")", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/group.py#L151-L158
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/group.py
python
GroupCluster.from_attr
(cls, group_endpoint, ep_name: str)
Instantiate by Cluster name.
Instantiate by Cluster name.
[ "Instantiate", "by", "Cluster", "name", "." ]
def from_attr(cls, group_endpoint, ep_name: str): """Instantiate by Cluster name.""" for cluster in cls._registry.values(): if hasattr(cluster, "ep_attribute") and cluster.ep_attribute == ep_name: return cluster(group_endpoint, is_server=True) raise AttributeError(f"Unsupported {ep_name} group cluster")
[ "def", "from_attr", "(", "cls", ",", "group_endpoint", ",", "ep_name", ":", "str", ")", ":", "for", "cluster", "in", "cls", ".", "_registry", ".", "values", "(", ")", ":", "if", "hasattr", "(", "cluster", ",", "\"ep_attribute\"", ")", "and", "cluster", ".", "ep_attribute", "==", "ep_name", ":", "return", "cluster", "(", "group_endpoint", ",", "is_server", "=", "True", ")", "raise", "AttributeError", "(", "f\"Unsupported {ep_name} group cluster\"", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/group.py#L161-L167
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/group.py
python
GroupEndpoint.__init__
(self, group: Group)
Instantiate GroupRequest.
Instantiate GroupRequest.
[ "Instantiate", "GroupRequest", "." ]
def __init__(self, group: Group): """Instantiate GroupRequest.""" self._group = group self._clusters = {} self._cluster_by_attr = {}
[ "def", "__init__", "(", "self", ",", "group", ":", "Group", ")", ":", "self", ".", "_group", "=", "group", "self", ".", "_clusters", "=", "{", "}", "self", ".", "_cluster_by_attr", "=", "{", "}" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/group.py#L176-L180
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/group.py
python
GroupEndpoint.clusters
(self)
return self._clusters
Group clusters. most of the times, group requests are addressed from client -> server clusters.
Group clusters.
[ "Group", "clusters", "." ]
def clusters(self): """Group clusters. most of the times, group requests are addressed from client -> server clusters. """ return self._clusters
[ "def", "clusters", "(", "self", ")", ":", "return", "self", ".", "_clusters" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/group.py#L183-L188
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/group.py
python
GroupEndpoint.device
(self)
return self._group
Group is our fake zigpy device
Group is our fake zigpy device
[ "Group", "is", "our", "fake", "zigpy", "device" ]
def device(self): """Group is our fake zigpy device""" return self._group
[ "def", "device", "(", "self", ")", ":", "return", "self", ".", "_group" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/group.py#L191-L193
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/group.py
python
GroupEndpoint.request
(self, cluster, sequence, data, *args, **kwargs)
return self.device.request(zha_profile.PROFILE_ID, cluster, sequence, data)
Send multicast request.
Send multicast request.
[ "Send", "multicast", "request", "." ]
def request(self, cluster, sequence, data, *args, **kwargs): """Send multicast request.""" return self.device.request(zha_profile.PROFILE_ID, cluster, sequence, data)
[ "def", "request", "(", "self", ",", "cluster", ",", "sequence", ",", "data", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "device", ".", "request", "(", "zha_profile", ".", "PROFILE_ID", ",", "cluster", ",", "sequence", ",", "data", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/group.py#L195-L197
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/group.py
python
GroupEndpoint.reply
(self, cluster, sequence, data, *args, **kwargs)
return self.request(cluster, sequence, data, *args, **kwargs)
Send multicast reply. do we really need this one :shrug:
Send multicast reply.
[ "Send", "multicast", "reply", "." ]
def reply(self, cluster, sequence, data, *args, **kwargs): """Send multicast reply. do we really need this one :shrug: """ return self.request(cluster, sequence, data, *args, **kwargs)
[ "def", "reply", "(", "self", ",", "cluster", ",", "sequence", ",", "data", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "request", "(", "cluster", ",", "sequence", ",", "data", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/group.py#L199-L204
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/group.py
python
GroupEndpoint.__getitem__
(self, item: int)
return cluster
Return or instantiate a group cluster.
Return or instantiate a group cluster.
[ "Return", "or", "instantiate", "a", "group", "cluster", "." ]
def __getitem__(self, item: int): """Return or instantiate a group cluster.""" try: return self.clusters[item] except KeyError: self.debug("trying to create new group %s cluster id", item) cluster = GroupCluster.from_id(self, item) self.clusters[item] = cluster return cluster
[ "def", "__getitem__", "(", "self", ",", "item", ":", "int", ")", ":", "try", ":", "return", "self", ".", "clusters", "[", "item", "]", "except", "KeyError", ":", "self", ".", "debug", "(", "\"trying to create new group %s cluster id\"", ",", "item", ")", "cluster", "=", "GroupCluster", ".", "from_id", "(", "self", ",", "item", ")", "self", ".", "clusters", "[", "item", "]", "=", "cluster", "return", "cluster" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/group.py#L211-L220
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/group.py
python
GroupEndpoint.__getattr__
(self, name: str)
return cluster
Return or instantiate a group cluster by cluster name.
Return or instantiate a group cluster by cluster name.
[ "Return", "or", "instantiate", "a", "group", "cluster", "by", "cluster", "name", "." ]
def __getattr__(self, name: str): """Return or instantiate a group cluster by cluster name.""" try: return self._cluster_by_attr[name] except KeyError: self.debug("trying to create a new group '%s' cluster", name) cluster = GroupCluster.from_attr(self, name) self._cluster_by_attr[name] = cluster return cluster
[ "def", "__getattr__", "(", "self", ",", "name", ":", "str", ")", ":", "try", ":", "return", "self", ".", "_cluster_by_attr", "[", "name", "]", "except", "KeyError", ":", "self", ".", "debug", "(", "\"trying to create a new group '%s' cluster\"", ",", "name", ")", "cluster", "=", "GroupCluster", ".", "from_attr", "(", "self", ",", "name", ")", "self", ".", "_cluster_by_attr", "[", "name", "]", "=", "cluster", "return", "cluster" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/group.py#L222-L231
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/neighbor.py
python
Neighbor.__init__
(self, neighbor: zigpy.zdo.types.Neighbor, device: DeviceType)
Initialize neighbor instance.
Initialize neighbor instance.
[ "Initialize", "neighbor", "instance", "." ]
def __init__(self, neighbor: zigpy.zdo.types.Neighbor, device: DeviceType): """Initialize neighbor instance.""" self._device = device self._neighbor = neighbor
[ "def", "__init__", "(", "self", ",", "neighbor", ":", "zigpy", ".", "zdo", ".", "types", ".", "Neighbor", ",", "device", ":", "DeviceType", ")", ":", "self", ".", "_device", "=", "device", "self", ".", "_neighbor", "=", "neighbor" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/neighbor.py#L23-L26
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/neighbor.py
python
Neighbor.device
(self)
return self._device
Return zigpy device corresponding to this neighbor.
Return zigpy device corresponding to this neighbor.
[ "Return", "zigpy", "device", "corresponding", "to", "this", "neighbor", "." ]
def device(self) -> zigpy.typing.DeviceType: """Return zigpy device corresponding to this neighbor.""" return self._device
[ "def", "device", "(", "self", ")", "->", "zigpy", ".", "typing", ".", "DeviceType", ":", "return", "self", ".", "_device" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/neighbor.py#L29-L31
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/neighbor.py
python
Neighbor.neighbor
(self)
return self._neighbor
Return neighbor.
Return neighbor.
[ "Return", "neighbor", "." ]
def neighbor(self) -> zigpy.zdo.types.Neighbor: """Return neighbor.""" return self._neighbor
[ "def", "neighbor", "(", "self", ")", "->", "zigpy", ".", "zdo", ".", "types", ".", "Neighbor", ":", "return", "self", ".", "_neighbor" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/neighbor.py#L34-L36
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/neighbor.py
python
Neighbors.__init__
(self, device: DeviceType)
Initialize instance.
Initialize instance.
[ "Initialize", "instance", "." ]
def __init__(self, device: DeviceType) -> None: """Initialize instance.""" self._device = device self._neighbors: NeighborListType = [] self._staging: NeighborListType = [] self._supported: bool = True self._listeners = {} self.last_scan = None
[ "def", "__init__", "(", "self", ",", "device", ":", "DeviceType", ")", "->", "None", ":", "self", ".", "_device", "=", "device", "self", ".", "_neighbors", ":", "NeighborListType", "=", "[", "]", "self", ".", "_staging", ":", "NeighborListType", "=", "[", "]", "self", ".", "_supported", ":", "bool", "=", "True", "self", ".", "_listeners", "=", "{", "}", "self", ".", "last_scan", "=", "None" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/neighbor.py#L42-L49
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/neighbor.py
python
Neighbors.append
(self, *args, **kwargs)
return self.neighbors.append(*args, **kwargs)
Append method.
Append method.
[ "Append", "method", "." ]
def append(self, *args, **kwargs) -> None: """Append method.""" return self.neighbors.append(*args, **kwargs)
[ "def", "append", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "->", "None", ":", "return", "self", ".", "neighbors", ".", "append", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/neighbor.py#L51-L53
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/neighbor.py
python
Neighbors.__getitem__
(self, *args, **kwargs)
return self.neighbors.__getitem__(*args, **kwargs)
Get item method.
Get item method.
[ "Get", "item", "method", "." ]
def __getitem__(self, *args, **kwargs) -> Neighbor: """Get item method.""" return self.neighbors.__getitem__(*args, **kwargs)
[ "def", "__getitem__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "->", "Neighbor", ":", "return", "self", ".", "neighbors", ".", "__getitem__", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/neighbor.py#L55-L57
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/neighbor.py
python
Neighbors.__setitem__
(self, *args, **kwargs)
return self.neighbors.__setitem__(*args, **kwargs)
Set item method.
Set item method.
[ "Set", "item", "method", "." ]
def __setitem__(self, *args, **kwargs) -> None: """Set item method.""" return self.neighbors.__setitem__(*args, **kwargs)
[ "def", "__setitem__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "->", "None", ":", "return", "self", ".", "neighbors", ".", "__setitem__", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/neighbor.py#L59-L61
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/neighbor.py
python
Neighbors.__len__
(self)
return self.neighbors.__len__()
Len item method.
Len item method.
[ "Len", "item", "method", "." ]
def __len__(self) -> int: """Len item method.""" return self.neighbors.__len__()
[ "def", "__len__", "(", "self", ")", "->", "int", ":", "return", "self", ".", "neighbors", ".", "__len__", "(", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/neighbor.py#L63-L65
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/neighbor.py
python
Neighbors.__iter__
(self)
return self.neighbors.__iter__()
Iter item method.
Iter item method.
[ "Iter", "item", "method", "." ]
def __iter__(self) -> Iterator: """Iter item method.""" return self.neighbors.__iter__()
[ "def", "__iter__", "(", "self", ")", "->", "Iterator", ":", "return", "self", ".", "neighbors", ".", "__iter__", "(", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/neighbor.py#L67-L69
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/neighbor.py
python
Neighbors.ieee
(self)
return self._device.ieee
Return IEEE of the device.
Return IEEE of the device.
[ "Return", "IEEE", "of", "the", "device", "." ]
def ieee(self) -> zigpy.types.EUI64: """Return IEEE of the device.""" return self._device.ieee
[ "def", "ieee", "(", "self", ")", "->", "zigpy", ".", "types", ".", "EUI64", ":", "return", "self", ".", "_device", ".", "ieee" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/neighbor.py#L72-L74
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/neighbor.py
python
Neighbors.neighbors
(self)
return self._neighbors
Return our list of Neighbors.
Return our list of Neighbors.
[ "Return", "our", "list", "of", "Neighbors", "." ]
def neighbors(self) -> NeighborListType: """Return our list of Neighbors.""" return self._neighbors
[ "def", "neighbors", "(", "self", ")", "->", "NeighborListType", ":", "return", "self", ".", "_neighbors" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/neighbor.py#L77-L79
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/neighbor.py
python
Neighbors.supported
(self)
return self._supported
Return True if Mgmt_lqi_req is supported.
Return True if Mgmt_lqi_req is supported.
[ "Return", "True", "if", "Mgmt_lqi_req", "is", "supported", "." ]
def supported(self) -> bool: """Return True if Mgmt_lqi_req is supported.""" return self._supported
[ "def", "supported", "(", "self", ")", "->", "bool", ":", "return", "self", ".", "_supported" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/neighbor.py#L82-L84
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/neighbor.py
python
Neighbors.scan
(self)
Scan device for neighbors.
Scan device for neighbors.
[ "Scan", "device", "for", "neighbors", "." ]
async def scan(self) -> Optional[NeighborListType]: """Scan device for neighbors.""" try: return await self._scan() except (asyncio.TimeoutError, zigpy.exceptions.ZigbeeException): return None
[ "async", "def", "scan", "(", "self", ")", "->", "Optional", "[", "NeighborListType", "]", ":", "try", ":", "return", "await", "self", ".", "_scan", "(", ")", "except", "(", "asyncio", ".", "TimeoutError", ",", "zigpy", ".", "exceptions", ".", "ZigbeeException", ")", ":", "return", "None" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/neighbor.py#L91-L96
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/neighbor.py
python
Neighbors._scan
(self)
return self._neighbors
Scan device.
Scan device.
[ "Scan", "device", "." ]
async def _scan(self) -> NeighborListType: """Scan device.""" idx = 0 self._staging = [] while True: status, rsp = await self._device.zdo.Mgmt_Lqi_req(idx, tries=3, delay=1) self.debug("request status: %s. response: %s", status, rsp) if status != zigpy.zdo.types.Status.SUCCESS: self._supported = False self.debug("does not support 'Mgmt_Lqi_req'") return for neighbor in rsp.neighbor_table_list: if str(neighbor.ieee) in ( "00:00:00:00:00:00:00:00", "ff:ff:ff:ff:ff:ff:ff:ff", ): self.debug("ignoring invalid neighbor: %s", neighbor.ieee) idx += 1 continue self.stage_neighbor(neighbor) idx += 1 if idx >= rsp.entries or not rsp.neighbor_table_list: break await asyncio.sleep(random.uniform(*REQUEST_DELAY)) self.debug("Querying next starting at %s", idx) self.debug("Done scanning. Total %s neighbours", len(self._staging)) self.done_staging() self.listener_event("neighbors_updated") return self._neighbors
[ "async", "def", "_scan", "(", "self", ")", "->", "NeighborListType", ":", "idx", "=", "0", "self", ".", "_staging", "=", "[", "]", "while", "True", ":", "status", ",", "rsp", "=", "await", "self", ".", "_device", ".", "zdo", ".", "Mgmt_Lqi_req", "(", "idx", ",", "tries", "=", "3", ",", "delay", "=", "1", ")", "self", ".", "debug", "(", "\"request status: %s. response: %s\"", ",", "status", ",", "rsp", ")", "if", "status", "!=", "zigpy", ".", "zdo", ".", "types", ".", "Status", ".", "SUCCESS", ":", "self", ".", "_supported", "=", "False", "self", ".", "debug", "(", "\"does not support 'Mgmt_Lqi_req'\"", ")", "return", "for", "neighbor", "in", "rsp", ".", "neighbor_table_list", ":", "if", "str", "(", "neighbor", ".", "ieee", ")", "in", "(", "\"00:00:00:00:00:00:00:00\"", ",", "\"ff:ff:ff:ff:ff:ff:ff:ff\"", ",", ")", ":", "self", ".", "debug", "(", "\"ignoring invalid neighbor: %s\"", ",", "neighbor", ".", "ieee", ")", "idx", "+=", "1", "continue", "self", ".", "stage_neighbor", "(", "neighbor", ")", "idx", "+=", "1", "if", "idx", ">=", "rsp", ".", "entries", "or", "not", "rsp", ".", "neighbor_table_list", ":", "break", "await", "asyncio", ".", "sleep", "(", "random", ".", "uniform", "(", "*", "REQUEST_DELAY", ")", ")", "self", ".", "debug", "(", "\"Querying next starting at %s\"", ",", "idx", ")", "self", ".", "debug", "(", "\"Done scanning. Total %s neighbours\"", ",", "len", "(", "self", ".", "_staging", ")", ")", "self", ".", "done_staging", "(", ")", "self", ".", "listener_event", "(", "\"neighbors_updated\"", ")", "return", "self", ".", "_neighbors" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/neighbor.py#L98-L133
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/neighbor.py
python
Neighbors._add_neighbor
(self, staged: bool, neighbor: zigpy.zdo.types.Neighbor)
Add neighbor.
Add neighbor.
[ "Add", "neighbor", "." ]
def _add_neighbor(self, staged: bool, neighbor: zigpy.zdo.types.Neighbor) -> None: """Add neighbor.""" nei = Neighbor(neighbor, self._device.application.devices.get(neighbor.ieee)) if staged: self._staging.append(nei) return self._neighbors.append(nei)
[ "def", "_add_neighbor", "(", "self", ",", "staged", ":", "bool", ",", "neighbor", ":", "zigpy", ".", "zdo", ".", "types", ".", "Neighbor", ")", "->", "None", ":", "nei", "=", "Neighbor", "(", "neighbor", ",", "self", ".", "_device", ".", "application", ".", "devices", ".", "get", "(", "neighbor", ".", "ieee", ")", ")", "if", "staged", ":", "self", ".", "_staging", ".", "append", "(", "nei", ")", "return", "self", ".", "_neighbors", ".", "append", "(", "nei", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/neighbor.py#L135-L142
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/neighbor.py
python
Neighbors.done_staging
(self)
Switch staging.
Switch staging.
[ "Switch", "staging", "." ]
def done_staging(self) -> None: """Switch staging.""" self._neighbors = self._staging self._staging = None self.last_scan = time.time()
[ "def", "done_staging", "(", "self", ")", "->", "None", ":", "self", ".", "_neighbors", "=", "self", ".", "_staging", "self", ".", "_staging", "=", "None", "self", ".", "last_scan", "=", "time", ".", "time", "(", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/neighbor.py#L147-L151
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/device.py
python
Device.schedule_group_membership_scan
(self)
return self._group_scan_task
Rescan device group's membership.
Rescan device group's membership.
[ "Rescan", "device", "group", "s", "membership", "." ]
def schedule_group_membership_scan(self) -> asyncio.Task: """Rescan device group's membership.""" if self._group_scan_task and not self._group_scan_task.done(): self.debug("Cancelling old group rescan") self._group_scan_task.cancel() self._group_scan_task = asyncio.create_task(self.group_membership_scan()) return self._group_scan_task
[ "def", "schedule_group_membership_scan", "(", "self", ")", "->", "asyncio", ".", "Task", ":", "if", "self", ".", "_group_scan_task", "and", "not", "self", ".", "_group_scan_task", ".", "done", "(", ")", ":", "self", ".", "debug", "(", "\"Cancelling old group rescan\"", ")", "self", ".", "_group_scan_task", ".", "cancel", "(", ")", "self", ".", "_group_scan_task", "=", "asyncio", ".", "create_task", "(", "self", ".", "group_membership_scan", "(", ")", ")", "return", "self", ".", "_group_scan_task" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/device.py#L91-L98
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/device.py
python
Device.group_membership_scan
(self)
Sync up group membership.
Sync up group membership.
[ "Sync", "up", "group", "membership", "." ]
async def group_membership_scan(self) -> None: """Sync up group membership.""" for ep in self.non_zdo_endpoints: await ep.group_membership_scan()
[ "async", "def", "group_membership_scan", "(", "self", ")", "->", "None", ":", "for", "ep", "in", "self", ".", "non_zdo_endpoints", ":", "await", "ep", ".", "group_membership_scan", "(", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/device.py#L100-L103
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/device.py
python
Device.initializing
(self)
return self._initialize_task is not None and not self._initialize_task.done()
Return True if device is being initialized.
Return True if device is being initialized.
[ "Return", "True", "if", "device", "is", "being", "initialized", "." ]
def initializing(self) -> bool: """Return True if device is being initialized.""" return self._initialize_task is not None and not self._initialize_task.done()
[ "def", "initializing", "(", "self", ")", "->", "bool", ":", "return", "self", ".", "_initialize_task", "is", "not", "None", "and", "not", "self", ".", "_initialize_task", ".", "done", "(", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/device.py#L106-L108
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/device.py
python
Device.cancel_initialization
(self)
Cancel initialization call.
Cancel initialization call.
[ "Cancel", "initialization", "call", "." ]
def cancel_initialization(self) -> None: """Cancel initialization call.""" if self.initializing: self.debug("Canceling old initialize call") self._initialize_task.cancel()
[ "def", "cancel_initialization", "(", "self", ")", "->", "None", ":", "if", "self", ".", "initializing", ":", "self", ".", "debug", "(", "\"Canceling old initialize call\"", ")", "self", ".", "_initialize_task", ".", "cancel", "(", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/device.py#L110-L114
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/device.py
python
Device._initialize
(self)
Attempts multiple times to discover all basic information about a device: namely its node descriptor, all endpoints and clusters, and the model and manufacturer attributes from any Basic cluster exposing those attributes.
Attempts multiple times to discover all basic information about a device: namely its node descriptor, all endpoints and clusters, and the model and manufacturer attributes from any Basic cluster exposing those attributes.
[ "Attempts", "multiple", "times", "to", "discover", "all", "basic", "information", "about", "a", "device", ":", "namely", "its", "node", "descriptor", "all", "endpoints", "and", "clusters", "and", "the", "model", "and", "manufacturer", "attributes", "from", "any", "Basic", "cluster", "exposing", "those", "attributes", "." ]
async def _initialize(self): """ Attempts multiple times to discover all basic information about a device: namely its node descriptor, all endpoints and clusters, and the model and manufacturer attributes from any Basic cluster exposing those attributes. """ # Some devices are improperly initialized and are missing a node descriptor if self.node_desc is None: await self.get_node_descriptor() # Devices should have endpoints other than ZDO if self.has_non_zdo_endpoints: self.info("Already have endpoints: %s", self.endpoints) else: self.info("Discovering endpoints") status, _, endpoints = await self.zdo.Active_EP_req( self.nwk, tries=3, delay=0.5 ) if status != zdo.types.Status.SUCCESS: raise zigpy.exceptions.InvalidResponse( f"Endpoint request failed: {status}" ) self.info("Discovered endpoints: %s", endpoints) for endpoint_id in endpoints: self.add_endpoint(endpoint_id) self.status = Status.ZDO_INIT # Initialize all of the discovered endpoints if self.all_endpoints_init: self.info( "All endpoints are already initialized: %s", self.non_zdo_endpoints ) else: self.info("Initializing endpoints %s", self.non_zdo_endpoints) for ep in self.non_zdo_endpoints: await ep.initialize() # Query model info if self.model is not None and self.manufacturer is not None: self.info("Already have model and manufacturer info") else: for ep in self.non_zdo_endpoints: if self.model is None or self.manufacturer is None: model, manufacturer = await ep.get_model_info() self.info( "Read model %r and manufacturer %r from %s", model, manufacturer, ep, ) if model is not None: self.model = model if manufacturer is not None: self.manufacturer = manufacturer self.status = Status.ENDPOINTS_INIT self.info("Discovered basic device information for %s", self) # Signal to the application that the device is ready self._application.device_initialized(self)
[ "async", "def", "_initialize", "(", "self", ")", ":", "# Some devices are improperly initialized and are missing a node descriptor", "if", "self", ".", "node_desc", "is", "None", ":", "await", "self", ".", "get_node_descriptor", "(", ")", "# Devices should have endpoints other than ZDO", "if", "self", ".", "has_non_zdo_endpoints", ":", "self", ".", "info", "(", "\"Already have endpoints: %s\"", ",", "self", ".", "endpoints", ")", "else", ":", "self", ".", "info", "(", "\"Discovering endpoints\"", ")", "status", ",", "_", ",", "endpoints", "=", "await", "self", ".", "zdo", ".", "Active_EP_req", "(", "self", ".", "nwk", ",", "tries", "=", "3", ",", "delay", "=", "0.5", ")", "if", "status", "!=", "zdo", ".", "types", ".", "Status", ".", "SUCCESS", ":", "raise", "zigpy", ".", "exceptions", ".", "InvalidResponse", "(", "f\"Endpoint request failed: {status}\"", ")", "self", ".", "info", "(", "\"Discovered endpoints: %s\"", ",", "endpoints", ")", "for", "endpoint_id", "in", "endpoints", ":", "self", ".", "add_endpoint", "(", "endpoint_id", ")", "self", ".", "status", "=", "Status", ".", "ZDO_INIT", "# Initialize all of the discovered endpoints", "if", "self", ".", "all_endpoints_init", ":", "self", ".", "info", "(", "\"All endpoints are already initialized: %s\"", ",", "self", ".", "non_zdo_endpoints", ")", "else", ":", "self", ".", "info", "(", "\"Initializing endpoints %s\"", ",", "self", ".", "non_zdo_endpoints", ")", "for", "ep", "in", "self", ".", "non_zdo_endpoints", ":", "await", "ep", ".", "initialize", "(", ")", "# Query model info", "if", "self", ".", "model", "is", "not", "None", "and", "self", ".", "manufacturer", "is", "not", "None", ":", "self", ".", "info", "(", "\"Already have model and manufacturer info\"", ")", "else", ":", "for", "ep", "in", "self", ".", "non_zdo_endpoints", ":", "if", "self", ".", "model", "is", "None", "or", "self", ".", "manufacturer", "is", "None", ":", "model", ",", "manufacturer", "=", "await", "ep", ".", "get_model_info", "(", ")", "self", ".", "info", "(", "\"Read model %r and manufacturer %r from %s\"", ",", "model", ",", "manufacturer", ",", "ep", ",", ")", "if", "model", "is", "not", "None", ":", "self", ".", "model", "=", "model", "if", "manufacturer", "is", "not", "None", ":", "self", ".", "manufacturer", "=", "manufacturer", "self", ".", "status", "=", "Status", ".", "ENDPOINTS_INIT", "self", ".", "info", "(", "\"Discovered basic device information for %s\"", ",", "self", ")", "# Signal to the application that the device is ready", "self", ".", "_application", ".", "device_initialized", "(", "self", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/device.py#L165-L234
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/device.py
python
Device.manufacturer_id
(self)
Return manufacturer id.
Return manufacturer id.
[ "Return", "manufacturer", "id", "." ]
def manufacturer_id(self) -> Optional[int]: """Return manufacturer id.""" if self.manufacturer_id_override: return self.manufacturer_id_override elif self.node_desc is not None: return self.node_desc.manufacturer_code else: return None
[ "def", "manufacturer_id", "(", "self", ")", "->", "Optional", "[", "int", "]", ":", "if", "self", ".", "manufacturer_id_override", ":", "return", "self", ".", "manufacturer_id_override", "elif", "self", ".", "node_desc", "is", "not", "None", ":", "return", "self", ".", "node_desc", ".", "manufacturer_code", "else", ":", "return", "None" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/device.py#L397-L404
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/device.py
python
Device.relays
(self)
return self._relays
Relay list.
Relay list.
[ "Relay", "list", "." ]
def relays(self) -> Optional[Relays]: """Relay list.""" return self._relays
[ "def", "relays", "(", "self", ")", "->", "Optional", "[", "Relays", "]", ":", "return", "self", ".", "_relays" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/device.py#L427-L429
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/endpoint.py
python
Endpoint.add_input_cluster
(self, cluster_id, cluster=None)
return cluster
Adds an endpoint's input cluster (a server cluster supported by the device)
Adds an endpoint's input cluster
[ "Adds", "an", "endpoint", "s", "input", "cluster" ]
def add_input_cluster(self, cluster_id, cluster=None): """Adds an endpoint's input cluster (a server cluster supported by the device) """ if cluster_id in self.in_clusters and cluster is None: return self.in_clusters[cluster_id] if cluster is None: cluster = zigpy.zcl.Cluster.from_id(self, cluster_id, is_server=True) self.in_clusters[cluster_id] = cluster if hasattr(cluster, "ep_attribute"): self._cluster_attr[cluster.ep_attribute] = cluster if hasattr(self._device.application, "_dblistener"): listener = zigpy.zcl.ClusterPersistingListener( self._device.application._dblistener, cluster ) cluster.add_listener(listener) return cluster
[ "def", "add_input_cluster", "(", "self", ",", "cluster_id", ",", "cluster", "=", "None", ")", ":", "if", "cluster_id", "in", "self", ".", "in_clusters", "and", "cluster", "is", "None", ":", "return", "self", ".", "in_clusters", "[", "cluster_id", "]", "if", "cluster", "is", "None", ":", "cluster", "=", "zigpy", ".", "zcl", ".", "Cluster", ".", "from_id", "(", "self", ",", "cluster_id", ",", "is_server", "=", "True", ")", "self", ".", "in_clusters", "[", "cluster_id", "]", "=", "cluster", "if", "hasattr", "(", "cluster", ",", "\"ep_attribute\"", ")", ":", "self", ".", "_cluster_attr", "[", "cluster", ".", "ep_attribute", "]", "=", "cluster", "if", "hasattr", "(", "self", ".", "_device", ".", "application", ",", "\"_dblistener\"", ")", ":", "listener", "=", "zigpy", ".", "zcl", ".", "ClusterPersistingListener", "(", "self", ".", "_device", ".", "application", ".", "_dblistener", ",", "cluster", ")", "cluster", ".", "add_listener", "(", "listener", ")", "return", "cluster" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/endpoint.py#L88-L108
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/endpoint.py
python
Endpoint.add_output_cluster
(self, cluster_id, cluster=None)
return cluster
Adds an endpoint's output cluster (a client cluster supported by the device)
Adds an endpoint's output cluster
[ "Adds", "an", "endpoint", "s", "output", "cluster" ]
def add_output_cluster(self, cluster_id, cluster=None): """Adds an endpoint's output cluster (a client cluster supported by the device) """ if cluster_id in self.out_clusters and cluster is None: return self.out_clusters[cluster_id] if cluster is None: cluster = zigpy.zcl.Cluster.from_id(self, cluster_id, is_server=False) self.out_clusters[cluster_id] = cluster return cluster
[ "def", "add_output_cluster", "(", "self", ",", "cluster_id", ",", "cluster", "=", "None", ")", ":", "if", "cluster_id", "in", "self", ".", "out_clusters", "and", "cluster", "is", "None", ":", "return", "self", ".", "out_clusters", "[", "cluster_id", "]", "if", "cluster", "is", "None", ":", "cluster", "=", "zigpy", ".", "zcl", ".", "Cluster", ".", "from_id", "(", "self", ",", "cluster_id", ",", "is_server", "=", "False", ")", "self", ".", "out_clusters", "[", "cluster_id", "]", "=", "cluster", "return", "cluster" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/endpoint.py#L110-L121
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/endpoint.py
python
Endpoint.group_membership_scan
(self)
Sync up group membership.
Sync up group membership.
[ "Sync", "up", "group", "membership", "." ]
async def group_membership_scan(self) -> None: """Sync up group membership.""" try: res = await self.groups.get_membership([]) except AttributeError: return except (asyncio.TimeoutError, zigpy.exceptions.ZigbeeException): self.debug("Failed to sync-up group membership") return groups = {group for group in res[1]} self.device.application.groups.update_group_membership(self, groups)
[ "async", "def", "group_membership_scan", "(", "self", ")", "->", "None", ":", "try", ":", "res", "=", "await", "self", ".", "groups", ".", "get_membership", "(", "[", "]", ")", "except", "AttributeError", ":", "return", "except", "(", "asyncio", ".", "TimeoutError", ",", "zigpy", ".", "exceptions", ".", "ZigbeeException", ")", ":", "self", ".", "debug", "(", "\"Failed to sync-up group membership\"", ")", "return", "groups", "=", "{", "group", "for", "group", "in", "res", "[", "1", "]", "}", "self", ".", "device", ".", "application", ".", "groups", ".", "update_group_membership", "(", "self", ",", "groups", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/endpoint.py#L153-L164
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/endpoint.py
python
Endpoint.deserialize
(self, cluster_id, data)
return cluster.deserialize(data)
Deserialize data for ZCL
Deserialize data for ZCL
[ "Deserialize", "data", "for", "ZCL" ]
def deserialize(self, cluster_id, data): """Deserialize data for ZCL""" if cluster_id not in self.in_clusters and cluster_id not in self.out_clusters: raise KeyError("No cluster ID 0x%04x on %s" % (cluster_id, self.unique_id)) cluster = self.in_clusters.get(cluster_id, self.out_clusters.get(cluster_id)) return cluster.deserialize(data)
[ "def", "deserialize", "(", "self", ",", "cluster_id", ",", "data", ")", ":", "if", "cluster_id", "not", "in", "self", ".", "in_clusters", "and", "cluster_id", "not", "in", "self", ".", "out_clusters", ":", "raise", "KeyError", "(", "\"No cluster ID 0x%04x on %s\"", "%", "(", "cluster_id", ",", "self", ".", "unique_id", ")", ")", "cluster", "=", "self", ".", "in_clusters", ".", "get", "(", "cluster_id", ",", "self", ".", "out_clusters", ".", "get", "(", "cluster_id", ")", ")", "return", "cluster", ".", "deserialize", "(", "data", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/endpoint.py#L182-L188
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/endpoint.py
python
Endpoint.manufacturer_id
(self)
return self.device.manufacturer_id
Return device's manufacturer id code.
Return device's manufacturer id code.
[ "Return", "device", "s", "manufacturer", "id", "code", "." ]
def manufacturer_id(self) -> Optional[int]: """Return device's manufacturer id code.""" return self.device.manufacturer_id
[ "def", "manufacturer_id", "(", "self", ")", "->", "Optional", "[", "int", "]", ":", "return", "self", ".", "device", ".", "manufacturer_id" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/endpoint.py#L274-L276
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/appdb.py
python
PersistingListener.new
( cls, database_file: str, app: zigpy.typing.ControllerApplicationType )
return listener
Create an instance of persisting listener.
Create an instance of persisting listener.
[ "Create", "an", "instance", "of", "persisting", "listener", "." ]
async def new( cls, database_file: str, app: zigpy.typing.ControllerApplicationType ) -> PersistingListener: """Create an instance of persisting listener.""" sqlite_conn = await aiosqlite.connect( database_file, detect_types=sqlite3.PARSE_DECLTYPES ) listener = cls(sqlite_conn, app) try: await listener.initialize_tables() except asyncio.CancelledError: raise except Exception: await listener.shutdown() raise listener.running = True return listener
[ "async", "def", "new", "(", "cls", ",", "database_file", ":", "str", ",", "app", ":", "zigpy", ".", "typing", ".", "ControllerApplicationType", ")", "->", "PersistingListener", ":", "sqlite_conn", "=", "await", "aiosqlite", ".", "connect", "(", "database_file", ",", "detect_types", "=", "sqlite3", ".", "PARSE_DECLTYPES", ")", "listener", "=", "cls", "(", "sqlite_conn", ",", "app", ")", "try", ":", "await", "listener", ".", "initialize_tables", "(", ")", "except", "asyncio", ".", "CancelledError", ":", "raise", "except", "Exception", ":", "await", "listener", ".", "shutdown", "(", ")", "raise", "listener", ".", "running", "=", "True", "return", "listener" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/appdb.py#L75-L93
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/appdb.py
python
PersistingListener._worker
(self)
Process request in the received order.
Process request in the received order.
[ "Process", "request", "in", "the", "received", "order", "." ]
async def _worker(self) -> None: """Process request in the received order.""" while True: cb_name, args = await self._callback_handlers.get() handler = getattr(self, cb_name) assert handler try: await handler(*args) except aiosqlite.Error as exc: LOGGER.debug( "Error handling '%s' event with %s params: %s", cb_name, args, str(exc), ) except asyncio.CancelledError: raise except Exception as ex: LOGGER.error( "Unexpected error while processing %s(%s): %s", cb_name, args, ex ) self._callback_handlers.task_done()
[ "async", "def", "_worker", "(", "self", ")", "->", "None", ":", "while", "True", ":", "cb_name", ",", "args", "=", "await", "self", ".", "_callback_handlers", ".", "get", "(", ")", "handler", "=", "getattr", "(", "self", ",", "cb_name", ")", "assert", "handler", "try", ":", "await", "handler", "(", "*", "args", ")", "except", "aiosqlite", ".", "Error", "as", "exc", ":", "LOGGER", ".", "debug", "(", "\"Error handling '%s' event with %s params: %s\"", ",", "cb_name", ",", "args", ",", "str", "(", "exc", ")", ",", ")", "except", "asyncio", ".", "CancelledError", ":", "raise", "except", "Exception", "as", "ex", ":", "LOGGER", ".", "error", "(", "\"Unexpected error while processing %s(%s): %s\"", ",", "cb_name", ",", "args", ",", "ex", ")", "self", ".", "_callback_handlers", ".", "task_done", "(", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/appdb.py#L95-L116
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/appdb.py
python
PersistingListener.shutdown
(self)
Shutdown connection.
Shutdown connection.
[ "Shutdown", "connection", "." ]
async def shutdown(self) -> None: """Shutdown connection.""" self.running = False await self._callback_handlers.join() if not self._worker_task.done(): self._worker_task.cancel() await self._db.close()
[ "async", "def", "shutdown", "(", "self", ")", "->", "None", ":", "self", ".", "running", "=", "False", "await", "self", ".", "_callback_handlers", ".", "join", "(", ")", "if", "not", "self", ".", "_worker_task", ".", "done", "(", ")", ":", "self", ".", "_worker_task", ".", "cancel", "(", ")", "await", "self", ".", "_db", ".", "close", "(", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/appdb.py#L118-L124
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/appdb.py
python
PersistingListener.enqueue
(self, cb_name: str, *args)
Enqueue an async callback handler action.
Enqueue an async callback handler action.
[ "Enqueue", "an", "async", "callback", "handler", "action", "." ]
def enqueue(self, cb_name: str, *args) -> None: """Enqueue an async callback handler action.""" if not self.running: LOGGER.warning("Discarding %s event", cb_name) return self._callback_handlers.put_nowait((cb_name, args))
[ "def", "enqueue", "(", "self", ",", "cb_name", ":", "str", ",", "*", "args", ")", "->", "None", ":", "if", "not", "self", ".", "running", ":", "LOGGER", ".", "warning", "(", "\"Discarding %s event\"", ",", "cb_name", ")", "return", "self", ".", "_callback_handlers", ".", "put_nowait", "(", "(", "cb_name", ",", "args", ")", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/appdb.py#L126-L131
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/appdb.py
python
PersistingListener.executescript
(self, sql)
Naive replacement for `sqlite3.Cursor.executescript` that does not execute a `COMMIT` before running the script. This extra `COMMIT` breaks transactions that run scripts.
Naive replacement for `sqlite3.Cursor.executescript` that does not execute a `COMMIT` before running the script. This extra `COMMIT` breaks transactions that run scripts.
[ "Naive", "replacement", "for", "sqlite3", ".", "Cursor", ".", "executescript", "that", "does", "not", "execute", "a", "COMMIT", "before", "running", "the", "script", ".", "This", "extra", "COMMIT", "breaks", "transactions", "that", "run", "scripts", "." ]
async def executescript(self, sql): """ Naive replacement for `sqlite3.Cursor.executescript` that does not execute a `COMMIT` before running the script. This extra `COMMIT` breaks transactions that run scripts. """ # XXX: This will break if you use a semicolon anywhere but at the end of a line for statement in sql.split(";"): await self.execute(statement)
[ "async", "def", "executescript", "(", "self", ",", "sql", ")", ":", "# XXX: This will break if you use a semicolon anywhere but at the end of a line", "for", "statement", "in", "sql", ".", "split", "(", "\";\"", ")", ":", "await", "self", ".", "execute", "(", "statement", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/appdb.py#L136-L145
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/appdb.py
python
PersistingListener.device_relays_updated
( self, device: zigpy.typing.DeviceType, relays: t.Relays | None )
Device relay list is updated.
Device relay list is updated.
[ "Device", "relay", "list", "is", "updated", "." ]
def device_relays_updated( self, device: zigpy.typing.DeviceType, relays: t.Relays | None ) -> None: """Device relay list is updated.""" self.enqueue("_save_device_relays", device.ieee, relays)
[ "def", "device_relays_updated", "(", "self", ",", "device", ":", "zigpy", ".", "typing", ".", "DeviceType", ",", "relays", ":", "t", ".", "Relays", "|", "None", ")", "->", "None", ":", "self", ".", "enqueue", "(", "\"_save_device_relays\"", ",", "device", ".", "ieee", ",", "relays", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/appdb.py#L160-L164
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/appdb.py
python
PersistingListener.neighbors_updated
(self, neighbors: zigpy.neighbor.Neighbors)
Neighbor update from ZDO_Lqi_rsp.
Neighbor update from ZDO_Lqi_rsp.
[ "Neighbor", "update", "from", "ZDO_Lqi_rsp", "." ]
def neighbors_updated(self, neighbors: zigpy.neighbor.Neighbors) -> None: """Neighbor update from ZDO_Lqi_rsp.""" self.enqueue("_neighbors_updated", neighbors)
[ "def", "neighbors_updated", "(", "self", ",", "neighbors", ":", "zigpy", ".", "neighbor", ".", "Neighbors", ")", "->", "None", ":", "self", ".", "enqueue", "(", "\"_neighbors_updated\"", ",", "neighbors", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/appdb.py#L211-L213
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/appdb.py
python
PersistingListener.group_added
(self, group: zigpy.group.Group)
Group is added.
Group is added.
[ "Group", "is", "added", "." ]
def group_added(self, group: zigpy.group.Group) -> None: """Group is added.""" self.enqueue("_group_added", group)
[ "def", "group_added", "(", "self", ",", "group", ":", "zigpy", ".", "group", ".", "Group", ")", "->", "None", ":", "self", ".", "enqueue", "(", "\"_group_added\"", ",", "group", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/appdb.py#L228-L230
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/appdb.py
python
PersistingListener.group_member_added
( self, group: zigpy.group.Group, ep: zigpy.typing.EndpointType )
Called when a group member is added.
Called when a group member is added.
[ "Called", "when", "a", "group", "member", "is", "added", "." ]
def group_member_added( self, group: zigpy.group.Group, ep: zigpy.typing.EndpointType ) -> None: """Called when a group member is added.""" self.enqueue("_group_member_added", group, ep)
[ "def", "group_member_added", "(", "self", ",", "group", ":", "zigpy", ".", "group", ".", "Group", ",", "ep", ":", "zigpy", ".", "typing", ".", "EndpointType", ")", "->", "None", ":", "self", ".", "enqueue", "(", "\"_group_member_added\"", ",", "group", ",", "ep", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/appdb.py#L237-L241
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/appdb.py
python
PersistingListener.group_member_removed
( self, group: zigpy.group.Group, ep: zigpy.typing.EndpointType )
Called when a group member is removed.
Called when a group member is removed.
[ "Called", "when", "a", "group", "member", "is", "removed", "." ]
def group_member_removed( self, group: zigpy.group.Group, ep: zigpy.typing.EndpointType ) -> None: """Called when a group member is removed.""" self.enqueue("_group_member_removed", group, ep)
[ "def", "group_member_removed", "(", "self", ",", "group", ":", "zigpy", ".", "group", ".", "Group", ",", "ep", ":", "zigpy", ".", "typing", ".", "EndpointType", ")", "->", "None", ":", "self", ".", "enqueue", "(", "\"_group_member_removed\"", ",", "group", ",", "ep", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/appdb.py#L250-L254
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/appdb.py
python
PersistingListener.group_removed
(self, group: zigpy.group.Group)
Called when a group is removed.
Called when a group is removed.
[ "Called", "when", "a", "group", "is", "removed", "." ]
def group_removed(self, group: zigpy.group.Group) -> None: """Called when a group is removed.""" self.enqueue("_group_removed", group)
[ "def", "group_removed", "(", "self", ",", "group", ":", "zigpy", ".", "group", ".", "Group", ")", "->", "None", ":", "self", ".", "enqueue", "(", "\"_group_removed\"", ",", "group", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/appdb.py#L265-L267
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/appdb.py
python
PersistingListener._load_unsupported_attributes
(self)
Load unsuppoted attributes.
Load unsuppoted attributes.
[ "Load", "unsuppoted", "attributes", "." ]
async def _load_unsupported_attributes(self) -> None: """Load unsuppoted attributes.""" async with self.execute( f"SELECT * FROM unsupported_attributes{DB_V}" ) as cursor: async for (ieee, endpoint_id, cluster_id, attrid) in cursor: dev = self._application.get_device(ieee) ep = dev.endpoints[endpoint_id] try: cluster = ep.in_clusters[cluster_id] except KeyError: continue cluster.add_unsupported_attribute(attrid, inhibit_events=True)
[ "async", "def", "_load_unsupported_attributes", "(", "self", ")", "->", "None", ":", "async", "with", "self", ".", "execute", "(", "f\"SELECT * FROM unsupported_attributes{DB_V}\"", ")", "as", "cursor", ":", "async", "for", "(", "ieee", ",", "endpoint_id", ",", "cluster_id", ",", "attrid", ")", "in", "cursor", ":", "dev", "=", "self", ".", "_application", ".", "get_device", "(", "ieee", ")", "ep", "=", "dev", ".", "endpoints", "[", "endpoint_id", "]", "try", ":", "cluster", "=", "ep", ".", "in_clusters", "[", "cluster_id", "]", "except", "KeyError", ":", "continue", "cluster", ".", "add_unsupported_attribute", "(", "attrid", ",", "inhibit_events", "=", "True", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/appdb.py#L430-L445
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/appdb.py
python
PersistingListener._run_migrations
(self)
Migrates the database to the newest schema.
Migrates the database to the newest schema.
[ "Migrates", "the", "database", "to", "the", "newest", "schema", "." ]
async def _run_migrations(self): """Migrates the database to the newest schema.""" async with self.execute("PRAGMA user_version") as cursor: (db_version,) = await cursor.fetchone() LOGGER.debug("Current database version is v%s", db_version) # Very old databases did not set `user_version` but still should be migrated if db_version == 0 and not await self._table_exists("devices"): # If this is a brand new database, just load the current schema await self.executescript(zigpy.appdb_schemas.SCHEMAS[DB_VERSION]) return elif db_version > DB_VERSION: LOGGER.error( "This zigpy release uses database schema v%s but the database is v%s." " Downgrading zigpy is *not* recommended and may result in data loss." " Use at your own risk.", DB_VERSION, db_version, ) return # All migrations must succeed. If any fail, the database is not touched. await self.execute("BEGIN TRANSACTION") try: for migration, to_db_version in [ (self._migrate_to_v4, 4), (self._migrate_to_v5, 5), (self._migrate_to_v6, 6), (self._migrate_to_v7, 7), ]: if db_version >= min(to_db_version, DB_VERSION): continue LOGGER.info( "Migrating database from v%d to v%d", db_version, to_db_version ) await self.executescript(zigpy.appdb_schemas.SCHEMAS[to_db_version]) await migration() db_version = to_db_version except Exception: await self.execute("ROLLBACK") raise else: await self.execute("COMMIT")
[ "async", "def", "_run_migrations", "(", "self", ")", ":", "async", "with", "self", ".", "execute", "(", "\"PRAGMA user_version\"", ")", "as", "cursor", ":", "(", "db_version", ",", ")", "=", "await", "cursor", ".", "fetchone", "(", ")", "LOGGER", ".", "debug", "(", "\"Current database version is v%s\"", ",", "db_version", ")", "# Very old databases did not set `user_version` but still should be migrated", "if", "db_version", "==", "0", "and", "not", "await", "self", ".", "_table_exists", "(", "\"devices\"", ")", ":", "# If this is a brand new database, just load the current schema", "await", "self", ".", "executescript", "(", "zigpy", ".", "appdb_schemas", ".", "SCHEMAS", "[", "DB_VERSION", "]", ")", "return", "elif", "db_version", ">", "DB_VERSION", ":", "LOGGER", ".", "error", "(", "\"This zigpy release uses database schema v%s but the database is v%s.\"", "\" Downgrading zigpy is *not* recommended and may result in data loss.\"", "\" Use at your own risk.\"", ",", "DB_VERSION", ",", "db_version", ",", ")", "return", "# All migrations must succeed. If any fail, the database is not touched.", "await", "self", ".", "execute", "(", "\"BEGIN TRANSACTION\"", ")", "try", ":", "for", "migration", ",", "to_db_version", "in", "[", "(", "self", ".", "_migrate_to_v4", ",", "4", ")", ",", "(", "self", ".", "_migrate_to_v5", ",", "5", ")", ",", "(", "self", ".", "_migrate_to_v6", ",", "6", ")", ",", "(", "self", ".", "_migrate_to_v7", ",", "7", ")", ",", "]", ":", "if", "db_version", ">=", "min", "(", "to_db_version", ",", "DB_VERSION", ")", ":", "continue", "LOGGER", ".", "info", "(", "\"Migrating database from v%d to v%d\"", ",", "db_version", ",", "to_db_version", ")", "await", "self", ".", "executescript", "(", "zigpy", ".", "appdb_schemas", ".", "SCHEMAS", "[", "to_db_version", "]", ")", "await", "migration", "(", ")", "db_version", "=", "to_db_version", "except", "Exception", ":", "await", "self", ".", "execute", "(", "\"ROLLBACK\"", ")", "raise", "else", ":", "await", "self", ".", "execute", "(", "\"COMMIT\"", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/appdb.py#L531-L578
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/appdb.py
python
PersistingListener._migrate_tables
( self, table_map: dict[str, str], *, errors: str = "raise" )
Copy rows from one set of tables into another.
Copy rows from one set of tables into another.
[ "Copy", "rows", "from", "one", "set", "of", "tables", "into", "another", "." ]
async def _migrate_tables( self, table_map: dict[str, str], *, errors: str = "raise" ): """Copy rows from one set of tables into another.""" # Insertion order matters for foreign key constraints but any rows that fail # to insert due to constraint violations can be discarded for old_table, new_table in table_map.items(): async with self.execute(f"SELECT * FROM {old_table}") as cursor: async for row in cursor: placeholders = ",".join("?" * len(row)) try: await self.execute( f"INSERT INTO {new_table} VALUES ({placeholders})", row ) except aiosqlite.IntegrityError as e: if errors == "raise": raise elif errors == "warn": LOGGER.warning( "Failed to migrate row %s%s: %s", old_table, row, e ) elif errors == "ignore": pass else: raise ValueError( f"Invalid value for `errors`: {errors}!r" )
[ "async", "def", "_migrate_tables", "(", "self", ",", "table_map", ":", "dict", "[", "str", ",", "str", "]", ",", "*", ",", "errors", ":", "str", "=", "\"raise\"", ")", ":", "# Insertion order matters for foreign key constraints but any rows that fail", "# to insert due to constraint violations can be discarded", "for", "old_table", ",", "new_table", "in", "table_map", ".", "items", "(", ")", ":", "async", "with", "self", ".", "execute", "(", "f\"SELECT * FROM {old_table}\"", ")", "as", "cursor", ":", "async", "for", "row", "in", "cursor", ":", "placeholders", "=", "\",\"", ".", "join", "(", "\"?\"", "*", "len", "(", "row", ")", ")", "try", ":", "await", "self", ".", "execute", "(", "f\"INSERT INTO {new_table} VALUES ({placeholders})\"", ",", "row", ")", "except", "aiosqlite", ".", "IntegrityError", "as", "e", ":", "if", "errors", "==", "\"raise\"", ":", "raise", "elif", "errors", "==", "\"warn\"", ":", "LOGGER", ".", "warning", "(", "\"Failed to migrate row %s%s: %s\"", ",", "old_table", ",", "row", ",", "e", ")", "elif", "errors", "==", "\"ignore\"", ":", "pass", "else", ":", "raise", "ValueError", "(", "f\"Invalid value for `errors`: {errors}!r\"", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/appdb.py#L580-L608
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/appdb.py
python
PersistingListener._migrate_to_v4
(self)
Schema v4 expanded the node descriptor and neighbor table columns
Schema v4 expanded the node descriptor and neighbor table columns
[ "Schema", "v4", "expanded", "the", "node", "descriptor", "and", "neighbor", "table", "columns" ]
async def _migrate_to_v4(self): """Schema v4 expanded the node descriptor and neighbor table columns""" # The `node_descriptors` table was added in v1 if await self._table_exists("node_descriptors"): async with self.execute("SELECT * FROM node_descriptors") as cur: async for dev_ieee, value in cur: node_desc, rest = zdo_t.NodeDescriptor.deserialize(value) assert not rest await self.execute( "INSERT INTO node_descriptors_v4" " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)", (dev_ieee,) + node_desc.as_tuple(), ) # The `neighbors` table was added in v3 but the version number was not # incremented. It may not exist. if await self._table_exists("neighbors"): async with self.execute("SELECT * FROM neighbors") as cur: async for dev_ieee, epid, ieee, nwk, packed, prm, depth, lqi in cur: neighbor = zdo_t.Neighbor( extended_pan_id=epid, ieee=ieee, nwk=nwk, permit_joining=prm, depth=depth, lqi=lqi, reserved2=0b000000, **zdo_t.Neighbor._parse_packed(packed), ) await self.execute( "INSERT INTO neighbors_v4 VALUES (?,?,?,?,?,?,?,?,?,?,?,?)", (dev_ieee,) + neighbor.as_tuple(), )
[ "async", "def", "_migrate_to_v4", "(", "self", ")", ":", "# The `node_descriptors` table was added in v1", "if", "await", "self", ".", "_table_exists", "(", "\"node_descriptors\"", ")", ":", "async", "with", "self", ".", "execute", "(", "\"SELECT * FROM node_descriptors\"", ")", "as", "cur", ":", "async", "for", "dev_ieee", ",", "value", "in", "cur", ":", "node_desc", ",", "rest", "=", "zdo_t", ".", "NodeDescriptor", ".", "deserialize", "(", "value", ")", "assert", "not", "rest", "await", "self", ".", "execute", "(", "\"INSERT INTO node_descriptors_v4\"", "\" VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)\"", ",", "(", "dev_ieee", ",", ")", "+", "node_desc", ".", "as_tuple", "(", ")", ",", ")", "# The `neighbors` table was added in v3 but the version number was not", "# incremented. It may not exist.", "if", "await", "self", ".", "_table_exists", "(", "\"neighbors\"", ")", ":", "async", "with", "self", ".", "execute", "(", "\"SELECT * FROM neighbors\"", ")", "as", "cur", ":", "async", "for", "dev_ieee", ",", "epid", ",", "ieee", ",", "nwk", ",", "packed", ",", "prm", ",", "depth", ",", "lqi", "in", "cur", ":", "neighbor", "=", "zdo_t", ".", "Neighbor", "(", "extended_pan_id", "=", "epid", ",", "ieee", "=", "ieee", ",", "nwk", "=", "nwk", ",", "permit_joining", "=", "prm", ",", "depth", "=", "depth", ",", "lqi", "=", "lqi", ",", "reserved2", "=", "0b000000", ",", "*", "*", "zdo_t", ".", "Neighbor", ".", "_parse_packed", "(", "packed", ")", ",", ")", "await", "self", ".", "execute", "(", "\"INSERT INTO neighbors_v4 VALUES (?,?,?,?,?,?,?,?,?,?,?,?)\"", ",", "(", "dev_ieee", ",", ")", "+", "neighbor", ".", "as_tuple", "(", ")", ",", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/appdb.py#L610-L644
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/appdb.py
python
PersistingListener._migrate_to_v5
(self)
Schema v5 introduced global table version suffixes and removed stale rows
Schema v5 introduced global table version suffixes and removed stale rows
[ "Schema", "v5", "introduced", "global", "table", "version", "suffixes", "and", "removed", "stale", "rows" ]
async def _migrate_to_v5(self): """Schema v5 introduced global table version suffixes and removed stale rows""" # Copy the devices table first, it should have no conflicts await self.execute("INSERT INTO devices_v5 SELECT * FROM devices") await self._migrate_tables( { "endpoints": "endpoints_v5", "clusters": "in_clusters_v5", "output_clusters": "out_clusters_v5", "groups": "groups_v5", "group_members": "group_members_v5", "relays": "relays_v5", "attributes": "attributes_cache_v5", # These were migrated in v4 "neighbors_v4": "neighbors_v5", "node_descriptors_v4": "node_descriptors_v5", }, errors="warn", )
[ "async", "def", "_migrate_to_v5", "(", "self", ")", ":", "# Copy the devices table first, it should have no conflicts", "await", "self", ".", "execute", "(", "\"INSERT INTO devices_v5 SELECT * FROM devices\"", ")", "await", "self", ".", "_migrate_tables", "(", "{", "\"endpoints\"", ":", "\"endpoints_v5\"", ",", "\"clusters\"", ":", "\"in_clusters_v5\"", ",", "\"output_clusters\"", ":", "\"out_clusters_v5\"", ",", "\"groups\"", ":", "\"groups_v5\"", ",", "\"group_members\"", ":", "\"group_members_v5\"", ",", "\"relays\"", ":", "\"relays_v5\"", ",", "\"attributes\"", ":", "\"attributes_cache_v5\"", ",", "# These were migrated in v4", "\"neighbors_v4\"", ":", "\"neighbors_v5\"", ",", "\"node_descriptors_v4\"", ":", "\"node_descriptors_v5\"", ",", "}", ",", "errors", "=", "\"warn\"", ",", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/appdb.py#L646-L665
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/appdb.py
python
PersistingListener._migrate_to_v6
(self)
Schema v6 relaxed the `attribute_cache` table schema to ignore endpoints
Schema v6 relaxed the `attribute_cache` table schema to ignore endpoints
[ "Schema", "v6", "relaxed", "the", "attribute_cache", "table", "schema", "to", "ignore", "endpoints" ]
async def _migrate_to_v6(self): """Schema v6 relaxed the `attribute_cache` table schema to ignore endpoints""" # Copy the devices table first, it should have no conflicts await self.execute("INSERT INTO devices_v6 SELECT * FROM devices_v5") await self._migrate_tables( { "endpoints_v5": "endpoints_v6", "in_clusters_v5": "in_clusters_v6", "out_clusters_v5": "out_clusters_v6", "groups_v5": "groups_v6", "group_members_v5": "group_members_v6", "relays_v5": "relays_v6", "attributes_cache_v5": "attributes_cache_v6", "neighbors_v5": "neighbors_v6", "node_descriptors_v5": "node_descriptors_v6", } ) # See if we can migrate any `attributes_cache` rows skipped by the v5 migration if await self._table_exists("attributes"): async with self.execute("SELECT count(*) FROM attributes") as cur: (num_attrs_v4,) = await cur.fetchone() async with self.execute("SELECT count(*) FROM attributes_cache_v6") as cur: (num_attrs_v6,) = await cur.fetchone() if num_attrs_v6 < num_attrs_v4: LOGGER.warning( "Migrating up to %d rows skipped by v5 migration", num_attrs_v4 - num_attrs_v6, ) await self._migrate_tables( {"attributes": "attributes_cache_v6"}, errors="ignore" )
[ "async", "def", "_migrate_to_v6", "(", "self", ")", ":", "# Copy the devices table first, it should have no conflicts", "await", "self", ".", "execute", "(", "\"INSERT INTO devices_v6 SELECT * FROM devices_v5\"", ")", "await", "self", ".", "_migrate_tables", "(", "{", "\"endpoints_v5\"", ":", "\"endpoints_v6\"", ",", "\"in_clusters_v5\"", ":", "\"in_clusters_v6\"", ",", "\"out_clusters_v5\"", ":", "\"out_clusters_v6\"", ",", "\"groups_v5\"", ":", "\"groups_v6\"", ",", "\"group_members_v5\"", ":", "\"group_members_v6\"", ",", "\"relays_v5\"", ":", "\"relays_v6\"", ",", "\"attributes_cache_v5\"", ":", "\"attributes_cache_v6\"", ",", "\"neighbors_v5\"", ":", "\"neighbors_v6\"", ",", "\"node_descriptors_v5\"", ":", "\"node_descriptors_v6\"", ",", "}", ")", "# See if we can migrate any `attributes_cache` rows skipped by the v5 migration", "if", "await", "self", ".", "_table_exists", "(", "\"attributes\"", ")", ":", "async", "with", "self", ".", "execute", "(", "\"SELECT count(*) FROM attributes\"", ")", "as", "cur", ":", "(", "num_attrs_v4", ",", ")", "=", "await", "cur", ".", "fetchone", "(", ")", "async", "with", "self", ".", "execute", "(", "\"SELECT count(*) FROM attributes_cache_v6\"", ")", "as", "cur", ":", "(", "num_attrs_v6", ",", ")", "=", "await", "cur", ".", "fetchone", "(", ")", "if", "num_attrs_v6", "<", "num_attrs_v4", ":", "LOGGER", ".", "warning", "(", "\"Migrating up to %d rows skipped by v5 migration\"", ",", "num_attrs_v4", "-", "num_attrs_v6", ",", ")", "await", "self", ".", "_migrate_tables", "(", "{", "\"attributes\"", ":", "\"attributes_cache_v6\"", "}", ",", "errors", "=", "\"ignore\"", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/appdb.py#L667-L702
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/appdb.py
python
PersistingListener._migrate_to_v7
(self)
Schema v7 just adds a new table.
Schema v7 just adds a new table.
[ "Schema", "v7", "just", "adds", "a", "new", "table", "." ]
async def _migrate_to_v7(self): """Schema v7 just adds a new table.""" # Copy the devices table first, it should have no conflicts await self.execute("INSERT INTO devices_v7 SELECT * FROM devices_v6") await self._migrate_tables( { "endpoints_v6": "endpoints_v7", "in_clusters_v6": "in_clusters_v7", "out_clusters_v6": "out_clusters_v7", "groups_v6": "groups_v7", "group_members_v6": "group_members_v7", "relays_v6": "relays_v7", "attributes_cache_v6": "attributes_cache_v7", "neighbors_v6": "neighbors_v7", "node_descriptors_v6": "node_descriptors_v7", } )
[ "async", "def", "_migrate_to_v7", "(", "self", ")", ":", "# Copy the devices table first, it should have no conflicts", "await", "self", ".", "execute", "(", "\"INSERT INTO devices_v7 SELECT * FROM devices_v6\"", ")", "await", "self", ".", "_migrate_tables", "(", "{", "\"endpoints_v6\"", ":", "\"endpoints_v7\"", ",", "\"in_clusters_v6\"", ":", "\"in_clusters_v7\"", ",", "\"out_clusters_v6\"", ":", "\"out_clusters_v7\"", ",", "\"groups_v6\"", ":", "\"groups_v7\"", ",", "\"group_members_v6\"", ":", "\"group_members_v7\"", ",", "\"relays_v6\"", ":", "\"relays_v7\"", ",", "\"attributes_cache_v6\"", ":", "\"attributes_cache_v7\"", ",", "\"neighbors_v6\"", ":", "\"neighbors_v7\"", ",", "\"node_descriptors_v6\"", ":", "\"node_descriptors_v7\"", ",", "}", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/appdb.py#L704-L721
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/state.py
python
CounterGroup.__init__
( self, collection_name: str | None = None, )
Initialize instance.
Initialize instance.
[ "Initialize", "instance", "." ]
def __init__( self, collection_name: str | None = None, ) -> None: """Initialize instance.""" self._name: str | None = collection_name super().__init__()
[ "def", "__init__", "(", "self", ",", "collection_name", ":", "str", "|", "None", "=", "None", ",", ")", "->", "None", ":", "self", ".", "_name", ":", "str", "|", "None", "=", "collection_name", "super", "(", ")", ".", "__init__", "(", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/state.py#L150-L157
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/state.py
python
CounterGroup.counters
(self)
return (counter for counter in self.values() if isinstance(counter, Counter))
Return an iterable of the counters
Return an iterable of the counters
[ "Return", "an", "iterable", "of", "the", "counters" ]
def counters(self) -> Iterable[Counter]: """Return an iterable of the counters""" return (counter for counter in self.values() if isinstance(counter, Counter))
[ "def", "counters", "(", "self", ")", "->", "Iterable", "[", "Counter", "]", ":", "return", "(", "counter", "for", "counter", "in", "self", ".", "values", "(", ")", "if", "isinstance", "(", "counter", ",", "Counter", ")", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/state.py#L159-L161
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/state.py
python
CounterGroup.groups
(self)
return (group for group in self.values() if isinstance(group, CounterGroup))
Return an iterable of the counter groups
Return an iterable of the counter groups
[ "Return", "an", "iterable", "of", "the", "counter", "groups" ]
def groups(self) -> Iterable[CounterGroup]: """Return an iterable of the counter groups""" return (group for group in self.values() if isinstance(group, CounterGroup))
[ "def", "groups", "(", "self", ")", "->", "Iterable", "[", "CounterGroup", "]", ":", "return", "(", "group", "for", "group", "in", "self", ".", "values", "(", ")", "if", "isinstance", "(", "group", ",", "CounterGroup", ")", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/state.py#L163-L165
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/state.py
python
CounterGroup.tags
(self)
return (group.name for group in self.groups())
Return an iterable if tags
Return an iterable if tags
[ "Return", "an", "iterable", "if", "tags" ]
def tags(self) -> Iterable[int | str]: """Return an iterable if tags""" return (group.name for group in self.groups())
[ "def", "tags", "(", "self", ")", "->", "Iterable", "[", "int", "|", "str", "]", ":", "return", "(", "group", ".", "name", "for", "group", "in", "self", ".", "groups", "(", ")", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/state.py#L167-L169
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/state.py
python
CounterGroup.__missing__
(self, counter_id: Any)
return counter
Default counter factory.
Default counter factory.
[ "Default", "counter", "factory", "." ]
def __missing__(self, counter_id: Any) -> Counter: """Default counter factory.""" counter = Counter(counter_id) self[counter_id] = counter return counter
[ "def", "__missing__", "(", "self", ",", "counter_id", ":", "Any", ")", "->", "Counter", ":", "counter", "=", "Counter", "(", "counter_id", ")", "self", "[", "counter_id", "]", "=", "counter", "return", "counter" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/state.py#L171-L176
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/state.py
python
CounterGroup.__repr__
(self)
return f"{self.__class__.__name__}('{self.name}', {{{counters}}})"
Representation magic method.
Representation magic method.
[ "Representation", "magic", "method", "." ]
def __repr__(self) -> str: """Representation magic method.""" counters = ( f"{counter.__class__.__name__}('{counter.name}', {int(counter)})" for counter in self.counters() ) counters = ", ".join(counters) return f"{self.__class__.__name__}('{self.name}', {{{counters}}})"
[ "def", "__repr__", "(", "self", ")", "->", "str", ":", "counters", "=", "(", "f\"{counter.__class__.__name__}('{counter.name}', {int(counter)})\"", "for", "counter", "in", "self", ".", "counters", "(", ")", ")", "counters", "=", "\", \"", ".", "join", "(", "counters", ")", "return", "f\"{self.__class__.__name__}('{self.name}', {{{counters}}})\"" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/state.py#L178-L185
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/state.py
python
CounterGroup.__str__
(self)
return f"{self.name}: [{', '.join(counters)}]"
String magic method.
String magic method.
[ "String", "magic", "method", "." ]
def __str__(self) -> str: """String magic method.""" counters = [str(counter) for counter in self.counters()] return f"{self.name}: [{', '.join(counters)}]"
[ "def", "__str__", "(", "self", ")", "->", "str", ":", "counters", "=", "[", "str", "(", "counter", ")", "for", "counter", "in", "self", ".", "counters", "(", ")", "]", "return", "f\"{self.name}: [{', '.join(counters)}]\"" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/state.py#L187-L190
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/state.py
python
CounterGroup.name
(self)
return self._name
Return counter collection name.
Return counter collection name.
[ "Return", "counter", "collection", "name", "." ]
def name(self) -> str: """Return counter collection name.""" return self._name
[ "def", "name", "(", "self", ")", "->", "str", ":", "return", "self", ".", "_name" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/state.py#L193-L195
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/state.py
python
CounterGroup.increment
(self, name: int | str, *tags: int | str)
Create and Update all counters recursively.
Create and Update all counters recursively.
[ "Create", "and", "Update", "all", "counters", "recursively", "." ]
def increment(self, name: int | str, *tags: int | str) -> None: """Create and Update all counters recursively.""" if tags: tag, *rest = tags self.setdefault(tag, CounterGroup(tag)) self[tag][name].increment() self[tag].increment(name, *rest) return
[ "def", "increment", "(", "self", ",", "name", ":", "int", "|", "str", ",", "*", "tags", ":", "int", "|", "str", ")", "->", "None", ":", "if", "tags", ":", "tag", ",", "", "*", "rest", "=", "tags", "self", ".", "setdefault", "(", "tag", ",", "CounterGroup", "(", "tag", ")", ")", "self", "[", "tag", "]", "[", "name", "]", ".", "increment", "(", ")", "self", "[", "tag", "]", ".", "increment", "(", "name", ",", "*", "rest", ")", "return" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/state.py#L197-L205
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/state.py
python
CounterGroup.reset
(self)
Clear and rollover counters.
Clear and rollover counters.
[ "Clear", "and", "rollover", "counters", "." ]
def reset(self) -> None: """Clear and rollover counters.""" for counter in self.values(): counter.reset()
[ "def", "reset", "(", "self", ")", "->", "None", ":", "for", "counter", "in", "self", ".", "values", "(", ")", ":", "counter", ".", "reset", "(", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/state.py#L207-L211
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/state.py
python
CounterGroups.__iter__
(self)
return (counter_group for counter_group in self.values())
Return an iterable of the counters
Return an iterable of the counters
[ "Return", "an", "iterable", "of", "the", "counters" ]
def __iter__(self) -> Iterable[CounterGroup]: """Return an iterable of the counters""" return (counter_group for counter_group in self.values())
[ "def", "__iter__", "(", "self", ")", "->", "Iterable", "[", "CounterGroup", "]", ":", "return", "(", "counter_group", "for", "counter_group", "in", "self", ".", "values", "(", ")", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/state.py#L217-L219
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/state.py
python
CounterGroups.__missing__
(self, counter_group_name: Any)
return counter_group
Default counter factory.
Default counter factory.
[ "Default", "counter", "factory", "." ]
def __missing__(self, counter_group_name: Any) -> CounterGroup: """Default counter factory.""" counter_group = CounterGroup(counter_group_name) super().__setitem__(counter_group_name, counter_group) return counter_group
[ "def", "__missing__", "(", "self", ",", "counter_group_name", ":", "Any", ")", "->", "CounterGroup", ":", "counter_group", "=", "CounterGroup", "(", "counter_group_name", ")", "super", "(", ")", ".", "__setitem__", "(", "counter_group_name", ",", "counter_group", ")", "return", "counter_group" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/state.py#L221-L226
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/quirks/registry.py
python
DeviceRegistry.add_to_registry
(self, custom_device: CustomDeviceType)
Add a device to the registry
Add a device to the registry
[ "Add", "a", "device", "to", "the", "registry" ]
def add_to_registry(self, custom_device: CustomDeviceType) -> None: """Add a device to the registry""" models_info = custom_device.signature.get(SIG_MODELS_INFO) if models_info: for manuf, model in models_info: if custom_device not in self.registry[manuf][model]: self.registry[manuf][model].insert(0, custom_device) else: manufacturer = custom_device.signature.get(SIG_MANUFACTURER) model = custom_device.signature.get(SIG_MODEL) if custom_device not in self.registry[manufacturer][model]: self.registry[manufacturer][model].insert(0, custom_device)
[ "def", "add_to_registry", "(", "self", ",", "custom_device", ":", "CustomDeviceType", ")", "->", "None", ":", "models_info", "=", "custom_device", ".", "signature", ".", "get", "(", "SIG_MODELS_INFO", ")", "if", "models_info", ":", "for", "manuf", ",", "model", "in", "models_info", ":", "if", "custom_device", "not", "in", "self", ".", "registry", "[", "manuf", "]", "[", "model", "]", ":", "self", ".", "registry", "[", "manuf", "]", "[", "model", "]", ".", "insert", "(", "0", ",", "custom_device", ")", "else", ":", "manufacturer", "=", "custom_device", ".", "signature", ".", "get", "(", "SIG_MANUFACTURER", ")", "model", "=", "custom_device", ".", "signature", ".", "get", "(", "SIG_MODEL", ")", "if", "custom_device", "not", "in", "self", ".", "registry", "[", "manufacturer", "]", "[", "model", "]", ":", "self", ".", "registry", "[", "manufacturer", "]", "[", "model", "]", ".", "insert", "(", "0", ",", "custom_device", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/quirks/registry.py#L31-L42
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/quirks/registry.py
python
DeviceRegistry.get_device
(self, device: DeviceType)
return device
Get a CustomDevice object, if one is available
Get a CustomDevice object, if one is available
[ "Get", "a", "CustomDevice", "object", "if", "one", "is", "available" ]
def get_device(self, device: DeviceType) -> Union[CustomDeviceType, DeviceType]: """Get a CustomDevice object, if one is available""" if isinstance(device, zigpy.quirks.CustomDevice): return device dev_ep = set(device.endpoints) - {0} _LOGGER.debug( "Checking quirks for %s %s (%s)", device.manufacturer, device.model, device.ieee, ) for candidate in itertools.chain( self.registry[device.manufacturer][device.model], self.registry[device.manufacturer][None], self.registry[None][device.model], self.registry[None][None], ): _LOGGER.debug("Considering %s", candidate) if not device.model == candidate.signature.get(SIG_MODEL, device.model): _LOGGER.debug("Fail, because device model mismatch: '%s'", device.model) continue if not ( device.manufacturer == candidate.signature.get(SIG_MANUFACTURER, device.manufacturer) ): _LOGGER.debug( "Fail, because device manufacturer mismatch: '%s'", device.manufacturer, ) continue sig = candidate.signature.get(SIG_ENDPOINTS) if sig is None: continue if not self._match(sig, dev_ep): _LOGGER.debug( "Fail because endpoint list mismatch: %s %s", set(sig.keys()), dev_ep, ) continue if not all( [ device[eid].profile_id == sig[eid].get(SIG_EP_PROFILE, device[eid].profile_id) for eid in sig ] ): _LOGGER.debug( "Fail because profile_id mismatch on at least one endpoint" ) continue if not all( [ device[eid].device_type == sig[eid].get(SIG_EP_TYPE, device[eid].device_type) for eid in sig ] ): _LOGGER.debug( "Fail because device_type mismatch on at least one endpoint" ) continue if not all( [ self._match(device[eid].in_clusters, ep.get(SIG_EP_INPUT, [])) for eid, ep in sig.items() ] ): _LOGGER.debug( "Fail because input cluster mismatch on at least one endpoint" ) continue if not all( [ self._match(device[eid].out_clusters, ep.get(SIG_EP_OUTPUT, [])) for eid, ep in sig.items() ] ): _LOGGER.debug( "Fail because output cluster mismatch on at least one endpoint" ) continue _LOGGER.debug( "Found custom device replacement for %s: %s", device.ieee, candidate ) device = candidate(device._application, device.ieee, device.nwk, device) break return device
[ "def", "get_device", "(", "self", ",", "device", ":", "DeviceType", ")", "->", "Union", "[", "CustomDeviceType", ",", "DeviceType", "]", ":", "if", "isinstance", "(", "device", ",", "zigpy", ".", "quirks", ".", "CustomDevice", ")", ":", "return", "device", "dev_ep", "=", "set", "(", "device", ".", "endpoints", ")", "-", "{", "0", "}", "_LOGGER", ".", "debug", "(", "\"Checking quirks for %s %s (%s)\"", ",", "device", ".", "manufacturer", ",", "device", ".", "model", ",", "device", ".", "ieee", ",", ")", "for", "candidate", "in", "itertools", ".", "chain", "(", "self", ".", "registry", "[", "device", ".", "manufacturer", "]", "[", "device", ".", "model", "]", ",", "self", ".", "registry", "[", "device", ".", "manufacturer", "]", "[", "None", "]", ",", "self", ".", "registry", "[", "None", "]", "[", "device", ".", "model", "]", ",", "self", ".", "registry", "[", "None", "]", "[", "None", "]", ",", ")", ":", "_LOGGER", ".", "debug", "(", "\"Considering %s\"", ",", "candidate", ")", "if", "not", "device", ".", "model", "==", "candidate", ".", "signature", ".", "get", "(", "SIG_MODEL", ",", "device", ".", "model", ")", ":", "_LOGGER", ".", "debug", "(", "\"Fail, because device model mismatch: '%s'\"", ",", "device", ".", "model", ")", "continue", "if", "not", "(", "device", ".", "manufacturer", "==", "candidate", ".", "signature", ".", "get", "(", "SIG_MANUFACTURER", ",", "device", ".", "manufacturer", ")", ")", ":", "_LOGGER", ".", "debug", "(", "\"Fail, because device manufacturer mismatch: '%s'\"", ",", "device", ".", "manufacturer", ",", ")", "continue", "sig", "=", "candidate", ".", "signature", ".", "get", "(", "SIG_ENDPOINTS", ")", "if", "sig", "is", "None", ":", "continue", "if", "not", "self", ".", "_match", "(", "sig", ",", "dev_ep", ")", ":", "_LOGGER", ".", "debug", "(", "\"Fail because endpoint list mismatch: %s %s\"", ",", "set", "(", "sig", ".", "keys", "(", ")", ")", ",", "dev_ep", ",", ")", "continue", "if", "not", "all", "(", "[", "device", "[", "eid", "]", ".", "profile_id", "==", "sig", "[", "eid", "]", ".", "get", "(", "SIG_EP_PROFILE", ",", "device", "[", "eid", "]", ".", "profile_id", ")", "for", "eid", "in", "sig", "]", ")", ":", "_LOGGER", ".", "debug", "(", "\"Fail because profile_id mismatch on at least one endpoint\"", ")", "continue", "if", "not", "all", "(", "[", "device", "[", "eid", "]", ".", "device_type", "==", "sig", "[", "eid", "]", ".", "get", "(", "SIG_EP_TYPE", ",", "device", "[", "eid", "]", ".", "device_type", ")", "for", "eid", "in", "sig", "]", ")", ":", "_LOGGER", ".", "debug", "(", "\"Fail because device_type mismatch on at least one endpoint\"", ")", "continue", "if", "not", "all", "(", "[", "self", ".", "_match", "(", "device", "[", "eid", "]", ".", "in_clusters", ",", "ep", ".", "get", "(", "SIG_EP_INPUT", ",", "[", "]", ")", ")", "for", "eid", ",", "ep", "in", "sig", ".", "items", "(", ")", "]", ")", ":", "_LOGGER", ".", "debug", "(", "\"Fail because input cluster mismatch on at least one endpoint\"", ")", "continue", "if", "not", "all", "(", "[", "self", ".", "_match", "(", "device", "[", "eid", "]", ".", "out_clusters", ",", "ep", ".", "get", "(", "SIG_EP_OUTPUT", ",", "[", "]", ")", ")", "for", "eid", ",", "ep", "in", "sig", ".", "items", "(", ")", "]", ")", ":", "_LOGGER", ".", "debug", "(", "\"Fail because output cluster mismatch on at least one endpoint\"", ")", "continue", "_LOGGER", ".", "debug", "(", "\"Found custom device replacement for %s: %s\"", ",", "device", ".", "ieee", ",", "candidate", ")", "device", "=", "candidate", "(", "device", ".", "_application", ",", "device", ".", "ieee", ",", "device", ".", "nwk", ",", "device", ")", "break", "return", "device" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/quirks/registry.py#L54-L151
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/quirks/__init__.py
python
get_device
(device: zigpy.device.Device, registry: Optional[DeviceRegistry] = None)
return registry.get_device(device)
Get a CustomDevice object, if one is available
Get a CustomDevice object, if one is available
[ "Get", "a", "CustomDevice", "object", "if", "one", "is", "available" ]
def get_device(device: zigpy.device.Device, registry: Optional[DeviceRegistry] = None): """Get a CustomDevice object, if one is available""" if registry is None: return _DEVICE_REGISTRY.get_device(device) return registry.get_device(device)
[ "def", "get_device", "(", "device", ":", "zigpy", ".", "device", ".", "Device", ",", "registry", ":", "Optional", "[", "DeviceRegistry", "]", "=", "None", ")", ":", "if", "registry", "is", "None", ":", "return", "_DEVICE_REGISTRY", ".", "get_device", "(", "device", ")", "return", "registry", ".", "get_device", "(", "device", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/quirks/__init__.py#L41-L46
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/quirks/__init__.py
python
get_quirk_list
( manufacturer: str, model: str, registry: Optional[DeviceRegistry] = None )
return registry.registry[manufacturer][model]
Get the Quirk list for a given manufacturer and model.
Get the Quirk list for a given manufacturer and model.
[ "Get", "the", "Quirk", "list", "for", "a", "given", "manufacturer", "and", "model", "." ]
def get_quirk_list( manufacturer: str, model: str, registry: Optional[DeviceRegistry] = None ): """Get the Quirk list for a given manufacturer and model.""" if registry is None: return _DEVICE_REGISTRY.registry[manufacturer][model] return registry.registry[manufacturer][model]
[ "def", "get_quirk_list", "(", "manufacturer", ":", "str", ",", "model", ":", "str", ",", "registry", ":", "Optional", "[", "DeviceRegistry", "]", "=", "None", ")", ":", "if", "registry", "is", "None", ":", "return", "_DEVICE_REGISTRY", ".", "registry", "[", "manufacturer", "]", "[", "model", "]", "return", "registry", ".", "registry", "[", "manufacturer", "]", "[", "model", "]" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/quirks/__init__.py#L49-L56
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/quirks/__init__.py
python
register_uninitialized_device_message_handler
(handler: Callable)
Register an handler for messages received by uninitialized devices. each handler is passed same parameters as zigpy.application.ControllerApplication.handle_message
Register an handler for messages received by uninitialized devices.
[ "Register", "an", "handler", "for", "messages", "received", "by", "uninitialized", "devices", "." ]
def register_uninitialized_device_message_handler(handler: Callable) -> None: """Register an handler for messages received by uninitialized devices. each handler is passed same parameters as zigpy.application.ControllerApplication.handle_message """ if handler not in _uninitialized_device_message_handlers: _uninitialized_device_message_handlers.append(handler)
[ "def", "register_uninitialized_device_message_handler", "(", "handler", ":", "Callable", ")", "->", "None", ":", "if", "handler", "not", "in", "_uninitialized_device_message_handlers", ":", "_uninitialized_device_message_handlers", ".", "append", "(", "handler", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/quirks/__init__.py#L59-L66
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/quirks/__init__.py
python
handle_message_from_uninitialized_sender
( sender: zigpy.device.Device, profile: int, cluster: int, src_ep: int, dst_ep: int, message: bytes, )
Processes message from an uninitialized sender.
Processes message from an uninitialized sender.
[ "Processes", "message", "from", "an", "uninitialized", "sender", "." ]
def handle_message_from_uninitialized_sender( sender: zigpy.device.Device, profile: int, cluster: int, src_ep: int, dst_ep: int, message: bytes, ) -> None: """Processes message from an uninitialized sender.""" for handler in _uninitialized_device_message_handlers: if handler(sender, profile, cluster, src_ep, dst_ep, message): break
[ "def", "handle_message_from_uninitialized_sender", "(", "sender", ":", "zigpy", ".", "device", ".", "Device", ",", "profile", ":", "int", ",", "cluster", ":", "int", ",", "src_ep", ":", "int", ",", "dst_ep", ":", "int", ",", "message", ":", "bytes", ",", ")", "->", "None", ":", "for", "handler", "in", "_uninitialized_device_message_handlers", ":", "if", "handler", "(", "sender", ",", "profile", ",", "cluster", ",", "src_ep", ",", "dst_ep", ",", "message", ")", ":", "break" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/quirks/__init__.py#L280-L291
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/quirks/__init__.py
python
CustomCluster._is_manuf_specific
(self)
return 0xFC00 <= self.cluster_id <= 0xFFFF
Return True if cluster_id is within manufacturer specific range.
Return True if cluster_id is within manufacturer specific range.
[ "Return", "True", "if", "cluster_id", "is", "within", "manufacturer", "specific", "range", "." ]
def _is_manuf_specific(self) -> bool: """Return True if cluster_id is within manufacturer specific range.""" return 0xFC00 <= self.cluster_id <= 0xFFFF
[ "def", "_is_manuf_specific", "(", "self", ")", "->", "bool", ":", "return", "0xFC00", "<=", "self", ".", "cluster_id", "<=", "0xFFFF" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/quirks/__init__.py#L159-L161
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/quirks/__init__.py
python
CustomCluster._has_manuf_attr
(self, attrs_to_process: Union[Iterable, List, Dict])
return self._is_manuf_specific or ( set.intersection(set(self.manufacturer_attributes), attrs_to_process) )
Return True if contains a manufacturer specific attribute.
Return True if contains a manufacturer specific attribute.
[ "Return", "True", "if", "contains", "a", "manufacturer", "specific", "attribute", "." ]
def _has_manuf_attr(self, attrs_to_process: Union[Iterable, List, Dict]) -> bool: """Return True if contains a manufacturer specific attribute.""" return self._is_manuf_specific or ( set.intersection(set(self.manufacturer_attributes), attrs_to_process) )
[ "def", "_has_manuf_attr", "(", "self", ",", "attrs_to_process", ":", "Union", "[", "Iterable", ",", "List", ",", "Dict", "]", ")", "->", "bool", ":", "return", "self", ".", "_is_manuf_specific", "or", "(", "set", ".", "intersection", "(", "set", "(", "self", ".", "manufacturer_attributes", ")", ",", "attrs_to_process", ")", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/quirks/__init__.py#L163-L167
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/quirks/__init__.py
python
CustomCluster._configure_reporting
( self, args: List[foundation.Attribute], manufacturer: Optional[int] = None )
return super()._configure_reporting(args, manufacturer=manufacturer)
Configure reporting ZCL foundation command.
Configure reporting ZCL foundation command.
[ "Configure", "reporting", "ZCL", "foundation", "command", "." ]
def _configure_reporting( self, args: List[foundation.Attribute], manufacturer: Optional[int] = None ): """Configure reporting ZCL foundation command.""" if manufacturer is None and self._has_manuf_attr([a.attrid for a in args]): manufacturer = self.endpoint.manufacturer_id return super()._configure_reporting(args, manufacturer=manufacturer)
[ "def", "_configure_reporting", "(", "self", ",", "args", ":", "List", "[", "foundation", ".", "Attribute", "]", ",", "manufacturer", ":", "Optional", "[", "int", "]", "=", "None", ")", ":", "if", "manufacturer", "is", "None", "and", "self", ".", "_has_manuf_attr", "(", "[", "a", ".", "attrid", "for", "a", "in", "args", "]", ")", ":", "manufacturer", "=", "self", ".", "endpoint", ".", "manufacturer_id", "return", "super", "(", ")", ".", "_configure_reporting", "(", "args", ",", "manufacturer", "=", "manufacturer", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/quirks/__init__.py#L247-L253
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/quirks/__init__.py
python
CustomCluster._read_attributes
( self, args: List[t.uint16_t], manufacturer: Optional[int] = None )
return super()._read_attributes(args, manufacturer=manufacturer)
Read attributes ZCL foundation command.
Read attributes ZCL foundation command.
[ "Read", "attributes", "ZCL", "foundation", "command", "." ]
def _read_attributes( self, args: List[t.uint16_t], manufacturer: Optional[int] = None ): """Read attributes ZCL foundation command.""" if manufacturer is None and self._has_manuf_attr(args): manufacturer = self.endpoint.manufacturer_id return super()._read_attributes(args, manufacturer=manufacturer)
[ "def", "_read_attributes", "(", "self", ",", "args", ":", "List", "[", "t", ".", "uint16_t", "]", ",", "manufacturer", ":", "Optional", "[", "int", "]", "=", "None", ")", ":", "if", "manufacturer", "is", "None", "and", "self", ".", "_has_manuf_attr", "(", "args", ")", ":", "manufacturer", "=", "self", ".", "endpoint", ".", "manufacturer_id", "return", "super", "(", ")", ".", "_read_attributes", "(", "args", ",", "manufacturer", "=", "manufacturer", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/quirks/__init__.py#L255-L261
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/quirks/__init__.py
python
CustomCluster._write_attributes
( self, args: List[foundation.Attribute], manufacturer: Optional[int] = None )
return super()._write_attributes(args, manufacturer=manufacturer)
Write attribute ZCL foundation command.
Write attribute ZCL foundation command.
[ "Write", "attribute", "ZCL", "foundation", "command", "." ]
def _write_attributes( self, args: List[foundation.Attribute], manufacturer: Optional[int] = None ): """Write attribute ZCL foundation command.""" if manufacturer is None and self._has_manuf_attr([a.attrid for a in args]): manufacturer = self.endpoint.manufacturer_id return super()._write_attributes(args, manufacturer=manufacturer)
[ "def", "_write_attributes", "(", "self", ",", "args", ":", "List", "[", "foundation", ".", "Attribute", "]", ",", "manufacturer", ":", "Optional", "[", "int", "]", "=", "None", ")", ":", "if", "manufacturer", "is", "None", "and", "self", ".", "_has_manuf_attr", "(", "[", "a", ".", "attrid", "for", "a", "in", "args", "]", ")", ":", "manufacturer", "=", "self", ".", "endpoint", ".", "manufacturer_id", "return", "super", "(", ")", ".", "_write_attributes", "(", "args", ",", "manufacturer", "=", "manufacturer", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/quirks/__init__.py#L263-L269
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/quirks/__init__.py
python
CustomCluster._write_attributes_undivided
( self, args: List[foundation.Attribute], manufacturer: Optional[int] = None )
return super()._write_attributes_undivided(args, manufacturer=manufacturer)
Write attribute undivided ZCL foundation command.
Write attribute undivided ZCL foundation command.
[ "Write", "attribute", "undivided", "ZCL", "foundation", "command", "." ]
def _write_attributes_undivided( self, args: List[foundation.Attribute], manufacturer: Optional[int] = None ): """Write attribute undivided ZCL foundation command.""" if manufacturer is None and self._has_manuf_attr([a.attrid for a in args]): manufacturer = self.endpoint.manufacturer_id return super()._write_attributes_undivided(args, manufacturer=manufacturer)
[ "def", "_write_attributes_undivided", "(", "self", ",", "args", ":", "List", "[", "foundation", ".", "Attribute", "]", ",", "manufacturer", ":", "Optional", "[", "int", "]", "=", "None", ")", ":", "if", "manufacturer", "is", "None", "and", "self", ".", "_has_manuf_attr", "(", "[", "a", ".", "attrid", "for", "a", "in", "args", "]", ")", ":", "manufacturer", "=", "self", ".", "endpoint", ".", "manufacturer_id", "return", "super", "(", ")", ".", "_write_attributes_undivided", "(", "args", ",", "manufacturer", "=", "manufacturer", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/quirks/__init__.py#L271-L277
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/ota/validators.py
python
parse_silabs_ebl
(data: bytes)
Parses a Silicon Labs EBL firmware image.
Parses a Silicon Labs EBL firmware image.
[ "Parses", "a", "Silicon", "Labs", "EBL", "firmware", "image", "." ]
def parse_silabs_ebl(data: bytes) -> typing.Iterable[typing.Tuple[bytes, bytes]]: """ Parses a Silicon Labs EBL firmware image. """ if len(data) % 64 != 0: raise ValidationError( f"Image size ({len(data)}) must be a multiple of 64 bytes" ) orig_data = data while True: if len(data) < 4: raise ValidationError( "Image is truncated: not long enough to contain a valid tag" ) tag = data[:2] length = int.from_bytes(data[2:4], "big") value = data[4 : 4 + length] if len(value) < length: raise ValidationError("Image is truncated: tag value is cut off") data = data[4 + length :] yield tag, value # EBL end tag if tag != b"\xFC\x04": continue # At this point the EBL should contain nothing but padding if data.strip(b"\xFF"): raise ValidationError("Image padding contains invalid bytes") unpadded_image = orig_data[: -len(data)] if data else orig_data computed_crc = zlib.crc32(unpadded_image) if computed_crc != VALID_SILABS_CRC: raise ValidationError( f"Image CRC-32 is invalid:" f" expected 0x{VALID_SILABS_CRC:08X}, got 0x{computed_crc:08X}" ) break
[ "def", "parse_silabs_ebl", "(", "data", ":", "bytes", ")", "->", "typing", ".", "Iterable", "[", "typing", ".", "Tuple", "[", "bytes", ",", "bytes", "]", "]", ":", "if", "len", "(", "data", ")", "%", "64", "!=", "0", ":", "raise", "ValidationError", "(", "f\"Image size ({len(data)}) must be a multiple of 64 bytes\"", ")", "orig_data", "=", "data", "while", "True", ":", "if", "len", "(", "data", ")", "<", "4", ":", "raise", "ValidationError", "(", "\"Image is truncated: not long enough to contain a valid tag\"", ")", "tag", "=", "data", "[", ":", "2", "]", "length", "=", "int", ".", "from_bytes", "(", "data", "[", "2", ":", "4", "]", ",", "\"big\"", ")", "value", "=", "data", "[", "4", ":", "4", "+", "length", "]", "if", "len", "(", "value", ")", "<", "length", ":", "raise", "ValidationError", "(", "\"Image is truncated: tag value is cut off\"", ")", "data", "=", "data", "[", "4", "+", "length", ":", "]", "yield", "tag", ",", "value", "# EBL end tag", "if", "tag", "!=", "b\"\\xFC\\x04\"", ":", "continue", "# At this point the EBL should contain nothing but padding", "if", "data", ".", "strip", "(", "b\"\\xFF\"", ")", ":", "raise", "ValidationError", "(", "\"Image padding contains invalid bytes\"", ")", "unpadded_image", "=", "orig_data", "[", ":", "-", "len", "(", "data", ")", "]", "if", "data", "else", "orig_data", "computed_crc", "=", "zlib", ".", "crc32", "(", "unpadded_image", ")", "if", "computed_crc", "!=", "VALID_SILABS_CRC", ":", "raise", "ValidationError", "(", "f\"Image CRC-32 is invalid:\"", "f\" expected 0x{VALID_SILABS_CRC:08X}, got 0x{computed_crc:08X}\"", ")", "break" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/ota/validators.py#L22-L68
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/ota/validators.py
python
parse_silabs_gbl
(data: bytes)
Parses a Silicon Labs GBL firmware image.
Parses a Silicon Labs GBL firmware image.
[ "Parses", "a", "Silicon", "Labs", "GBL", "firmware", "image", "." ]
def parse_silabs_gbl(data: bytes) -> typing.Iterable[typing.Tuple[bytes, bytes]]: """ Parses a Silicon Labs GBL firmware image. """ orig_data = data while True: if len(data) < 8: raise ValidationError( "Image is truncated: not long enough to contain a valid tag" ) tag = data[:4] length = int.from_bytes(data[4:8], "little") value = data[8 : 8 + length] if len(value) < length: raise ValidationError("Image is truncated: tag value is cut off") data = data[8 + length :] yield tag, value # GBL end tag if tag != b"\xFC\x04\x04\xFC": continue # GBL images aren't expected to contain padding but some are (i.e. Hue) unpadded_image = orig_data[: -len(data)] if data else orig_data computed_crc = zlib.crc32(unpadded_image) if computed_crc != VALID_SILABS_CRC: raise ValidationError( f"Image CRC-32 is invalid:" f" expected 0x{VALID_SILABS_CRC:08X}, got 0x{computed_crc:08X}" ) break
[ "def", "parse_silabs_gbl", "(", "data", ":", "bytes", ")", "->", "typing", ".", "Iterable", "[", "typing", ".", "Tuple", "[", "bytes", ",", "bytes", "]", "]", ":", "orig_data", "=", "data", "while", "True", ":", "if", "len", "(", "data", ")", "<", "8", ":", "raise", "ValidationError", "(", "\"Image is truncated: not long enough to contain a valid tag\"", ")", "tag", "=", "data", "[", ":", "4", "]", "length", "=", "int", ".", "from_bytes", "(", "data", "[", "4", ":", "8", "]", ",", "\"little\"", ")", "value", "=", "data", "[", "8", ":", "8", "+", "length", "]", "if", "len", "(", "value", ")", "<", "length", ":", "raise", "ValidationError", "(", "\"Image is truncated: tag value is cut off\"", ")", "data", "=", "data", "[", "8", "+", "length", ":", "]", "yield", "tag", ",", "value", "# GBL end tag", "if", "tag", "!=", "b\"\\xFC\\x04\\x04\\xFC\"", ":", "continue", "# GBL images aren't expected to contain padding but some are (i.e. Hue)", "unpadded_image", "=", "orig_data", "[", ":", "-", "len", "(", "data", ")", "]", "if", "data", "else", "orig_data", "computed_crc", "=", "zlib", ".", "crc32", "(", "unpadded_image", ")", "if", "computed_crc", "!=", "VALID_SILABS_CRC", ":", "raise", "ValidationError", "(", "f\"Image CRC-32 is invalid:\"", "f\" expected 0x{VALID_SILABS_CRC:08X}, got 0x{computed_crc:08X}\"", ")", "break" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/ota/validators.py#L71-L109
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/ota/validators.py
python
validate_firmware
(data: bytes)
return ValidationResult.VALID
Validates a firmware image.
Validates a firmware image.
[ "Validates", "a", "firmware", "image", "." ]
def validate_firmware(data: bytes) -> ValidationResult: """ Validates a firmware image. """ parser = None if data.startswith(b"\xEB\x17\xA6\x03"): parser = parse_silabs_gbl elif data.startswith(b"\x00\x00\x00\x8C"): parser = parse_silabs_ebl else: return ValidationResult.UNKNOWN tuple(parser(data)) return ValidationResult.VALID
[ "def", "validate_firmware", "(", "data", ":", "bytes", ")", "->", "ValidationResult", ":", "parser", "=", "None", "if", "data", ".", "startswith", "(", "b\"\\xEB\\x17\\xA6\\x03\"", ")", ":", "parser", "=", "parse_silabs_gbl", "elif", "data", ".", "startswith", "(", "b\"\\x00\\x00\\x00\\x8C\"", ")", ":", "parser", "=", "parse_silabs_ebl", "else", ":", "return", "ValidationResult", ".", "UNKNOWN", "tuple", "(", "parser", "(", "data", ")", ")", "return", "ValidationResult", ".", "VALID" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/ota/validators.py#L112-L127
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/ota/validators.py
python
validate_ota_image
(image: OTAImage)
return ValidationResult.VALID
Validates a Zigbee OTA image's embedded firmwares and indicates if an image is valid, invalid, or of an unknown type.
Validates a Zigbee OTA image's embedded firmwares and indicates if an image is valid, invalid, or of an unknown type.
[ "Validates", "a", "Zigbee", "OTA", "image", "s", "embedded", "firmwares", "and", "indicates", "if", "an", "image", "is", "valid", "invalid", "or", "of", "an", "unknown", "type", "." ]
def validate_ota_image(image: OTAImage) -> ValidationResult: """ Validates a Zigbee OTA image's embedded firmwares and indicates if an image is valid, invalid, or of an unknown type. """ results = [] for subelement in image.subelements: if subelement.tag_id == ElementTagId.UPGRADE_IMAGE: results.append(validate_firmware(subelement.data)) if not results or any(r == ValidationResult.UNKNOWN for r in results): return ValidationResult.UNKNOWN return ValidationResult.VALID
[ "def", "validate_ota_image", "(", "image", ":", "OTAImage", ")", "->", "ValidationResult", ":", "results", "=", "[", "]", "for", "subelement", "in", "image", ".", "subelements", ":", "if", "subelement", ".", "tag_id", "==", "ElementTagId", ".", "UPGRADE_IMAGE", ":", "results", ".", "append", "(", "validate_firmware", "(", "subelement", ".", "data", ")", ")", "if", "not", "results", "or", "any", "(", "r", "==", "ValidationResult", ".", "UNKNOWN", "for", "r", "in", "results", ")", ":", "return", "ValidationResult", ".", "UNKNOWN", "return", "ValidationResult", ".", "VALID" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/ota/validators.py#L130-L145
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/ota/validators.py
python
check_invalid
(image: BaseOTAImage)
Checks if an image is invalid or not. Unknown image types are considered valid.
Checks if an image is invalid or not. Unknown image types are considered valid.
[ "Checks", "if", "an", "image", "is", "invalid", "or", "not", ".", "Unknown", "image", "types", "are", "considered", "valid", "." ]
def check_invalid(image: BaseOTAImage) -> bool: """ Checks if an image is invalid or not. Unknown image types are considered valid. """ if not isinstance(image, OTAImage): return False try: validate_ota_image(image) return False except ValidationError as e: LOGGER.warning("Image %s is invalid: %s", image.header, e) return True
[ "def", "check_invalid", "(", "image", ":", "BaseOTAImage", ")", "->", "bool", ":", "if", "not", "isinstance", "(", "image", ",", "OTAImage", ")", ":", "return", "False", "try", ":", "validate_ota_image", "(", "image", ")", "return", "False", "except", "ValidationError", "as", "e", ":", "LOGGER", ".", "warning", "(", "\"Image %s is invalid: %s\"", ",", "image", ".", "header", ",", "e", ")", "return", "True" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/ota/validators.py#L148-L161
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/ota/provider.py
python
Basic.initialize_provider
(self, ota_config: Dict)
Initialize OTA provider.
Initialize OTA provider.
[ "Initialize", "OTA", "provider", "." ]
async def initialize_provider(self, ota_config: Dict) -> None: """Initialize OTA provider."""
[ "async", "def", "initialize_provider", "(", "self", ",", "ota_config", ":", "Dict", ")", "->", "None", ":" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/ota/provider.py#L48-L49
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/ota/provider.py
python
Basic.refresh_firmware_list
(self)
Loads list of firmware into memory.
Loads list of firmware into memory.
[ "Loads", "list", "of", "firmware", "into", "memory", "." ]
async def refresh_firmware_list(self) -> None: """Loads list of firmware into memory."""
[ "async", "def", "refresh_firmware_list", "(", "self", ")", "->", "None", ":" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/ota/provider.py#L52-L53
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/ota/provider.py
python
Basic.filter_get_image
(self, key: ImageKey)
return False
Filter unwanted get_image lookups.
Filter unwanted get_image lookups.
[ "Filter", "unwanted", "get_image", "lookups", "." ]
async def filter_get_image(self, key: ImageKey) -> bool: """Filter unwanted get_image lookups.""" return False
[ "async", "def", "filter_get_image", "(", "self", ",", "key", ":", "ImageKey", ")", "->", "bool", ":", "return", "False" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/ota/provider.py#L55-L57
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/ota/provider.py
python
Basic.expired
(self)
return datetime.datetime.now() - self._last_refresh > self.REFRESH
Return True if firmware list needs refreshing.
Return True if firmware list needs refreshing.
[ "Return", "True", "if", "firmware", "list", "needs", "refreshing", "." ]
def expired(self) -> bool: """Return True if firmware list needs refreshing.""" if self._last_refresh is None: return True return datetime.datetime.now() - self._last_refresh > self.REFRESH
[ "def", "expired", "(", "self", ")", "->", "bool", ":", "if", "self", ".", "_last_refresh", "is", "None", ":", "return", "True", "return", "datetime", ".", "datetime", ".", "now", "(", ")", "-", "self", ".", "_last_refresh", ">", "self", ".", "REFRESH" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/ota/provider.py#L91-L96
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/ota/provider.py
python
Basic.log
(self, lvl, msg, *args, **kwargs)
return LOGGER.log(lvl, msg, *args, **kwargs)
Log a message
Log a message
[ "Log", "a", "message" ]
def log(self, lvl, msg, *args, **kwargs): """Log a message""" msg = f"{self.__class__.__name__}: {msg}" return LOGGER.log(lvl, msg, *args, **kwargs)
[ "def", "log", "(", "self", ",", "lvl", ",", "msg", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "msg", "=", "f\"{self.__class__.__name__}: {msg}\"", "return", "LOGGER", ".", "log", "(", "lvl", ",", "msg", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/ota/provider.py#L98-L101
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/ota/provider.py
python
FileStore.validate_ota_dir
(ota_dir: str)
return None
Return True if exists and is a dir.
Return True if exists and is a dir.
[ "Return", "True", "if", "exists", "and", "is", "a", "dir", "." ]
def validate_ota_dir(ota_dir: str) -> str: """Return True if exists and is a dir.""" if ota_dir is None: return None if os.path.exists(ota_dir): if os.path.isdir(ota_dir): return ota_dir LOGGER.error("OTA image path '%s' is not a directory", ota_dir) else: LOGGER.debug("OTA image directory '%s' does not exist", ota_dir) return None
[ "def", "validate_ota_dir", "(", "ota_dir", ":", "str", ")", "->", "str", ":", "if", "ota_dir", "is", "None", ":", "return", "None", "if", "os", ".", "path", ".", "exists", "(", "ota_dir", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "ota_dir", ")", ":", "return", "ota_dir", "LOGGER", ".", "error", "(", "\"OTA image path '%s' is not a directory\"", ",", "ota_dir", ")", "else", ":", "LOGGER", ".", "debug", "(", "\"OTA image directory '%s' does not exist\"", ",", "ota_dir", ")", "return", "None" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/ota/provider.py#L457-L468
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/ota/image.py
python
parse_ota_image
(data: bytes)
Attempts to extract any known OTA image type from data. Does not validate firmware.
Attempts to extract any known OTA image type from data. Does not validate firmware.
[ "Attempts", "to", "extract", "any", "known", "OTA", "image", "type", "from", "data", ".", "Does", "not", "validate", "firmware", "." ]
def parse_ota_image(data: bytes) -> typing.Tuple[BaseOTAImage, bytes]: """ Attempts to extract any known OTA image type from data. Does not validate firmware. """ # IKEA container needs to be unwrapped if data.startswith(b"NGIS"): if len(data) <= 24: raise ValueError( f"Data too short to contain IKEA container header: {len(data)}" ) offset = int.from_bytes(data[16:20], "little") size = int.from_bytes(data[20:24], "little") if len(data) <= offset + size: raise ValueError(f"Data too short to be IKEA container: {len(data)}") wrapped_data = data[offset : offset + size] image, rest = OTAImage.deserialize(wrapped_data) if rest: LOGGER.warning( "Fixing IKEA OTA image with trailing data (%s bytes)", size - image.header.image_size, ) image.header.image_size += len(rest) # No other structure has been observed assert len(image.subelements) == 1 assert image.subelements[0].tag_id == ElementTagId.UPGRADE_IMAGE image.subelements[0].data += rest rest = b"" return image, rest try: # Hue sbl-ota images start with a Zigbee OTA header but contain no valid # subelements after that. Try it first. return HueSBLOTAImage.deserialize(data) except ValueError: return OTAImage.deserialize(data)
[ "def", "parse_ota_image", "(", "data", ":", "bytes", ")", "->", "typing", ".", "Tuple", "[", "BaseOTAImage", ",", "bytes", "]", ":", "# IKEA container needs to be unwrapped", "if", "data", ".", "startswith", "(", "b\"NGIS\"", ")", ":", "if", "len", "(", "data", ")", "<=", "24", ":", "raise", "ValueError", "(", "f\"Data too short to contain IKEA container header: {len(data)}\"", ")", "offset", "=", "int", ".", "from_bytes", "(", "data", "[", "16", ":", "20", "]", ",", "\"little\"", ")", "size", "=", "int", ".", "from_bytes", "(", "data", "[", "20", ":", "24", "]", ",", "\"little\"", ")", "if", "len", "(", "data", ")", "<=", "offset", "+", "size", ":", "raise", "ValueError", "(", "f\"Data too short to be IKEA container: {len(data)}\"", ")", "wrapped_data", "=", "data", "[", "offset", ":", "offset", "+", "size", "]", "image", ",", "rest", "=", "OTAImage", ".", "deserialize", "(", "wrapped_data", ")", "if", "rest", ":", "LOGGER", ".", "warning", "(", "\"Fixing IKEA OTA image with trailing data (%s bytes)\"", ",", "size", "-", "image", ".", "header", ".", "image_size", ",", ")", "image", ".", "header", ".", "image_size", "+=", "len", "(", "rest", ")", "# No other structure has been observed", "assert", "len", "(", "image", ".", "subelements", ")", "==", "1", "assert", "image", ".", "subelements", "[", "0", "]", ".", "tag_id", "==", "ElementTagId", ".", "UPGRADE_IMAGE", "image", ".", "subelements", "[", "0", "]", ".", "data", "+=", "rest", "rest", "=", "b\"\"", "return", "image", ",", "rest", "try", ":", "# Hue sbl-ota images start with a Zigbee OTA header but contain no valid", "# subelements after that. Try it first.", "return", "HueSBLOTAImage", ".", "deserialize", "(", "data", ")", "except", "ValueError", ":", "return", "OTAImage", ".", "deserialize", "(", "data", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/ota/image.py#L222-L264
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/types/named.py
python
Addressing.ieee
(cls, ieee: EUI64, endpoint: Union[basic.uint8_t, int])
return cls.IEEE(AddrMode.IEEE, ieee, endpoint)
Return IEEE addressing mode.
Return IEEE addressing mode.
[ "Return", "IEEE", "addressing", "mode", "." ]
def ieee(cls, ieee: EUI64, endpoint: Union[basic.uint8_t, int]) -> _AddressingIEEE: """Return IEEE addressing mode.""" return cls.IEEE(AddrMode.IEEE, ieee, endpoint)
[ "def", "ieee", "(", "cls", ",", "ieee", ":", "EUI64", ",", "endpoint", ":", "Union", "[", "basic", ".", "uint8_t", ",", "int", "]", ")", "->", "_AddressingIEEE", ":", "return", "cls", ".", "IEEE", "(", "AddrMode", ".", "IEEE", ",", "ieee", ",", "endpoint", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/types/named.py#L538-L541
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/types/named.py
python
Addressing.group
(cls, group: Group)
return cls.Group(AddrMode.Group, group)
Return Group addressing mode.
Return Group addressing mode.
[ "Return", "Group", "addressing", "mode", "." ]
def group(cls, group: Group) -> _AddressingGroup: """Return Group addressing mode.""" return cls.Group(AddrMode.Group, group)
[ "def", "group", "(", "cls", ",", "group", ":", "Group", ")", "->", "_AddressingGroup", ":", "return", "cls", ".", "Group", "(", "AddrMode", ".", "Group", ",", "group", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/types/named.py#L544-L547
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/types/named.py
python
Addressing.nwk
(cls, nwk: NWK, endpoint: Union[basic.uint8_t, int])
return cls.NWK(AddrMode.NWK, nwk, endpoint)
Return NWK addressing mode.
Return NWK addressing mode.
[ "Return", "NWK", "addressing", "mode", "." ]
def nwk(cls, nwk: NWK, endpoint: Union[basic.uint8_t, int]) -> _AddressingNWK: """Return NWK addressing mode.""" return cls.NWK(AddrMode.NWK, nwk, endpoint)
[ "def", "nwk", "(", "cls", ",", "nwk", ":", "NWK", ",", "endpoint", ":", "Union", "[", "basic", ".", "uint8_t", ",", "int", "]", ")", "->", "_AddressingNWK", ":", "return", "cls", ".", "NWK", "(", "AddrMode", ".", "NWK", ",", "nwk", ",", "endpoint", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/types/named.py#L550-L553
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/types/named.py
python
Addressing.deserialize
( cls, data: bytes )
Deserialize data.
Deserialize data.
[ "Deserialize", "data", "." ]
def deserialize( cls, data: bytes ) -> Tuple[Union[_AddressingGroup, _AddressingIEEE, _AddressingNWK], bytes]: """Deserialize data.""" if data[0] == AddrMode.IEEE: return cls.IEEE.deserialize(data) elif data[0] == AddrMode.Group: return cls.Group.deserialize(data) elif data[0] == AddrMode.NWK: return cls.NWK.deserialize(data) raise ValueError(f"Invalid '0x{data[0]:02x}' addressing mode")
[ "def", "deserialize", "(", "cls", ",", "data", ":", "bytes", ")", "->", "Tuple", "[", "Union", "[", "_AddressingGroup", ",", "_AddressingIEEE", ",", "_AddressingNWK", "]", ",", "bytes", "]", ":", "if", "data", "[", "0", "]", "==", "AddrMode", ".", "IEEE", ":", "return", "cls", ".", "IEEE", ".", "deserialize", "(", "data", ")", "elif", "data", "[", "0", "]", "==", "AddrMode", ".", "Group", ":", "return", "cls", ".", "Group", ".", "deserialize", "(", "data", ")", "elif", "data", "[", "0", "]", "==", "AddrMode", ".", "NWK", ":", "return", "cls", ".", "NWK", ".", "deserialize", "(", "data", ")", "raise", "ValueError", "(", "f\"Invalid '0x{data[0]:02x}' addressing mode\"", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/types/named.py#L556-L568
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/types/basic.py
python
bitmap_factory
(int_type: CALLABLE_T)
return _NewEnum
Mixins are broken by Python 3.8.6 so we must dynamically create the enum with the appropriate methods but with only one non-Enum parent class.
Mixins are broken by Python 3.8.6 so we must dynamically create the enum with the appropriate methods but with only one non-Enum parent class.
[ "Mixins", "are", "broken", "by", "Python", "3", ".", "8", ".", "6", "so", "we", "must", "dynamically", "create", "the", "enum", "with", "the", "appropriate", "methods", "but", "with", "only", "one", "non", "-", "Enum", "parent", "class", "." ]
def bitmap_factory(int_type: CALLABLE_T) -> CALLABLE_T: """ Mixins are broken by Python 3.8.6 so we must dynamically create the enum with the appropriate methods but with only one non-Enum parent class. """ class _NewEnum(int_type, enum.Flag): # Rebind classmethods to our own class _missing_ = classmethod(enum.IntFlag._missing_.__func__) _create_pseudo_member_ = classmethod( enum.IntFlag._create_pseudo_member_.__func__ ) __or__ = enum.IntFlag.__or__ __and__ = enum.IntFlag.__and__ __xor__ = enum.IntFlag.__xor__ __ror__ = enum.IntFlag.__ror__ __rand__ = enum.IntFlag.__rand__ __rxor__ = enum.IntFlag.__rxor__ __invert__ = enum.IntFlag.__invert__ return _NewEnum
[ "def", "bitmap_factory", "(", "int_type", ":", "CALLABLE_T", ")", "->", "CALLABLE_T", ":", "class", "_NewEnum", "(", "int_type", ",", "enum", ".", "Flag", ")", ":", "# Rebind classmethods to our own class", "_missing_", "=", "classmethod", "(", "enum", ".", "IntFlag", ".", "_missing_", ".", "__func__", ")", "_create_pseudo_member_", "=", "classmethod", "(", "enum", ".", "IntFlag", ".", "_create_pseudo_member_", ".", "__func__", ")", "__or__", "=", "enum", ".", "IntFlag", ".", "__or__", "__and__", "=", "enum", ".", "IntFlag", ".", "__and__", "__xor__", "=", "enum", ".", "IntFlag", ".", "__xor__", "__ror__", "=", "enum", ".", "IntFlag", ".", "__ror__", "__rand__", "=", "enum", ".", "IntFlag", ".", "__rand__", "__rxor__", "=", "enum", ".", "IntFlag", ".", "__rxor__", "__invert__", "=", "enum", ".", "IntFlag", ".", "__invert__", "return", "_NewEnum" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/types/basic.py#L256-L277
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/types/basic.py
python
enum_factory
(int_type: CALLABLE_T, undefined: str = "undefined")
return _NewEnum
Enum factory.
Enum factory.
[ "Enum", "factory", "." ]
def enum_factory(int_type: CALLABLE_T, undefined: str = "undefined") -> CALLABLE_T: """Enum factory.""" class _NewEnum(int_type, enum.Enum, metaclass=_IntEnumMeta): @classmethod def _missing_(cls, value): new = cls._member_type_.__new__(cls, value) if cls._bits % 8 == 0: name = f"{undefined}_{new._hex_repr().lower()}" else: name = f"{undefined}_{new._bin_repr()}" new._name_ = name.format(value) new._value_ = value return new return _NewEnum
[ "def", "enum_factory", "(", "int_type", ":", "CALLABLE_T", ",", "undefined", ":", "str", "=", "\"undefined\"", ")", "->", "CALLABLE_T", ":", "class", "_NewEnum", "(", "int_type", ",", "enum", ".", "Enum", ",", "metaclass", "=", "_IntEnumMeta", ")", ":", "@", "classmethod", "def", "_missing_", "(", "cls", ",", "value", ")", ":", "new", "=", "cls", ".", "_member_type_", ".", "__new__", "(", "cls", ",", "value", ")", "if", "cls", ".", "_bits", "%", "8", "==", "0", ":", "name", "=", "f\"{undefined}_{new._hex_repr().lower()}\"", "else", ":", "name", "=", "f\"{undefined}_{new._bin_repr()}\"", "new", ".", "_name_", "=", "name", ".", "format", "(", "value", ")", "new", ".", "_value_", "=", "value", "return", "new", "return", "_NewEnum" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/types/basic.py#L280-L297
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/types/basic.py
python
BaseFloat._convert_format
(*, src: "BaseFloat", dst: "BaseFloat", n: int)
return ( src_sign << (dst._exponent_bits + dst._fraction_bits) | dst_biased_exp << (dst._fraction_bits) | dst_frac )
Converts an integer representing a float from one format into another. Note: 1. Format is assumed to be little endian: 0b[sign bit] [exponent] [fraction] 2. Truncates/extends the exponent, preserving the special cases of all 1's and all 0's. 3. Truncates/extends the fractional bits from the right, allowing lossless conversion to a "bigger" representation.
Converts an integer representing a float from one format into another. Note:
[ "Converts", "an", "integer", "representing", "a", "float", "from", "one", "format", "into", "another", ".", "Note", ":" ]
def _convert_format(*, src: "BaseFloat", dst: "BaseFloat", n: int) -> int: """ Converts an integer representing a float from one format into another. Note: 1. Format is assumed to be little endian: 0b[sign bit] [exponent] [fraction] 2. Truncates/extends the exponent, preserving the special cases of all 1's and all 0's. 3. Truncates/extends the fractional bits from the right, allowing lossless conversion to a "bigger" representation. """ src_sign = n >> (src._exponent_bits + src._fraction_bits) src_frac = n & ((1 << src._fraction_bits) - 1) src_biased_exp = (n >> src._fraction_bits) & ((1 << src._exponent_bits) - 1) src_exp = src_biased_exp - 2 ** (src._exponent_bits - 1) if src_biased_exp == (1 << src._exponent_bits) - 1: dst_biased_exp = 2 ** dst._exponent_bits - 1 elif src_biased_exp == 0: dst_biased_exp = 0 else: dst_min_exp = 2 - 2 ** (dst._exponent_bits - 1) # Can't be all zeroes dst_max_exp = 2 ** (dst._exponent_bits - 1) - 2 # Can't be all ones dst_exp = min(max(dst_min_exp, src_exp), dst_max_exp) dst_biased_exp = dst_exp + 2 ** (dst._exponent_bits - 1) # We add/remove LSBs if src._fraction_bits > dst._fraction_bits: dst_frac = src_frac >> (src._fraction_bits - dst._fraction_bits) else: dst_frac = src_frac << (dst._fraction_bits - src._fraction_bits) return ( src_sign << (dst._exponent_bits + dst._fraction_bits) | dst_biased_exp << (dst._fraction_bits) | dst_frac )
[ "def", "_convert_format", "(", "*", ",", "src", ":", "\"BaseFloat\"", ",", "dst", ":", "\"BaseFloat\"", ",", "n", ":", "int", ")", "->", "int", ":", "src_sign", "=", "n", ">>", "(", "src", ".", "_exponent_bits", "+", "src", ".", "_fraction_bits", ")", "src_frac", "=", "n", "&", "(", "(", "1", "<<", "src", ".", "_fraction_bits", ")", "-", "1", ")", "src_biased_exp", "=", "(", "n", ">>", "src", ".", "_fraction_bits", ")", "&", "(", "(", "1", "<<", "src", ".", "_exponent_bits", ")", "-", "1", ")", "src_exp", "=", "src_biased_exp", "-", "2", "**", "(", "src", ".", "_exponent_bits", "-", "1", ")", "if", "src_biased_exp", "==", "(", "1", "<<", "src", ".", "_exponent_bits", ")", "-", "1", ":", "dst_biased_exp", "=", "2", "**", "dst", ".", "_exponent_bits", "-", "1", "elif", "src_biased_exp", "==", "0", ":", "dst_biased_exp", "=", "0", "else", ":", "dst_min_exp", "=", "2", "-", "2", "**", "(", "dst", ".", "_exponent_bits", "-", "1", ")", "# Can't be all zeroes", "dst_max_exp", "=", "2", "**", "(", "dst", ".", "_exponent_bits", "-", "1", ")", "-", "2", "# Can't be all ones", "dst_exp", "=", "min", "(", "max", "(", "dst_min_exp", ",", "src_exp", ")", ",", "dst_max_exp", ")", "dst_biased_exp", "=", "dst_exp", "+", "2", "**", "(", "dst", ".", "_exponent_bits", "-", "1", ")", "# We add/remove LSBs", "if", "src", ".", "_fraction_bits", ">", "dst", ".", "_fraction_bits", ":", "dst_frac", "=", "src_frac", ">>", "(", "src", ".", "_fraction_bits", "-", "dst", ".", "_fraction_bits", ")", "else", ":", "dst_frac", "=", "src_frac", "<<", "(", "dst", ".", "_fraction_bits", "-", "src", ".", "_fraction_bits", ")", "return", "(", "src_sign", "<<", "(", "dst", ".", "_exponent_bits", "+", "dst", ".", "_fraction_bits", ")", "|", "dst_biased_exp", "<<", "(", "dst", ".", "_fraction_bits", ")", "|", "dst_frac", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/types/basic.py#L402-L438
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/zdo/types.py
python
ZDOHeader.command_id
(self)
return self._command_id
Return ZDO command.
Return ZDO command.
[ "Return", "ZDO", "command", "." ]
def command_id(self) -> ZDOCmd: """Return ZDO command.""" return self._command_id
[ "def", "command_id", "(", "self", ")", "->", "ZDOCmd", ":", "return", "self", ".", "_command_id" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/zdo/types.py#L699-L701
zigpy/zigpy
0e901b013da074d24de18aca1e579287e756cd84
zigpy/zdo/types.py
python
ZDOHeader.command_id
(self, value: t.uint16_t)
Command ID setter.
Command ID setter.
[ "Command", "ID", "setter", "." ]
def command_id(self, value: t.uint16_t) -> None: """Command ID setter.""" self._command_id = ZDOCmd(value)
[ "def", "command_id", "(", "self", ",", "value", ":", "t", ".", "uint16_t", ")", "->", "None", ":", "self", ".", "_command_id", "=", "ZDOCmd", "(", "value", ")" ]
https://github.com/zigpy/zigpy/blob/0e901b013da074d24de18aca1e579287e756cd84/zigpy/zdo/types.py#L704-L706