meshcore-cli 1.6.11__tar.gz → 1.6.13__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,22 @@
1
+ Metadata-Version: 2.5
2
+ Name: meshcore-cli
3
+ Version: 1.6.13
4
+ Summary: Command line interface to meshcore companion radios and repeaters
5
+ Project-URL: Homepage, https://github.com/fdlamotte/meshcore-cli
6
+ Project-URL: Issues, https://github.com/fdlamotte/meshcore-cli/issues
7
+ Author-email: Florent de Lamotte <florent@frizoncorrea.fr>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Programming Language :: Python :: 3
12
+ Requires-Python: >=3.10
13
+ Requires-Dist: bleak>=0.22
14
+ Requires-Dist: meshcore>=2.3.22
15
+ Requires-Dist: prompt-toolkit>=3.0.50
16
+ Requires-Dist: requests>=2.28.0
17
+ Requires-Dist: zeroconf>=0.131
18
+ Description-Content-Type: text/markdown
19
+
1
20
  # meshcore-cli
2
21
 
3
22
  meshcore-cli : CLI interface to MeshCore companion app over BLE, TCP or Serial
@@ -61,8 +80,8 @@ Arguments mostly deals with connection to the node
61
80
  -j : json output (disables init file)
62
81
  -D : debug
63
82
  -S : scan for devices and show a selector
64
- -l : list available ble/serial devices and exit
65
- -T &lt;timeout&gt; : timeout for the ble scan (-S and -l) default 2s
83
+ -l : list available ble/tcp (mDNS)/serial devices and exit
84
+ -T &lt;timeout&gt; : timeout for the ble/mDNS scan (-S and -l) default 2s
66
85
  -a &lt;address&gt; : specifies device address (can be a name)
67
86
  -d &lt;name&gt; : filter meshcore devices with name or address
68
87
  -P : forces pairing via the OS
@@ -95,6 +114,9 @@ Commands are given after arguments, they can be chained and some have shortcuts.
95
114
  aliases_load : load aliases from a file
96
115
  handler_attach &lt;d&gt; &lt;c&gt; : attach c as a handler for d (rxlog|msgs|chan_data|telemetry)
97
116
  handler_detach &lt;n&gt; : detach an handler (from its handle n)
117
+ timer &lt;s&gt; &lt;c&gt; : runs command c every s seconds
118
+ timer_cancel &lt;n&gt; : cancels a timer (from its handle n)
119
+ timers : lists current timers
98
120
  Messaging
99
121
  msg &lt;name&gt; &lt;msg&gt; : send message to node by name m {
100
122
  wait_ack : wait an ack wa }
@@ -230,6 +252,18 @@ handler_attach rxlog cat
230
252
 
231
253
  Will print out the content of `rx_log` as it comes in.
232
254
 
255
+ #### Timers
256
+
257
+ `timer [-j] [-c<contact>] [-s<scope>] <s> <line>` runs `line` every `s` seconds.
258
+
259
+ - `-c` sets the contact the line is run from (`~` for root).
260
+ - `-s` sets the scope for the line (default is the current scope of the node).
261
+ - `-j` forces json output for the timed line.
262
+
263
+ `timers` lists the running timers and `timer_cancel <n>` cancels timer `n`.
264
+
265
+ From the command line, timers only run while a command is waiting, so end the command list with `sleep <s>` or `wk` (`meshcli timer 60 "chan 1 hi" sleep 3600`). In chat mode, a `sleep` or `wk` holds up timers until it returns.
266
+
233
267
  ### Contact management
234
268
 
235
269
  To receive a message from another user, it is necessary to have its public key. This key is stored on a contact list in the device, and this list has a finite size (50 when meshcore started, now over 350 for most devices).
@@ -1,21 +1,3 @@
1
- Metadata-Version: 2.5
2
- Name: meshcore-cli
3
- Version: 1.6.11
4
- Summary: Command line interface to meshcore companion radios and repeaters
5
- Project-URL: Homepage, https://github.com/fdlamotte/meshcore-cli
6
- Project-URL: Issues, https://github.com/fdlamotte/meshcore-cli/issues
7
- Author-email: Florent de Lamotte <florent@frizoncorrea.fr>
8
- License-Expression: MIT
9
- License-File: LICENSE
10
- Classifier: Operating System :: OS Independent
11
- Classifier: Programming Language :: Python :: 3
12
- Requires-Python: >=3.10
13
- Requires-Dist: bleak>=0.22
14
- Requires-Dist: meshcore>=2.3.22
15
- Requires-Dist: prompt-toolkit>=3.0.50
16
- Requires-Dist: requests>=2.28.0
17
- Description-Content-Type: text/markdown
18
-
19
1
  # meshcore-cli
20
2
 
21
3
  meshcore-cli : CLI interface to MeshCore companion app over BLE, TCP or Serial
@@ -79,8 +61,8 @@ Arguments mostly deals with connection to the node
79
61
  -j : json output (disables init file)
80
62
  -D : debug
81
63
  -S : scan for devices and show a selector
82
- -l : list available ble/serial devices and exit
83
- -T &lt;timeout&gt; : timeout for the ble scan (-S and -l) default 2s
64
+ -l : list available ble/tcp (mDNS)/serial devices and exit
65
+ -T &lt;timeout&gt; : timeout for the ble/mDNS scan (-S and -l) default 2s
84
66
  -a &lt;address&gt; : specifies device address (can be a name)
