import meshtastic.serial_interface
import meshtastic.mesh_interface
from pubsub import pub
import json
import time
import os
import sys
import signal

def onDisconnection(interface):
    #there's no need to close a connection once disconnected
    print("Awknowledged disconnection")


def onConnection(interface):
    print("Awknowledged connection")

def onReceive(packet, interface):
    if True:
        json_packet = json.dumps(packet, indent=4, default=lambda s: " ".join(str(s).split()))
        print(f"{json_packet}\n\n")
        if os.path.exists(file_path):
            with open(file_path, 'r+') as json_file:
                content = json_file.read().strip()
                if content:
                    if content.endswith(']'):
                        content = content[:-1].rstrip() + ',\n'
                    else:
                        content = '['
                    json_file.seek(0)
                    json_file.write(content + json_packet + '\n]')
                else:
                    json_file.seek(0)
                    json_file.write('[' + json_packet + '\n]')
                json_file.truncate()
        else:
            with open(file_path, 'w') as json_file:
                json_file.write('[\n' + json_packet + '\n]')

# You need to close any active connections if you exit
# If you don't, the interface will continue to be active
# and any stored messages will stay stored on the device
# and will be sent on the stale connection
def signal_handler(sig, frame):
    print("closing")
    interface.close()
    sys.exit(0)

signal.signal(signal.SIGINT, signal_handler)

# The python library will authmatically process any messages stored, so there
# is no need to manually scan for messages on connection
pub.subscribe(onReceive, 'meshtastic.receive')

pub.subscribe(onDisconnection, 'meshtastic.connection.lost')

pub.subscribe(onConnection, 'meshtastic.connection.established')

interface = meshtastic.serial_interface.SerialInterface()
local_node_id = interface.getNode('^local')
file_path = 'received_data.json'

while True:
    time.sleep(1)
