Skip to content

Commit a29ee84

Browse files
Adding mypy typing
1 parent 53b0e35 commit a29ee84

10 files changed

Lines changed: 181 additions & 158 deletions

File tree

meshtastic/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -104,13 +104,13 @@ def onConnection(interface, topic=pub.AUTO_TOPIC): # called when we (re)connect
104104
LOCAL_ADDR = "^local"
105105
"""A special ID that means the local node"""
106106

107-
BROADCAST_NUM = 0xFFFFFFFF
107+
BROADCAST_NUM: int = 0xFFFFFFFF
108108
"""if using 8 bit nodenums this will be shortened on the target"""
109109

110110
BROADCAST_ADDR = "^all"
111111
"""A special ID that means broadcast"""
112112

113-
OUR_APP_VERSION = 20300
113+
OUR_APP_VERSION: int = 20300
114114
"""The numeric buildnumber (shared with android apps) specifying the
115115
level of device code we are guaranteed to understand
116116

meshtastic/__main__.py

Lines changed: 19 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import platform
99
import sys
1010
import time
11+
from typing import List
1112

1213
import pyqrcode # type: ignore[import-untyped]
1314
import yaml
@@ -22,7 +23,7 @@
2223
from meshtastic.ble_interface import BLEInterface
2324
from meshtastic.mesh_interface import MeshInterface
2425

25-
def onReceive(packet, interface):
26+
def onReceive(packet, interface) -> None:
2627
"""Callback invoked when a packet arrives"""
2728
args = mt_config.args
2829
try:
@@ -53,7 +54,7 @@ def onReceive(packet, interface):
5354
print(f"Warning: There is no field {ex} in the packet.")
5455

5556

56-
def onConnection(interface, topic=pub.AUTO_TOPIC): # pylint: disable=W0613
57+
def onConnection(interface, topic=pub.AUTO_TOPIC) -> None: # pylint: disable=W0613
5758
"""Callback invoked when we connect/disconnect from a radio"""
5859
print(f"Connection changed: {topic.getName()}")
5960

@@ -63,7 +64,7 @@ def checkChannel(interface: MeshInterface, channelIndex: int) -> bool:
6364
logging.debug(f"ch:{ch}")
6465
return (ch and ch.role != channel_pb2.Channel.Role.DISABLED)
6566

66-
def getPref(node, comp_name):
67+
def getPref(node, comp_name) -> bool:
6768
"""Get a channel or preferences value"""
6869

6970
name = splitCompoundName(comp_name)
@@ -78,11 +79,11 @@ def getPref(node, comp_name):
7879
# First validate the input
7980
localConfig = node.localConfig
8081
moduleConfig = node.moduleConfig
81-
found = False
82+
found: bool = False
8283
for config in [localConfig, moduleConfig]:
8384
objDesc = config.DESCRIPTOR
8485
config_type = objDesc.fields_by_name.get(name[0])
85-
pref = False
86+
pref = False #FIXME - checkme - Used here as boolean, but set 2 lines below as a string.
8687
if config_type:
8788
pref = config_type.message_type.fields_by_name.get(snake_name)
8889
if pref or wholeField:
@@ -129,15 +130,15 @@ def getPref(node, comp_name):
129130
return True
130131

131132

132-
def splitCompoundName(comp_name):
133+
def splitCompoundName(comp_name: str) -> List[str]:
133134
"""Split compound (dot separated) preference name into parts"""
134-
name = comp_name.split(".")
135+
name: List[str] = comp_name.split(".")
135136
if len(name) < 2:
136137
name[0] = comp_name
137138
name.append(comp_name)
138139
return name
139140

140-
def traverseConfig(config_root, config, interface_config):
141+
def traverseConfig(config_root, config, interface_config) -> bool:
141142
"""Iterate through current config level preferences and either traverse deeper if preference is a dict or set preference"""
142143
snake_name = meshtastic.util.camel_to_snake(config_root)
143144
for pref in config:
@@ -884,7 +885,7 @@ def setSimpleConfig(modem_preset):
884885
sys.exit(1)
885886

886887

887-
def printConfig(config):
888+
def printConfig(config) -> None:
888889
"""print configuration"""
889890
objDesc = config.DESCRIPTOR
890891
for config_section in objDesc.fields:
@@ -901,12 +902,12 @@ def printConfig(config):
901902
print(f" {temp_name}")
902903

903904

904-
def onNode(node):
905+
def onNode(node) -> None:
905906
"""Callback invoked when the node DB changes"""
906907
print(f"Node changed: {node}")
907908

908909

909-
def subscribe():
910+
def subscribe() -> None:
910911
"""Subscribe to the topics the user probably wants to see, prints output to stdout"""
911912
pub.subscribe(onReceive, "meshtastic.receive")
912913
# pub.subscribe(onConnection, "meshtastic.connection")
@@ -917,7 +918,7 @@ def subscribe():
917918
# pub.subscribe(onNode, "meshtastic.node")
918919

919920

920-
def export_config(interface):
921+
def export_config(interface) -> str:
921922
"""used in --export-config"""
922923
configObj = {}
923924

@@ -949,7 +950,7 @@ def export_config(interface):
949950
if alt:
950951
configObj["location"]["alt"] = alt
951952

952-
config = MessageToDict(interface.localNode.localConfig)
953+
config = MessageToDict(interface.localNode.localConfig) #checkme - Used as a dictionary here and a string below
953954
if config:
954955
# Convert inner keys to correct snake/camelCase
955956
prefs = {}
@@ -959,7 +960,7 @@ def export_config(interface):
959960
else:
960961
prefs[pref] = config[pref]
961962
if mt_config.camel_case:
962-
configObj["config"] = config
963+
configObj["config"] = config #Identical command here and 2 lines below?
963964
else:
964965
configObj["config"] = config
965966

@@ -975,10 +976,10 @@ def export_config(interface):
975976
else:
976977
configObj["module_config"] = prefs
977978

978-
config = "# start of Meshtastic configure yaml\n"
979-
config += yaml.dump(configObj)
980-
print(config)
981-
return config
979+
config_txt = "# start of Meshtastic configure yaml\n" #checkme - "config" (now changed to config_out) was used as a string here and a Dictionary above
980+
config_txt += yaml.dump(configObj)
981+
print(config_txt)
982+
return config_txt
982983

983984

984985
def common():

meshtastic/ble_interface.py

Lines changed: 27 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
"""Bluetooth interface
22
"""
3+
import io
34
import logging
45
import time
56
import struct
67
import asyncio
78
from threading import Thread, Event
8-
from typing import Optional
9+
from typing import List, Optional, Tuple
910

1011
from bleak import BleakScanner, BleakClient
1112

@@ -32,7 +33,7 @@ class BLEState(): # pylint: disable=C0115
3233
MESH = False
3334

3435

35-
def __init__(self, address: Optional[str], noProto: bool = False, debugOut = None, noNodes: bool = False):
36+
def __init__(self, address: Optional[str], noProto: bool = False, debugOut: Optional[io.TextIOWrapper] = None, noNodes: bool = False) -> None:
3637
self.state = BLEInterface.BLEState()
3738

3839
if not address:
@@ -72,14 +73,14 @@ def __init__(self, address: Optional[str], noProto: bool = False, debugOut = Non
7273
self.client.start_notify(FROMNUM_UUID, self.from_num_handler)
7374

7475

75-
async def from_num_handler(self, _, b): # pylint: disable=C0116
76+
async def from_num_handler(self, _, b: bytes) -> None: # pylint: disable=C0116
7677
from_num = struct.unpack('<I', bytes(b))[0]
7778
logging.debug(f"FROMNUM notify: {from_num}")
7879
self.should_read = True
7980

8081

81-
def scan(self):
82-
"Scan for available BLE devices"
82+
def scan(self) -> List[Tuple]:
83+
"""Scan for available BLE devices"""
8384
with BLEClient() as client:
8485
return [
8586
(x[0], x[1]) for x in (client.discover(
@@ -89,8 +90,8 @@ def scan(self):
8990
]
9091

9192

92-
def find_device(self, address):
93-
"Find a device by address"
93+
def find_device(self, address: Optional[str]):
94+
"""Find a device by address"""
9495
meshtastic_devices = self.scan()
9596

9697
addressed_devices = list(filter(lambda x: address in (x[1].local_name, x[0].name), meshtastic_devices))
@@ -106,18 +107,21 @@ def find_device(self, address):
106107
raise BLEInterface.BLEError(f"More than one Meshtastic BLE peripheral with identifier or address '{address}' found.")
107108
return addressed_devices[0][0]
108109

109-
def _sanitize_address(address): # pylint: disable=E0213
110-
"Standardize BLE address by removing extraneous characters and lowercasing"
111-
return address \
112-
.replace("-", "") \
113-
.replace("_", "") \
114-
.replace(":", "") \
115-
.lower()
116-
117-
def connect(self, address):
110+
def _sanitize_address(address: Optional[str]) -> Optional[str]: # pylint: disable=E0213
111+
"""Standardize BLE address by removing extraneous characters and lowercasing"""
112+
if address is None:
113+
return None
114+
else:
115+
return address \
116+
.replace("-", "") \
117+
.replace("_", "") \
118+
.replace(":", "") \
119+
.lower()
120+
121+
def connect(self, address) -> BLEClient:
118122
"Connect to a device by address"
119123
device = self.find_device(address)
120-
client = BLEClient(device.address)
124+
client: BLEClient = BLEClient(device.address)
121125
client.connect()
122126
try:
123127
client.pair()
@@ -128,12 +132,12 @@ def connect(self, address):
128132
return client
129133

130134

131-
def _receiveFromRadioImpl(self):
135+
def _receiveFromRadioImpl(self) -> None:
132136
self._receiveThread_started.set()
133137
while self._receiveThread_started.is_set():
134138
if self.should_read:
135139
self.should_read = False
136-
retries = 0
140+
retries: int = 0
137141
while True:
138142
b = bytes(self.client.read_gatt_char(FROMRADIO_UUID))
139143
if not b:
@@ -148,8 +152,8 @@ def _receiveFromRadioImpl(self):
148152
time.sleep(0.1)
149153
self._receiveThread_stopped.set()
150154

151-
def _sendToRadioImpl(self, toRadio):
152-
b = toRadio.SerializeToString()
155+
def _sendToRadioImpl(self, toRadio) -> None:
156+
b: bytes = toRadio.SerializeToString()
153157
if b:
154158
logging.debug(f"TORADIO write: {b.hex()}")
155159
self.client.write_gatt_char(TORADIO_UUID, b, response = True)
@@ -158,7 +162,7 @@ def _sendToRadioImpl(self, toRadio):
158162
self.should_read = True
159163

160164

161-
def close(self):
165+
def close(self) -> None:
162166
if self.state.MESH:
163167
MeshInterface.close(self)
164168

@@ -173,7 +177,7 @@ def close(self):
173177

174178
class BLEClient():
175179
"""Client for managing connection to a BLE device"""
176-
def __init__(self, address = None, **kwargs):
180+
def __init__(self, address = None, **kwargs) -> None:
177181
self._eventThread = Thread(target = self._run_event_loop)
178182
self._eventThread_started = Event()
179183
self._eventThread_stopped = Event()

meshtastic/remote_hardware.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
from meshtastic.util import our_exit
99

1010

11-
def onGPIOreceive(packet, interface):
11+
def onGPIOreceive(packet, interface) -> None:
1212
"""Callback for received GPIO responses"""
1313
logging.debug(f"packet:{packet} interface:{interface}")
1414
gpioValue = 0
@@ -37,7 +37,7 @@ class RemoteHardwareClient:
3737
code for how you can connect to your own custom meshtastic services
3838
"""
3939