85
67
  -d &lt;name&gt; : filter meshcore devices with name or address
86
68
  -P : forces pairing via the OS
@@ -113,6 +95,9 @@ Commands are given after arguments, they can be chained and some have shortcuts.
113
95
  aliases_load : load aliases from a file
114
96
  handler_attach &lt;d&gt; &lt;c&gt; : attach c as a handler for d (rxlog|msgs|chan_data|telemetry)
115
97
  handler_detach &lt;n&gt; : detach an handler (from its handle n)
98
+ timer &lt;s&gt; &lt;c&gt; : runs command c every s seconds
99
+ timer_cancel &lt;n&gt; : cancels a timer (from its handle n)
100
+ timers : lists current timers
116
101
  Messaging
117
102
  msg &lt;name&gt; &lt;msg&gt; : send message to node by name m {
118
103
  wait_ack : wait an ack wa }
@@ -248,6 +233,18 @@ handler_attach rxlog cat
248
233
 
249
234
  Will print out the content of `rx_log` as it comes in.
250
235
 
236
+ #### Timers
237
+
238
+ `timer [-j] [-c<contact>] [-s<scope>] <s> <line>` runs `line` every `s` seconds.
239
+
240
+ - `-c` sets the contact the line is run from (`~` for root).
241
+ - `-s` sets the scope for the line (default is the current scope of the node).
242
+ - `-j` forces json output for the timed line.
243
+
244
+ `timers` lists the running timers and `timer_cancel <n>` cancels timer `n`.
245
+
246
+ From the command line, timers only run while a command is waiting, so end the command list with `sleep <s>` or `wk` (`meshcli timer 60 "chan 1 hi" sleep 3600`). In chat mode, a `sleep` or `wk` holds up timers until it returns.
247
+
251
248
  ### Contact management
252
249
 
253
250
  To receive a message from another user, it is necessary to have its public key. This key is stored on a contact list in the device, and this list has a finite size (50 when meshcore started, now over 350 for most devices).
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "meshcore-cli"
7
- version = "1.6.11"
7
+ version = "1.6.13"
8
8
  authors = [
9
9
  { name="Florent de Lamotte", email="florent@frizoncorrea.fr" },
10
10
  ]
@@ -19,6 +19,7 @@ license = "MIT"
19
19
  license-files = ["LICEN[CS]E*"]
20
20
  dependencies = [ "meshcore >= 2.3.22",
21
21
  "bleak >= 0.22",
22
+ "zeroconf >= 0.131",
22
23
  "prompt_toolkit >= 3.0.50",
23
24
  "requests >= 2.28.0" ]
24
25
 
@@ -11,7 +11,6 @@ import getopt, json, shlex, re
11
11
  import logging
12
12
  import requests
13
13
  import serial.tools.list_ports
14
- from pathlib import Path
15
14
  import traceback
16
15
  import subprocess
17
16
  import math
@@ -32,10 +31,17 @@ try:
32
31
  except ImportError:
33
32
  BLEAK_AVAILABLE = False
34
33
 
34
+ try:
35
+ from zeroconf import ServiceStateChange
36
+ from zeroconf.asyncio import AsyncZeroconf, AsyncServiceBrowser, AsyncServiceInfo
37
+ ZEROCONF_AVAILABLE = True
38
+ except ImportError:
39
+ ZEROCONF_AVAILABLE = False
40
+
35
41
  from meshcore import MeshCore, EventType, logger
36
42
 
37
43
  # Version
38
- VERSION = "v1.6.11"
44
+ VERSION = "v1.6.13"
39
45
 
40
46
  # default ble address is stored in a config file
41
47
  MCCLI_CONFIG_DIR = os.path.expanduser("~/.config/meshcore/")
