diff --git a/db_handler.py b/db_handler.py index 2169d51..dbf73b5 100644 --- a/db_handler.py +++ b/db_handler.py @@ -144,6 +144,7 @@ def load_messages_from_db(): def init_nodedb(): """Initialize the node database and update it with nodes from the interface.""" + try: if not globals.interface.nodes: return # No nodes to initialize diff --git a/globals.py b/globals.py index a174cf8..78b9475 100644 --- a/globals.py +++ b/globals.py @@ -9,4 +9,5 @@ myNodeNum = 0 selected_channel = 0 selected_message = 0 selected_node = 0 -current_window = 0 \ No newline at end of file +current_window = 0 +lock = None \ No newline at end of file diff --git a/main.py b/main.py index ab0efd3..9b88fd1 100644 --- a/main.py +++ b/main.py @@ -11,6 +11,7 @@ from pubsub import pub import os import logging import traceback +import threading from utilities.arg_parser import setup_parser from utilities.interfaces import initialize_interface @@ -38,6 +39,8 @@ logging.basicConfig( format="%(asctime)s - %(levelname)s - %(message)s" ) +globals.lock = threading.Lock() + def main(stdscr): try: draw_splash(stdscr) @@ -45,15 +48,16 @@ def main(stdscr): args = parser.parse_args() logging.info("Initializing interface %s", args) - globals.interface = initialize_interface(args) - logging.info("Interface initialized") - globals.myNodeNum = get_nodeNum() - globals.channel_list = get_channels() - globals.node_list = get_node_list() - pub.subscribe(on_receive, 'meshtastic.receive') - init_nodedb() - load_messages_from_db() - logging.info("Starting main UI") + with globals.lock: + globals.interface = initialize_interface(args) + logging.info("Interface initialized") + globals.myNodeNum = get_nodeNum() + globals.channel_list = get_channels() + globals.node_list = get_node_list() + pub.subscribe(on_receive, 'meshtastic.receive') + init_nodedb() + load_messages_from_db() + logging.info("Starting main UI") main_ui(stdscr) except Exception as e: logging.error("An error occurred: %s", e) diff --git a/message_handlers/rx_handler.py b/message_handlers/rx_handler.py index 0261e3d..3ba0276 100644 --- a/message_handlers/rx_handler.py +++ b/message_handlers/rx_handler.py @@ -12,93 +12,94 @@ from datetime import datetime def on_receive(packet, interface): - # Update packet log - globals.packet_buffer.append(packet) - if len(globals.packet_buffer) > 20: - # Trim buffer to 20 packets - globals.packet_buffer = globals.packet_buffer[-20:] - - if globals.display_log: - draw_packetlog_win() - try: - if 'decoded' not in packet: - return + with globals.lock: + # Update packet log + globals.packet_buffer.append(packet) + if len(globals.packet_buffer) > 20: + # Trim buffer to 20 packets + globals.packet_buffer = globals.packet_buffer[-20:] + + if globals.display_log: + draw_packetlog_win() + try: + if 'decoded' not in packet: + return - # Assume any incoming packet could update the last seen time for a node - changed = refresh_node_list() - if(changed): - draw_node_list() + # Assume any incoming packet could update the last seen time for a node + changed = refresh_node_list() + if(changed): + draw_node_list() - if packet['decoded']['portnum'] == 'NODEINFO_APP': - if "user" in packet['decoded'] and "longName" in packet['decoded']["user"]: - maybe_store_nodeinfo_in_db(packet) + if packet['decoded']['portnum'] == 'NODEINFO_APP': + if "user" in packet['decoded'] and "longName" in packet['decoded']["user"]: + maybe_store_nodeinfo_in_db(packet) - elif packet['decoded']['portnum'] == 'TEXT_MESSAGE_APP': - message_bytes = packet['decoded']['payload'] - message_string = message_bytes.decode('utf-8') + elif packet['decoded']['portnum'] == 'TEXT_MESSAGE_APP': + message_bytes = packet['decoded']['payload'] + message_string = message_bytes.decode('utf-8') - refresh_channels = False - refresh_messages = False + refresh_channels = False + refresh_messages = False - if packet.get('channel'): - channel_number = packet['channel'] - else: - channel_number = 0 - - if packet['to'] == globals.myNodeNum: - if packet['from'] in globals.channel_list: - pass + if packet.get('channel'): + channel_number = packet['channel'] else: - globals.channel_list.append(packet['from']) - if(packet['from'] not in globals.all_messages): - globals.all_messages[packet['from']] = [] - update_node_info_in_db(packet['from'], chat_archived=False) + channel_number = 0 + + if packet['to'] == globals.myNodeNum: + if packet['from'] in globals.channel_list: + pass + else: + globals.channel_list.append(packet['from']) + if(packet['from'] not in globals.all_messages): + globals.all_messages[packet['from']] = [] + update_node_info_in_db(packet['from'], chat_archived=False) + refresh_channels = True + + channel_number = globals.channel_list.index(packet['from']) + + if globals.channel_list[channel_number] != globals.channel_list[globals.selected_channel]: + add_notification(channel_number) refresh_channels = True + else: + refresh_messages = True - channel_number = globals.channel_list.index(packet['from']) + # Add received message to the messages list + message_from_id = packet['from'] + message_from_string = get_name_from_database(message_from_id, type='short') + ":" - if globals.channel_list[channel_number] != globals.channel_list[globals.selected_channel]: - add_notification(channel_number) - refresh_channels = True - else: - refresh_messages = True + if globals.channel_list[channel_number] not in globals.all_messages: + globals.all_messages[globals.channel_list[channel_number]] = [] - # Add received message to the messages list - message_from_id = packet['from'] - message_from_string = get_name_from_database(message_from_id, type='short') + ":" + # Timestamp handling + current_timestamp = time.time() + current_hour = datetime.fromtimestamp(current_timestamp).strftime('%Y-%m-%d %H:00') - if globals.channel_list[channel_number] not in globals.all_messages: - globals.all_messages[globals.channel_list[channel_number]] = [] - - # Timestamp handling - current_timestamp = time.time() - current_hour = datetime.fromtimestamp(current_timestamp).strftime('%Y-%m-%d %H:00') - - # Retrieve the last timestamp if available - channel_messages = globals.all_messages[globals.channel_list[channel_number]] - if channel_messages: - # Check the last entry for a timestamp - for entry in reversed(channel_messages): - if entry[0].startswith("--"): - last_hour = entry[0].strip("- ").strip() - break + # Retrieve the last timestamp if available + channel_messages = globals.all_messages[globals.channel_list[channel_number]] + if channel_messages: + # Check the last entry for a timestamp + for entry in reversed(channel_messages): + if entry[0].startswith("--"): + last_hour = entry[0].strip("- ").strip() + break + else: + last_hour = None else: last_hour = None - else: - last_hour = None - # Add a new timestamp if it's a new hour - if last_hour != current_hour: - globals.all_messages[globals.channel_list[channel_number]].append((f"-- {current_hour} --", "")) + # Add a new timestamp if it's a new hour + if last_hour != current_hour: + globals.all_messages[globals.channel_list[channel_number]].append((f"-- {current_hour} --", "")) - globals.all_messages[globals.channel_list[channel_number]].append((f"{config.message_prefix} {message_from_string} ", message_string)) + globals.all_messages[globals.channel_list[channel_number]].append((f"{config.message_prefix} {message_from_string} ", message_string)) - if refresh_channels: - draw_channel_list() - if refresh_messages: - draw_messages_window(True) + if refresh_channels: + draw_channel_list() + if refresh_messages: + draw_messages_window(True) - save_message_to_db(globals.channel_list[channel_number], message_from_id, message_string) + save_message_to_db(globals.channel_list[channel_number], message_from_id, message_string) - except KeyError as e: - logging.error(f"Error processing packet: {e}") + except KeyError as e: + logging.error(f"Error processing packet: {e}") diff --git a/ui/curses_ui.py b/ui/curses_ui.py index b8768a2..5154154 100644 --- a/ui/curses_ui.py +++ b/ui/curses_ui.py @@ -417,8 +417,8 @@ def draw_messages_window(scroll_to_bottom = False): def draw_node_list(): global nodes_pad - if nodes_pad is None: - nodes_pad = curses.newpad(1, 1) + # if nodes_pad is None: + nodes_pad = curses.newpad(1, 1) try: nodes_pad.erase()