Skip to content

Commit db1891b

Browse files
committed
Added Logging Handler Names
1 parent c60b5d4 commit db1891b

12 files changed

Lines changed: 220 additions & 202 deletions

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: 21 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,10 @@
99
from types import ModuleType
1010

1111
import argparse
12+
import logging
13+
14+
logger = logging.getLogger(__name__)
15+
1216
argcomplete: Union[None, ModuleType] = None
1317
try:
1418
import argcomplete # type: ignore
@@ -67,7 +71,7 @@ def onReceive(packet, interface) -> None:
6771
args = mt_config.args
6872
try:
6973
d = packet.get("decoded")
70-
logging.debug(f"in onReceive() d:{d}")
74+
logger.debug(f"in onReceive() d:{d}")
7175

7276
# Exit once we receive a reply
7377
if (
@@ -101,7 +105,7 @@ def onConnection(interface, topic=pub.AUTO_TOPIC) -> None: # pylint: disable=W0
101105
def checkChannel(interface: MeshInterface, channelIndex: int) -> bool:
102106
"""Given an interface and channel index, return True if that channel is non-disabled on the local node"""
103107
ch = interface.localNode.getChannelByChannelIndex(channelIndex)
104-
logging.debug(f"ch:{ch}")
108+
logger.debug(f"ch:{ch}")
105109
return ch and ch.role != channel_pb2.Channel.Role.DISABLED
106110

107111

@@ -114,7 +118,7 @@ def _printSetting(config_type, uni_name, pref_value, repeated):
114118
else:
115119
pref_value = meshtastic.util.toStr(pref_value)
116120
print(f"{str(config_type.name)}.{uni_name}: {str(pref_value)}")
117-
logging.debug(f"{str(config_type.name)}.{uni_name}: {str(pref_value)}")
121+
logger.debug(f"{str(config_type.name)}.{uni_name}: {str(pref_value)}")
118122

119123
name = splitCompoundName(comp_name)
120124
wholeField = name[0] == name[1] # We want the whole field
@@ -123,8 +127,8 @@ def _printSetting(config_type, uni_name, pref_value, repeated):
123127
# Note: protobufs has the keys in snake_case, so snake internally
124128
snake_name = meshtastic.util.camel_to_snake(name[1])
125129
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}")
130+
logger.debug(f"snake_name:{snake_name} camel_name:{camel_name}")
131+
logger.debug(f"use camel:{mt_config.camel_case}")
128132

129133
# First validate the input
130134
localConfig = node.localConfig
@@ -198,8 +202,8 @@ def setPref(config, comp_name, raw_val) -> bool:
198202
snake_name = meshtastic.util.camel_to_snake(name[-1])
199203
camel_name = meshtastic.util.snake_to_camel(name[-1])
200204
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}")
205+
logger.debug(f"snake_name:{snake_name}")
206+
logger.debug(f"camel_name:{camel_name}")
203207

204208
objDesc = config.DESCRIPTOR
205209
config_part = config
@@ -223,7 +227,7 @@ def setPref(config, comp_name, raw_val) -> bool:
223227
val = meshtastic.util.fromStr(raw_val)
224228
else:
225229
val = raw_val
226-
logging.debug(f"valStr:{raw_val} val:{val}")
230+
logger.debug(f"valStr:{raw_val} val:{val}")
227231

228232
if snake_name == "wifi_psk" and len(str(raw_val)) < 8:
229233
print("Warning: network.wifi_psk must be 8 or more characters.")
@@ -603,7 +607,7 @@ def onConnected(interface):
603607
time.sleep(1)
604608
if interface.gotResponse:
605609
break
606-
logging.debug(f"end of gpio_rd")
610+
logger.debug(f"end of gpio_rd")
607611

608612
if args.gpio_watch:
609613
bitmask = int(args.gpio_watch, 16)
@@ -1059,7 +1063,7 @@ def setSimpleConfig(modem_preset):
10591063
# Even if others said we could close, stay open if the user asked for a tunnel
10601064
closeNow = False
10611065
if interface.noProto:
1062-
logging.warning(f"Not starting Tunnel - disabled by noProto")
1066+
logger.warning(f"Not starting Tunnel - disabled by noProto")
10631067
else:
10641068
if args.tunnel_net:
10651069
tunnel.Tunnel(interface, subnet=args.tunnel_net)
@@ -1250,14 +1254,14 @@ def create_power_meter():
12501254
meter = SimPowerSupply()
12511255

