meshtastic / python

The Python CLI and API for talking to Meshtastic devices
https://meshtastic.org
371 stars 158 forks source link

meshtastic.SerialInterface().nodes and json.Dumps problem #83

Closed iz1kga closed 3 years ago

iz1kga commented 3 years ago

After some time of execution is not possible to json.Dumps -> meshtastic.SerialInterface().nodes

How to reproduce: execute this code and wait

import meshtastic
from pubsub import pub
import json

def update(interface, packet):
    print("--- --- --- interface.nodes: --- --- ---")
    print(interface.nodes)
    print("--- --- --- JSON DUMPS --- --- ---")
    print(json.dumps(interface.nodes))

if __name__ == '__main__':
    interface = meshtastic.SerialInterface()
    pub.subscribe(update, "meshtastic.receive")

IMHO it seems that in raw some quotes are missing

{'!b22483d0': {'num': 2988737488, 'user': {'id': '!b22483d0', 'longName': 'VillarFocchiardo_83d0', 'shortName': 'VF1', 'macaddr': 'rGeyJIPQ', 'hwModel': 'TBEAM', 'raw': id: "!b22483d0"
long_name: "VillarFocchiardo_83d0"
short_name: "VF1"
macaddr: "\254g\262$\203\320"
hw_model: TBEAM
}, 'position': {'latitudeI': 451072996, 'longitudeI': 72335516, 'altitude': 425, 'time': 1618251348, 'raw': latitude_i: 451072996
longitude_i: 72335516
altitude: 425
time: 1618251348
, 'latitude': 45.1072996, 'longitude': 7.233551599999999}, 'lastHeard': 1618251203}}
iz1kga commented 3 years ago

https://meshtastic.discourse.group/t/problem-with-invalid-json/3010/7

maybe also related to

https://meshtastic.discourse.group/t/strange-behaviour-on-t-beam/3096

iz1kga commented 3 years ago

I Had time to look into the code, for what i can understand raw protobuf object cannot be direcly serialized with json.dumps().

So how to serialize meshtastic.SerialInterface().nodes easily?

iz1kga commented 3 years ago

ok, so, the issue is not an issue, the dict containing a protobuf object cannot be serialized with json.dumps() I solved with a function that recursively strips the key you don't want (in my case "raw").

def stripKey(inDict, keys):
    keySet = set(keys)
    strippedDict = {}
    for key, value in inDict.items():
        if key not in keySet:
            if isinstance(value, dict):
                strippedDict[key] = stripKey(value, keySet)
            else:
                strippedDict[key] = value
    return strippedDict