mirror of
https://github.com/meshtastic/python.git
synced 2025-12-26 09:27:52 -05:00
Compare commits
27 Commits
2.3.4.post
...
2.3.6
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
70c5a30b77 | ||
|
|
9f0ba7aeae | ||
|
|
4226201423 | ||
|
|
bdf3a24be1 | ||
|
|
e8ba5581f6 | ||
|
|
948846e0f1 | ||
|
|
6c4dbb6fe6 | ||
|
|
afbabf9538 | ||
|
|
d8107122a2 | ||
|
|
03c1f08e45 | ||
|
|
760fcfcea7 | ||
|
|
a4830f5f62 | ||
|
|
2b1f337a41 | ||
|
|
ddad5f08b3 | ||
|
|
6e7933a3ce | ||
|
|
f449ff9506 | ||
|
|
a07e853f69 | ||
|
|
0d57449030 | ||
|
|
067cddd354 | ||
|
|
4af1b322da | ||
|
|
c580df15e1 | ||
|
|
b280d0ba23 | ||
|
|
439b1ade2e | ||
|
|
9f2b54eb98 | ||
|
|
278ca74a70 | ||
|
|
1c93b7bd52 | ||
|
|
590b60fefb |
24
.github/workflows/release.yml
vendored
24
.github/workflows/release.yml
vendored
@@ -14,19 +14,19 @@ jobs:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v2
|
||||
|
||||
#- name: Bump version
|
||||
# run: >-
|
||||
# bin/bump_version.py
|
||||
- name: Bump version
|
||||
run: >-
|
||||
bin/bump_version.py
|
||||
|
||||
#- name: Commit updated version.py
|
||||
# id: commit_updated
|
||||
# run: |
|
||||
# git config --global user.name 'github-actions'
|
||||
# git config --global user.email 'bot@noreply.github.com'
|
||||
# git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/${{ github.repository }}
|
||||
# git add setup.py
|
||||
# git commit -m "bump version" && git push || echo "No changes to commit"
|
||||
# git log -n 1 --pretty=format:"%H" | tail -n 1 | awk '{print "::set-output name=sha::"$0}'
|
||||
- name: Commit updated version.py
|
||||
id: commit_updated
|
||||
run: |
|
||||
git config --global user.name 'github-actions'
|
||||
git config --global user.email 'bot@noreply.github.com'
|
||||
git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/${{ github.repository }}
|
||||
git add setup.py
|
||||
git commit -m "bump version" && git push || echo "No changes to commit"
|
||||
git log -n 1 --pretty=format:"%H" | tail -n 1 | awk '{print "::set-output name=sha::"$0}'
|
||||
|
||||
- name: Get version
|
||||
id: get_version
|
||||
|
||||
@@ -16,16 +16,14 @@ from pubsub import pub # type: ignore[import-untyped]
|
||||
|
||||
import meshtastic.test
|
||||
import meshtastic.util
|
||||
from meshtastic import mt_config
|
||||
from meshtastic import channel_pb2, config_pb2, portnums_pb2, remote_hardware, BROADCAST_ADDR
|
||||
from meshtastic.version import get_active_version
|
||||
from meshtastic.ble_interface import BLEInterface
|
||||
from meshtastic.globals import Globals
|
||||
|
||||
|
||||
def onReceive(packet, interface):
|
||||
"""Callback invoked when a packet arrives"""
|
||||
our_globals = Globals.getInstance()
|
||||
args = our_globals.get_args()
|
||||
args = mt_config.args
|
||||
try:
|
||||
d = packet.get("decoded")
|
||||
logging.debug(f"in onReceive() d:{d}")
|
||||
@@ -69,7 +67,7 @@ def getPref(node, comp_name):
|
||||
# Note: protobufs has the keys in snake_case, so snake internally
|
||||
snake_name = meshtastic.util.camel_to_snake(name[1])
|
||||
logging.debug(f"snake_name:{snake_name} camel_name:{camel_name}")
|
||||
logging.debug(f"use camel:{Globals.getInstance().get_camel_case()}")
|
||||
logging.debug(f"use camel:{mt_config.camel_case}")
|
||||
|
||||
# First validate the input
|
||||
localConfig = node.localConfig
|
||||
@@ -86,7 +84,7 @@ def getPref(node, comp_name):
|
||||
break
|
||||
|
||||
if not found:
|
||||
if Globals.getInstance().get_camel_case():
|
||||
if mt_config.camel_case:
|
||||
print(
|
||||
f"{localConfig.__class__.__name__} and {moduleConfig.__class__.__name__} do not have an attribute {snake_name}."
|
||||
)
|
||||
@@ -105,7 +103,7 @@ def getPref(node, comp_name):
|
||||
config_values = getattr(config, config_type.name)
|
||||
if not wholeField:
|
||||
pref_value = getattr(config_values, pref.name)
|
||||
if Globals.getInstance().get_camel_case():
|
||||
if mt_config.camel_case:
|
||||
print(f"{str(config_type.name)}.{camel_name}: {str(pref_value)}")
|
||||
logging.debug(
|
||||
f"{str(config_type.name)}.{camel_name}: {str(pref_value)}"
|
||||
@@ -127,25 +125,46 @@ def getPref(node, comp_name):
|
||||
|
||||
def splitCompoundName(comp_name):
|
||||
"""Split compound (dot separated) preference name into parts"""
|
||||
name = comp_name.split(".", 1)
|
||||
if len(name) != 2:
|
||||
name = comp_name.split(".")
|
||||
if len(name) < 2:
|
||||
name[0] = comp_name
|
||||
name.append(comp_name)
|
||||
return name
|
||||
|
||||
def traverseConfig(config_root, config, interface_config):
|
||||
"""Iterate through current config level preferences and either traverse deeper if preference is a dict or set preference"""
|
||||
snake_name = meshtastic.util.camel_to_snake(config_root)
|
||||
for pref in config:
|
||||
pref_name = f"{snake_name}.{pref}"
|
||||
if isinstance(config[pref], dict):
|
||||
traverseConfig(pref_name, config[pref], interface_config)
|
||||
else:
|
||||
setPref(
|
||||
interface_config,
|
||||
pref_name,
|
||||
str(config[pref])
|
||||
)
|
||||
|
||||
return True
|
||||
|
||||
def setPref(config, comp_name, valStr) -> bool:
|
||||
"""Set a channel or preferences value"""
|
||||
|
||||
name = splitCompoundName(comp_name)
|
||||
|
||||
snake_name = meshtastic.util.camel_to_snake(name[1])
|
||||
camel_name = meshtastic.util.snake_to_camel(name[1])
|
||||
snake_name = meshtastic.util.camel_to_snake(name[-1])
|
||||
camel_name = meshtastic.util.snake_to_camel(name[-1])
|
||||
logging.debug(f"snake_name:{snake_name}")
|
||||
logging.debug(f"camel_name:{camel_name}")
|
||||
|
||||
objDesc = config.DESCRIPTOR
|
||||
config_part = config
|
||||
config_type = objDesc.fields_by_name.get(name[0])
|
||||
if config_type and config_type.message_type is not None:
|
||||
for name_part in name[1:-1]:
|
||||
part_snake_name = meshtastic.util.camel_to_snake((name_part))
|
||||
config_part = getattr(config, config_type.name)
|
||||
config_type = config_type.message_type.fields_by_name.get(part_snake_name)
|
||||
pref = None
|
||||
if config_type and config_type.message_type is not None:
|
||||
pref = config_type.message_type.fields_by_name.get(snake_name)
|
||||
@@ -171,7 +190,7 @@ def setPref(config, comp_name, valStr) -> bool:
|
||||
if e:
|
||||
val = e.number
|
||||
else:
|
||||
if Globals.getInstance().get_camel_case():
|
||||
if mt_config.camel_case:
|
||||
print(
|
||||
f"{name[0]}.{camel_name} does not have an enum called {val}, so you can not set it."
|
||||
)
|
||||
@@ -192,13 +211,13 @@ def setPref(config, comp_name, valStr) -> bool:
|
||||
if snake_name != "ignore_incoming":
|
||||
try:
|
||||
if config_type.message_type is not None:
|
||||
config_values = getattr(config, config_type.name)
|
||||
config_values = getattr(config_part, config_type.name)
|
||||
setattr(config_values, pref.name, val)
|
||||
else:
|
||||
setattr(config, snake_name, val)
|
||||
setattr(config_part, snake_name, val)
|
||||
except TypeError:
|
||||
# The setter didn't like our arg type guess try again as a string
|
||||
config_values = getattr(config, config_type.name)
|
||||
config_values = getattr(config_part, config_type.name)
|
||||
setattr(config_values, pref.name, valStr)
|
||||
else:
|
||||
if val == 0:
|
||||
@@ -209,8 +228,8 @@ def setPref(config, comp_name, valStr) -> bool:
|
||||
print(f"Adding '{val}' to the ignore_incoming list")
|
||||
config_type.message_type.ignore_incoming.extend([val])
|
||||
|
||||
prefix = f"{name[0]}." if config_type.message_type is not None else ""
|
||||
if Globals.getInstance().get_camel_case():
|
||||
prefix = f"{'.'.join(name[0:-1])}." if config_type.message_type is not None else ""
|
||||
if mt_config.camel_case:
|
||||
print(f"Set {prefix}{camel_name} to {valStr}")
|
||||
else:
|
||||
print(f"Set {prefix}{snake_name} to {valStr}")
|
||||
@@ -225,8 +244,7 @@ def onConnected(interface):
|
||||
False # Should we wait for an acknowledgment if we send to a remote node?
|
||||
)
|
||||
try:
|
||||
our_globals = Globals.getInstance()
|
||||
args = our_globals.get_args()
|
||||
args = mt_config.args
|
||||
|
||||
# do not print this line if we are exporting the config
|
||||
if not args.export_config:
|
||||
@@ -259,7 +277,12 @@ def onConnected(interface):
|
||||
interface.localNode.writeConfig("position")
|
||||
elif not args.no_time:
|
||||
# We normally provide a current time to the mesh when we connect
|
||||
interface.sendPosition()
|
||||
if interface.localNode.nodeNum in interface.nodesByNum and "position" in interface.nodesByNum[interface.localNode.nodeNum]:
|
||||
# send the same position the node already knows, just to update time
|
||||
position = interface.nodesByNum[interface.localNode.nodeNum]["position"]
|
||||
interface.sendPosition(position.get("latitude", 0.0), position.get("longitude", 0.0), position.get("altitude", 0.0))
|
||||
else:
|
||||
interface.sendPosition()
|
||||
|
||||
if args.set_owner:
|
||||
closeNow = True
|
||||
@@ -365,6 +388,11 @@ def onConnected(interface):
|
||||
waitForAckNak = True
|
||||
interface.getNode(args.dest, False).factoryReset()
|
||||
|
||||
if args.remove_node:
|
||||
closeNow = True
|
||||
waitForAckNak = True
|
||||
interface.getNode(args.dest, False).removeNode(args.remove_node)
|
||||
|
||||
if args.reset_nodedb:
|
||||
closeNow = True
|
||||
waitForAckNak = True
|
||||
@@ -407,6 +435,13 @@ def onConnected(interface):
|
||||
print(f"Sending telemetry request to {args.dest} (this could take a while)")
|
||||
interface.sendTelemetry(destinationId=args.dest, wantResponse=True)
|
||||
|
||||
if args.request_position:
|
||||
if args.dest == BROADCAST_ADDR:
|
||||
meshtastic.util.our_exit("Warning: Must use a destination node ID.")
|
||||
else:
|
||||
print(f"Sending position request to {args.dest} (this could take a while)")
|
||||
interface.sendPosition(destinationId=args.dest, wantResponse=True)
|
||||
|
||||
if args.gpio_wrb or args.gpio_rd or args.gpio_watch:
|
||||
if args.dest == BROADCAST_ADDR:
|
||||
meshtastic.util.our_exit("Warning: Must use a destination node ID.")
|
||||
@@ -472,7 +507,7 @@ def onConnected(interface):
|
||||
print("Writing modified preferences to device")
|
||||
node.writeConfig(field)
|
||||
else:
|
||||
if Globals.getInstance().get_camel_case():
|
||||
if mt_config.camel_case:
|
||||
print(
|
||||
f"{node.localConfig.__class__.__name__} and {node.moduleConfig.__class__.__name__} do not have an attribute {pref[0]}."
|
||||
)
|
||||
@@ -529,15 +564,15 @@ def onConnected(interface):
|
||||
localConfig = interface.localNode.localConfig
|
||||
|
||||
if "alt" in configuration["location"]:
|
||||
alt = int(configuration["location"]["alt"])
|
||||
alt = int(configuration["location"]["alt"] or 0)
|
||||
localConfig.position.fixed_position = True
|
||||
print(f"Fixing altitude at {alt} meters")
|
||||
if "lat" in configuration["location"]:
|
||||
lat = float(configuration["location"]["lat"])
|
||||
lat = float(configuration["location"]["lat"] or 0)
|
||||
localConfig.position.fixed_position = True
|
||||
print(f"Fixing latitude at {lat} degrees")
|
||||
if "lon" in configuration["location"]:
|
||||
lon = float(configuration["location"]["lon"])
|
||||
lon = float(configuration["location"]["lon"] or 0)
|
||||
localConfig.position.fixed_position = True
|
||||
print(f"Fixing longitude at {lon} degrees")
|
||||
print("Setting device position")
|
||||
@@ -547,12 +582,7 @@ def onConnected(interface):
|
||||
if "config" in configuration:
|
||||
localConfig = interface.getNode(args.dest).localConfig
|
||||
for section in configuration["config"]:
|
||||
for pref in configuration["config"][section]:
|
||||
setPref(
|
||||
localConfig,
|
||||
f"{meshtastic.util.camel_to_snake(section)}.{pref}",
|
||||
str(configuration["config"][section][pref]),
|
||||
)
|
||||
traverseConfig(section, configuration["config"][section], localConfig)
|
||||
interface.getNode(args.dest).writeConfig(
|
||||
meshtastic.util.camel_to_snake(section)
|
||||
)
|
||||
@@ -560,12 +590,7 @@ def onConnected(interface):
|
||||
if "module_config" in configuration:
|
||||
moduleConfig = interface.getNode(args.dest).moduleConfig
|
||||
for section in configuration["module_config"]:
|
||||
for pref in configuration["module_config"][section]:
|
||||
setPref(
|
||||
moduleConfig,
|
||||
f"{meshtastic.util.camel_to_snake(section)}.{pref}",
|
||||
str(configuration["module_config"][section][pref]),
|
||||
)
|
||||
traverseConfig(section, configuration["module_config"][section], moduleConfig)
|
||||
interface.getNode(args.dest).writeConfig(
|
||||
meshtastic.util.camel_to_snake(section)
|
||||
)
|
||||
@@ -585,7 +610,7 @@ def onConnected(interface):
|
||||
# handle changing channels
|
||||
|
||||
if args.ch_add:
|
||||
channelIndex = our_globals.get_channel_index()
|
||||
channelIndex = mt_config.channel_index
|
||||
if channelIndex is not None:
|
||||
# Since we set the channel index after adding a channel, don't allow --ch-index
|
||||
meshtastic.util.our_exit(
|
||||
@@ -616,12 +641,12 @@ def onConnected(interface):
|
||||
n.writeChannel(ch.index)
|
||||
if channelIndex is None:
|
||||
print(f"Setting newly-added channel's {ch.index} as '--ch-index' for further modifications")
|
||||
our_globals.set_channel_index(ch.index)
|
||||
mt_config.channel_index = ch.index
|
||||
|
||||
if args.ch_del:
|
||||
closeNow = True
|
||||
|
||||
channelIndex = our_globals.get_channel_index()
|
||||
channelIndex = mt_config.channel_index
|
||||
if channelIndex is None:
|
||||
meshtastic.util.our_exit(
|
||||
"Warning: Need to specify '--ch-index' for '--ch-del'.", 1
|
||||
@@ -637,7 +662,7 @@ def onConnected(interface):
|
||||
|
||||
def setSimpleConfig(modem_preset):
|
||||
"""Set one of the simple modem_config"""
|
||||
channelIndex = our_globals.get_channel_index()
|
||||
channelIndex = mt_config.channel_index
|
||||
if channelIndex is not None and channelIndex > 0:
|
||||
meshtastic.util.our_exit(
|
||||
"Warning: Cannot set modem preset for non-primary channel", 1
|
||||
@@ -672,7 +697,7 @@ def onConnected(interface):
|
||||
if args.ch_set or args.ch_enable or args.ch_disable:
|
||||
closeNow = True
|
||||
|
||||
channelIndex = our_globals.get_channel_index()
|
||||
channelIndex = mt_config.channel_index
|
||||
if channelIndex is None:
|
||||
meshtastic.util.our_exit("Warning: Need to specify '--ch-index'.", 1)
|
||||
ch = interface.getNode(args.dest).channels[channelIndex]
|
||||
@@ -827,7 +852,7 @@ def printConfig(config):
|
||||
names = []
|
||||
for field in config.message_type.fields:
|
||||
tmp_name = f"{config_section.name}.{field.name}"
|
||||
if Globals.getInstance().get_camel_case():
|
||||
if mt_config.camel_case:
|
||||
tmp_name = meshtastic.util.snake_to_camel(tmp_name)
|
||||
names.append(tmp_name)
|
||||
for temp_name in sorted(names):
|
||||
@@ -872,23 +897,26 @@ def export_config(interface):
|
||||
if owner_short:
|
||||
configObj["owner_short"] = owner_short
|
||||
if channel_url:
|
||||
if Globals.getInstance().get_camel_case():
|
||||
if mt_config.camel_case:
|
||||
configObj["channelUrl"] = channel_url
|
||||
else:
|
||||
configObj["channel_url"] = channel_url
|
||||
if lat or lon or alt:
|
||||
configObj["location"] = {"lat": lat, "lon": lon, "alt": alt}
|
||||
# lat and lon don't make much sense without the other (so fill with 0s), and alt isn't meaningful without both
|
||||
if lat or lon:
|
||||
configObj["location"] = {"lat": lat or float(0), "lon": lon or float(0)}
|
||||
if alt:
|
||||
configObj["location"]["alt"] = alt
|
||||
|
||||
config = MessageToDict(interface.localNode.localConfig)
|
||||
if config:
|
||||
# Convert inner keys to correct snake/camelCase
|
||||
prefs = {}
|
||||
for pref in config:
|
||||
if Globals.getInstance().get_camel_case():
|
||||
if mt_config.camel_case:
|
||||
prefs[meshtastic.util.snake_to_camel(pref)] = config[pref]
|
||||
else:
|
||||
prefs[pref] = config[pref]
|
||||
if Globals.getInstance().get_camel_case():
|
||||
if mt_config.camel_case:
|
||||
configObj["config"] = config
|
||||
else:
|
||||
configObj["config"] = config
|
||||
@@ -900,7 +928,7 @@ def export_config(interface):
|
||||
for pref in module_config:
|
||||
if len(module_config[pref]) > 0:
|
||||
prefs[pref] = module_config[pref]
|
||||
if Globals.getInstance().get_camel_case():
|
||||
if mt_config.camel_case:
|
||||
configObj["module_config"] = prefs
|
||||
else:
|
||||
configObj["module_config"] = prefs
|
||||
@@ -914,9 +942,8 @@ def export_config(interface):
|
||||
def common():
|
||||
"""Shared code for all of our command line wrappers"""
|
||||
logfile = None
|
||||
our_globals = Globals.getInstance()
|
||||
args = our_globals.get_args()
|
||||
parser = our_globals.get_parser()
|
||||
args = mt_config.args
|
||||
parser = mt_config.parser
|
||||
logging.basicConfig(
|
||||
level=logging.DEBUG if (args.debug or args.listen) else logging.INFO,
|
||||
format="%(levelname)s file:%(filename)s %(funcName)s line:%(lineno)s %(message)s",
|
||||
@@ -932,7 +959,7 @@ def common():
|
||||
|
||||
if args.ch_index is not None:
|
||||
channelIndex = int(args.ch_index)
|
||||
our_globals.set_channel_index(channelIndex)
|
||||
mt_config.channel_index = channelIndex
|
||||
|
||||
if not args.dest:
|
||||
args.dest = BROADCAST_ADDR
|
||||
@@ -967,7 +994,7 @@ def common():
|
||||
# Note: using "line buffering"
|
||||
# pylint: disable=R1732
|
||||
logfile = open(args.seriallog, "w+", buffering=1, encoding="utf8")
|
||||
our_globals.set_logfile(logfile)
|
||||
mt_config.logfile = logfile
|
||||
|
||||
subscribe()
|
||||
if args.ble_scan:
|
||||
@@ -1058,9 +1085,8 @@ def addConnectionArgs(parser: argparse.ArgumentParser) -> argparse.ArgumentParse
|
||||
|
||||
def initParser():
|
||||
"""Initialize the command line argument parsing."""
|
||||
our_globals = Globals.getInstance()
|
||||
parser = our_globals.get_parser()
|
||||
args = our_globals.get_args()
|
||||
parser = mt_config.parser
|
||||
args = mt_config.args
|
||||
|
||||
# The "Help" group includes the help option and other informational stuff about the CLI itself
|
||||
outerHelpGroup = parser.add_argument_group('Help')
|
||||
@@ -1281,9 +1307,17 @@ def initParser():
|
||||
)
|
||||
|
||||
group.add_argument(
|
||||
"--request-telemetry",
|
||||
"--request-telemetry",
|
||||
help="Request telemetry from a node. "
|
||||
"You need pass the destination ID as argument with '--dest'. "
|
||||
"You need to pass the destination ID as argument with '--dest'. "
|
||||
"For repeaters, the nodeNum is required.",
|
||||
action="store_true",
|
||||
)
|
||||
|
||||
group.add_argument(
|
||||
"--request-position",
|
||||
help="Request the position from a nade. "
|
||||
"You need to pass the destination ID as an argument with '--dest'. "
|
||||
"For repeaters, the nodeNum is required.",
|
||||
action="store_true",
|
||||
)
|
||||
@@ -1332,9 +1366,13 @@ def initParser():
|
||||
action="store_true",
|
||||
)
|
||||
|
||||
group.add_argument(
|
||||
"--remove-node",
|
||||
help="Tell the destination node to remove a specific node from its DB, by node number or ID"
|
||||
)
|
||||
group.add_argument(
|
||||
"--reset-nodedb",
|
||||
help="Tell the destination node clear its list of nodes",
|
||||
help="Tell the destination node to clear its list of nodes",
|
||||
action="store_true",
|
||||
)
|
||||
|
||||
@@ -1422,34 +1460,32 @@ def initParser():
|
||||
|
||||
|
||||
args = parser.parse_args()
|
||||
our_globals.set_args(args)
|
||||
our_globals.set_parser(parser)
|
||||
mt_config.args = args
|
||||
mt_config.parser = parser
|
||||
|
||||
|
||||
def main():
|
||||
"""Perform command line meshtastic operations"""
|
||||
our_globals = Globals.getInstance()
|
||||
parser = argparse.ArgumentParser(
|
||||
add_help=False,
|
||||
epilog="If no connection arguments are specified, we search for a compatible serial device, "
|
||||
"and if none is found, then attempt a TCP connection to localhost.")
|
||||
our_globals.set_parser(parser)
|
||||
mt_config.parser = parser
|
||||
initParser()
|
||||
common()
|
||||
logfile = our_globals.get_logfile()
|
||||
logfile = mt_config.logfile
|
||||
if logfile:
|
||||
logfile.close()
|
||||
|
||||
|
||||
def tunnelMain():
|
||||
"""Run a meshtastic IP tunnel"""
|
||||
our_globals = Globals.getInstance()
|
||||
parser = argparse.ArgumentParser(add_help=False)
|
||||
our_globals.set_parser(parser)
|
||||
mt_config.parser = parser
|
||||
initParser()
|
||||
args = our_globals.get_args()
|
||||
args = mt_config.args
|
||||
args.tunnel = True
|
||||
our_globals.set_args(args)
|
||||
mt_config.args = args
|
||||
common()
|
||||
|
||||
|
||||
|
||||
@@ -575,27 +575,25 @@ class Config(google.protobuf.message.Message):
|
||||
DEVICE_BATTERY_INA_ADDRESS_FIELD_NUMBER: builtins.int
|
||||
is_power_saving: builtins.bool
|
||||
"""
|
||||
If set, we are powered from a low-current source (i.e. solar), so even if it looks like we have power flowing in
|
||||
we should try to minimize power consumption as much as possible.
|
||||
YOU DO NOT NEED TO SET THIS IF YOU'VE set is_router (it is implied in that case).
|
||||
Advanced Option
|
||||
Description: Will sleep everything as much as possible, for the tracker and sensor role this will also include the lora radio.
|
||||
Don't use this setting if you want to use your device with the phone apps or are using a device without a user button.
|
||||
Technical Details: Works for ESP32 devices and NRF52 devices in the Sensor or Tracker roles
|
||||
"""
|
||||
on_battery_shutdown_after_secs: builtins.int
|
||||
"""
|
||||
If non-zero, the device will fully power off this many seconds after external power is removed.
|
||||
Description: If non-zero, the device will fully power off this many seconds after external power is removed.
|
||||
"""
|
||||
adc_multiplier_override: builtins.float
|
||||
"""
|
||||
Ratio of voltage divider for battery pin eg. 3.20 (R1=100k, R2=220k)
|
||||
Overrides the ADC_MULTIPLIER defined in variant for battery voltage calculation.
|
||||
Should be set to floating point value between 2 and 4
|
||||
Fixes issues on Heltec v2
|
||||
https://meshtastic.org/docs/configuration/radio/power/#adc-multiplier-override
|
||||
Should be set to floating point value between 2 and 6
|
||||
"""
|
||||
wait_bluetooth_secs: builtins.int
|
||||
"""
|
||||
Wait Bluetooth Seconds
|
||||
The number of seconds for to wait before turning off BLE in No Bluetooth states
|
||||
0 for default of 1 minute
|
||||
Description: The number of seconds for to wait before turning off BLE in No Bluetooth states
|
||||
Technical Details: ESP32 Only 0 for default of 1 minute
|
||||
"""
|
||||
sds_secs: builtins.int
|
||||
"""
|
||||
@@ -606,16 +604,13 @@ class Config(google.protobuf.message.Message):
|
||||
"""
|
||||
ls_secs: builtins.int
|
||||
"""
|
||||
Light Sleep Seconds
|
||||
In light sleep the CPU is suspended, LoRa radio is on, BLE is off an GPS is on
|
||||
ESP32 Only
|
||||
0 for default of 300
|
||||
Description: In light sleep the CPU is suspended, LoRa radio is on, BLE is off an GPS is on
|
||||
Technical Details: ESP32 Only 0 for default of 300
|
||||
"""
|
||||
min_wake_secs: builtins.int
|
||||
"""
|
||||
Minimum Wake Seconds
|
||||
While in light sleep when we receive packets on the LoRa radio we will wake and handle them and stay awake in no BLE mode for this value
|
||||
0 for default of 10 seconds
|
||||
Description: While in light sleep when we receive packets on the LoRa radio we will wake and handle them and stay awake in no BLE mode for this value
|
||||
Technical Details: ESP32 Only 0 for default of 10 seconds
|
||||
"""
|
||||
device_battery_ina_address: builtins.int
|
||||
"""
|
||||
|
||||
@@ -1,96 +0,0 @@
|
||||
"""Globals singleton class.
|
||||
|
||||
Instead of using a global, stuff your variables in this "trash can".
|
||||
This is not much better than using python's globals, but it allows
|
||||
us to better test meshtastic. Plus, there are some weird python
|
||||
global issues/gotcha that we can hopefully avoid by using this
|
||||
class instead.
|
||||
|
||||
"""
|
||||
|
||||
|
||||
class Globals:
|
||||
"""Globals class is a Singleton."""
|
||||
|
||||
__instance = None
|
||||
|
||||
@staticmethod
|
||||
def getInstance():
|
||||
"""Get an instance of the Globals class."""
|
||||
if Globals.__instance is None:
|
||||
Globals()
|
||||
return Globals.__instance
|
||||
|
||||
def __init__(self):
|
||||
"""Constructor for the Globals CLass"""
|
||||
if Globals.__instance is not None:
|
||||
raise Exception("This class is a singleton") # pylint: disable=W0719
|
||||
else:
|
||||
Globals.__instance = self
|
||||
self.args = None
|
||||
self.parser = None
|
||||
self.channel_index = None
|
||||
self.logfile = None
|
||||
self.tunnelInstance = None
|
||||
# TODO: to migrate to camel_case for v1.3 change this value to True
|
||||
self.camel_case = False
|
||||
|
||||
def reset(self):
|
||||
"""Reset all of our globals. If you add a member, add it to this method, too."""
|
||||
self.args = None
|
||||
self.parser = None
|
||||
self.channel_index = None
|
||||
self.logfile = None
|
||||
self.tunnelInstance = None
|
||||
# TODO: to migrate to camel_case for v1.3 change this value to True
|
||||
self.camel_case = False
|
||||
|
||||
# setters
|
||||
def set_args(self, args):
|
||||
"""Set the args"""
|
||||
self.args = args
|
||||
|
||||
def set_parser(self, parser):
|
||||
"""Set the parser"""
|
||||
self.parser = parser
|
||||
|
||||
def set_channel_index(self, channel_index):
|
||||
"""Set the channel_index"""
|
||||
self.channel_index = channel_index
|
||||
|
||||
def set_logfile(self, logfile):
|
||||
"""Set the logfile"""
|
||||
self.logfile = logfile
|
||||
|
||||
def set_tunnelInstance(self, tunnelInstance):
|
||||
"""Set the tunnelInstance"""
|
||||
self.tunnelInstance = tunnelInstance
|
||||
|
||||
def set_camel_case(self):
|
||||
"""Force using camelCase for things like prefs/set/set"""
|
||||
self.camel_case = True
|
||||
|
||||
# getters
|
||||
def get_args(self):
|
||||
"""Get args"""
|
||||
return self.args
|
||||
|
||||
def get_parser(self):
|
||||
"""Get parser"""
|
||||
return self.parser
|
||||
|
||||
def get_channel_index(self):
|
||||
"""Get channel_index"""
|
||||
return self.channel_index
|
||||
|
||||
def get_logfile(self):
|
||||
"""Get logfile"""
|
||||
return self.logfile
|
||||
|
||||
def get_tunnelInstance(self):
|
||||
"""Get tunnelInstance"""
|
||||
return self.tunnelInstance
|
||||
|
||||
def get_camel_case(self):
|
||||
"""Get whether or not to use camelCase"""
|
||||
return self.camel_case
|
||||
@@ -10,6 +10,8 @@ import threading
|
||||
import time
|
||||
from datetime import datetime
|
||||
|
||||
from typing import Any, Callable, Dict, List, Optional, Union
|
||||
|
||||
import google.protobuf.json_format
|
||||
import timeago # type: ignore[import-untyped]
|
||||
from pubsub import pub # type: ignore[import-untyped]
|
||||
@@ -54,7 +56,7 @@ class MeshInterface:
|
||||
self.message = message
|
||||
super().__init__(self.message)
|
||||
|
||||
def __init__(self, debugOut=None, noProto=False):
|
||||
def __init__(self, debugOut=None, noProto: bool=False) -> None:
|
||||
"""Constructor
|
||||
|
||||
Keyword Arguments:
|
||||
@@ -62,27 +64,27 @@ class MeshInterface:
|
||||
link - just be a dumb serial client.
|
||||
"""
|
||||
self.debugOut = debugOut
|
||||
self.nodes = None # FIXME
|
||||
self.isConnected = threading.Event()
|
||||
self.noProto = noProto
|
||||
self.localNode = meshtastic.node.Node(self, -1) # We fixup nodenum later
|
||||
self.myInfo = None # We don't have device info yet
|
||||
self.metadata = None # We don't have device metadata yet
|
||||
self.responseHandlers = {} # A map from request ID to the handler
|
||||
self.nodes: Optional[Dict[str,Dict]] = None # FIXME
|
||||
self.isConnected: threading.Event = threading.Event()
|
||||
self.noProto: bool = noProto
|
||||
self.localNode: meshtastic.node.Node = meshtastic.node.Node(self, -1) # We fixup nodenum later
|
||||
self.myInfo: Optional[mesh_pb2.MyNodeInfo] = None # We don't have device info yet
|
||||
self.metadata: Optional[mesh_pb2.DeviceMetadata] = None # We don't have device metadata yet
|
||||
self.responseHandlers: Dict[int,ResponseHandler] = {} # A map from request ID to the handler
|
||||
self.failure = (
|
||||
None # If we've encountered a fatal exception it will be kept here
|
||||
)
|
||||
self._timeout = Timeout()
|
||||
self._acknowledgment = Acknowledgment()
|
||||
self.heartbeatTimer = None
|
||||
self._timeout: Timeout = Timeout()
|
||||
self._acknowledgment: Acknowledgment = Acknowledgment()
|
||||
self.heartbeatTimer: Optional[threading.Timer] = None
|
||||
random.seed() # FIXME, we should not clobber the random seedval here, instead tell user they must call it
|
||||
self.currentPacketId = random.randint(0, 0xFFFFFFFF)
|
||||
self.nodesByNum = None
|
||||
self.configId = None
|
||||
self.gotResponse = False # used in gpio read
|
||||
self.mask = None # used in gpio read and gpio watch
|
||||
self.queueStatus = None
|
||||
self.queue = collections.OrderedDict()
|
||||
self.currentPacketId: int = random.randint(0, 0xFFFFFFFF)
|
||||
self.nodesByNum: Optional[Dict[int, Dict]] = None
|
||||
self.configId: Optional[int] = None
|
||||
self.gotResponse: bool = False # used in gpio read
|
||||
self.mask: Optional[int] = None # used in gpio read and gpio watch
|
||||
self.queueStatus: Optional[mesh_pb2.QueueStatus] = None
|
||||
self.queue: collections.OrderedDict = collections.OrderedDict()
|
||||
|
||||
def close(self):
|
||||
"""Shutdown this interface"""
|
||||
@@ -103,7 +105,7 @@ class MeshInterface:
|
||||
logging.error(f"Traceback: {traceback}")
|
||||
self.close()
|
||||
|
||||
def showInfo(self, file=sys.stdout): # pylint: disable=W0613
|
||||
def showInfo(self, file=sys.stdout) -> str: # pylint: disable=W0613
|
||||
"""Show human readable summary about this object"""
|
||||
owner = f"Owner: {self.getLongName()} ({self.getShortName()})"
|
||||
myinfo = ""
|
||||
@@ -135,20 +137,20 @@ class MeshInterface:
|
||||
print(infos)
|
||||
return infos
|
||||
|
||||
def showNodes(self, includeSelf=True, file=sys.stdout): # pylint: disable=W0613
|
||||
def showNodes(self, includeSelf: bool=True, file=sys.stdout) -> str: # pylint: disable=W0613
|
||||
"""Show table summary of nodes in mesh"""
|
||||
|
||||
def formatFloat(value, precision=2, unit=""):
|
||||
def formatFloat(value, precision=2, unit="") -> Optional[str]:
|
||||
"""Format a float value with precision."""
|
||||
return f"{value:.{precision}f}{unit}" if value else None
|
||||
|
||||
def getLH(ts):
|
||||
def getLH(ts) -> Optional[str]:
|
||||
"""Format last heard"""
|
||||
return (
|
||||
datetime.fromtimestamp(ts).strftime("%Y-%m-%d %H:%M:%S") if ts else None
|
||||
)
|
||||
|
||||
def getTimeAgo(ts):
|
||||
def getTimeAgo(ts) -> Optional[str]:
|
||||
"""Format how long ago have we heard from this node (aka timeago)."""
|
||||
return (
|
||||
timeago.format(datetime.fromtimestamp(ts), datetime.now())
|
||||
@@ -156,7 +158,7 @@ class MeshInterface:
|
||||
else None
|
||||
)
|
||||
|
||||
rows = []
|
||||
rows: List[Dict[str, Any]] = []
|
||||
if self.nodesByNum:
|
||||
logging.debug(f"self.nodes:{self.nodes}")
|
||||
for node in self.nodesByNum.values():
|
||||
@@ -208,6 +210,7 @@ class MeshInterface:
|
||||
row.update(
|
||||
{
|
||||
"SNR": formatFloat(node.get("snr"), 2, " dB"),
|
||||
"Hops Away": node.get("hopsAway", "unknown"),
|
||||
"Channel": node.get("channel"),
|
||||
"LastHeard": getLH(node.get("lastHeard")),
|
||||
"Since": getTimeAgo(node.get("lastHeard")),
|
||||
@@ -224,7 +227,7 @@ class MeshInterface:
|
||||
print(table)
|
||||
return table
|
||||
|
||||
def getNode(self, nodeId, requestChannels=True):
|
||||
def getNode(self, nodeId: str, requestChannels: bool=True) -> meshtastic.node.Node:
|
||||
"""Return a node object which contains device settings and channel info"""
|
||||
if nodeId in (LOCAL_ADDR, BROADCAST_ADDR):
|
||||
return self.localNode
|
||||
@@ -241,11 +244,11 @@ class MeshInterface:
|
||||
def sendText(
|
||||
self,
|
||||
text: str,
|
||||
destinationId=BROADCAST_ADDR,
|
||||
wantAck=False,
|
||||
wantResponse=False,
|
||||
onResponse=None,
|
||||
channelIndex=0,
|
||||
destinationId: Union[int, str]=BROADCAST_ADDR,
|
||||
wantAck: bool=False,
|
||||
wantResponse: bool=False,
|
||||
onResponse: Optional[Callable[[mesh_pb2.MeshPacket], Any]]=None,
|
||||
channelIndex: int=0,
|
||||
):
|
||||
"""Send a utf8 string to some other node, if the node has a display it
|
||||
will also be shown on the device.
|
||||
@@ -280,12 +283,12 @@ class MeshInterface:
|
||||
def sendData(
|
||||
self,
|
||||
data,
|
||||
destinationId=BROADCAST_ADDR,
|
||||
portNum=portnums_pb2.PortNum.PRIVATE_APP,
|
||||
wantAck=False,
|
||||
wantResponse=False,
|
||||
onResponse=None,
|
||||
channelIndex=0,
|
||||
destinationId: Union[int, str]=BROADCAST_ADDR,
|
||||
portNum: portnums_pb2.PortNum.ValueType=portnums_pb2.PortNum.PRIVATE_APP,
|
||||
wantAck: bool=False,
|
||||
wantResponse: bool=False,
|
||||
onResponse: Optional[Callable[[mesh_pb2.MeshPacket], Any]]=None,
|
||||
channelIndex: int=0,
|
||||
):
|
||||
"""Send a data packet to some other node
|
||||
|
||||
@@ -334,19 +337,20 @@ class MeshInterface:
|
||||
meshPacket.id = self._generatePacketId()
|
||||
|
||||
if onResponse is not None:
|
||||
logging.debug(f"Setting a response handler for requestId {meshPacket.id}")
|
||||
self._addResponseHandler(meshPacket.id, onResponse)
|
||||
p = self._sendPacket(meshPacket, destinationId, wantAck=wantAck)
|
||||
return p
|
||||
|
||||
def sendPosition(
|
||||
self,
|
||||
latitude=0.0,
|
||||
longitude=0.0,
|
||||
altitude=0,
|
||||
timeSec=0,
|
||||
destinationId=BROADCAST_ADDR,
|
||||
wantAck=False,
|
||||
wantResponse=False,
|
||||
latitude: float=0.0,
|
||||
longitude: float=0.0,
|
||||
altitude: int=0,
|
||||
timeSec: int=0,
|
||||
destinationId: Union[int, str]=BROADCAST_ADDR,
|
||||
wantAck: bool=False,
|
||||
wantResponse: bool=False,
|
||||
):
|
||||
"""
|
||||
Send a position packet to some other node (normally a broadcast)
|
||||
@@ -373,19 +377,56 @@ class MeshInterface:
|
||||
logging.debug(f"p.altitude:{p.altitude}")
|
||||
|
||||
if timeSec == 0:
|
||||
timeSec = time.time() # returns unix timestamp in seconds
|
||||
p.time = int(timeSec)
|
||||
timeSec = int(time.time()) # returns unix timestamp in seconds
|
||||
p.time = timeSec
|
||||
logging.debug(f"p.time:{p.time}")
|
||||
|
||||
return self.sendData(
|
||||
if wantResponse:
|
||||
onResponse = self.onResponsePosition
|
||||
else:
|
||||
onResponse = None
|
||||
|
||||
d = self.sendData(
|
||||
p,
|
||||
destinationId,
|
||||
portNum=portnums_pb2.PortNum.POSITION_APP,
|
||||
wantAck=wantAck,
|
||||
wantResponse=wantResponse,
|
||||
onResponse=onResponse,
|
||||
)
|
||||
if wantResponse:
|
||||
self.waitForPosition()
|
||||
return d
|
||||
|
||||
def sendTraceRoute(self, dest, hopLimit):
|
||||
def onResponsePosition(self, p):
|
||||
"""on response for position"""
|
||||
if p["decoded"]["portnum"] == 'POSITION_APP':
|
||||
self._acknowledgment.receivedPosition = True
|
||||
position = mesh_pb2.Position()
|
||||
position.ParseFromString(p["decoded"]["payload"])
|
||||
|
||||
ret = "Position received: "
|
||||
if position.latitude_i != 0 and position.longitude_i != 0:
|
||||
ret += f"({position.latitude_i * 10**-7}, {position.longitude_i * 10**-7})"
|
||||
else:
|
||||
ret += "(unknown)"
|
||||
if position.altitude != 0:
|
||||
ret += f" {position.altitude}m"
|
||||
|
||||
if position.precision_bits not in [0,32]:
|
||||
ret += f" precision:{position.precision_bits}"
|
||||
elif position.precision_bits == 32:
|
||||
ret += " full precision"
|
||||
elif position.precision_bits == 0:
|
||||
ret += " position disabled"
|
||||
|
||||
print(ret)
|
||||
|
||||
elif p["decoded"]["portnum"] == 'ROUTING_APP':
|
||||
if p["decoded"]["routing"]["errorReason"] == 'NO_RESPONSE':
|
||||
our_exit("No response from node. At least firmware 2.1.22 is required on the destination node.")
|
||||
|
||||
def sendTraceRoute(self, dest: Union[int, str], hopLimit: int):
|
||||
"""Send the trace route"""
|
||||
r = mesh_pb2.RouteDiscovery()
|
||||
self.sendData(
|
||||
@@ -396,7 +437,7 @@ class MeshInterface:
|
||||
onResponse=self.onResponseTraceRoute,
|
||||
)
|
||||
# extend timeout based on number of nodes, limit by configured hopLimit
|
||||
waitFactor = min(len(self.nodes) - 1, hopLimit)
|
||||
waitFactor = min(len(self.nodes) - 1 if self.nodes else 0, hopLimit)
|
||||
self.waitForTraceRoute(waitFactor)
|
||||
|
||||
def onResponseTraceRoute(self, p):
|
||||
@@ -441,11 +482,6 @@ class MeshInterface:
|
||||
else:
|
||||
onResponse = None
|
||||
|
||||
if destinationId.startswith("!"):
|
||||
destinationId = int(destinationId[1:], 16)
|
||||
else:
|
||||
destinationId = int(destinationId)
|
||||
|
||||
self.sendData(
|
||||
r,
|
||||
destinationId=destinationId,
|
||||
@@ -479,10 +515,10 @@ class MeshInterface:
|
||||
if p["decoded"]["routing"]["errorReason"] == 'NO_RESPONSE':
|
||||
our_exit("No response from node. At least firmware 2.1.22 is required on the destination node.")
|
||||
|
||||
def _addResponseHandler(self, requestId, callback):
|
||||
def _addResponseHandler(self, requestId: int, callback: Callable):
|
||||
self.responseHandlers[requestId] = ResponseHandler(callback)
|
||||
|
||||
def _sendPacket(self, meshPacket, destinationId=BROADCAST_ADDR, wantAck=False):
|
||||
def _sendPacket(self, meshPacket: mesh_pb2.MeshPacket, destinationId: Union[int,str]=BROADCAST_ADDR, wantAck: bool=False):
|
||||
"""Send a MeshPacket to the specified node (or if unspecified, broadcast).
|
||||
You probably don't want this - use sendData instead.
|
||||
|
||||
@@ -496,7 +532,7 @@ class MeshInterface:
|
||||
|
||||
toRadio = mesh_pb2.ToRadio()
|
||||
|
||||
nodeNum = 0
|
||||
nodeNum: int = 0
|
||||
if destinationId is None:
|
||||
our_exit("Warning: destinationId must not be None")
|
||||
elif isinstance(destinationId, int):
|
||||
@@ -514,9 +550,10 @@ class MeshInterface:
|
||||
else:
|
||||
if self.nodes:
|
||||
node = self.nodes.get(destinationId)
|
||||
if not node:
|
||||
if node is None:
|
||||
our_exit(f"Warning: NodeId {destinationId} not found in DB")
|
||||
nodeNum = node["num"]
|
||||
else:
|
||||
nodeNum = node["num"]
|
||||
else:
|
||||
logging.warning("Warning: There were no self.nodes.")
|
||||
|
||||
@@ -568,9 +605,15 @@ class MeshInterface:
|
||||
if not success:
|
||||
raise MeshInterface.MeshInterfaceError("Timed out waiting for telemetry")
|
||||
|
||||
def getMyNodeInfo(self):
|
||||
def waitForPosition(self):
|
||||
"""Wait for position"""
|
||||
success = self._timeout.waitForPosition(self._acknowledgment)
|
||||
if not success:
|
||||
raise MeshInterface.MeshInterfaceError("Timed out waiting for position")
|
||||
|
||||
def getMyNodeInfo(self) -> Optional[Dict]:
|
||||
"""Get info about my node."""
|
||||
if self.myInfo is None:
|
||||
if self.myInfo is None or self.nodesByNum is None:
|
||||
return None
|
||||
logging.debug(f"self.nodesByNum:{self.nodesByNum}")
|
||||
return self.nodesByNum.get(self.myInfo.my_node_num)
|
||||
@@ -607,7 +650,7 @@ class MeshInterface:
|
||||
if self.failure:
|
||||
raise self.failure
|
||||
|
||||
def _generatePacketId(self):
|
||||
def _generatePacketId(self) -> int:
|
||||
"""Get a new unique packet ID"""
|
||||
if self.currentPacketId is None:
|
||||
raise MeshInterface.MeshInterfaceError("Not connected yet, can not generate packet")
|
||||
@@ -669,18 +712,18 @@ class MeshInterface:
|
||||
m.disconnect = True
|
||||
self._sendToRadio(m)
|
||||
|
||||
def _queueHasFreeSpace(self):
|
||||
def _queueHasFreeSpace(self) -> bool:
|
||||
# We never got queueStatus, maybe the firmware is old
|
||||
if self.queueStatus is None:
|
||||
return True
|
||||
return self.queueStatus.free > 0
|
||||
|
||||
def _queueClaim(self):
|
||||
def _queueClaim(self) -> None:
|
||||
if self.queueStatus is None:
|
||||
return
|
||||
self.queueStatus.free -= 1
|
||||
|
||||
def _sendToRadio(self, toRadio):
|
||||
def _sendToRadio(self, toRadio: mesh_pb2.ToRadio) -> None:
|
||||
"""Send a ToRadio protobuf to the device"""
|
||||
if self.noProto:
|
||||
logging.warning(
|
||||
@@ -729,18 +772,18 @@ class MeshInterface:
|
||||
self.queue[packetId] = packet
|
||||
# logging.warn("queue + resentQueue: " + " ".join(f'{k:08x}' for k in self.queue))
|
||||
|
||||
def _sendToRadioImpl(self, toRadio):
|
||||
def _sendToRadioImpl(self, toRadio: mesh_pb2.ToRadio) -> None:
|
||||
"""Send a ToRadio protobuf to the device"""
|
||||
logging.error(f"Subclass must provide toradio: {toRadio}")
|
||||
|
||||
def _handleConfigComplete(self):
|
||||
def _handleConfigComplete(self) -> None:
|
||||
"""
|
||||
Done with initial config messages, now send regular MeshPackets
|
||||
to ask for settings and channels
|
||||
"""
|
||||
self.localNode.requestChannels()
|
||||
|
||||
def _handleQueueStatusFromRadio(self, queueStatus):
|
||||
def _handleQueueStatusFromRadio(self, queueStatus) -> None:
|
||||
self.queueStatus = queueStatus
|
||||
logging.debug(
|
||||
f"TX QUEUE free {queueStatus.free} of {queueStatus.maxlen}, res = {queueStatus.res}, id = {queueStatus.mesh_packet_id:08x} "
|
||||
@@ -891,7 +934,7 @@ class MeshInterface:
|
||||
else:
|
||||
logging.debug("Unexpected FromRadio payload")
|
||||
|
||||
def _fixupPosition(self, position):
|
||||
def _fixupPosition(self, position: Dict) -> Dict:
|
||||
"""Convert integer lat/lon into floats
|
||||
|
||||
Arguments:
|
||||
@@ -1030,14 +1073,16 @@ class MeshInterface:
|
||||
# Is this message in response to a request, if so, look for a handler
|
||||
requestId = decoded.get("requestId")
|
||||
if requestId is not None:
|
||||
logging.debug(f"Got a response for requestId {requestId}")
|
||||
# We ignore ACK packets, but send NAKs and data responses to the handlers
|
||||
routing = decoded.get("routing")
|
||||
isAck = routing is not None and ("errorReason" not in routing)
|
||||
isAck = routing is not None and ("errorReason" not in routing or routing["errorReason"] == "NONE")
|
||||
if not isAck:
|
||||
# we keep the responseHandler in dict until we get a non ack
|
||||
handler = self.responseHandlers.pop(requestId, None)
|
||||
if handler is not None:
|
||||
if not isAck or (isAck and handler.__name__ == "onAckNak"):
|
||||
logging.debug(f"Calling response handler for requestId {requestId}")
|
||||
handler.callback(asDict)
|
||||
|
||||
logging.debug(f"Publishing {topic}: packet={stripnl(asDict)} ")
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -267,6 +267,10 @@ class _HardwareModelEnumTypeWrapper(google.protobuf.internal.enum_type_wrapper._
|
||||
Teledatics TD-LORAC NRF52840 based M.2 LoRA module
|
||||
Compatible with the TD-WRLS development board
|
||||
"""
|
||||
CDEBYTE_EORA_S3: _HardwareModel.ValueType # 61
|
||||
"""
|
||||
CDEBYTE EoRa-S3 board using their own MM modules, clone of LILYGO T3S3
|
||||
"""
|
||||
PRIVATE_HW: _HardwareModel.ValueType # 255
|
||||
"""
|
||||
------------------------------------------------------------------------------------------------------------------------------------------
|
||||
@@ -519,6 +523,10 @@ TD_LORAC: HardwareModel.ValueType # 60
|
||||
Teledatics TD-LORAC NRF52840 based M.2 LoRA module
|
||||
Compatible with the TD-WRLS development board
|
||||
"""
|
||||
CDEBYTE_EORA_S3: HardwareModel.ValueType # 61
|
||||
"""
|
||||
CDEBYTE EoRa-S3 board using their own MM modules, clone of LILYGO T3S3
|
||||
"""
|
||||
PRIVATE_HW: HardwareModel.ValueType # 255
|
||||
"""
|
||||
------------------------------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
37
meshtastic/mt_config.py
Normal file
37
meshtastic/mt_config.py
Normal file
@@ -0,0 +1,37 @@
|
||||
"""
|
||||
Globals singleton class.
|
||||
|
||||
The Global object is gone, as are all its setters and getters. Instead the
|
||||
module itself is the singleton namespace, which can be imported into
|
||||
whichever module is used. The associated tests have also been removed,
|
||||
since we now rely on built in Python mechanisms.
|
||||
|
||||
This is intended to make the Python read more naturally, and to make the
|
||||
intention of the code clearer and more compact. It is merely a sticking
|
||||
plaster over the use of shared mt_config, but the coupling issues wil be dealt
|
||||
with rather more easily once the code is simplified by this change.
|
||||
|
||||
"""
|
||||
|
||||
def reset():
|
||||
"""
|
||||
Restore the namespace to pristine condition.
|
||||
"""
|
||||
# pylint: disable=W0603
|
||||
global args, parser, channel_index, logfile, tunnelInstance, camel_case
|
||||
args = None
|
||||
parser = None
|
||||
channel_index = None
|
||||
logfile = None
|
||||
tunnelInstance = None
|
||||
# TODO: to migrate to camel_case for v1.3 change this value to True
|
||||
camel_case = False
|
||||
|
||||
# These assignments are used instead of calling reset()
|
||||
# purely to shut pylint up.
|
||||
args = None
|
||||
parser = None
|
||||
channel_index = None
|
||||
logfile = None
|
||||
tunnelInstance = None
|
||||
camel_case = False
|
||||
@@ -5,6 +5,8 @@ import base64
|
||||
import logging
|
||||
import time
|
||||
|
||||
from typing import Union
|
||||
|
||||
from meshtastic import admin_pb2, apponly_pb2, channel_pb2, localonly_pb2, portnums_pb2
|
||||
from meshtastic.util import (
|
||||
Timeout,
|
||||
@@ -603,6 +605,23 @@ class Node:
|
||||
onResponse = self.onAckNak
|
||||
return self._sendAdmin(p, onResponse=onResponse)
|
||||
|
||||
def removeNode(self, nodeId: Union[int, str]):
|
||||
"""Tell the node to remove a specific node by ID"""
|
||||
if isinstance(nodeId, str):
|
||||
if nodeId.startswith("!"):
|
||||
nodeId = int(nodeId[1:], 16)
|
||||
else:
|
||||
nodeId = int(nodeId)
|
||||
|
||||
p = admin_pb2.AdminMessage()
|
||||
p.remove_by_nodenum = nodeId
|
||||
|
||||
if self == self.iface.localNode:
|
||||
onResponse = None
|
||||
else:
|
||||
onResponse = self.onAckNak
|
||||
return self._sendAdmin(p, onResponse=onResponse)
|
||||
|
||||
def resetNodeDb(self):
|
||||
"""Tell the node to reset its list of nodes."""
|
||||
p = admin_pb2.AdminMessage()
|
||||
@@ -740,9 +759,9 @@ class Node:
|
||||
def _sendAdmin(
|
||||
self,
|
||||
p: admin_pb2.AdminMessage,
|
||||
wantResponse=True,
|
||||
wantResponse: bool=True,
|
||||
onResponse=None,
|
||||
adminIndex=0,
|
||||
adminIndex: int=0,
|
||||
):
|
||||
"""Send an admin message to the specified node (or the local node if destNodeNum is zero)"""
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ _sym_db = _symbol_database.Default()
|
||||
|
||||
|
||||
|
||||
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1ameshtastic/telemetry.proto\x12\nmeshtastic\"i\n\rDeviceMetrics\x12\x15\n\rbattery_level\x18\x01 \x01(\r\x12\x0f\n\x07voltage\x18\x02 \x01(\x02\x12\x1b\n\x13\x63hannel_utilization\x18\x03 \x01(\x02\x12\x13\n\x0b\x61ir_util_tx\x18\x04 \x01(\x02\"\x9b\x01\n\x12\x45nvironmentMetrics\x12\x13\n\x0btemperature\x18\x01 \x01(\x02\x12\x19\n\x11relative_humidity\x18\x02 \x01(\x02\x12\x1b\n\x13\x62\x61rometric_pressure\x18\x03 \x01(\x02\x12\x16\n\x0egas_resistance\x18\x04 \x01(\x02\x12\x0f\n\x07voltage\x18\x05 \x01(\x02\x12\x0f\n\x07\x63urrent\x18\x06 \x01(\x02\"\x8c\x01\n\x0cPowerMetrics\x12\x13\n\x0b\x63h1_voltage\x18\x01 \x01(\x02\x12\x13\n\x0b\x63h1_current\x18\x02 \x01(\x02\x12\x13\n\x0b\x63h2_voltage\x18\x03 \x01(\x02\x12\x13\n\x0b\x63h2_current\x18\x04 \x01(\x02\x12\x13\n\x0b\x63h3_voltage\x18\x05 \x01(\x02\x12\x13\n\x0b\x63h3_current\x18\x06 \x01(\x02\"\xbf\x02\n\x11\x41irQualityMetrics\x12\x15\n\rpm10_standard\x18\x01 \x01(\r\x12\x15\n\rpm25_standard\x18\x02 \x01(\r\x12\x16\n\x0epm100_standard\x18\x03 \x01(\r\x12\x1a\n\x12pm10_environmental\x18\x04 \x01(\r\x12\x1a\n\x12pm25_environmental\x18\x05 \x01(\r\x12\x1b\n\x13pm100_environmental\x18\x06 \x01(\r\x12\x16\n\x0eparticles_03um\x18\x07 \x01(\r\x12\x16\n\x0eparticles_05um\x18\x08 \x01(\r\x12\x16\n\x0eparticles_10um\x18\t \x01(\r\x12\x16\n\x0eparticles_25um\x18\n \x01(\r\x12\x16\n\x0eparticles_50um\x18\x0b \x01(\r\x12\x17\n\x0fparticles_100um\x18\x0c \x01(\r\"\x89\x02\n\tTelemetry\x12\x0c\n\x04time\x18\x01 \x01(\x07\x12\x33\n\x0e\x64\x65vice_metrics\x18\x02 \x01(\x0b\x32\x19.meshtastic.DeviceMetricsH\x00\x12=\n\x13\x65nvironment_metrics\x18\x03 \x01(\x0b\x32\x1e.meshtastic.EnvironmentMetricsH\x00\x12<\n\x13\x61ir_quality_metrics\x18\x04 \x01(\x0b\x32\x1d.meshtastic.AirQualityMetricsH\x00\x12\x31\n\rpower_metrics\x18\x05 \x01(\x0b\x32\x18.meshtastic.PowerMetricsH\x00\x42\t\n\x07variant*\xe0\x01\n\x13TelemetrySensorType\x12\x10\n\x0cSENSOR_UNSET\x10\x00\x12\n\n\x06\x42ME280\x10\x01\x12\n\n\x06\x42ME680\x10\x02\x12\x0b\n\x07MCP9808\x10\x03\x12\n\n\x06INA260\x10\x04\x12\n\n\x06INA219\x10\x05\x12\n\n\x06\x42MP280\x10\x06\x12\t\n\x05SHTC3\x10\x07\x12\t\n\x05LPS22\x10\x08\x12\x0b\n\x07QMC6310\x10\t\x12\x0b\n\x07QMI8658\x10\n\x12\x0c\n\x08QMC5883L\x10\x0b\x12\t\n\x05SHT31\x10\x0c\x12\x0c\n\x08PMSA003I\x10\r\x12\x0b\n\x07INA3221\x10\x0e\x12\n\n\x06\x42MP085\x10\x0f\x42\x64\n\x13\x63om.geeksville.meshB\x0fTelemetryProtosZ\"github.com/meshtastic/go/generated\xaa\x02\x14Meshtastic.Protobufs\xba\x02\x00\x62\x06proto3')
|
||||
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1ameshtastic/telemetry.proto\x12\nmeshtastic\"\x81\x01\n\rDeviceMetrics\x12\x15\n\rbattery_level\x18\x01 \x01(\r\x12\x0f\n\x07voltage\x18\x02 \x01(\x02\x12\x1b\n\x13\x63hannel_utilization\x18\x03 \x01(\x02\x12\x13\n\x0b\x61ir_util_tx\x18\x04 \x01(\x02\x12\x16\n\x0euptime_seconds\x18\x05 \x01(\r\"\xa8\x01\n\x12\x45nvironmentMetrics\x12\x13\n\x0btemperature\x18\x01 \x01(\x02\x12\x19\n\x11relative_humidity\x18\x02 \x01(\x02\x12\x1b\n\x13\x62\x61rometric_pressure\x18\x03 \x01(\x02\x12\x16\n\x0egas_resistance\x18\x04 \x01(\x02\x12\x0f\n\x07voltage\x18\x05 \x01(\x02\x12\x0f\n\x07\x63urrent\x18\x06 \x01(\x02\x12\x0b\n\x03iaq\x18\x07 \x01(\r\"\x8c\x01\n\x0cPowerMetrics\x12\x13\n\x0b\x63h1_voltage\x18\x01 \x01(\x02\x12\x13\n\x0b\x63h1_current\x18\x02 \x01(\x02\x12\x13\n\x0b\x63h2_voltage\x18\x03 \x01(\x02\x12\x13\n\x0b\x63h2_current\x18\x04 \x01(\x02\x12\x13\n\x0b\x63h3_voltage\x18\x05 \x01(\x02\x12\x13\n\x0b\x63h3_current\x18\x06 \x01(\x02\"\xbf\x02\n\x11\x41irQualityMetrics\x12\x15\n\rpm10_standard\x18\x01 \x01(\r\x12\x15\n\rpm25_standard\x18\x02 \x01(\r\x12\x16\n\x0epm100_standard\x18\x03 \x01(\r\x12\x1a\n\x12pm10_environmental\x18\x04 \x01(\r\x12\x1a\n\x12pm25_environmental\x18\x05 \x01(\r\x12\x1b\n\x13pm100_environmental\x18\x06 \x01(\r\x12\x16\n\x0eparticles_03um\x18\x07 \x01(\r\x12\x16\n\x0eparticles_05um\x18\x08 \x01(\r\x12\x16\n\x0eparticles_10um\x18\t \x01(\r\x12\x16\n\x0eparticles_25um\x18\n \x01(\r\x12\x16\n\x0eparticles_50um\x18\x0b \x01(\r\x12\x17\n\x0fparticles_100um\x18\x0c \x01(\r\"\x89\x02\n\tTelemetry\x12\x0c\n\x04time\x18\x01 \x01(\x07\x12\x33\n\x0e\x64\x65vice_metrics\x18\x02 \x01(\x0b\x32\x19.meshtastic.DeviceMetricsH\x00\x12=\n\x13\x65nvironment_metrics\x18\x03 \x01(\x0b\x32\x1e.meshtastic.EnvironmentMetricsH\x00\x12<\n\x13\x61ir_quality_metrics\x18\x04 \x01(\x0b\x32\x1d.meshtastic.AirQualityMetricsH\x00\x12\x31\n\rpower_metrics\x18\x05 \x01(\x0b\x32\x18.meshtastic.PowerMetricsH\x00\x42\t\n\x07variant*\xe0\x01\n\x13TelemetrySensorType\x12\x10\n\x0cSENSOR_UNSET\x10\x00\x12\n\n\x06\x42ME280\x10\x01\x12\n\n\x06\x42ME680\x10\x02\x12\x0b\n\x07MCP9808\x10\x03\x12\n\n\x06INA260\x10\x04\x12\n\n\x06INA219\x10\x05\x12\n\n\x06\x42MP280\x10\x06\x12\t\n\x05SHTC3\x10\x07\x12\t\n\x05LPS22\x10\x08\x12\x0b\n\x07QMC6310\x10\t\x12\x0b\n\x07QMI8658\x10\n\x12\x0c\n\x08QMC5883L\x10\x0b\x12\t\n\x05SHT31\x10\x0c\x12\x0c\n\x08PMSA003I\x10\r\x12\x0b\n\x07INA3221\x10\x0e\x12\n\n\x06\x42MP085\x10\x0f\x42\x64\n\x13\x63om.geeksville.meshB\x0fTelemetryProtosZ\"github.com/meshtastic/go/generated\xaa\x02\x14Meshtastic.Protobufs\xba\x02\x00\x62\x06proto3')
|
||||
|
||||
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
|
||||
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'meshtastic.telemetry_pb2', globals())
|
||||
@@ -21,16 +21,16 @@ if _descriptor._USE_C_DESCRIPTORS == False:
|
||||
|
||||
DESCRIPTOR._options = None
|
||||
DESCRIPTOR._serialized_options = b'\n\023com.geeksville.meshB\017TelemetryProtosZ\"github.com/meshtastic/go/generated\252\002\024Meshtastic.Protobufs\272\002\000'
|
||||
_TELEMETRYSENSORTYPE._serialized_start=1041
|
||||
_TELEMETRYSENSORTYPE._serialized_end=1265
|
||||
_DEVICEMETRICS._serialized_start=42
|
||||
_DEVICEMETRICS._serialized_end=147
|
||||
_ENVIRONMENTMETRICS._serialized_start=150
|
||||
_ENVIRONMENTMETRICS._serialized_end=305
|
||||
_POWERMETRICS._serialized_start=308
|
||||
_POWERMETRICS._serialized_end=448
|
||||
_AIRQUALITYMETRICS._serialized_start=451
|
||||
_AIRQUALITYMETRICS._serialized_end=770
|
||||
_TELEMETRY._serialized_start=773
|
||||
_TELEMETRY._serialized_end=1038
|
||||
_TELEMETRYSENSORTYPE._serialized_start=1079
|
||||
_TELEMETRYSENSORTYPE._serialized_end=1303
|
||||
_DEVICEMETRICS._serialized_start=43
|
||||
_DEVICEMETRICS._serialized_end=172
|
||||
_ENVIRONMENTMETRICS._serialized_start=175
|
||||
_ENVIRONMENTMETRICS._serialized_end=343
|
||||
_POWERMETRICS._serialized_start=346
|
||||
_POWERMETRICS._serialized_end=486
|
||||
_AIRQUALITYMETRICS._serialized_start=489
|
||||
_AIRQUALITYMETRICS._serialized_end=808
|
||||
_TELEMETRY._serialized_start=811
|
||||
_TELEMETRY._serialized_end=1076
|
||||
# @@protoc_insertion_point(module_scope)
|
||||
|
||||
@@ -170,6 +170,7 @@ class DeviceMetrics(google.protobuf.message.Message):
|
||||
VOLTAGE_FIELD_NUMBER: builtins.int
|
||||
CHANNEL_UTILIZATION_FIELD_NUMBER: builtins.int
|
||||
AIR_UTIL_TX_FIELD_NUMBER: builtins.int
|
||||
UPTIME_SECONDS_FIELD_NUMBER: builtins.int
|
||||
battery_level: builtins.int
|
||||
"""
|
||||
0-100 (>100 means powered)
|
||||
@@ -186,6 +187,10 @@ class DeviceMetrics(google.protobuf.message.Message):
|
||||
"""
|
||||
Percent of airtime for transmission used within the last hour.
|
||||
"""
|
||||
uptime_seconds: builtins.int
|
||||
"""
|
||||
How long the device has been running since the last reboot (in seconds)
|
||||
"""
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
@@ -193,8 +198,9 @@ class DeviceMetrics(google.protobuf.message.Message):
|
||||
voltage: builtins.float = ...,
|
||||
channel_utilization: builtins.float = ...,
|
||||
air_util_tx: builtins.float = ...,
|
||||
uptime_seconds: builtins.int = ...,
|
||||
) -> None: ...
|
||||
def ClearField(self, field_name: typing_extensions.Literal["air_util_tx", b"air_util_tx", "battery_level", b"battery_level", "channel_utilization", b"channel_utilization", "voltage", b"voltage"]) -> None: ...
|
||||
def ClearField(self, field_name: typing_extensions.Literal["air_util_tx", b"air_util_tx", "battery_level", b"battery_level", "channel_utilization", b"channel_utilization", "uptime_seconds", b"uptime_seconds", "voltage", b"voltage"]) -> None: ...
|
||||
|
||||
global___DeviceMetrics = DeviceMetrics
|
||||
|
||||
@@ -212,6 +218,7 @@ class EnvironmentMetrics(google.protobuf.message.Message):
|
||||
GAS_RESISTANCE_FIELD_NUMBER: builtins.int
|
||||
VOLTAGE_FIELD_NUMBER: builtins.int
|
||||
CURRENT_FIELD_NUMBER: builtins.int
|
||||
IAQ_FIELD_NUMBER: builtins.int
|
||||
temperature: builtins.float
|
||||
"""
|
||||
Temperature measured
|
||||
@@ -236,6 +243,11 @@ class EnvironmentMetrics(google.protobuf.message.Message):
|
||||
"""
|
||||
Current measured (To be depreciated in favor of PowerMetrics in Meshtastic 3.x)
|
||||
"""
|
||||
iaq: builtins.int
|
||||
"""
|
||||
relative scale IAQ value as measured by Bosch BME680 . value 0-500.
|
||||
Belongs to Air Quality but is not particle but VOC measurement. Other VOC values can also be put in here.
|
||||
"""
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
@@ -245,8 +257,9 @@ class EnvironmentMetrics(google.protobuf.message.Message):
|
||||
gas_resistance: builtins.float = ...,
|
||||
voltage: builtins.float = ...,
|
||||
current: builtins.float = ...,
|
||||
iaq: builtins.int = ...,
|
||||
) -> None: ...
|
||||
def ClearField(self, field_name: typing_extensions.Literal["barometric_pressure", b"barometric_pressure", "current", b"current", "gas_resistance", b"gas_resistance", "relative_humidity", b"relative_humidity", "temperature", b"temperature", "voltage", b"voltage"]) -> None: ...
|
||||
def ClearField(self, field_name: typing_extensions.Literal["barometric_pressure", b"barometric_pressure", "current", b"current", "gas_resistance", b"gas_resistance", "iaq", b"iaq", "relative_humidity", b"relative_humidity", "temperature", b"temperature", "voltage", b"voltage"]) -> None: ...
|
||||
|
||||
global___EnvironmentMetrics = EnvironmentMetrics
|
||||
|
||||
|
||||
@@ -5,18 +5,18 @@ from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from meshtastic.__main__ import Globals
|
||||
from meshtastic import mt_config
|
||||
|
||||
from ..mesh_interface import MeshInterface
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def reset_globals():
|
||||
"""Fixture to reset globals."""
|
||||
def reset_mt_config():
|
||||
"""Fixture to reset mt_config."""
|
||||
parser = None
|
||||
parser = argparse.ArgumentParser(add_help=False)
|
||||
Globals.getInstance().reset()
|
||||
Globals.getInstance().set_parser(parser)
|
||||
mt_config.reset()
|
||||
mt_config.parser = parser
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
"""Meshtastic unit tests for globals.py
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
from ..globals import Globals
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_globals_get_instaance():
|
||||
"""Test that we can instantiate a Globals instance"""
|
||||
ourglobals = Globals.getInstance()
|
||||
ourglobals2 = Globals.getInstance()
|
||||
assert ourglobals == ourglobals2
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_globals_there_can_be_only_one():
|
||||
"""Test that we can cannot create two Globals instances"""
|
||||
# if we have an instance, delete it
|
||||
Globals.getInstance()
|
||||
with pytest.raises(Exception) as pytest_wrapped_e:
|
||||
# try to create another instance
|
||||
Globals()
|
||||
assert pytest_wrapped_e.type == Exception
|
||||
@@ -6,9 +6,8 @@ from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from meshtastic import _onNodeInfoReceive, _onPositionReceive, _onTextReceive
|
||||
from meshtastic import _onNodeInfoReceive, _onPositionReceive, _onTextReceive, mt_config
|
||||
|
||||
from ..globals import Globals
|
||||
from ..serial_interface import SerialInterface
|
||||
|
||||
|
||||
@@ -16,7 +15,7 @@ from ..serial_interface import SerialInterface
|
||||
def test_init_onTextReceive_with_exception(caplog):
|
||||
"""Test _onTextReceive"""
|
||||
args = MagicMock()
|
||||
Globals.getInstance().set_args(args)
|
||||
mt_config.args = args
|
||||
iface = MagicMock(autospec=SerialInterface)
|
||||
packet = {}
|
||||
with caplog.at_level(logging.DEBUG):
|
||||
@@ -29,7 +28,7 @@ def test_init_onTextReceive_with_exception(caplog):
|
||||
def test_init_onPositionReceive(caplog):
|
||||
"""Test _onPositionReceive"""
|
||||
args = MagicMock()
|
||||
Globals.getInstance().set_args(args)
|
||||
mt_config.args = args
|
||||
iface = MagicMock(autospec=SerialInterface)
|
||||
packet = {"from": "foo", "decoded": {"position": {}}}
|
||||
with caplog.at_level(logging.DEBUG):
|
||||
@@ -41,7 +40,7 @@ def test_init_onPositionReceive(caplog):
|
||||
def test_init_onNodeInfoReceive(caplog, iface_with_nodes):
|
||||
"""Test _onNodeInfoReceive"""
|
||||
args = MagicMock()
|
||||
Globals.getInstance().set_args(args)
|
||||
mt_config.args = args
|
||||
iface = iface_with_nodes
|
||||
iface.myInfo.my_node_num = 2475227164
|
||||
packet = {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -16,16 +16,17 @@ from ..util import Timeout
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.usefixtures("reset_globals")
|
||||
@pytest.mark.usefixtures("reset_mt_config")
|
||||
def test_MeshInterface(capsys):
|
||||
"""Test that we can instantiate a MeshInterface"""
|
||||
iface = MeshInterface(noProto=True)
|
||||
|
||||
nodes = {
|
||||
"!9388f81c": {
|
||||
"num": 2475227164,
|
||||
NODE_ID = "!9388f81c"
|
||||
NODE_NUM = 2475227164
|
||||
node = {
|
||||
"num": NODE_NUM,
|
||||
"user": {
|
||||
"id": "!9388f81c",
|
||||
"id": NODE_ID,
|
||||
"longName": "Unknown f81c",
|
||||
"shortName": "?1C",
|
||||
"macaddr": "RBeTiPgc",
|
||||
@@ -34,10 +35,9 @@ def test_MeshInterface(capsys):
|
||||
"position": {},
|
||||
"lastHeard": 1640204888,
|
||||
}
|
||||
}
|
||||
|
||||
iface.nodesByNum = {2475227164: nodes["!9388f81c"]}
|
||||
iface.nodes = nodes
|
||||
iface.nodes = {NODE_ID: node}
|
||||
iface.nodesByNum = {NODE_NUM: node}
|
||||
|
||||
myInfo = MagicMock()
|
||||
iface.myInfo = myInfo
|
||||
@@ -57,7 +57,7 @@ def test_MeshInterface(capsys):
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.usefixtures("reset_globals")
|
||||
@pytest.mark.usefixtures("reset_mt_config")
|
||||
def test_getMyUser(iface_with_nodes):
|
||||
"""Test getMyUser()"""
|
||||
iface = iface_with_nodes
|
||||
@@ -68,7 +68,7 @@ def test_getMyUser(iface_with_nodes):
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.usefixtures("reset_globals")
|
||||
@pytest.mark.usefixtures("reset_mt_config")
|
||||
def test_getLongName(iface_with_nodes):
|
||||
"""Test getLongName()"""
|
||||
iface = iface_with_nodes
|
||||
@@ -78,7 +78,7 @@ def test_getLongName(iface_with_nodes):
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.usefixtures("reset_globals")
|
||||
@pytest.mark.usefixtures("reset_mt_config")
|
||||
def test_getShortName(iface_with_nodes):
|
||||
"""Test getShortName()."""
|
||||
iface = iface_with_nodes
|
||||
@@ -88,7 +88,7 @@ def test_getShortName(iface_with_nodes):
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.usefixtures("reset_globals")
|
||||
@pytest.mark.usefixtures("reset_mt_config")
|
||||
def test_handlePacketFromRadio_no_from(capsys):
|
||||
"""Test _handlePacketFromRadio with no 'from' in the mesh packet."""
|
||||
iface = MeshInterface(noProto=True)
|
||||
@@ -100,7 +100,7 @@ def test_handlePacketFromRadio_no_from(capsys):
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.usefixtures("reset_globals")
|
||||
@pytest.mark.usefixtures("reset_mt_config")
|
||||
def test_handlePacketFromRadio_with_a_portnum(caplog):
|
||||
"""Test _handlePacketFromRadio with a portnum
|
||||
Since we have an attribute called 'from', we cannot simply 'set' it.
|
||||
@@ -116,7 +116,7 @@ def test_handlePacketFromRadio_with_a_portnum(caplog):
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.usefixtures("reset_globals")
|
||||
@pytest.mark.usefixtures("reset_mt_config")
|
||||
def test_handlePacketFromRadio_no_portnum(caplog):
|
||||
"""Test _handlePacketFromRadio without a portnum"""
|
||||
iface = MeshInterface(noProto=True)
|
||||
@@ -128,7 +128,7 @@ def test_handlePacketFromRadio_no_portnum(caplog):
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.usefixtures("reset_globals")
|
||||
@pytest.mark.usefixtures("reset_mt_config")
|
||||
def test_getNode_with_local():
|
||||
"""Test getNode"""
|
||||
iface = MeshInterface(noProto=True)
|
||||
@@ -137,7 +137,7 @@ def test_getNode_with_local():
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.usefixtures("reset_globals")
|
||||
@pytest.mark.usefixtures("reset_mt_config")
|
||||
def test_getNode_not_local(caplog):
|
||||
"""Test getNode not local"""
|
||||
iface = MeshInterface(noProto=True)
|
||||
@@ -150,7 +150,7 @@ def test_getNode_not_local(caplog):
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.usefixtures("reset_globals")
|
||||
@pytest.mark.usefixtures("reset_mt_config")
|
||||
def test_getNode_not_local_timeout(capsys):
|
||||
"""Test getNode not local, simulate timeout"""
|
||||
iface = MeshInterface(noProto=True)
|
||||
@@ -167,7 +167,7 @@ def test_getNode_not_local_timeout(capsys):
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.usefixtures("reset_globals")
|
||||
@pytest.mark.usefixtures("reset_mt_config")
|
||||
def test_sendPosition(caplog):
|
||||
"""Test sendPosition"""
|
||||
iface = MeshInterface(noProto=True)
|
||||
@@ -179,7 +179,7 @@ def test_sendPosition(caplog):
|
||||
|
||||
# TODO
|
||||
# @pytest.mark.unit
|
||||
# @pytest.mark.usefixtures("reset_globals")
|
||||
# @pytest.mark.usefixtures("reset_mt_config")
|
||||
# def test_close_with_heartbeatTimer(caplog):
|
||||
# """Test close() with heartbeatTimer"""
|
||||
# iface = MeshInterface(noProto=True)
|
||||
@@ -197,7 +197,7 @@ def test_sendPosition(caplog):
|
||||
|
||||
# TODO
|
||||
# @pytest.mark.unit
|
||||
# @pytest.mark.usefixtures("reset_globals")
|
||||
# @pytest.mark.usefixtures("reset_mt_config")
|
||||
# def test_handleFromRadio_empty_payload(caplog):
|
||||
# """Test _handleFromRadio"""
|
||||
# iface = MeshInterface(noProto=True)
|
||||
@@ -208,7 +208,7 @@ def test_sendPosition(caplog):
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.usefixtures("reset_globals")
|
||||
@pytest.mark.usefixtures("reset_mt_config")
|
||||
def test_handleFromRadio_with_my_info(caplog):
|
||||
"""Test _handleFromRadio with my_info"""
|
||||
# Note: I captured the '--debug --info' for the bytes below.
|
||||
@@ -233,7 +233,7 @@ def test_handleFromRadio_with_my_info(caplog):
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.usefixtures("reset_globals")
|
||||
@pytest.mark.usefixtures("reset_mt_config")
|
||||
def test_handleFromRadio_with_node_info(caplog, capsys):
|
||||
"""Test _handleFromRadio with node_info"""
|
||||
# Note: I captured the '--debug --info' for the bytes below.
|
||||
@@ -269,7 +269,7 @@ def test_handleFromRadio_with_node_info(caplog, capsys):
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.usefixtures("reset_globals")
|
||||
@pytest.mark.usefixtures("reset_mt_config")
|
||||
def test_handleFromRadio_with_node_info_tbeam1(caplog, capsys):
|
||||
"""Test _handleFromRadio with node_info"""
|
||||
# Note: Captured the '--debug --info' for the bytes below.
|
||||
@@ -293,7 +293,7 @@ def test_handleFromRadio_with_node_info_tbeam1(caplog, capsys):
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.usefixtures("reset_globals")
|
||||
@pytest.mark.usefixtures("reset_mt_config")
|
||||
def test_handleFromRadio_with_node_info_tbeam_with_bad_data(caplog):
|
||||
"""Test _handleFromRadio with node_info with some bad data (issue#172) - ensure we do not throw exception"""
|
||||
# Note: Captured the '--debug --info' for the bytes below.
|
||||
@@ -305,7 +305,7 @@ def test_handleFromRadio_with_node_info_tbeam_with_bad_data(caplog):
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.usefixtures("reset_globals")
|
||||
@pytest.mark.usefixtures("reset_mt_config")
|
||||
def test_MeshInterface_sendToRadioImpl(caplog):
|
||||
"""Test _sendToRadioImp()"""
|
||||
iface = MeshInterface(noProto=True)
|
||||
@@ -316,7 +316,7 @@ def test_MeshInterface_sendToRadioImpl(caplog):
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.usefixtures("reset_globals")
|
||||
@pytest.mark.usefixtures("reset_mt_config")
|
||||
def test_MeshInterface_sendToRadio_no_proto(caplog):
|
||||
"""Test sendToRadio()"""
|
||||
iface = MeshInterface()
|
||||
@@ -327,7 +327,7 @@ def test_MeshInterface_sendToRadio_no_proto(caplog):
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.usefixtures("reset_globals")
|
||||
@pytest.mark.usefixtures("reset_mt_config")
|
||||
def test_sendData_too_long(caplog):
|
||||
"""Test when data payload is too big"""
|
||||
iface = MeshInterface(noProto=True)
|
||||
@@ -352,7 +352,7 @@ def test_sendData_too_long(caplog):
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.usefixtures("reset_globals")
|
||||
@pytest.mark.usefixtures("reset_mt_config")
|
||||
def test_sendData_unknown_app(capsys):
|
||||
"""Test sendData when unknown app"""
|
||||
iface = MeshInterface(noProto=True)
|
||||
@@ -366,7 +366,7 @@ def test_sendData_unknown_app(capsys):
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.usefixtures("reset_globals")
|
||||
@pytest.mark.usefixtures("reset_mt_config")
|
||||
def test_sendPosition_with_a_position(caplog):
|
||||
"""Test sendPosition when lat/long/alt"""
|
||||
iface = MeshInterface(noProto=True)
|
||||
@@ -378,7 +378,7 @@ def test_sendPosition_with_a_position(caplog):
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.usefixtures("reset_globals")
|
||||
@pytest.mark.usefixtures("reset_mt_config")
|
||||
def test_sendPacket_with_no_destination(capsys):
|
||||
"""Test _sendPacket()"""
|
||||
iface = MeshInterface(noProto=True)
|
||||
@@ -392,7 +392,7 @@ def test_sendPacket_with_no_destination(capsys):
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.usefixtures("reset_globals")
|
||||
@pytest.mark.usefixtures("reset_mt_config")
|
||||
def test_sendPacket_with_destination_as_int(caplog):
|
||||
"""Test _sendPacket() with int as a destination"""
|
||||
iface = MeshInterface(noProto=True)
|
||||
@@ -403,7 +403,7 @@ def test_sendPacket_with_destination_as_int(caplog):
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.usefixtures("reset_globals")
|
||||
@pytest.mark.usefixtures("reset_mt_config")
|
||||
def test_sendPacket_with_destination_starting_with_a_bang(caplog):
|
||||
"""Test _sendPacket() with int as a destination"""
|
||||
iface = MeshInterface(noProto=True)
|
||||
@@ -414,7 +414,7 @@ def test_sendPacket_with_destination_starting_with_a_bang(caplog):
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.usefixtures("reset_globals")
|
||||
@pytest.mark.usefixtures("reset_mt_config")
|
||||
def test_sendPacket_with_destination_as_BROADCAST_ADDR(caplog):
|
||||
"""Test _sendPacket() with BROADCAST_ADDR as a destination"""
|
||||
iface = MeshInterface(noProto=True)
|
||||
@@ -425,7 +425,7 @@ def test_sendPacket_with_destination_as_BROADCAST_ADDR(caplog):
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.usefixtures("reset_globals")
|
||||
@pytest.mark.usefixtures("reset_mt_config")
|
||||
def test_sendPacket_with_destination_as_LOCAL_ADDR_no_myInfo(capsys):
|
||||
"""Test _sendPacket() with LOCAL_ADDR as a destination with no myInfo"""
|
||||
iface = MeshInterface(noProto=True)
|
||||
@@ -440,7 +440,7 @@ def test_sendPacket_with_destination_as_LOCAL_ADDR_no_myInfo(capsys):
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.usefixtures("reset_globals")
|
||||
@pytest.mark.usefixtures("reset_mt_config")
|
||||
def test_sendPacket_with_destination_as_LOCAL_ADDR_with_myInfo(caplog):
|
||||
"""Test _sendPacket() with LOCAL_ADDR as a destination with myInfo"""
|
||||
iface = MeshInterface(noProto=True)
|
||||
@@ -454,7 +454,7 @@ def test_sendPacket_with_destination_as_LOCAL_ADDR_with_myInfo(caplog):
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.usefixtures("reset_globals")
|
||||
@pytest.mark.usefixtures("reset_mt_config")
|
||||
def test_sendPacket_with_destination_is_blank_with_nodes(capsys, iface_with_nodes):
|
||||
"""Test _sendPacket() with '' as a destination with myInfo"""
|
||||
iface = iface_with_nodes
|
||||
@@ -469,7 +469,7 @@ def test_sendPacket_with_destination_is_blank_with_nodes(capsys, iface_with_node
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.usefixtures("reset_globals")
|
||||
@pytest.mark.usefixtures("reset_mt_config")
|
||||
def test_sendPacket_with_destination_is_blank_without_nodes(caplog, iface_with_nodes):
|
||||
"""Test _sendPacket() with '' as a destination with myInfo"""
|
||||
iface = iface_with_nodes
|
||||
@@ -481,7 +481,7 @@ def test_sendPacket_with_destination_is_blank_without_nodes(caplog, iface_with_n
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.usefixtures("reset_globals")
|
||||
@pytest.mark.usefixtures("reset_mt_config")
|
||||
def test_getMyNodeInfo():
|
||||
"""Test getMyNodeInfo()"""
|
||||
iface = MeshInterface(noProto=True)
|
||||
@@ -496,7 +496,7 @@ def test_getMyNodeInfo():
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.usefixtures("reset_globals")
|
||||
@pytest.mark.usefixtures("reset_mt_config")
|
||||
def test_generatePacketId(capsys):
|
||||
"""Test _generatePacketId() when no currentPacketId (not connected)"""
|
||||
iface = MeshInterface(noProto=True)
|
||||
@@ -514,7 +514,7 @@ def test_generatePacketId(capsys):
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.usefixtures("reset_globals")
|
||||
@pytest.mark.usefixtures("reset_mt_config")
|
||||
def test_fixupPosition_empty_pos():
|
||||
"""Test _fixupPosition()"""
|
||||
iface = MeshInterface(noProto=True)
|
||||
@@ -524,7 +524,7 @@ def test_fixupPosition_empty_pos():
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.usefixtures("reset_globals")
|
||||
@pytest.mark.usefixtures("reset_mt_config")
|
||||
def test_fixupPosition_no_changes_needed():
|
||||
"""Test _fixupPosition()"""
|
||||
iface = MeshInterface(noProto=True)
|
||||
@@ -534,7 +534,7 @@ def test_fixupPosition_no_changes_needed():
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.usefixtures("reset_globals")
|
||||
@pytest.mark.usefixtures("reset_mt_config")
|
||||
def test_fixupPosition():
|
||||
"""Test _fixupPosition()"""
|
||||
iface = MeshInterface(noProto=True)
|
||||
@@ -549,7 +549,7 @@ def test_fixupPosition():
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.usefixtures("reset_globals")
|
||||
@pytest.mark.usefixtures("reset_mt_config")
|
||||
def test_nodeNumToId(iface_with_nodes):
|
||||
"""Test _nodeNumToId()"""
|
||||
iface = iface_with_nodes
|
||||
@@ -559,7 +559,7 @@ def test_nodeNumToId(iface_with_nodes):
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.usefixtures("reset_globals")
|
||||
@pytest.mark.usefixtures("reset_mt_config")
|
||||
def test_nodeNumToId_not_found(iface_with_nodes):
|
||||
"""Test _nodeNumToId()"""
|
||||
iface = iface_with_nodes
|
||||
@@ -569,7 +569,7 @@ def test_nodeNumToId_not_found(iface_with_nodes):
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.usefixtures("reset_globals")
|
||||
@pytest.mark.usefixtures("reset_mt_config")
|
||||
def test_nodeNumToId_to_all(iface_with_nodes):
|
||||
"""Test _nodeNumToId()"""
|
||||
iface = iface_with_nodes
|
||||
@@ -579,7 +579,7 @@ def test_nodeNumToId_to_all(iface_with_nodes):
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.usefixtures("reset_globals")
|
||||
@pytest.mark.usefixtures("reset_mt_config")
|
||||
def test_getOrCreateByNum_minimal(iface_with_nodes):
|
||||
"""Test _getOrCreateByNum()"""
|
||||
iface = iface_with_nodes
|
||||
@@ -589,7 +589,7 @@ def test_getOrCreateByNum_minimal(iface_with_nodes):
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.usefixtures("reset_globals")
|
||||
@pytest.mark.usefixtures("reset_mt_config")
|
||||
def test_getOrCreateByNum_not_found(iface_with_nodes):
|
||||
"""Test _getOrCreateByNum()"""
|
||||
iface = iface_with_nodes
|
||||
@@ -600,7 +600,7 @@ def test_getOrCreateByNum_not_found(iface_with_nodes):
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.usefixtures("reset_globals")
|
||||
@pytest.mark.usefixtures("reset_mt_config")
|
||||
def test_getOrCreateByNum(iface_with_nodes):
|
||||
"""Test _getOrCreateByNum()"""
|
||||
iface = iface_with_nodes
|
||||
|
||||
@@ -20,7 +20,7 @@ def test_StreamInterface():
|
||||
|
||||
# Note: This takes a bit, so moving from unit to slow
|
||||
@pytest.mark.unitslow
|
||||
@pytest.mark.usefixtures("reset_globals")
|
||||
@pytest.mark.usefixtures("reset_mt_config")
|
||||
def test_StreamInterface_with_noProto(caplog):
|
||||
"""Test that we can instantiate a StreamInterface based on nonProto
|
||||
and we can read/write bytes from a mocked stream
|
||||
@@ -41,7 +41,7 @@ def test_StreamInterface_with_noProto(caplog):
|
||||
### Tip: If you want to see the print output, run with '-s' flag:
|
||||
### pytest -s meshtastic/tests/test_stream_interface.py::test_sendToRadioImpl
|
||||
# @pytest.mark.unitslow
|
||||
# @pytest.mark.usefixtures("reset_globals")
|
||||
# @pytest.mark.usefixtures("reset_mt_config")
|
||||
# def test_sendToRadioImpl(caplog):
|
||||
# """Test _sendToRadioImpl()"""
|
||||
#
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
"""Meshtastic unit tests for tunnel.py"""
|
||||
|
||||
import logging
|
||||
import re
|
||||
import sys
|
||||
@@ -7,7 +6,8 @@ from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from ..globals import Globals
|
||||
from meshtastic import mt_config
|
||||
|
||||
from ..tcp_interface import TCPInterface
|
||||
from ..tunnel import Tunnel, onTunnelReceive
|
||||
|
||||
@@ -51,7 +51,7 @@ def test_Tunnel_with_interface(mock_platform_system, caplog, iface_with_nodes):
|
||||
with caplog.at_level(logging.WARNING):
|
||||
with patch("socket.socket"):
|
||||
tun = Tunnel(iface)
|
||||
assert tun == Globals.getInstance().get_tunnelInstance()
|
||||
assert tun == mt_config.tunnelInstance
|
||||
iface.close()
|
||||
assert re.search(r"Not creating a TapDevice()", caplog.text, re.MULTILINE)
|
||||
assert re.search(r"Not starting TUN reader", caplog.text, re.MULTILINE)
|
||||
@@ -65,7 +65,7 @@ def test_onTunnelReceive_from_ourselves(mock_platform_system, caplog, iface_with
|
||||
iface = iface_with_nodes
|
||||
iface.myInfo.my_node_num = 2475227164
|
||||
sys.argv = [""]
|
||||
Globals.getInstance().set_args(sys.argv)
|
||||
mt_config.args = sys.argv
|
||||
packet = {"decoded": {"payload": "foo"}, "from": 2475227164}
|
||||
a_mock = MagicMock()
|
||||
a_mock.return_value = "Linux"
|
||||
@@ -73,7 +73,7 @@ def test_onTunnelReceive_from_ourselves(mock_platform_system, caplog, iface_with
|
||||
with caplog.at_level(logging.DEBUG):
|
||||
with patch("socket.socket"):
|
||||
tun = Tunnel(iface)
|
||||
Globals.getInstance().set_tunnelInstance(tun)
|
||||
mt_config.tunnelInstance = tun
|
||||
onTunnelReceive(packet, iface)
|
||||
assert re.search(r"in onTunnelReceive", caplog.text, re.MULTILINE)
|
||||
assert re.search(r"Ignoring message we sent", caplog.text, re.MULTILINE)
|
||||
@@ -88,7 +88,7 @@ def test_onTunnelReceive_from_someone_else(
|
||||
iface = iface_with_nodes
|
||||
iface.myInfo.my_node_num = 2475227164
|
||||
sys.argv = [""]
|
||||
Globals.getInstance().set_args(sys.argv)
|
||||
mt_config.args = sys.argv
|
||||
packet = {"decoded": {"payload": "foo"}, "from": 123}
|
||||
a_mock = MagicMock()
|
||||
a_mock.return_value = "Linux"
|
||||
@@ -96,7 +96,7 @@ def test_onTunnelReceive_from_someone_else(
|
||||
with caplog.at_level(logging.DEBUG):
|
||||
with patch("socket.socket"):
|
||||
tun = Tunnel(iface)
|
||||
Globals.getInstance().set_tunnelInstance(tun)
|
||||
mt_config.tunnelInstance = tun
|
||||
onTunnelReceive(packet, iface)
|
||||
assert re.search(r"in onTunnelReceive", caplog.text, re.MULTILINE)
|
||||
|
||||
|
||||
@@ -22,16 +22,14 @@ import threading
|
||||
from pubsub import pub # type: ignore[import-untyped]
|
||||
from pytap2 import TapDevice
|
||||
|
||||
from meshtastic import portnums_pb2
|
||||
from meshtastic.globals import Globals
|
||||
from meshtastic import portnums_pb2, mt_config
|
||||
from meshtastic.util import ipstr, readnet_u16
|
||||
|
||||
|
||||
def onTunnelReceive(packet, interface): # pylint: disable=W0613
|
||||
"""Callback for received tunneled messages from mesh."""
|
||||
logging.debug(f"in onTunnelReceive()")
|
||||
our_globals = Globals.getInstance()
|
||||
tunnelInstance = our_globals.get_tunnelInstance()
|
||||
tunnelInstance = mt_config.tunnelInstance
|
||||
tunnelInstance.onReceive(packet)
|
||||
|
||||
|
||||
@@ -67,8 +65,7 @@ class Tunnel:
|
||||
if platform.system() != "Linux":
|
||||
raise Tunnel.TunnelError("Tunnel() can only be run instantiated on a Linux system")
|
||||
|
||||
our_globals = Globals.getInstance()
|
||||
our_globals.set_tunnelInstance(self)
|
||||
mt_config.tunnelInstance = self
|
||||
|
||||
"""A list of chatty UDP services we should never accidentally
|
||||
forward to our slow network"""
|
||||
|
||||
@@ -11,6 +11,8 @@ import threading
|
||||
import time
|
||||
import traceback
|
||||
from queue import Queue
|
||||
from typing import Union
|
||||
|
||||
from google.protobuf.json_format import MessageToJson
|
||||
|
||||
import packaging.version as pkg_version
|
||||
@@ -153,16 +155,16 @@ class dotdict(dict):
|
||||
class Timeout:
|
||||
"""Timeout class"""
|
||||
|
||||
def __init__(self, maxSecs=20):
|
||||
self.expireTime = 0
|
||||
self.sleepInterval = 0.1
|
||||
self.expireTimeout = maxSecs
|
||||
def __init__(self, maxSecs: int=20):
|
||||
self.expireTime: Union[int, float] = 0
|
||||
self.sleepInterval: float = 0.1
|
||||
self.expireTimeout: int = maxSecs
|
||||
|
||||
def reset(self):
|
||||
"""Restart the waitForSet timer"""
|
||||
self.expireTime = time.time() + self.expireTimeout
|
||||
|
||||
def waitForSet(self, target, attrs=()):
|
||||
def waitForSet(self, target, attrs=()) -> bool:
|
||||
"""Block until the specified attributes are set. Returns True if config has been received."""
|
||||
self.reset()
|
||||
while time.time() < self.expireTime:
|
||||
@@ -173,7 +175,7 @@ class Timeout:
|
||||
|
||||
def waitForAckNak(
|
||||
self, acknowledgment, attrs=("receivedAck", "receivedNak", "receivedImplAck")
|
||||
):
|
||||
) -> bool:
|
||||
"""Block until an ACK or NAK has been received. Returns True if ACK or NAK has been received."""
|
||||
self.reset()
|
||||
while time.time() < self.expireTime:
|
||||
@@ -183,7 +185,7 @@ class Timeout:
|
||||
time.sleep(self.sleepInterval)
|
||||
return False
|
||||
|
||||
def waitForTraceRoute(self, waitFactor, acknowledgment, attr="receivedTraceRoute"):
|
||||
def waitForTraceRoute(self, waitFactor, acknowledgment, attr="receivedTraceRoute") -> bool:
|
||||
"""Block until traceroute response is received. Returns True if traceroute response has been received."""
|
||||
self.expireTimeout *= waitFactor
|
||||
self.reset()
|
||||
@@ -194,7 +196,7 @@ class Timeout:
|
||||
time.sleep(self.sleepInterval)
|
||||
return False
|
||||
|
||||
def waitForTelemetry(self, acknowledgment):
|
||||
def waitForTelemetry(self, acknowledgment) -> bool:
|
||||
"""Block until telemetry response is received. Returns True if telemetry response has been received."""
|
||||
self.reset()
|
||||
while time.time() < self.expireTime:
|
||||
@@ -204,6 +206,16 @@ class Timeout:
|
||||
time.sleep(self.sleepInterval)
|
||||
return False
|
||||
|
||||
def waitForPosition(self, acknowledgment) -> bool:
|
||||
"""Block until position response is received. Returns True if position response has been received."""
|
||||
self.reset()
|
||||
while time.time() < self.expireTime:
|
||||
if getattr(acknowledgment, "receivedPosition", None):
|
||||
acknowledgment.reset()
|
||||
return True
|
||||
time.sleep(self.sleepInterval)
|
||||
return False
|
||||
|
||||
class Acknowledgment:
|
||||
"A class that records which type of acknowledgment was just received, if any."
|
||||
|
||||
@@ -214,6 +226,7 @@ class Acknowledgment:
|
||||
self.receivedImplAck = False
|
||||
self.receivedTraceRoute = False
|
||||
self.receivedTelemetry = False
|
||||
self.receivedPosition = False
|
||||
|
||||
def reset(self):
|
||||
"""reset"""
|
||||
@@ -222,6 +235,7 @@ class Acknowledgment:
|
||||
self.receivedImplAck = False
|
||||
self.receivedTraceRoute = False
|
||||
self.receivedTelemetry = False
|
||||
self.receivedPosition = False
|
||||
|
||||
|
||||
class DeferredExecution:
|
||||
|
||||
Submodule protobufs updated: 68720ed8db...0d08acd9c5
2
setup.py
2
setup.py
@@ -13,7 +13,7 @@ with open("README.md", "r") as fh:
|
||||
# This call to setup() does all the work
|
||||
setup(
|
||||
name="meshtastic",
|
||||
version="2.3.4.post1",
|
||||
version="2.3.5",
|
||||
description="Python API & client shell for talking to Meshtastic devices",
|
||||
long_description=long_description,
|
||||
long_description_content_type="text/markdown",
|
||||
|
||||
Reference in New Issue
Block a user