Skip to content

Commit cfb2378

Browse files
authored
Merge pull request #812 from shukari/loggingHandler2
Added Logging Handler Names & windows pytest support
2 parents 47e5b04 + 14ff3eb commit cfb2378

17 files changed

+310
-275
lines changed

meshtastic/__init__.py

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,7 @@ def onConnection(interface, topic=pub.AUTO_TOPIC): # called when we (re)connect
129129

130130
publishingThread = DeferredExecution("publishing")
131131

132+
logger = logging.getLogger(__name__)
132133

133134
class ResponseHandler(NamedTuple):
134135
"""A pending response callback, waiting for a response to one of our messages"""
@@ -160,31 +161,31 @@ def _onTextReceive(iface, asDict):
160161
#
161162
# Usually btw this problem is caused by apps sending binary data but setting the payload type to
162163
# text.
163-
logging.debug(f"in _onTextReceive() asDict:{asDict}")
164+
logger.debug(f"in _onTextReceive() asDict:{asDict}")
164165
try:
165166
asBytes = asDict["decoded"]["payload"]
166167
asDict["decoded"]["text"] = asBytes.decode("utf-8")
167168
except Exception as ex:
168-
logging.error(f"Malformatted utf8 in text message: {ex}")
169+
logger.error(f"Malformatted utf8 in text message: {ex}")
169170
_receiveInfoUpdate(iface, asDict)
170171

171172

172173
def _onPositionReceive(iface, asDict):
173174
"""Special auto parsing for received messages"""
174-
logging.debug(f"in _onPositionReceive() asDict:{asDict}")
175+
logger.debug(f"in _onPositionReceive() asDict:{asDict}")
175176
if "decoded" in asDict:
176177
if "position" in asDict["decoded"] and "from" in asDict:
177178
p = asDict["decoded"]["position"]
178-
logging.debug(f"p:{p}")
179+
logger.debug(f"p:{p}")
179180
p = iface._fixupPosition(p)
180-
logging.debug(f"after fixup p:{p}")
181+
logger.debug(f"after fixup p:{p}")
181182
# update node DB as needed
182183
iface._getOrCreateByNum(asDict["from"])["position"] = p
183184

184185

185186
def _onNodeInfoReceive(iface, asDict):
186187
"""Special auto parsing for received messages"""
187-
logging.debug(f"in _onNodeInfoReceive() asDict:{asDict}")
188+
logger.debug(f"in _onNodeInfoReceive() asDict:{asDict}")
188189
if "decoded" in asDict:
189190
if "user" in asDict["decoded"] and "from" in asDict:
190191
p = asDict["decoded"]["user"]
@@ -198,7 +199,7 @@ def _onNodeInfoReceive(iface, asDict):
198199

199200
def _onTelemetryReceive(iface, asDict):
200201
"""Automatically update device metrics on received packets"""
201-
logging.debug(f"in _onTelemetryReceive() asDict:{asDict}")
202+
logger.debug(f"in _onTelemetryReceive() asDict:{asDict}")
202203
if "from" not in asDict:
203204
return
204205

@@ -222,7 +223,7 @@ def _onTelemetryReceive(iface, asDict):
222223
updateObj = telemetry.get(toUpdate)
223224
newMetrics = node.get(toUpdate, {})
224225
newMetrics.update(updateObj)
225-
logging.debug(f"updating {toUpdate} metrics for {asDict['from']} to {newMetrics}")
226+
logger.debug(f"updating {toUpdate} metrics for {asDict['from']} to {newMetrics}")
226227
node[toUpdate] = newMetrics
227228

228229
def _receiveInfoUpdate(iface, asDict):
@@ -234,7 +235,7 @@ def _receiveInfoUpdate(iface, asDict):
234235

235236
def _onAdminReceive(iface, asDict):
236237
"""Special auto parsing for received messages"""
237-
logging.debug(f"in _onAdminReceive() asDict:{asDict}")
238+
logger.debug(f"in _onAdminReceive() asDict:{asDict}")
238239
if "decoded" in asDict and "from" in asDict and "admin" in asDict["decoded"]:
239240
adminMessage = asDict["decoded"]["admin"]["raw"]
240241
iface._getOrCreateByNum(asDict["from"])["adminSessionPassKey"] = adminMessage.session_passkey

meshtastic/__main__.py

Lines changed: 28 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
from types import ModuleType
1010

