From 3ea1994cf5b2503d3f9db83fbda91010cfa5274c Mon Sep 17 00:00:00 2001 From: dim5x Date: Thu, 5 Feb 2026 13:42:37 +0300 Subject: [PATCH] Refactor the Meshtastic TCP pub/sub example to ensure proper resource cleanup and clearer exception handling. --- examples/pub_sub_example2.py | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/examples/pub_sub_example2.py b/examples/pub_sub_example2.py index c5d3791dc..c7f620ad5 100644 --- a/examples/pub_sub_example2.py +++ b/examples/pub_sub_example2.py @@ -5,10 +5,9 @@ import sys import time -from pubsub import pub +from meshtastic.tcp_interface import TCPInterface -import meshtastic -import meshtastic.tcp_interface +from pubsub import pub # simple arg check if len(sys.argv) < 2: @@ -29,11 +28,15 @@ def onConnection(interface, topic=pub.AUTO_TOPIC): # pylint: disable=unused-arg pub.subscribe(onReceive, "meshtastic.receive") pub.subscribe(onConnection, "meshtastic.connection.established") + +iface=None try: - iface = meshtastic.tcp_interface.TCPInterface(hostname=sys.argv[1]) + iface = TCPInterface(hostname=sys.argv[1]) while True: time.sleep(1000) - iface.close() except Exception as ex: print(f"Error: Could not connect to {sys.argv[1]} {ex}") - sys.exit(1) + raise +finally: + if iface: + iface.close()