40-
def __init__(self, iface):
40+
def __init__(self, iface) -> None:
4141
"""
4242
Constructor
4343

meshtastic/serial_interface.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import platform
55
import time
66

7-
from typing import Optional
7+
from typing import List, Optional
88

99
import serial # type: ignore[import-untyped]
1010

@@ -18,7 +18,7 @@
1818
class SerialInterface(StreamInterface):
1919
"""Interface class for meshtastic devices over a serial link"""
2020

21-
def __init__(self, devPath: Optional[str]=None, debugOut=None, noProto=False, connectNow=True, noNodes: bool=False):
21+
def __init__(self, devPath: Optional[str]=None, debugOut=None, noProto: bool=False, connectNow: bool=True, noNodes: bool=False) -> None:
2222
"""Constructor, opens a connection to a specified serial port, or if unspecified try to
2323
find one Meshtastic device by probing
2424
@@ -31,13 +31,13 @@ def __init__(self, devPath: Optional[str]=None, debugOut=None, noProto=False, co
3131
self.devPath: Optional[str] = devPath
3232

3333
if self.devPath is None:
34-
ports = meshtastic.util.findPorts(True)
34+
ports: List[str] = meshtastic.util.findPorts(True)
3535
logging.debug(f"ports:{ports}")
3636
if len(ports) == 0:
3737
print("No Serial Meshtastic device detected, attempting TCP connection on localhost.")
3838
return
3939
elif len(ports) > 1:
40-
message = "Warning: Multiple serial ports were detected so one serial port must be specified with the '--port'.\n"
40+
message: str = "Warning: Multiple serial ports were detected so one serial port must be specified with the '--port'.\n"
4141
message += f" Ports detected:{ports}"
4242
meshtastic.util.our_exit(message)
4343
else:
@@ -65,7 +65,7 @@ def __init__(self, devPath: Optional[str]=None, debugOut=None, noProto=False, co
6565
self, debugOut=debugOut, noProto=noProto, connectNow=connectNow, noNodes=noNodes
6666
)
6767

68-
def close(self):
68+
def close(self) -> None:
6969
"""Close a connection to the device"""
7070
self.stream.flush()
7171
time.sleep(0.1)

0 commit comments

Comments
 (0)