diff --git a/circuitpython_nrf24l01/rf24_mesh.py b/circuitpython_nrf24l01/rf24_mesh.py index f51bed1..eaa55bf 100644 --- a/circuitpython_nrf24l01/rf24_mesh.py +++ b/circuitpython_nrf24l01/rf24_mesh.py @@ -40,6 +40,7 @@ NETWORK_DEFAULT_ADDR, NETWORK_MULTICAST_ADDR, NETWORK_POLL, + NETWORK_PING, MESH_ADDR_RELEASE, MESH_ADDR_LOOKUP, MESH_ID_LOOKUP, @@ -162,14 +163,23 @@ def _lookup_2_master(self, number: int, lookup_type: int) -> int: return struct.unpack(" bool: + def check_connection(self, attempts: int = 3, ping_master: bool = False) -> bool: """Check for network connectivity (not for use on master node).""" + if not self._parent: + return True + if self.node_address == NETWORK_DEFAULT_ADDR: + return False for _ in range(attempts): - result = self.lookup_address(self._id) - if result in (-2, 0): - return False - if result == self.node_address: - return True + if ping_master: + result = self.lookup_address(self._id) + if result == -2: + return False + if result == self.node_address: + return True + else: # ping parent + result = self.write(self._parent, NETWORK_PING, b"") + if result: + return True return False def update(self) -> int: diff --git a/docs/network_docs/mesh_api.rst b/docs/network_docs/mesh_api.rst index 5a8635e..ddb196f 100644 --- a/docs/network_docs/mesh_api.rst +++ b/docs/network_docs/mesh_api.rst @@ -175,6 +175,31 @@ Advanced API .. automethod:: circuitpython_nrf24l01.rf24_mesh.RF24Mesh.check_connection + :param attempts: The number of attempts to test for active connection to the mesh network. + :param ping_master: If this parameter is set to `True`, then this function will verify the + connectivity by using `lookup_address()` to transact with the master node. Setting this + parameter to `False` will simply ping the node's parent. + + .. warning:: + Setting this parameter to `True` can result in performance cost when used in + a large mesh network. The disadvantages in such a situation are: + + - increased load on master node + - increased network congestion + - unreliable connectivity information when a parent or grandparent of the current + node briefly loses connection. + + :returns: + - `True` if connected to the mesh network (or current node is the master node). + - `False` if not connected to the mesh network or mesh network is unresponsive. + + .. versionchanged:: 2.2.0 + Added ``attempts`` and ``ping_master`` parameters; changed return value for master nodes + + Previously, this function would return `False` when called from a master node. + This was changed to return `True` to help avoid erroneous user code calling + `renew_address()` on a master node. + .. automethod:: circuitpython_nrf24l01.rf24_mesh.RF24Mesh.release_address .. autoproperty:: circuitpython_nrf24l01.rf24_mesh.RF24Mesh.allow_children