1111
import argparse
12+
1213
argcomplete: Union[None, ModuleType] = None
1314
try:
1415
import argcomplete # type: ignore
@@ -62,12 +63,14 @@
6263
from meshtastic.protobuf import channel_pb2, config_pb2, portnums_pb2, mesh_pb2
6364
from meshtastic.version import get_active_version
6465

66+
logger = logging.getLogger(__name__)
67+
6568
def onReceive(packet, interface) -> None:
6669
"""Callback invoked when a packet arrives"""
6770
args = mt_config.args
6871
try:
6972
d = packet.get("decoded")
70-
logging.debug(f"in onReceive() d:{d}")
73+
logger.debug(f"in onReceive() d:{d}")
7174

7275
# Exit once we receive a reply
7376
if (
@@ -101,7 +104,7 @@ def onConnection(interface, topic=pub.AUTO_TOPIC) -> None: # pylint: disable=W0
101104
def checkChannel(interface: MeshInterface, channelIndex: int) -> bool:
102105
"""Given an interface and channel index, return True if that channel is non-disabled on the local node"""
103106
ch = interface.localNode.getChannelByChannelIndex(channelIndex)
104-
logging.debug(f"ch:{ch}")
107+
logger.debug(f"ch:{ch}")
105108
return ch and ch.role != channel_pb2.Channel.Role.DISABLED
106109

107110

@@ -114,7 +117,7 @@ def _printSetting(config_type, uni_name, pref_value, repeated):
114117
else:
115118
pref_value = meshtastic.util.toStr(pref_value)
116119
print(f"{str(config_type.name)}.{uni_name}: {str(pref_value)}")
117-
logging.debug(f"{str(config_type.name)}.{uni_name}: {str(pref_value)}")
120+
logger.debug(f"{str(config_type.name)}.{uni_name}: {str(pref_value)}")
118121

119122
name = splitCompoundName(comp_name)
120123
wholeField = name[0] == name[1] # We want the whole field
@@ -123,8 +126,8 @@ def _printSetting(config_type, uni_name, pref_value, repeated):
123126
# Note: protobufs has the keys in snake_case, so snake internally
124127
snake_name = meshtastic.util.camel_to_snake(name[1])
125128
uni_name = camel_name if mt_config.camel_case else snake_name
126-
logging.debug(f"snake_name:{snake_name} camel_name:{camel_name}")
127-
logging.debug(f"use camel:{mt_config.camel_case}")
129+
logger.debug(f"snake_name:{snake_name} camel_name:{camel_name}")
130+
logger.debug(f"use camel:{mt_config.camel_case}")
128131

129132
# First validate the input
130133
localConfig = node.localConfig
@@ -198,8 +201,8 @@ def setPref(config, comp_name, raw_val) -> bool:
198201
snake_name = meshtastic.util.camel_to_snake(name[-1])
199202
camel_name = meshtastic.util.snake_to_camel(name[-1])
200203
uni_name = camel_name if mt_config.camel_case else snake_name
201-
logging.debug(f"snake_name:{snake_name}")
202-
logging.debug(f"camel_name:{camel_name}")
204+
logger.debug(f"snake_name:{snake_name}")
205+
logger.debug(f"camel_name:{camel_name}")
203206

204207
objDesc = config.DESCRIPTOR
205208
config_part = config
@@ -223,7 +226,7 @@ def setPref(config, comp_name, raw_val) -> bool:
223226
val = meshtastic.util.fromStr(raw_val)
224227
else:
225228
val = raw_val
226-
logging.debug(f"valStr:{raw_val} val:{val}")
229+
logger.debug(f"valStr:{raw_val} val:{val}")
227230

228231
if snake_name == "wifi_psk" and len(str(raw_val)) < 8:
229232
print("Warning: network.wifi_psk must be 8 or more characters.")
@@ -608,7 +611,7 @@ def onConnected(interface):
608611
time.sleep(1)
609612
if interface.gotResponse:
610613
break
611-
logging.debug(f"end of gpio_rd")
614+
logger.debug(f"end of gpio_rd")
612615

613616
if args.gpio_watch:
614617
bitmask = int(args.gpio_watch, 16)
@@ -1064,7 +1067,7 @@ def setSimpleConfig(modem_preset):
10641067
# Even if others said we could close, stay open if the user asked for a tunnel
10651068
closeNow = False
10661069
if interface.noProto:
1067-
logging.warning(f"Not starting Tunnel - disabled by noProto")
1070+
logger.warning(f"Not starting Tunnel - disabled by noProto")
10681071
else:
10691072
if args.tunnel_net:
10701073
tunnel.Tunnel(interface, subnet=args.tunnel_net)
@@ -1255,14 +1258,14 @@ def create_power_meter():
12551258
meter = SimPowerSupply()
12561259

12571260
if meter and v:
1258-
logging.info(f"Setting power supply to {v} volts")
1261+
logger.info(f"Setting power supply to {v} volts")
12591262
meter.v = v
12601263
meter.powerOn()
12611264

12621265
if args.power_wait:
12631266
input("Powered on, press enter to continue...")
12641267
else:
1265-
logging.info("Powered-on, waiting for device to boot")
1268+
logger.info("Powered-on, waiting for device to boot")
12661269
time.sleep(5)
12671270

12681271

@@ -1276,6 +1279,10 @@ def common():
12761279
format="%(levelname)s file:%(filename)s %(funcName)s line:%(lineno)s %(message)s",
12771280
)
12781281

