Skip to content

Commit 1ff7334

Browse files
committed
Merge branch 'master' into pr-poetry
2 parents e6a88e0 + b15e27c commit 1ff7334

5 files changed

Lines changed: 85 additions & 20 deletions

File tree

meshtastic/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ def onConnection(interface, topic=pub.AUTO_TOPIC): # called when we (re)connect
7676

7777
import google.protobuf.json_format
7878
import serial # type: ignore[import-untyped]
79-
import timeago # type: ignore[import-untyped]
79+
from dotmap import DotMap # type: ignore[import-untyped]
8080
from google.protobuf.json_format import MessageToJson
8181
from pubsub import pub # type: ignore[import-untyped]
8282
from tabulate import tabulate

meshtastic/mesh_interface.py

Lines changed: 30 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@
1414
from typing import Any, Callable, Dict, List, Optional, Union
1515

1616
import google.protobuf.json_format
17-
import timeago # type: ignore[import-untyped]
1817
from pubsub import pub # type: ignore[import-untyped]
1918
from tabulate import tabulate
2019

@@ -42,6 +41,29 @@
4241
)
4342

4443

44+
def _timeago(delta_secs: int) -> str:
45+
"""Convert a number of seconds in the past into a short, friendly string
46+
e.g. "now", "30 sec ago", "1 hour ago"
47+
Zero or negative intervals simply return "now"
48+
"""
49+
intervals = (
50+
("year", 60 * 60 * 24 * 365),
51+
("month", 60 * 60 * 24 * 30),
52+
("day", 60 * 60 * 24),
53+
("hour", 60 * 60),
54+
("min", 60),
55+
("sec", 1),
56+
)
57+
for name, interval_duration in intervals:
58+
if delta_secs < interval_duration:
59+
continue
60+
x = delta_secs // interval_duration
61+
plur = "s" if x > 1 else ""
62+
return f"{x} {name}{plur} ago"
63+
64+
return "now"
65+
66+
4567
class MeshInterface: # pylint: disable=R0902
4668
"""Interface class for meshtastic devices
4769
@@ -158,11 +180,13 @@ def getLH(ts) -> Optional[str]:
158180

159181
def getTimeAgo(ts) -> Optional[str]:
160182
"""Format how long ago have we heard from this node (aka timeago)."""
161-
return (
162-
timeago.format(datetime.fromtimestamp(ts), datetime.now())
163-
if ts
164-
else None
165-
)
183+
if ts is None:
184+
return None
185+
delta = datetime.now() - datetime.fromtimestamp(ts)
186+
delta_secs = int(delta.total_seconds())
187+
if delta_secs < 0:
188+
return None # not handling a timestamp from the future
189+
return _timeago(delta_secs)
166190

167191
rows: List[Dict[str, Any]] = []
168192
if self.nodesByNum:

meshtastic/tests/test_mesh_interface.py

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,10 @@
55
from unittest.mock import MagicMock, patch
66

77
import pytest
8+
from hypothesis import given, strategies as st
89

910
from .. import mesh_pb2, config_pb2, BROADCAST_ADDR, LOCAL_ADDR
10-
from ..mesh_interface import MeshInterface
11+
from ..mesh_interface import MeshInterface, _timeago
1112
from ..node import Node
1213

1314
# TODO
@@ -684,3 +685,21 @@ def test_waitConnected_isConnected_timeout(capsys):
684685
out, err = capsys.readouterr()
685686
assert re.search(r"warn about something", err, re.MULTILINE)
686687
assert out == ""
688+
689+
690+
@pytest.mark.unit
691+
def test_timeago():
692+
"""Test that the _timeago function returns sane values"""
693+
assert _timeago(0) == "now"
694+
assert _timeago(1) == "1 sec ago"
695+
assert _timeago(15) == "15 secs ago"
696+
assert _timeago(333) == "5 mins ago"
697+
assert _timeago(99999) == "1 day ago"
698+
assert _timeago(9999999) == "3 months ago"
699+
assert _timeago(-999) == "now"
700+
701+
@given(seconds=st.integers())
702+
def test_timeago_fuzz(seconds):
703+
"""Fuzz _timeago to ensure it works with any integer"""
704+
val = _timeago(seconds)
705+
assert re.match(r"(now|\d+ (secs?|mins?|hours?|days?|months?|years?))", val)

meshtastic/util.py

Lines changed: 32 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,16 @@
2424
from meshtastic.supported_device import supported_devices
2525
from meshtastic.version import get_active_version
2626

27-
"""Some devices such as a seger jlink we never want to accidentally open"""
28-
blacklistVids = dict.fromkeys([0x1366])
27+
"""Some devices such as a seger jlink or st-link we never want to accidentally open
28+
0x1915 NordicSemi (PPK2)
29+
"""
30+
blacklistVids = dict.fromkeys([0x1366, 0x0483, 0x1915])
31+
32+
"""Some devices are highly likely to be meshtastic.
33+
0x239a RAK4631
34+
0x303a Heltec tracker"""
35+
whitelistVids = dict.fromkeys([0x239a, 0x303a])
36+
2937

3038
def quoteBooleans(a_string):
3139
"""Quote booleans
@@ -130,19 +138,35 @@ def findPorts(eliminate_duplicates: bool=False) -> List[str]:
130138
Returns:
131139
list -- a list of device paths
132140
"""
133-
l = list(
141+
all_ports = serial.tools.list_ports.comports()
142+
143+
# look for 'likely' meshtastic devices
144+
ports = list(
134145
map(
135146
lambda port: port.device,
136147
filter(
137-
lambda port: port.vid is not None and port.vid not in blacklistVids,
138-
serial.tools.list_ports.comports(),
148+
lambda port: port.vid is not None and port.vid in whitelistVids,
149+
all_ports,
139150
),
140151
)
141152
)
142-
l.sort()
153+
154+
# if no likely devices, just list everything not blacklisted
155+
if len(ports) == 0:
156+
ports = list(
157+
map(
158+
lambda port: port.device,
159+
filter(
160+
lambda port: port.vid is not None and port.vid not in blacklistVids,
161+
all_ports,
162+
),
163+
)
164+
)
165+
166+
ports.sort()
143167
if eliminate_duplicates:
144-
l = eliminate_duplicate_port(l)
145-
return l
168+
ports = eliminate_duplicate_port(ports)
169+
return ports
146170

147171

148172
class dotdict(dict):

tests/hello_world.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,7 @@
1-
import time
2-
3-
import meshtastic
1+
import meshtastic.serial_interface
42

53
interface = (
6-
meshtastic.SerialInterface()
4+
meshtastic.serial_interface.SerialInterface()
75
) # By default will try to find a meshtastic device, otherwise provide a device path like /dev/ttyUSB0
86
interface.sendText("hello mesh")
97
interface.close()

0 commit comments

Comments
 (0)