|
| 1 | +import time |
| 2 | +import sys |
| 3 | +from pubsub import pub |
| 4 | +from meshtastic.tcp_interface import TCPInterface |
| 5 | +from meshtastic import portnums_pb2 |
| 6 | + |
| 7 | +node_ip = '192.168.1.125' # Replace with your Meshtastic node's IP address |
| 8 | + |
| 9 | +def get_node_info(node_ip): |
| 10 | + print("Initializing TcpInterface to get node info...") |
| 11 | + local = TCPInterface(hostname=node_ip) |
| 12 | + node_info = local.nodes |
| 13 | + local.close() |
| 14 | + print("Node info retrieved.") |
| 15 | + return node_info |
| 16 | + |
| 17 | +def parse_node_info(node_info): |
| 18 | + print("Parsing node info...") |
| 19 | + nodes = [] |
| 20 | + for node_id, node in node_info.items(): |
| 21 | + nodes.append({ |
| 22 | + 'num': node_id, |
| 23 | + 'user': { |
| 24 | + 'shortName': node.get('user', {}).get('shortName', 'Unknown') |
| 25 | + } |
| 26 | + }) |
| 27 | + print("Node info parsed.") |
| 28 | + return nodes |
| 29 | + |
| 30 | +def on_receive(packet, interface, node_list): |
| 31 | + try: |
| 32 | + if packet['decoded'].get('portnum') == 'TEXT_MESSAGE_APP': |
| 33 | + message = packet['decoded']['payload'].decode('utf-8') |
| 34 | + fromnum = packet['fromId'] |
| 35 | + shortname = next((node['user']['shortName'] for node in node_list if node['num'] == fromnum), 'Unknown') |
| 36 | + print(f"{shortname}: {message}") |
| 37 | + except KeyError: |
| 38 | + pass # Ignore KeyError silently |
| 39 | + except UnicodeDecodeError: |
| 40 | + pass # Ignore UnicodeDecodeError silently |
| 41 | + |
| 42 | +def main(): |
| 43 | + print(f"Using node IP: {node_ip}") |
| 44 | + |
| 45 | + # Retrieve and parse node information |
| 46 | + node_info = get_node_info(node_ip) |
| 47 | + node_list = parse_node_info(node_info) |
| 48 | + |
| 49 | + # Print node list for debugging |
| 50 | + print("Node List:") |
| 51 | + for node in node_list: |
| 52 | + print(node) |
| 53 | + |
| 54 | + # Subscribe the callback function to message reception |
| 55 | + def on_receive_wrapper(packet, interface): |
| 56 | + on_receive(packet, interface, node_list) |
| 57 | + |
| 58 | + pub.subscribe(on_receive_wrapper, "meshtastic.receive") |
| 59 | + print("Subscribed to meshtastic.receive") |
| 60 | + |
| 61 | + # Set up the TcpInterface for message listening |
| 62 | + local = TCPInterface(hostname=node_ip) |
| 63 | + print("TcpInterface setup for listening.") |
| 64 | + |
| 65 | + # Keep the script running to listen for messages |
| 66 | + try: |
| 67 | + while True: |
| 68 | + sys.stdout.flush() |
| 69 | + time.sleep(1) # Sleep to reduce CPU usage |
| 70 | + except KeyboardInterrupt: |
| 71 | + print("Script terminated by user") |
| 72 | + local.close() |
| 73 | + |
| 74 | +if __name__ == "__main__": |
| 75 | + main() |
0 commit comments