1282+
# set all meshtastic loggers to DEBUG
1283+
if not (args.debug or args.listen) and args.debuglib:
1284+
logging.getLogger('meshtastic').setLevel(logging.DEBUG)
1285+
12791286
if len(sys.argv) == 1:
12801287
parser.print_help(sys.stderr)
12811288
meshtastic.util.our_exit("", 1)
@@ -1317,7 +1324,7 @@ def common():
13171324
args.seriallog = "none" # assume no debug output in this case
13181325

13191326
if args.deprecated is not None:
1320-
logging.error(
1327+
logger.error(
13211328
"This option has been deprecated, see help below for the correct replacement..."
13221329
)
13231330
parser.print_help(sys.stderr)
@@ -1336,18 +1343,18 @@ def common():
13361343
logfile = sys.stdout
13371344
elif args.seriallog == "none":
13381345
args.seriallog = None
1339-
logging.debug("Not logging serial output")
1346+
logger.debug("Not logging serial output")
13401347
logfile = None
13411348
else:
1342-
logging.info(f"Logging serial output to {args.seriallog}")
1349+
logger.info(f"Logging serial output to {args.seriallog}")
13431350
# Note: using "line buffering"
13441351
# pylint: disable=R1732
13451352
logfile = open(args.seriallog, "w+", buffering=1, encoding="utf8")
13461353
mt_config.logfile = logfile
13471354

13481355
subscribe()
13491356
if args.ble_scan:
1350-
logging.debug("BLE scan starting")
1357+
logger.debug("BLE scan starting")
13511358
for x in BLEInterface.scan():
13521359
print(f"Found: name='{x.name}' address='{x.address}'")
13531360
meshtastic.util.our_exit("BLE scan finished", 0)
@@ -1438,7 +1445,7 @@ def common():
14381445
while True:
14391446
time.sleep(1000)
14401447
except KeyboardInterrupt:
1441-
logging.info("Exiting due to keyboard interrupt")
1448+
logger.info("Exiting due to keyboard interrupt")
14421449

14431450
# don't call exit, background threads might be running still
14441451
# sys.exit(0)
@@ -2045,6 +2052,10 @@ def initParser():
20452052
"--debug", help="Show API library debug log messages", action="store_true"
20462053
)
20472054

2055+
group.add_argument(
2056+
"--debuglib", help="Show only API library debug log messages", action="store_true"
2057+
)
2058+
20482059
group.add_argument(
20492060
"--test",
20502061
help="Run stress test against all connected Meshtastic devices",

meshtastic/analysis/__main__.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import argparse
44
import logging
5+
import os
56
from typing import cast, List
67

78
import dash_bootstrap_components as dbc # type: ignore[import-untyped]
@@ -143,8 +144,8 @@ def create_dash(slog_path: str) -> Dash:
143144
"""
144145
app = Dash(external_stylesheets=[dbc.themes.BOOTSTRAP])
145146

146-
dpwr = read_pandas(f"{slog_path}/power.feather")
147-
dslog = read_pandas(f"{slog_path}/slog.feather")
147+
dpwr = read_pandas(os.path.join(slog_path, "power.feather"))
148+
dslog = read_pandas(os.path.join(slog_path, "slog.feather"))
148149

149150
pmon_raises = get_pmon_raises(dslog)
150151

@@ -190,7 +191,7 @@ def main():
190191
parser = create_argparser()
191192
args = parser.parse_args()
192193
if not args.slog:
193-
args.slog = f"{root_dir()}/latest"
194+
args.slog = os.path.join(root_dir(), "latest")
194195

195196
app = create_dash(slog_path=args.slog)
196197
port = 8051

0 commit comments

Comments
 (0)