File: print-packets-json-log.py

package info (click to toggle)
gtk-meshtastic-client 1.5-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 3,056 kB
  • sloc: python: 4,794; xml: 64; makefile: 3
file content (64 lines) | stat: -rw-r--r-- 2,095 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
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)