12521256
if meter and v:
1253-
logging.info(f"Setting power supply to {v} volts")
1257+
logger.info(f"Setting power supply to {v} volts")
12541258
meter.v = v
12551259
meter.powerOn()
12561260

12571261
if args.power_wait:
12581262
input("Powered on, press enter to continue...")
12591263
else:
1260-
logging.info("Powered-on, waiting for device to boot")
1264+
logger.info("Powered-on, waiting for device to boot")
12611265
time.sleep(5)
12621266

12631267

@@ -1312,7 +1316,7 @@ def common():
13121316
args.seriallog = "none" # assume no debug output in this case
13131317

13141318
if args.deprecated is not None:
1315-
logging.error(
1319+
logger.error(
13161320
"This option has been deprecated, see help below for the correct replacement..."
13171321
)
13181322
parser.print_help(sys.stderr)
@@ -1331,18 +1335,18 @@ def common():
13311335
logfile = sys.stdout
13321336
elif args.seriallog == "none":
13331337
args.seriallog = None
1334-
logging.debug("Not logging serial output")
1338+
logger.debug("Not logging serial output")
13351339
logfile = None
13361340
else:
1337-
logging.info(f"Logging serial output to {args.seriallog}")
1341+
logger.info(f"Logging serial output to {args.seriallog}")
13381342
# Note: using "line buffering"
13391343
# pylint: disable=R1732
13401344
logfile = open(args.seriallog, "w+", buffering=1, encoding="utf8")
13411345
mt_config.logfile = logfile
13421346

13431347
subscribe()
13441348
if args.ble_scan:
1345-
logging.debug("BLE scan starting")
1349+
logger.debug("BLE scan starting")
13461350
for x in BLEInterface.scan():
13471351
print(f"Found: name='{x.name}' address='{x.address}'")
13481352
meshtastic.util.our_exit("BLE scan finished", 0)
@@ -1433,7 +1437,7 @@ def common():
14331437
while True:
14341438
time.sleep(1000)
14351439
except KeyboardInterrupt:
1436-
logging.info("Exiting due to keyboard interrupt")
1440+
logger.info("Exiting due to keyboard interrupt")
14371441

14381442
# don't call exit, background threads might be running still
14391443
# sys.exit(0)

meshtastic/ble_interface.py

Lines changed: 17 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
FROMNUM_UUID = "ed9da18c-a800-4f66-a670-aa7547e34453"
2424
LEGACY_LOGRADIO_UUID = "6c6fd238-78fa-436b-aacf-15c5be1ef2e2"
2525
LOGRADIO_UUID = "5a3d6e49-06e6-4423-9944-e9de8cdf9547"
26+
logger = logging.getLogger(__name__)
2627

2728

2829
class BLEInterface(MeshInterface):
@@ -44,19 +45,19 @@ def __init__(
4445

4546
self.should_read = False
4647

47-
logging.debug("Threads starting")
48+
logger.debug("Threads starting")
4849
self._want_receive = True
4950
self._receiveThread: Optional[Thread] = Thread(
5051
target=self._receiveFromRadioImpl, name="BLEReceive", daemon=True
5152
)
5253
self._receiveThread.start()
53-
logging.debug("Threads running")
54+
logger.debug("Threads running")
5455

5556
self.client: Optional[BLEClient] = None
5657
try:
57-
logging.debug(f"BLE connecting to: {address if address else 'any'}")
58+
logger.debug(f"BLE connecting to: {address if address else 'any'}")
5859
self.client = self.connect(address)
59-
logging.debug("BLE connected")
60+
logger.debug("BLE connected")
6061
except BLEInterface.BLEError as e:
6162
self.close()
6263
raise e
@@ -69,13 +70,13 @@ def __init__(
6970
if self.client.has_characteristic(LOGRADIO_UUID):
7071
self.client.start_notify(LOGRADIO_UUID, self.log_radio_handler)
7172

72-
logging.debug("Mesh configure starting")
73+
logger.debug("Mesh configure starting")
7374
self._startConfig()
7475
if not self.noProto:
7576
self._waitConnected(timeout=60.0)
7677
self.waitForConfig()
7778

78-
logging.debug("Register FROMNUM notify callback")
79+
logger.debug("Register FROMNUM notify callback")
7980
self.client.start_notify(FROMNUM_UUID, self.from_num_handler)
8081

8182
# We MUST run atexit (if we can) because otherwise (at least on linux) the BLE device is not disconnected
@@ -99,7 +100,7 @@ def from_num_handler(self, _, b: bytes) -> None: # pylint: disable=C0116
99100
Note: this method does not need to be async because it is just setting a bool.
100101
"""
101102
from_num = struct.unpack("<I", bytes(b))[0]
102-
logging.debug(f"FROMNUM notify: {from_num}")
103+
logger.debug(f"FROMNUM notify: {from_num}")
103104
self.should_read = True
104105

105106
async def log_radio_handler(self, _, b): # pylint: disable=C0116
@@ -114,7 +115,7 @@ async def log_radio_handler(self, _, b): # pylint: disable=C0116
114115
)
115116
self._handleLogLine(message)
116117
except google.protobuf.message.DecodeError:
117-
logging.warning("Malformed LogRecord received. Skipping.")
118+
logger.warning("Malformed LogRecord received. Skipping.")
118119

119120
async def legacy_log_radio_handler(self, _, b): # pylint: disable=C0116
120121
log_radio = b.decode("utf-8").replace("\n", "")
@@ -124,7 +125,7 @@ async def legacy_log_radio_handler(self, _, b): # pylint: disable=C0116
124125
def scan() -> List[BLEDevice]:
125126
"""Scan for available BLE devices."""
126127
with BLEClient() as client:
127-
logging.info("Scanning for BLE devices (takes 10 seconds)...")
128+
logger.info("Scanning for BLE devices (takes 10 seconds)...")
128129
response = client.discover(
129130
timeout=10, return_adv=True, service_uuids=[SERVICE_UUID]
130131
)
@@ -186,19 +187,19 @@ def _receiveFromRadioImpl(self) -> None:
186187
retries: int = 0
187188
while self._want_receive:
188189
if self.client is None:
189-
logging.debug(f"BLE client is None, shutting down")
190+
logger.debug(f"BLE client is None, shutting down")
190191
self._want_receive = False
191192
continue
192193
try:
193194
b = bytes(self.client.read_gatt_char(FROMRADIO_UUID))
194195
except BleakDBusError as e:
195196
# Device disconnected probably, so end our read loop immediately
196-
logging.debug(f"Device disconnected, shutting down {e}")
197+
logger.debug(f"Device disconnected, shutting down {e}")
197198
self._want_receive = False
198199
except BleakError as e:
199200
# We were definitely disconnected
200201
if "Not connected" in str(e):
201-
logging.debug(f"Device disconnected, shutting down {e}")
202+
logger.debug(f"Device disconnected, shutting down {e}")
202203
self._want_receive = False
203204
else:
204205
raise BLEInterface.BLEError("Error reading BLE") from e
@@ -208,15 +209,15 @@ def _receiveFromRadioImpl(self) -> None:
208209
retries += 1
209210
continue
210211
break
211-
logging.debug(f"FROMRADIO read: {b.hex()}")
212+
logger.debug(f"FROMRADIO read: {b.hex()}")
212213
self._handleFromRadio(b)
213214
else:
214215
time.sleep(0.01)
215216

216217
def _sendToRadioImpl(self, toRadio) -> None:
217218
b: bytes = toRadio.SerializeToString()
218219
if b and self.client: # we silently ignore writes while we are shutting down
219-
logging.debug(f"TORADIO write: {b.hex()}")
220+
logger.debug(f"TORADIO write: {b.hex()}")
220221
try:
221222
self.client.write_gatt_char(
222223
TORADIO_UUID, b, response=True
@@ -234,7 +235,7 @@ def close(self) -> None:
234235
try:
235236
MeshInterface.close(self)
236237
except Exception as e:
237-
logging.error(f"Error closing mesh interface: {e}")
238+
logger.error(f"Error closing mesh interface: {e}")
238239

239240
if self._want_receive:
240241
self._want_receive = False # Tell the thread we want it to stop
@@ -263,7 +264,7 @@ def __init__(self, address=None, **kwargs) -> None:
263264
self._eventThread.start()
264265

265266
if not address:
266-
logging.debug("No address provided - only discover method will work.")
267+
logger.debug("No address provided - only discover method will work.")
267268
return
268269

269270
self.bleak_client = BleakClient(address, **kwargs)

0 commit comments

Comments
 (0)