@@ -62,6 +68,9 @@ PAYLOAD_TYPENAMES = ["REQ", "RESPONSE", "TEXT_MSG", "ACK", "ADVERT", "GRP_TXT",
62
68
  ROUTE_TYPENAMES = ["TC_FLOOD", "FLOOD", "DIRECT", "TC_DIRECT"]
63
69
  CONTACT_TYPENAMES = ["NONE","CLI","REP","ROOM","SENS"]
64
70
 
71
+ # mDNS service type browsed to discover companion radios reachable over tcp
72
+ MDNS_SERVICE = "_meshcore._tcp.local."
73
+
65
74
  # Fallback address if config file not found
66
75
  # if None or "" then a scan is performed
67
76
  ADDRESS = ""
@@ -123,6 +132,11 @@ HANDLERS = { # dicts that will be indexed by numbers
123
132
  LAST_HANDLER_ID = 0
124
133
  HANDLER_QUEUE_SIZE = 100
125
134
 
135
+ # Timers for repeating commands
136
+ TIMERS = {}
137
+ LAST_TIMER_ID = 0
138
+ CMD_LOCK = asyncio.Lock()
139
+
126
140
  # is the companion supposed to have cli
127
141
  HAS_CLI_CMD = False
128
142
 
@@ -157,6 +171,15 @@ LC_SORT_ORDER = ""
157
171
 
158
172
  LAST_DISCOVERED_NODES = []
159
173
 
174
+ def parse_duration(s, unit="s"):
175
+ mult = {"s": 1, "m": 60, "h": 3600, "d": 86400}
176
+ s = str(s).strip()
177
+ if s and s[-1] in mult:
178
+ unit = s[-1]
179
+ s = s[:-1]
180
+ secs = float(s) * mult[unit]
181
+ return secs
182
+
160
183
  def time_ago_from_timestamp (timestamp):
161
184
  if timestamp == 0:
162
185
  return "0"
@@ -228,6 +251,23 @@ def enqueue_handler_event(handler_type, payload):
228
251
  except asyncio.QueueFull:
229
252
  logger.warning(f"Handler {handler['id']} queue is full; dropping event")
230
253
 
254
+ async def run_timer(mc, timer):
255
+ while True:
256
+ await asyncio.sleep(timer["secs"])
257
+ async with CMD_LOCK:
258
+ base = set_scope.current_scope
259
+ if base is None:
260
+ base = ""
261
+ try:
262
+ if timer["scope"] != base:
263
+ await set_scope(mc, timer["scope"])
264
+ await process_redirected_line(mc, timer["cmd"], timer["contact"], timer["scope"], None, base, json_output=timer["json"], sink=sys.stdout)
265
+ except Exception as e:
266
+ logger.error(f"Timer {timer['id']}: {e}")
267
+ finally:
268
+ if timer["scope"] != base:
269
+ await set_scope(mc, base)
270
+
231
271
  async def write_handler(handler):
232
272
  try:
233
273
  while True:
@@ -752,6 +792,9 @@ def make_completion_dict(contacts, pending=None, to=None, channels=None):
752
792
  "handler_attach": {"rxlog":None, "msgs":None, "chan_data":None, "telemetry":None},
753
793
  "handler_detach": None,
754
794
  "handlers": None,
795
+ "timer": None,
796
+ "timer_cancel": None,
797
+ "timers": None,
755
798
  "login" : contact_list,
756
799
  "cmd" : contact_list,
757
800
  "req_status" : contact_list,
@@ -827,9 +870,9 @@ def make_completion_dict(contacts, pending=None, to=None, channels=None):
827
870
  "agc.reset.interval": None,
828
871
  "multi.acks": None,
829
872
  "pin": None,
830
- "wifi.status": None,
831
873
  "wifi.ssid": None,
832
874
  "wifi.pwd": None,
875
+ "wifi.enabled" : {"0": None, "1": None,},
833
876
  "ui.show_clock": None,
834
877
  "ui.auto_off_delay": None,
835
878
  "ui.backlight_delay": None,
@@ -898,6 +941,7 @@ def make_completion_dict(contacts, pending=None, to=None, channels=None):
898
941
  "wifi.status": None,
899
942
  "wifi.ssid": None,
900
943
  "wifi.pwd": None,
944
+ "wifi.enabled": None,
901
945
  "ui.show_clock": None,
902
946
  "ui.auto_off_delay": None,
903
947
  "ui.backlight_delay": None,
@@ -911,6 +955,7 @@ def make_completion_dict(contacts, pending=None, to=None, channels=None):
911
955
  "?scope":None,
912
956
  "?contact_info":None,
913
957
  "?apply_to":None,
958
+ "?timer":None,
914
959
  "?at":None,
915
960
  "?lc":None,
916
961
  "?node_discover":None,
@@ -954,6 +999,7 @@ def make_completion_dict(contacts, pending=None, to=None, channels=None):
954
999
  "unsub_telemetry" : None,
955
1000
  "req_binary" : None,
956
1001
  "forget_password" : None,
1002
+ "timer" : None,
957
1003
  }
958
1004
 
959
1005
  client_completion_list = dict(contact_completion_list)
@@ -1175,9 +1221,6 @@ Some cmds have an help accessible with ?<cmd>. Do ?[Tab] to get a list.
1175
1221
 
1176
1222
  last_ack = True
1177
1223
  while True:
1178
- # reset scope (if changed)
1179
- scope = await set_scope(mc, scope)
1180
-
1181
1224
  # reset sink to stdout
1182
1225
  sink = sys.stdout
1183
1226
 
@@ -1281,40 +1324,15 @@ Some cmds have an help accessible with ?<cmd>. Do ?[Tab] to get a list.
1281
1324
  if line == "quit" or line == "q" or line == "/quit" or line == "/q" :
1282
1325
  break
1283
1326
 
1284
- if line.startswith("@") and len(line) > 1: # alias => replace and resolve parameters
1285
- args = shlex.split(line[1:])
1286
- try:
1287
- alias = ALIASES[args[0]]
1288
-
1289
- if has_placeholder(alias, "c"):
1290
- if not contact is None and contact["type"] > 0:
1291
- keywords = {"c": contact['adv_name']}
1292
- pargs = args[1:]
1293
- else:
1294
- keywords = {"c": args[1]}
1295
- pargs = args[2:]
1296
- else:
1297
- keywords = {}
1298
- pargs = args[1:]
1299
-
1300
- line = formatter.format(alias, *pargs, **keywords)
1301
- except IndexError as e:
1302
- logger.error(f"Error {e}")
1303
- continue
1304
- except KeyError as e:
1305
- logger.error(f"Error {e}")
1306
- continue
1307
- except ValueError as e:
1308
- logger.error(f"Error {e}")
1309
- continue
1310
-
1311
1327
  jo = json_output
1312
1328
  if line.startswith(".") : # toggle json-output for this loop
1313
1329
  jo = True
1314
1330
  line = line[1:].strip()
1315
1331
 
1316
1332
  try:
1317
- (new_contact, new_scope, last_ack) = await process_redirected_line(mc, line, contact, scope, prev_contact, prev_scope, json_output=jo, sink=sink)
1333
+ async with CMD_LOCK:
1334
+ scope = await set_scope(mc, scope) # reset scope (if changed)
1335
+ (new_contact, new_scope, last_ack) = await process_redirected_line(mc, line, contact, scope, prev_contact, prev_scope, json_output=jo, sink=sink)
1318
1336
  except Exception as e:
1319
1337
  logger.error(f"Unexpected error: {e}")
1320
1338
  logger.debug(traceback.format_exc())
@@ -1335,14 +1353,37 @@ Some cmds have an help accessible with ?<cmd>. Do ?[Tab] to get a list.
1335
1353
  # Handle task cancellation from KeyboardInterrupt in asyncio.run()
1336
1354
  sink.write("Exiting cli\n")
1337
1355
  sink.flush()
1356
+ finally:
1357
+ for nb in list(TIMERS):
1358
+ TIMERS.pop(nb)["task"].cancel()
1338
1359
 
1339
1360
  if platform.system() == "Darwin" or platform.system() == "Windows":
1340
1361
  interactive_loop.classic = True
1341
1362
  else:
1342
1363
  interactive_loop.classic = False
1343
1364
 
1344
-
1345
1365
  async def process_redirected_line(mc, line, contact=None, scope="*", prev_contact=None, prev_scope="*", json_output=False, sink=sys.stdout, end="\n"):
1366
+ if line.startswith("@") and len(line) > 1: # alias => replace and resolve parameters
1367
+ try:
1368
+ args = shlex.split(line[1:])
1369
+ alias = ALIASES[args[0]]
1370
+
1371
+ if has_placeholder(alias, "c"):
1372
+ if not contact is None and contact["type"] > 0:
1373
+ keywords = {"c": contact['adv_name']}
1374
+ pargs = args[1:]
1375
+ else:
1376
+ keywords = {"c": args[1]}
1377
+ pargs = args[2:]
1378
+ else:
1379
+ keywords = {}
1380
+ pargs = args[1:]
1381
+
1382
+ line = formatter.format(alias, *pargs, **keywords)
1383
+ except (IndexError, KeyError, ValueError) as e:
1384
+ logger.error(f"Error {e}")
1385
+ return contact, scope, True
1386
+
1346
1387
  new_contact = contact
1347
1388
  new_scope = scope
1348
1389
  last_ack = True
@@ -1767,7 +1808,7 @@ async def process_contact_chat_line(mc, contact, line, inside=False, json_output
1767
1808
 
1768
1809
  if line.startswith("sleep ") or line.startswith("s "):
1769
1810
  try:
1770
- sleeptime = int(line.split(" ",2)[1])
1811
+ sleeptime = parse_duration(line.split(" ",2)[1])
1771
1812
  cmd_pos = 2
1772
1813
  except IndexError: # nothing arg after sleep
1773
1814
  sleeptime = 1
@@ -1826,7 +1867,7 @@ async def process_contact_chat_line(mc, contact, line, inside=False, json_output
1826
1867
 
1827
1868
  if line.startswith("set timeout "):
1828
1869
  cmds=line.split(" ")
1829
- contact["timeout"] = float(cmds[2])
1870
+ contact["timeout"] = parse_duration(cmds[2])
1830
1871
  return True
1831
1872
 
1832
1873
  if line == "get timeout":
@@ -1898,6 +1939,12 @@ async def process_contact_chat_line(mc, contact, line, inside=False, json_output
1898
1939
  # same but for commands with a parameter
1899
1940
  if " " in line:
1900
1941
  cmds = line.split(" ", 1)
1942
+
1943
+ if cmds[0] == "timer": # timer on this contact (a user-given -c still overrides)
1944
+ args = shlex.split(line, posix=True)
1945
+ await process_cmds(mc, args[:1] + ["-c" + contact["adv_name"]] + args[1:], json_output=json_output, sink=sink)
1946
+ return True
1947
+
1901
1948
  if "%" in cmds[0]:
1902
1949
  dest_scope = cmds[0].split("%")[-1]
1903
1950
  cmds[0] = cmds[0][:-len(dest_scope)-1]
@@ -1990,12 +2037,8 @@ async def apply_command_to_contacts(mc, contact_filter, line, json_output=False,
1990
2037
  elif f[0] == "u": #updated
1991
2038
  val_str = f[2:]
1992
2039
  t = time.time()
1993
- if val_str[-1] == "d": # value in days
1994
- t = t - float(val_str[0:-1]) * 86400
1995
- elif val_str[-1] == "h": # value in hours
1996
- t = t - float(val_str[0:-1]) * 3600
1997
- elif val_str[-1] == "m": # value in minutes
1998
- t = t - float(val_str[0:-1]) * 60
2040
+ if val_str[-1] in "smhd": # age
2041
+ t = t - parse_duration(val_str)
1999
2042
  else:
2000
2043
  t = int(val_str)
2001
2044
  if f[1] == "<": #before
@@ -2008,12 +2051,8 @@ async def apply_command_to_contacts(mc, contact_filter, line, json_output=False,
2008
2051
  elif f[0] == "a": # last advert
2009
2052
  val_str = f[2:]
2010
2053
  t = time.time()
2011
- if val_str[-1] == "d": # value in days
2012
- t = t - float(val_str[0:-1]) * 86400
2013
- elif val_str[-1] == "h": # value in hours
2014
- t = t - float(val_str[0:-1]) * 3600
2015
- elif val_str[-1] == "m": # value in minutes
2016
- t = t - float(val_str[0:-1]) * 60
2054
+ if val_str[-1] in "smhd": # age
2055
+ t = t - parse_duration(val_str)
2017
2056
  else:
2018
2057
  t = int(val_str)
2019
2058
  if f[1] == "<": #before
@@ -2436,7 +2475,7 @@ async def next_cmd(mc, cmds, json_output=False, sink=sys.stdout, end="\n"):
2436
2475
  """ process next command
2437
2476
  returns (following, output_str)
2438
2477
  """
2439
- global ARROW_HEAD, SLASH_START, SLASH_END, INVERT_SLASH, LAST_HANDLER_ID
2478
+ global ARROW_HEAD, SLASH_START, SLASH_END, INVERT_SLASH, LAST_HANDLER_ID, LAST_TIMER_ID
2440
2479
  global LC_DISPLAY_TYPES, LC_OUTPUT_FORMAT, LC_SORT_ORDER
2441
2480
  global LAST_DISCOVERED_NODES
2442
2481
  output_str = ""
@@ -3496,7 +3535,7 @@ async def next_cmd(mc, cmds, json_output=False, sink=sys.stdout, end="\n"):
3496
3535
  else:
3497
3536
  output_str += f"Unknown contact {cmds[1]}{end}"
3498
3537
  else:
3499
- contact["timeout"] = float(cmds[2])
3538
+ contact["timeout"] = parse_duration(cmds[2])
3500
3539
 
3501
3540
  case "disc_path" | "dp" :
3502
3541
  argnum = 1
@@ -3753,12 +3792,7 @@ async def next_cmd(mc, cmds, json_output=False, sink=sys.stdout, end="\n"):
3753
3792
  else:
3754
3793
  output_str += f"Unknown contact {cmds[1]}{end}"
3755
3794
  else:
3756
- if cmds[2].endswith("m"):
3757
- duration = int(cmds[2][:-1]) * 60
3758
- elif cmds[2].endswith("h"):
3759
- duration = int(cmds[2][:-1]) * 3600
3760
- else:
3761
- duration = int(cmds[2])
3795
+ duration = int(parse_duration(cmds[2]))
3762
3796
  if cmds[3].startswith('[') or cmds[3].startswith('{'): # json
3763
3797
  min_deltas = json.loads(cmds[3])
3764
3798
  else: # custom formating: chan:type:value,
@@ -3824,22 +3858,8 @@ async def next_cmd(mc, cmds, json_output=False, sink=sys.stdout, end="\n"):
3824
3858
  else:
3825
3859
  output_str += f"Unknown contact {cmds[1]}{end}"
3826
3860
  else:
3827
- if cmds[2][-1] == "s":
3828
- from_secs = int(cmds[2][0:-1])
3829
- elif cmds[2][-1] == "m":
3830
- from_secs = int(cmds[2][0:-1]) * 60
3831
- elif cmds[2][-1] == "h":
3832
- from_secs = int(cmds[2][0:-1]) * 3600
3833
- else :
3834
- from_secs = int(cmds[2]) * 60 # same as tdeck
3835
- if cmds[3][-1] == "s":
3836
- to_secs = int(cmds[3][0:-1])
3837
- elif cmds[3][-1] == "m":
3838
- to_secs = int(cmds[3][0:-1]) * 60
3839
- elif cmds[3][-1] == "h":
3840
- to_secs = int(cmds[3][0:-1]) * 3600
3841
- else :
3842
- to_secs = int(cmds[3]) * 60
3861
+ from_secs = int(parse_duration(cmds[2], "m")) # minutes by default, same as tdeck
3862
+ to_secs = int(parse_duration(cmds[3], "m"))
3843
3863
  timeout = 0 if not "timeout" in contact else contact["timeout"]
3844
3864
  res = await mc.commands.req_mma_sync(contact, from_secs, to_secs, timeout)
3845
3865
  if res is None :
@@ -4453,7 +4473,7 @@ async def next_cmd(mc, cmds, json_output=False, sink=sys.stdout, end="\n"):
4453
4473
 
4454
4474
  case "sleep" | "s" :
4455
4475
  argnum = 1
4456
- await asyncio.sleep(int(cmds[1]))
4476
+ await asyncio.sleep(parse_duration(cmds[1]))
4457
4477
 
4458
4478
  case "wait_key" | "wk" :
4459
4479
  try :
@@ -4477,7 +4497,7 @@ async def next_cmd(mc, cmds, json_output=False, sink=sys.stdout, end="\n"):
4477
4497
 
4478
4498
  case "trywait_msg" | "wmt" :
4479
4499
  argnum = 1
4480
- if await mc.wait_for_event(EventType.MESSAGES_WAITING, timeout=int(cmds[1])) :
4500
+ if await mc.wait_for_event(EventType.MESSAGES_WAITING, timeout=parse_duration(cmds[1])) :
4481
4501
  res = await mc.commands.get_msg()
4482
4502
  logger.debug(res)
4483
4503
  output_str += await process_event_message(mc, res, json_output)
@@ -4637,6 +4657,86 @@ async def next_cmd(mc, cmds, json_output=False, sink=sys.stdout, end="\n"):
4637
4657
  case "handlers":
4638
4658
  output_str += json.dumps(HANDLERS, default=str)+end
4639
4659
 
4660
+ case "timer":
4661
+ argnum = 2 # [-j] [-c<contact>] [-s<scope>] secs line
4662
+ t_contact = None
4663
+ t_scope = set_scope.current_scope
4664
+ if t_scope is None:
4665
+ t_scope = ""
4666
+ t_json = json_output
4667
+ valid = True
4668
+
4669
+ args = cmds[1:]
4670
+ while len(args) > 0 and args[0][0] == "-":
4671
+ argnum += 1
4672
+
4673
+ if args[0].startswith("-j"): # force json output for the timer
4674
+ t_json = True
4675
+
4676
+ if args[0].startswith("-c"): # contact (~ for root)
4677
+ c = args[0][2:]
4678
+ if c == "~" or c == "/":
4679
+ t_contact = None
4680
+ else:
4681
+ t_contact = await get_contact_from_arg(mc, c)
4682
+ if t_contact is None:
4683
+ if c == "public":
4684
+ t_contact = {"adv_name" : "public", "type" : 0, "chan_nb" : 0}
4685
+ if hasattr(mc, "channels"):
4686
+ t_contact["adv_name"] = mc.channels[0]["channel_name"]
4687
+ elif c.startswith("ch") and c[2:].isnumeric():
4688
+ nb = int(c[2:])
4689
+ t_contact = {"adv_name" : c, "type" : 0, "chan_nb" : nb}
4690
+ if hasattr(mc, "channels"):
4691
+ t_contact["adv_name"] = mc.channels[nb]["channel_name"]
4692
+ else:
4693
+ chan = await get_channel_by_name(mc, c)
4694
+ if chan is None:
4695
+ valid = False
4696
+ logger.error(f"Unknown contact {c}")
4697
+ else:
4698
+ t_contact = {"adv_name": chan["channel_name"],
4699
+ "type": 0,
4700
+ "chan_nb": chan["channel_idx"],}
4701
+
4702
+ if args[0].startswith("-s"): # scope
4703
+ t_scope = args[0][2:]
4704
+
4705
+ args = args[1:]
4706
+
4707
+ if valid:
4708
+ LAST_TIMER_ID = LAST_TIMER_ID + 1
4709
+ timer = {}
4710
+ timer["id"] = LAST_TIMER_ID
4711
+ timer["secs"] = parse_duration(args[0])
4712
+ timer["cmd"] = args[1]
4713
+ timer["scope"] = t_scope
4714
+ timer["contact"] = t_contact
4715
+ timer["json"] = t_json
4716
+ timer["task"] = asyncio.create_task(run_timer(mc, timer))
4717
+ TIMERS[LAST_TIMER_ID] = timer
4718
+ if json_output:
4719
+ output_str += json.dumps(timer, default=str)+end
4720
+ else:
4721
+ output_str += f"New timer {timer['id']}{end}"
4722
+
4723
+ case "timer_cancel":
4724
+ argnum = 1
4725
+ nb = int(cmds[1])
4726
+ timer = TIMERS.pop(nb)
4727
+ timer["task"].cancel()
4728
+ try:
4729
+ await timer["task"]
4730
+ except asyncio.CancelledError:
4731
+ pass
4732
+ if json_output:
4733
+ output_str += json.dumps({"timer": timer, "status": "cancelled"}, default=str)+end
4734
+ else:
4735
+ output_str += f"Cancelled timer {nb} of cmd {timer['cmd']}{end}"
4736
+
4737
+ case "timers":
4738
+ output_str += json.dumps(TIMERS, default=str)+end
4739
+
4640
4740
  case "chat" | "im" | "interactive":
4641
4741
  # kept for retrocompatibility, but this is now not
4642
4742
  # allowed to do chat from chat so this will break the loop
@@ -4719,6 +4819,9 @@ def command_help():
4719
4819
  aliases_load : load aliases from a file
4720
4820
  handler_attach <d> <c> : attach c as a handler for d
4721
4821
  handler_detach <n> : detach an handler (from its handle n)
4822
+ timer <s> <c> : runs command c every s seconds
4823
+ timer_cancel <n> : cancels a timer (from its handle n)
4824
+ timers : lists current timers
4722
4825
  Messaging
4723
4826
  msg <name> <msg> : send message to node by name m {
4724
4827
  wait_ack : wait an ack wa }
@@ -4802,8 +4905,8 @@ def command_usage() :
4802
4905
  -D : debug (sets logging to DEBUG)
4803
4906
  -q : quiet (sets logging to ERROR)
4804
4907
  -S : scan for devices and show a selector
4805
- -l : list available ble/serial devices and exit
4806
- -T <timeout> : timeout for the ble scan (-S and -l) default 2s
4908
+ -l : list available ble/tcp (mDNS)/serial devices and exit
4909
+ -T <timeout> : timeout for the ble/mDNS scan (-S and -l) default 2s
4807
4910
  -a <address> : specifies device address (can be a name)
4808
4911
  -d <name> : filter meshcore devices with name or address
4809
4912
  -P : forces pairing via the OS
@@ -5160,6 +5263,22 @@ meshcore-cli lets you attach shell process to msg rx_log chan_data or telemetry
5160
5263
 
5161
5264
  * `handler_detach <n>` detaches handler with number `n`
5162
5265
  * `handlers` lists current handlers
5266
+ """)
5267
+
5268
+ elif "timer" in cmdname:
5269
+ print("""timer [-j] [-c<contact>] [-s<scope>] <s> <line>: runs line every s seconds (s can be postfixed with s, m, h or d)
5270
+
5271
+ * args:
5272
+ - `-j` forces json output for the timed line.
5273
+ - `-c` sets the contact the line is run from (`~` for root).
5274
+ - `-s` sets the scope for the line, defaults to the current scope.
5275
+
5276
+ * `timer_cancel <n>` cancels timer number `n`
5277
+ * `timers` lists current timers
5278
+
5279
+ * Note:
5280
+ - The line has to be quoted if it has more than one word, redirections can be used inside the quotes.
5281
+
5163
5282
  """)
5164
5283
 
5165
5284
  else:
@@ -5601,6 +5720,67 @@ async def repeater_loop(ser):
5601
5720
  await process_repeater_line(ser, cmd, repeater_name=device_name)
5602
5721
 
5603
5722
 
5723
+ async def mdns_discover(timeout=2):
5724
+ """ Browse the network for MeshCore devices advertised through mDNS
5725
+
5726
+ Returns a list of dicts sorted by name, with keys :
5727
+ name : node name (txt record node-name, else instance name)
5728
+ host : mDNS hostname (e.g. "meshcore_mynode.local.") or None
5729
+ port : tcp port
5730
+ addresses : list of ip addresses (as strings)
5731
+ firmware : firmware version (txt record) or None
5732
+
5733
+ Returns an empty list if zeroconf is not available or if the
5734
+ network can't be browsed.
5735
+ """
5736
+ if not ZEROCONF_AVAILABLE:
5737
+ return []
5738
+
5739
+ found = {}
5740
+ pending = set()
5741
+
5742
+ async def resolve(zc, service_type, name):
5743
+ info = AsyncServiceInfo(service_type, name)
5744
+ if await info.async_request(zc, 2000):
5745
+ addresses = info.parsed_addresses()
5746
+ if info.port and addresses:
5747
+ # the instance name is sanitized by the firmware (meshcore_<name>),
5748
+ # the real node name is in the node-name txt record
5749
+ props = {k.decode(errors="replace"): v.decode(errors="replace")
5750
+ for k, v in (info.properties or {}).items() if v is not None}
5751
+ found[name] = {
5752
+ "name": props.get("node-name") or name.removesuffix("." + service_type),
5753
+ "host": info.server,
5754
+ "port": info.port,
5755
+ "addresses": addresses,
5756
+ "firmware": props.get("firmware-version"),
5757
+ }
5758
+
5759
+ def on_service_change(zeroconf, service_type, name, state_change):
5760
+ if state_change is ServiceStateChange.Added:
5761
+ task = asyncio.ensure_future(resolve(zeroconf, service_type, name))
5762
+ pending.add(task)
5763
+ task.add_done_callback(pending.discard)
5764
+
5765
+ aiozc = None
5766
+ browser = None
5767
+ try:
5768
+ aiozc = AsyncZeroconf()
5769
+ browser = AsyncServiceBrowser(aiozc.zeroconf, MDNS_SERVICE,
5770
+ handlers=[on_service_change])
5771
+ await asyncio.sleep(timeout)
5772
+ if pending:
5773
+ await asyncio.gather(*pending, return_exceptions=True)
5774
+ except OSError as e:
5775
+ logger.info(f"mDNS discovery not available: {e}")
5776
+ finally:
5777
+ if browser is not None:
5778
+ await browser.async_cancel()
5779
+ if aiozc is not None:
5780
+ await aiozc.async_close()
5781
+
5782
+ return sorted(found.values(), key=lambda s: s["name"])
5783
+
5604
5784
  async def main(argv):
5605
5785
  """ Do the job """
5606
5786
  global HAS_CLI_CMD
@@ -5678,7 +5858,11 @@ async def main(argv):
5678
5858
  case "-b" :
5679
5859
  baudrate = int(arg)
5680
5860
  case "-t" :
5681
- hostname = arg
5861
+ if arg.count(":") == 1:
5862
+ port = arg.split(":")[1]
5863
+ hostname = arg.split(":")[0]
5864
+ else:
5865
+ hostname = arg
5682
5866
  case "-p" :
5683
5867
  port = int(arg)
5684
5868
  case "-j" :
@@ -5690,7 +5874,7 @@ async def main(argv):
5690
5874
  usage()
5691
5875
  return
5692
5876
  case "-T" :
5693
- timeout = float(arg)
5877
+ timeout = parse_duration(arg)
5694
5878
  case "-v":
5695
5879
  version()
5696
5880
  return
@@ -5699,6 +5883,10 @@ async def main(argv):
5699
5883
  case "-q": # quiet (turns logger to ERROR only)
5700
5884
  quiet = True
5701
5885
  case "-l" :
5886
+ # start mDNS browsing now so it overlaps with the BLE scan
5887
+ mdns_task = None
5888
+ if ZEROCONF_AVAILABLE and not repeater_mode:
5889
+ mdns_task = asyncio.ensure_future(mdns_discover(timeout=timeout))
5702
5890
  if BLEAK_AVAILABLE and not repeater_mode:
5703
5891
  print("BLE devices:")
5704
5892
  try :
@@ -5711,6 +5899,14 @@ async def main(argv):
5711
5899
  except (BleakError, BleakDBusError):
5712
5900
  print(" No BLE HW")
5713
5901
  print("")
5902
+ if mdns_task is not None:
5903
+ print("TCP devices (mDNS):")
5904
+ services = await mdns_task
5905
+ if len(services) == 0:
5906
+ print(" No mDNS device found")
5907
+ for s in services:
5908
+ print(f" {s['addresses'][0] + ':' + str(s['port']):<22} {s['name']}")
5909
+ print("")
5714
5910
  print("Serial ports:")
5715
5911
  ports = serial.tools.list_ports.comports()
5716
5912
  for port, desc, hwid in sorted(ports):
@@ -5718,7 +5914,10 @@ async def main(argv):
5718
5914
  return
5719
5915
  case "-S" :
5720
5916
  choices = []
5721
-
5917
+ # start mDNS browsing now so it overlaps with the BLE scan
5918
+ mdns_task = None
5919
+ if ZEROCONF_AVAILABLE and not repeater_mode:
5920
+ mdns_task = asyncio.ensure_future(mdns_discover(timeout=timeout))
5722
5921
  if BLEAK_AVAILABLE and not repeater_mode:
5723
5922
  try :
5724
5923
  devices = await BleakScanner.discover(timeout=timeout)
@@ -5727,7 +5926,10 @@ async def main(argv):
5727
5926
  choices.append(({"type":"ble","device":d}, f"{d.address:<22} {d.name}"))
5728
5927
  except (BleakError, BleakDBusError):
5729
5928
  logger.info("No BLE Device")
5730
-
5929
+ if mdns_task is not None:
5930
+ services = await mdns_task
5931
+ for s in services:
5932
+ choices.append(({"type":"tcp","address":s['addresses'][0],"port":s['port']}, f"{s['addresses'][0] + ':' + str(s['port']):<22} {s['name']}"))
5731
5933
  ports = serial.tools.list_ports.comports()
5732
5934
  for port, desc, hwid in sorted(ports):
5733
5935
  choices.append(({"type":"serial","port":port}, f"{port:<22} {desc}"))
@@ -5749,6 +5951,9 @@ async def main(argv):
5749
5951
  device = result["device"]
5750
5952
  elif result["type"] == "serial":
5751
5953
  serial_port = result["port"]
5954
+ elif result["type"] == "tcp":
5955
+ hostname = result["address"]
5956
+ port = result["port"]
5752
5957
  else:
5753
5958
  logger.error("Invalid choice")
5754
5959
  return
@@ -5780,7 +5985,39 @@ async def main(argv):
5780
5985
 
5781
5986
  mc = None
5782
5987
  if not hostname is None : # connect via tcp
5783
- mc = await MeshCore.create_tcp(host=hostname, port=port, debug=debug, only_error=json_output)
5988
+ try:
5989
+ mc = await MeshCore.create_tcp(host=hostname, port=port, debug=debug, only_error=json_output)
5990
+ except Exception as err:
5991
+ if ZEROCONF_AVAILABLE and not repeater_mode and hostname and not (':' in hostname or hostname.replace('.', '').isdigit()):
5992
+ logger.debug(f"Error trying to connect via TCP: {err} ... trying mDNS")
5993
+ services = await mdns_discover(timeout=timeout)
5994
+ mc = None
5995
+ name = hostname.lower()
5996
+ srv = None
5997
+ for s in services:
5998
+ if name == s['name'].lower(): # priorize exact match
5999
+ srv = s
6000
+ break
6001
+ if srv is None:
6002
+ for s in services:
6003
+ if name in s['name'].lower() or s['host'] and name in s['host'].lower():
6004
+ srv = s
6005
+ break
6006
+ if srv:
6007
+ hostname = srv['addresses'][0]
6008
+ port = srv['port']
6009
+ else:
6010
+ print(f"Could not find {hostname} with mDNS")
6011
+ return
6012
+
6013
+ try:
6014
+ mc = await MeshCore.create_tcp(host=hostname, port=port, debug=debug, only_error=json_output)
6015
+ except Exception:
6016
+ print("Could not connect via TCP")
6017
+ return
6018
+ else:
6019
+ print(f"Could not connect via TCP err:{err}")
6020
+ return
5784
6021
  elif not serial_port is None : # connect via serial port
5785
6022
  mc = await MeshCore.create_serial(port=serial_port, baudrate=baudrate, debug=debug, only_error=json_output, dtr=serial_dtr, rts=serial_rts)
5786
6023
  if mc is None: # did not connect
File without changes
File without changes
File without changes
File without changes