meshcore-cli 1.6.4__tar.gz → 1.6.6__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,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: meshcore-cli
3
- Version: 1.6.4
3
+ Version: 1.6.6
4
4
  Summary: Command line interface to meshcore companion radios and repeaters
5
5
  Project-URL: Homepage, https://github.com/fdlamotte/meshcore-cli
6
6
  Project-URL: Issues, https://github.com/fdlamotte/meshcore-cli/issues
@@ -11,7 +11,7 @@ Classifier: Operating System :: OS Independent
11
11
  Classifier: Programming Language :: Python :: 3
12
12
  Requires-Python: >=3.10
13
13
  Requires-Dist: bleak>=0.22
14
- Requires-Dist: meshcore>=2.3.11
14
+ Requires-Dist: meshcore>=2.3.16
15
15
  Requires-Dist: prompt-toolkit>=3.0.50
16
16
  Requires-Dist: requests>=2.28.0
17
17
  Description-Content-Type: text/markdown
@@ -17,12 +17,12 @@
17
17
 
18
18
  meshcore = python3Packages.buildPythonPackage rec {
19
19
  pname = "meshcore";
20
- version = "2.3.11";
20
+ version = "2.3.16";
21
21
  pyproject = true;
22
22
 
23
23
  src = python3Packages.fetchPypi {
24
24
  inherit pname version;
25
- sha256 = "sha256-eBu8VzOyVuGrxK1pfGzDjxxPx8zFORHeyslxehYgeWE=";
25
+ sha256 = "sha256-HU3D2oJKwtecMJHv7zGUjIuuk+hPfRBZQTMaSNamR9A=";
26
26
  };
27
27
 
28
28
  build-system = [ python3Packages.hatchling ];
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "meshcore-cli"
7
- version = "1.6.4"
7
+ version = "1.6.6"
8
8
  authors = [
9
9
  { name="Florent de Lamotte", email="florent@frizoncorrea.fr" },
10
10
  ]
@@ -17,7 +17,7 @@ classifiers = [
17
17
  ]
18
18
  license = "MIT"
19
19
  license-files = ["LICEN[CS]E*"]
20
- dependencies = [ "meshcore >= 2.3.11",
20
+ dependencies = [ "meshcore >= 2.3.16",
21
21
  "bleak >= 0.22",
22
22
  "prompt_toolkit >= 3.0.50",
23
23
  "requests >= 2.28.0" ]
@@ -35,7 +35,7 @@ except ImportError:
35
35
  from meshcore import MeshCore, EventType, logger
36
36
 
37
37
  # Version
38
- VERSION = "v1.6.4"
38
+ VERSION = "v1.6.6"
39
39
 
40
40
  # default ble address is stored in a config file
41
41
  MCCLI_CONFIG_DIR = os.path.expanduser("~/.config/meshcore/")
@@ -69,6 +69,7 @@ JSON = False
69
69
 
70
70
  PS = None
71
71
  CS = None
72
+ DS = None
72
73
 
73
74
  # Ansi colors
74
75
  ANSI_END = "\033[0m"
@@ -116,6 +117,7 @@ ALIASES={}
116
117
  HANDLERS = { # dicts that will be indexed by numbers
117
118
  "rxlog" : {},
118
119
  "msgs" : {},
120
+ "chan_data" : {},
119
121
  }
120
122
  LAST_HANDLER_ID = 0
121
123
  HANDLER_QUEUE_SIZE = 100
@@ -153,7 +155,17 @@ LC_OUTPUT_FORMAT = "tkah"
153
155
  LC_SORT_ORDER = ""
154
156
 
155
157
  def time_ago_from_timestamp (timestamp):
158
+ if timestamp == 0:
159
+ return "0"
160
+
156
161
  duration = int(time.time()) - timestamp
162
+ in_future=False
163
+ if duration < 0 :
164
+ in_future = True
165
+ duration = -duration
166
+ if duration > 86400: # > 1 day drift
167
+ return ""
168
+
157
169
  if duration / 86400 >= 1 : # result in days
158
170
  days_ago = int(duration/86400)
159
171
  if days_ago >= 365:
@@ -166,6 +178,10 @@ def time_ago_from_timestamp (timestamp):
166
178
  time_ago = f"{int(duration/60)}m"
167
179
  else :
168
180
  time_ago = f"{int(duration)}s"
181
+
182
+ if in_future :
183
+ time_ago = "+" + time_ago
184
+
169
185
  return time_ago
170
186
 
171
187
  def haversine_distance(coord1, coord2):
@@ -313,7 +329,9 @@ async def process_event_message(mc, ev, json_output, end="\n"):
313
329
 
314
330
  path_str = ""
315
331
 
316
- if process_event_message.timestamp != "" and process_event_message.timestamp != "off":
332
+ if "sender_timestamp" in data\
333
+ and process_event_message.timestamp != ""\
334
+ and process_event_message.timestamp != "off":
317
335
  ts = data["sender_timestamp"]
318
336
  if process_event_message.timestamp == "on":
319
337
  if (abs(time.time()-ts) < 86400):
@@ -331,7 +349,7 @@ async def process_event_message(mc, ev, json_output, end="\n"):
331
349
  if "SNR" in data and process_event_message.print_snr:
332
350
  path_str = path_str + f",{data['SNR']}dB"
333
351
 
334
- if (data['type'] == "PRIV") :
352
+ if ('type' in data and data['type'] == "PRIV") :
335
353
  ct = mc.get_contact_by_key_prefix(data['pubkey_prefix'])
336
354
  if ct is None:
337
355
  logger.debug(f"Unknown contact with pubkey prefix: {data['pubkey_prefix']}")
@@ -369,7 +387,7 @@ async def process_event_message(mc, ev, json_output, end="\n"):
369
387
 
370
388
  output_str += disp + end
371
389
 
372
- elif (data['type'] == "CHAN") :
390
+ elif ('type' in data and data['type'] == "CHAN") :
373
391
  path_str = f"{ANSI_YELLOW}({path_str}){ANSI_END}"
374
392
  if hasattr(mc, "channels"):
375
393
  ch_name = mc.channels[data['channel_idx']]['channel_name']
@@ -388,12 +406,32 @@ async def process_event_message(mc, ev, json_output, end="\n"):
388
406
  disp = escape_ansi(disp)
389
407
 
390
408
  output_str += disp + end
409
+
410
+ elif ('type' in data and data['type'] == "DATA") :
411
+ if process_event_message.display_channel_data:
412
+ path_str = f"{ANSI_YELLOW}({path_str}){ANSI_END}"
413
+ if hasattr(mc, "channels"):
414
+ ch_name = mc.channels[data['channel_idx']]['channel_name']
415
+ disp = f"{ANSI_GREEN}{ch_name} {path_str}"
416
+ process_event_message.last_node = {"adv_name" : ch_name, "type" : 0, "chan_nb" : data['channel_idx']}
417
+ elif data["channel_idx"] == 0: #public
418
+ disp = f"{ANSI_GREEN}public {path_str}"
419
+ process_event_message.last_node = {"adv_name" : "public", "type" : 0, "chan_nb" : 0}
420
+ else :
421
+ disp = f"{ANSI_GREEN}ch{data['channel_idx']} {path_str}"
422
+ process_event_message.last_node = {"adv_name" : f"ch{data['channel_idx']}", "type" : 0, "chan_nb" : data['channel_idx']}
423
+ disp = disp + f"{ANSI_END} "
424
+ disp += json.dumps(ev.payload)
425
+
426
+ output_str += disp + end
427
+
391
428
  else:
392
429
  output_str += json.dumps(ev.payload) + end
393
430
  return output_str
394
431
  process_event_message.print_snr=False
395
432
  process_event_message.color=True
396
433
  process_event_message.last_node=None
434
+ process_event_message.display_channel_data=True
397
435
  process_event_message.timestamp=""
398
436
 
399
437
  async def handle_log_rx(event):
@@ -543,24 +581,25 @@ async def log_message(mc, msg):
543
581
  if log_message.file is None:
544
582
  return
545
583
 
546
- if msg["type"] == "PRIV" :
547
- ct = mc.get_contact_by_key_prefix(msg['pubkey_prefix'])
548
- if ct is None:
549
- msg["name"] = msg["pubkey_prefix"]
550
- msg["sender"] = msg["pubkey_prefix"]
551
- else:
552
- msg["name"] = ct["adv_name"]
553
- msg["sender"] = ct["adv_name"]
554
- elif msg["type"] == "CHAN" :
555
- if hasattr(mc, 'channels') :
556
- msg["sender"] = mc.channels[msg['channel_idx']]["channel_name"]
557
- else:
558
- msg["sender"] = f"channel {msg['channel_idx']}"
559
- msg["name"] = msg["sender"]
560
- msg["timestamp"] = int(time.time())
561
-
562
- with open(log_message.file, "a") as logfile:
563
- logfile.write(json.dumps(msg) + "\n")
584
+ if "type" in msg and msg["type"] != "DATA":
585
+ if msg["type"] == "PRIV" :
586
+ ct = mc.get_contact_by_key_prefix(msg['pubkey_prefix'])
587
+ if ct is None:
588
+ msg["name"] = msg["pubkey_prefix"]
589
+ msg["sender"] = msg["pubkey_prefix"]
590
+ else:
591
+ msg["name"] = ct["adv_name"]
592
+ msg["sender"] = ct["adv_name"]
593
+ elif msg["type"] == "CHAN" :
594
+ if hasattr(mc, 'channels') :
595
+ msg["sender"] = mc.channels[msg['channel_idx']]["channel_name"]
596
+ else:
597
+ msg["sender"] = f"channel {msg['channel_idx']}"
598
+ msg["name"] = msg["sender"]
599
+ msg["timestamp"] = int(time.time())
600
+
601
+ with open(log_message.file, "a") as logfile:
602
+ logfile.write(json.dumps(msg) + "\n")
564
603
 
565
604
  log_message.file=None
566
605
 
@@ -571,7 +610,11 @@ async def handle_message(event):
571
610
  json_output=handle_message.json_output), end="")
572
611
  await log_message(handle_message.mc, event.payload.copy())
573
612
 
574
- enqueue_handler_event("msgs", event.payload)
613
+ pld = event.payload
614
+ if "type" in pld and pld["type"] == "DATA":
615
+ enqueue_handler_event("chan_data", event.payload)
616
+ else:
617
+ enqueue_handler_event("msgs", event.payload)
575
618
 
576
619
  handle_message.json_output=False
577
620
  handle_message.mc=None
@@ -579,7 +622,7 @@ handle_message.display=True
579
622
 
580
623
  async def subscribe_to_msgs(mc, json_output=False):
581
624
  """ Subscribe to incoming messages """
582
- global PS, CS
625
+ global PS, CS, DS
583
626
  await mc.ensure_contacts()
584
627
  handle_message.json_output = json_output
585
628
  # Subscribe to private messages
@@ -588,6 +631,9 @@ async def subscribe_to_msgs(mc, json_output=False):
588
631
  # Subscribe to channel messages
589
632
  if CS is None :
590
633
  CS = mc.subscribe(EventType.CHANNEL_MSG_RECV, handle_message)
634
+ # Subscribe to channel data
635
+ if DS is None :
636
+ DS = mc.subscribe(EventType.CHANNEL_DATA_RECV, handle_message)
591
637
  await mc.start_auto_message_fetching()
592
638
 
593
639
  # redefine get_completion to let user put symbols in first item
@@ -650,11 +696,12 @@ def make_completion_dict(contacts, pending=None, to=None, channels=None):
650
696
  completion_list = {
651
697
  "to" : to_list,
652
698
  "/to" : to_list,
653
- "public" : None,
654
- "chan" : None,
655
699
  }
656
700
 
657
701
  root_completion_list = {
702
+ "public" : None,
703
+ "chan" : None,
704
+ "chan_data" : None,
658
705
  "ver" : None,
659
706
  "infos" : None,
660
707
  "advert" : None,
@@ -685,12 +732,13 @@ def make_completion_dict(contacts, pending=None, to=None, channels=None):
685
732
  "change_flags" : contact_list,
686
733
  "remove_contact" : contact_list,
687
734
  "add_contact" : {"key type name":None},
735
+ "reset_advert_time" : contact_list,
688
736
  "import_contact" : {"meshcore://":None},
689
737
  "reload_contacts" : None,
690
738
  "aliases" : None,
691
739
  "aliases_load" : None,
692
740
  "alias" : None,
693
- "handler_attach": {"rxlog":None, "msgs":None},
741
+ "handler_attach": {"rxlog":None, "msgs":None, "chan_data":None},
694
742
  "handler_detach": None,
695
743
  "handlers": None,
696
744
  "login" : contact_list,
@@ -731,6 +779,7 @@ def make_completion_dict(contacts, pending=None, to=None, channels=None):
731
779
  "lc_output_format":None,
732
780
  "lc_sort_order":None,
733
781
  "print_adverts" : {"on":None, "off":None},
782
+ "display_channel_data" : {"on":None, "off":None},
734
783
  "json_log_rx" : {"on":None, "off":None},
735
784
  "channel_echoes" : {"on":None, "off":None},
736
785
  "advert_echoes" : {"on":None, "off":None},
@@ -766,6 +815,7 @@ def make_completion_dict(contacts, pending=None, to=None, channels=None):
766
815
  "print_timestamp":None,
767
816
  "json_msgs":None,
768
817
  "color":None,
818
+ "display_channel_data":None,
769
819
  "lc_output_format":None,
770
820
  "lc_sort_order":None,
771
821
  "print_adverts":None,
@@ -840,6 +890,7 @@ def make_completion_dict(contacts, pending=None, to=None, channels=None):
840
890
  "reset_path" : None,
841
891
  "change_path" : None,
842
892
  "change_flags" : None,
893
+ "reset_advert_time" : None,
843
894
  "req_telemetry" : None,
844
895
  "req_binary" : None,
845
896
  "forget_password" : None,
@@ -1229,84 +1280,84 @@ else:
1229
1280
 
1230
1281
 
1231
1282
  async def process_redirected_line(mc, line, contact=None, scope="*", prev_contact=None, prev_scope="*", json_output=False, sink=sys.stdout, end="\n"):
1232
- new_contact = contact
1233
- new_scope = scope
1234
- last_ack = True
1235
-
1236
- if line.startswith(">>") : # append to-file redirection
1237
- line = line[2:].strip()
1238
- try:
1239
- fp, mcline = split_first_token(line)
1240
- fp = os.path.expanduser(fp)
1241
- with open(fp, "a") as file:
1242
- (new_contact, new_scope, last_ack) = await process_redirected_line(mc, mcline, contact, scope, prev_contact, prev_scope, json_output=json_output, sink=file)
1243
- except ValueError:
1244
- logger.error("Couldn't parse filename")
1245
- except OSError as e:
1246
- logger.error(f"Cannot append to file: {e}")
1283
+ new_contact = contact
1284
+ new_scope = scope
1285
+ last_ack = True
1247
1286
 
1248
- elif line.startswith(">") : # to-file redirection
1249
- line = line[1:].strip()
1250
- try:
1251
- fp, mcline = split_first_token(line)
1252
- fp = os.path.expanduser(fp)
1253
- with open(fp, "w") as file:
1254
- (new_contact, new_scope, last_ack) = await process_redirected_line(mc, mcline, contact, scope, prev_contact, prev_scope, json_output=json_output, sink=file)
1255
- except ValueError:
1256
- logger.error("Couldn't parse filename")
1257
- except OSError as e:
1258
- logger.error(f"Cannot write to file: {e}")
1287
+ if line.startswith(">>") : # append to-file redirection
1288
+ line = line[2:].strip()
1289
+ try:
1290
+ fp, mcline = split_first_token(line)
1291
+ fp = os.path.expanduser(fp)
1292
+ with open(fp, "a") as file:
1293
+ (new_contact, new_scope, last_ack) = await process_redirected_line(mc, mcline, contact, scope, prev_contact, prev_scope, json_output=json_output, sink=file)
1294
+ except ValueError:
1295
+ logger.error("Couldn't parse filename")
1296
+ except OSError as e:
1297
+ logger.error(f"Cannot append to file: {e}")
1259
1298
 
1260
- elif line.startswith("|") : # to process redirection
1261
- line = line[1:].strip()
1262
- try:
1263
- pcom, mcline = split_first_token(line)
1264
- with subprocess.Popen(shlex.split(pcom, posix=True), stdin=subprocess.PIPE, stdout=sink,text=True) as process:
1265
- (new_contact, new_scope, last_ack) = await process_redirected_line(mc, mcline, contact, scope, prev_contact, prev_scope, json_output=json_output, sink=process.stdin)
1266
- except ValueError:
1267
- logger.error("Couldn't parse name")
1268
- except FileNotFoundError:
1269
- logger.error(f"File not found {pcom}")
1270
- except PermissionError:
1271
- logger.error(f"Permission denied: {pcom}")
1272
- except OSError as e:
1273
- logger.error(f"Cannot pipe: {e}")
1274
- except BrokenPipeError:
1275
- logger.error(f"Broken pipe")
1299
+ elif line.startswith(">") : # to-file redirection
1300
+ line = line[1:].strip()
1301
+ try:
1302
+ fp, mcline = split_first_token(line)
1303
+ fp = os.path.expanduser(fp)
1304
+ with open(fp, "w") as file:
1305
+ (new_contact, new_scope, last_ack) = await process_redirected_line(mc, mcline, contact, scope, prev_contact, prev_scope, json_output=json_output, sink=file)
1306
+ except ValueError:
1307
+ logger.error("Couldn't parse filename")
1308
+ except OSError as e:
1309
+ logger.error(f"Cannot write to file: {e}")
1276
1310
 
1277
- elif line.startswith("<") : # from process redirection
1278
- try:
1279
- if line[1] == "|":
1280
- key = ""
1281
- line = line[2:].strip()
1282
- else:
1283
- key = line[1:].split("|", 1)[0].strip()
1284
- line = line[1:].split("|", 1)[1].strip()
1285
-
1286
- pcom, mcline = split_first_token(line)
1287
- res = subprocess.run(shlex.split(pcom, posix=True), capture_output=True, text=True)
1288
- replacement = res.stdout.strip()
1289
- if key == "":
1290
- mcline = formatter.format(mcline,replacement)
1291
- else:
1292
- keywords = {key: replacement}
1293
- mcline = formatter.format(mcline, **keywords)
1294
- (new_contact, new_scope, last_ack) = await process_redirected_line(mc, mcline, contact, scope, prev_contact, prev_scope, json_output=json_output, sink=sink)
1295
- except IndexError as e:
1296
- logger.error(f"Error with substitution: {e}")
1297
- except ValueError:
1298
- logger.error("Couldn't parse name")
1299
- except FileNotFoundError:
1300
- logger.error(f"File not found {pcom}")
1301
- except PermissionError:
1302
- logger.error(f"Permission denied: {pcom}")
1303
- except OSError as e:
1304
- logger.error(f"Cannot pipe: {e}")
1305
- except BrokenPipeError:
1306
- logger.error(f"Broken pipe")
1307
- else :
1308
- (new_contact, new_scope, last_ack) = await process_pipeline(mc, line, contact, scope, prev_contact, prev_scope, json_output=json_output, sink=sink)
1309
- return new_contact, new_scope, last_ack
1311
+ elif line.startswith("|") : # to process redirection
1312
+ line = line[1:].strip()
1313
+ try:
1314
+ pcom, mcline = split_first_token(line)
1315
+ with subprocess.Popen(shlex.split(pcom, posix=True), stdin=subprocess.PIPE, stdout=sink,text=True) as process:
1316
+ (new_contact, new_scope, last_ack) = await process_redirected_line(mc, mcline, contact, scope, prev_contact, prev_scope, json_output=json_output, sink=process.stdin)
1317
+ except ValueError:
1318
+ logger.error("Couldn't parse name")
1319
+ except FileNotFoundError:
1320
+ logger.error(f"File not found {pcom}")
1321
+ except PermissionError:
1322
+ logger.error(f"Permission denied: {pcom}")
1323
+ except OSError as e:
1324
+ logger.error(f"Cannot pipe: {e}")
1325
+ except BrokenPipeError:
1326
+ logger.error(f"Broken pipe")
1327
+
1328
+ elif line.startswith("<") : # from process redirection
1329
+ try:
1330
+ if line[1] == "|":
1331
+ key = ""
1332
+ line = line[2:].strip()
1333
+ else:
1334
+ key = line[1:].split("|", 1)[0].strip()
1335
+ line = line[1:].split("|", 1)[1].strip()
1336
+
1337
+ pcom, mcline = split_first_token(line)
1338
+ res = subprocess.run(shlex.split(pcom, posix=True), capture_output=True, text=True)
1339
+ replacement = res.stdout.strip()
1340
+ if key == "":
1341
+ mcline = formatter.format(mcline,replacement)
1342
+ else:
1343
+ keywords = {key: replacement}
1344
+ mcline = formatter.format(mcline, **keywords)
1345
+ (new_contact, new_scope, last_ack) = await process_redirected_line(mc, mcline, contact, scope, prev_contact, prev_scope, json_output=json_output, sink=sink)
1346
+ except IndexError as e:
1347
+ logger.error(f"Error with substitution: {e}")
1348
+ except ValueError:
1349
+ logger.error("Couldn't parse name")
1350
+ except FileNotFoundError:
1351
+ logger.error(f"File not found {pcom}")
1352
+ except PermissionError:
1353
+ logger.error(f"Permission denied: {pcom}")
1354
+ except OSError as e:
1355
+ logger.error(f"Cannot pipe: {e}")
1356
+ except BrokenPipeError:
1357
+ logger.error(f"Broken pipe")
1358
+ else :
1359
+ (new_contact, new_scope, last_ack) = await process_pipeline(mc, line, contact, scope, prev_contact, prev_scope, json_output=json_output, sink=sink)
1360
+ return new_contact, new_scope, last_ack
1310
1361
 
1311
1362
  async def process_pipeline(mc, pipeline, contact=None, scope="*", prev_contact=None, prev_scope="*", json_output=False, sink=sys.stdout, end="\n"):
1312
1363
 
@@ -1691,6 +1742,7 @@ async def process_contact_chat_line(mc, contact, line, inside=False, json_output
1691
1742
  line.startswith("req_acl") or line == "ra" or line.startswith("ra ") or\
1692
1743
  line.startswith("path ") or line == "path" or\
1693
1744
  line.startswith("advert_path") or line == "ap" or line.startswith("ap ") or\
1745
+ line.startswith("reset_advert_time") or\
1694
1746
  line.startswith("logout") :
1695
1747
  args = [line.split()[0], contact['adv_name']]
1696
1748
  out_str = ""
@@ -1851,6 +1903,8 @@ async def process_contact_chat_line(mc, contact, line, inside=False, json_output
1851
1903
  async def apply_command_to_contacts(mc, contact_filter, line, json_output=False, sink=sys.stdout, end="\n"):
1852
1904
  upd_before = None
1853
1905
  upd_after = None
1906
+ adv_before = None
1907
+ adv_after = None
1854
1908
  contact_type = None
1855
1909
  min_hops = None
1856
1910
  max_hops = None
@@ -1881,6 +1935,24 @@ async def apply_command_to_contacts(mc, contact_filter, line, json_output=False,
1881
1935
  else:
1882
1936
  logger.error(f"Time filter can only be < or >")
1883
1937
  return ""
1938
+ elif f[0] == "a": # last advert
1939
+ val_str = f[2:]
1940
+ t = time.time()
1941
+ if val_str[-1] == "d": # value in days
1942
+ t = t - float(val_str[0:-1]) * 86400
1943
+ elif val_str[-1] == "h": # value in hours
1944
+ t = t - float(val_str[0:-1]) * 3600
1945
+ elif val_str[-1] == "m": # value in minutes
1946
+ t = t - float(val_str[0:-1]) * 60
1947
+ else:
1948
+ t = int(val_str)
1949
+ if f[1] == "<": #before
1950
+ adv_before = t
1951
+ elif f[1] == ">":
1952
+ adv_after = t
1953
+ else:
1954
+ logger.error(f"Time filter can only be < or >")
1955
+ return ""
1884
1956
  elif f[0] == "t": # type
1885
1957
  if f[1] == "=":
1886
1958
  contact_type = int(f[2:])
@@ -1915,6 +1987,8 @@ async def apply_command_to_contacts(mc, contact_filter, line, json_output=False,
1915
1987
  if (contact_type is None or contact["type"] == contact_type) and\
1916
1988
  (upd_before is None or contact["lastmod"] < upd_before) and\
1917
1989
  (upd_after is None or contact["lastmod"] > upd_after) and\
1990
+ (adv_before is None or contact["last_advert"] < adv_before) and\
1991
+ (adv_after is None or contact["last_advert"] > adv_after) and\
1918
1992
  (min_hops is None or contact["out_path_len"] >= min_hops) and\
1919
1993
  (max_hops is None or contact["out_path_len"] <= max_hops) and\
1920
1994
  (flags is None or contact["flags"] & flags == flags):
@@ -2434,6 +2508,8 @@ async def next_cmd(mc, cmds, json_output=False, sink=sys.stdout, end="\n"):
2434
2508
  SLASH_END = cmds[2]
2435
2509
  case "invert_slash":
2436
2510
  INVERT_SLASH = cmds[2] == "on"
2511
+ case "display_channel_data":
2512
+ process_event_message.display_channel_data = (cmds[2] == "on")
2437
2513
  case "color" :
2438
2514
  process_event_message.color = (cmds[2] == "on")
2439
2515
  if json_output :
@@ -2732,6 +2808,11 @@ async def next_cmd(mc, cmds, json_output=False, sink=sys.stdout, end="\n"):
2732
2808
  output_str += json.dumps({"json_msgs" : handle_message.json_output})+end
2733
2809
  else:
2734
2810
  output_str += f"{'on' if handle_message.json_output else 'off'}{end}"
2811
+ case "display_channel_data":
2812
+ if json_output :
2813
+ output_str += json.dumps({"display_channel_data" : process_event_message.display_channel_data})+end
2814
+ else:
2815
+ output_str += f"{'on' if process_event_message.display_channel_data else 'off'}{end}"
2735
2816
  case "color":
2736
2817
  if json_output :
2737
2818
  output_str += json.dumps({"color" : process_event_message.color})+end
@@ -3098,23 +3179,44 @@ async def next_cmd(mc, cmds, json_output=False, sink=sys.stdout, end="\n"):
3098
3179
  argnum = 2
3099
3180
  dest = None
3100
3181
 
3101
- if len(cmds[1]) >= 12: # possibly an hex prefix
3182
+ wait_ack = False
3183
+
3184
+ args = cmds[1:]
3185
+ while len(args) > 0 and args[0][0] == "-":
3186
+ argnum += 1
3187
+ if len(args[0]) <= 1: # just a dash
3188
+ args=args[1:]
3189
+ continue
3190
+ a = args[0][1:]
3191
+ if a[0] == "a": # wait for an ack
3192
+ wait_ack = True
3193
+
3194
+ args = args[1:]
3195
+
3196
+ if len(args[0]) >= 12: # possibly an hex prefix
3102
3197
  try:
3103
- dest = bytes.fromhex(cmds[1])
3198
+ dest = bytes.fromhex(args[0])
3104
3199
  except ValueError:
3105
3200
  dest = None
3106
3201
 
3107
3202
  if dest is None:
3108
- dest = await get_contact_from_arg(mc, cmds[1])
3203
+ dest = await get_contact_from_arg(mc, args[0])
3109
3204
 
3110
3205
  if dest is None:
3111
3206
  if json_output :
3112
- output_str += json.dumps({"error" : "unknown destination", "dest" : cmds[1]})+end
3207
+ output_str += json.dumps({"error" : "unknown destination", "dest" : args[0]})+end
3113
3208
  else:
3114
- output_str += f"Unknown destination {cmds[1]}{end}"
3209
+ output_str += f"Unknown destination {args[0]}{end}"
3115
3210
 
3116
- else :
3117
- res = await send_msg(mc, dest, cmds[2])
3211
+ elif wait_ack:
3212
+ ack = await msg_ack(mc, dest, args[1])
3213
+ if not ack:
3214
+ if json_output:
3215
+ output_str += json.dumps({"ack" : ack})+end
3216
+ else:
3217
+ output_str += f"No ack received{end}"
3218
+ else:
3219
+ res = await send_msg(mc, dest, args[1])
3118
3220
  logger.debug(res)
3119
3221
  if res.type == EventType.ERROR:
3120
3222
  output_str += f"Error sending message: {res}{end}"
@@ -3141,6 +3243,47 @@ async def next_cmd(mc, cmds, json_output=False, sink=sys.stdout, end="\n"):
3141
3243
  elif json_output :
3142
3244
  output_str += json.dumps(res.payload, indent=4)+end
3143
3245
 
3246
+ case "chan_data" :
3247
+ argnum = 3 # [-p path:hash_mode] chan datatype payload
3248
+ path_hash_mode = 0
3249
+ path = None
3250
+
3251
+ args = cmds[1:]
3252
+ while len(args) > 0 and args[0][0] == "-":
3253
+ arg = args[0]
3254
+
3255
+ if arg.startswith("-p"): # path comes as hex string with mode after `:`
3256
+ path_str = arg[2:]
3257
+ if ":" in path_str:
3258
+ path_hash_mode = int(path_str.split(":")[1])
3259
+ if path_str.split(":")[0] == "0": # 0-hop message
3260
+ path = bytes([])
3261
+ else:
3262
+ path = bytes.fromhex(path_str.split(":")[0])
3263
+
3264
+ argnum += 1
3265
+ args = args[1:] # next argument
3266
+
3267
+ if args[0].isnumeric() :
3268
+ nb = int(args[0])
3269
+ else:
3270
+ chan = await get_channel_by_name(mc, args[0])
3271
+ if chan is None:
3272
+ nb = None
3273
+ else:
3274
+ nb = chan['channel_idx']
3275
+ if nb is None:
3276
+ logger.error("Invalid channel")
3277
+ else:
3278
+ res = await mc.commands.send_channel_data(
3279
+ nb, int(args[1],0), bytes.fromhex(args[2]),
3280
+ path = path, path_hash_mode = path_hash_mode)
3281
+ logger.debug(res)
3282
+ if res.type == EventType.ERROR:
3283
+ output_str += f"Error sending chan data: {res}{end}"
3284
+ elif json_output :
3285
+ output_str += json.dumps(res.payload, indent=4)+end
3286
+
3144
3287
  case "public" | "dch" : # default chan
3145
3288
  argnum = 1
3146
3289
  res = await send_chan_msg(mc, 0, cmds[1])
@@ -3316,32 +3459,41 @@ async def next_cmd(mc, cmds, json_output=False, sink=sys.stdout, end="\n"):
3316
3459
  output_str += f"Path for {contact['adv_name']}: out {outp}, in {inp}{end}"
3317
3460
 
3318
3461
  case "node_discover"|"nd" :
3319
- argnum = 1
3462
+ argnum = 0
3463
+ types = 0xFF
3320
3464
  prefix_only = True
3465
+ filter_args = False
3321
3466
 
3322
- if len(cmds) == 1:
3323
- argnum = 0
3324
- types = 0xFF
3325
- else:
3326
- try: # try to decode type as int
3327
- types = int(cmds[1])
3328
- except ValueError:
3329
- if "all" in cmds[1]:
3330
- types = 0xFF
3331
- else :
3332
- types = 0
3333
- if "rep" in cmds[1] or "rpt" in cmds[1]:
3334
- types = types | 4
3335
- if "cli" in cmds[1] or "comp" in cmds[1]:
3336
- types = types | 2
3337
- if "room" in cmds[1]:
3338
- types = types | 8
3339
- if "sens" in cmds[1]:
3340
- types = types | 16
3341
-
3342
- if "full" in cmds[1]:
3467
+ args = cmds[1:]
3468
+ while len(args) > 0 and args[0][0] == "-": # Breaking change ...
3469
+
3470
+ if args[0].startswith('-f'): # -f or -full
3343
3471
  prefix_only = False
3344
3472
 
3473
+ if args[0].startswith('-t'): # same as before but with -t
3474
+ arg = args[0][2:]
3475
+ if not filter_args:
3476
+ filter_args = True
3477
+ types = 0
3478
+
3479
+ try: # try to decode type as int
3480
+ types = int(arg)
3481
+ except ValueError:
3482
+ if "all" in arg:
3483
+ types = 0xFF
3484
+ else :
3485
+ if "rep" in arg or "rpt" in arg:
3486
+ types = types | 4
3487
+ if "cli" in arg or "comp" in arg:
3488
+ types = types | 2
3489
+ if "room" in arg:
3490
+ types = types | 8
3491
+ if "sens" in arg:
3492
+ types = types | 16
3493
+
3494
+ argnum += 1
3495
+ args = args[1:]
3496
+
3345
3497
  res = await mc.commands.send_node_discover_req(types, prefix_only=prefix_only)
3346
3498
  if res is None or res.type == EventType.ERROR:
3347
3499
  output_str += "Error sending discover request" + end
@@ -3581,7 +3733,9 @@ async def next_cmd(mc, cmds, json_output=False, sink=sys.stdout, end="\n"):
3581
3733
  output_str += json.dumps(res, indent=4)+end
3582
3734
  else:
3583
3735
  width = shutil.get_terminal_size(fallback=(80, 24)).columns
3584
- output_str += f"Got {res['results_count']} neighbours out of {res['neighbours_count']} from {contact['adv_name']}:\n"
3736
+ output_str += f"Got {res['results_count']} neighbours out of {res['neighbours_count']} from {contact['adv_name']}:"
3737
+ if res['results_count'] > 0:
3738
+ output_str += '\n'
3585
3739
  first = True
3586
3740
  for n in res['neighbours']:
3587
3741
  if first :
@@ -3643,6 +3797,8 @@ async def next_cmd(mc, cmds, json_output=False, sink=sys.stdout, end="\n"):
3643
3797
  display_types = LC_DISPLAY_TYPES
3644
3798
  output_format = LC_OUTPUT_FORMAT
3645
3799
  filter_flag = 0
3800
+ quiet = False
3801
+ display_total = True
3646
3802
 
3647
3803
  args = cmds[1:]
3648
3804
  while len(args) > 0 and args[0][0] == "-":
@@ -3663,68 +3819,77 @@ async def next_cmd(mc, cmds, json_output=False, sink=sys.stdout, end="\n"):
3663
3819
  elif a[0] == "b": # flag
3664
3820
  filter_flag = int(a[1:], 0)
3665
3821
 
3666
- args=args[1:]
3822
+ elif a[0] == "q": # quiet
3823
+ quiet = True
3667
3824
 
3668
- res = mc.contacts
3669
- ct = list(res.values())
3825
+ elif a[0] == "l": # only displays contact list (no total)
3826
+ display_total = False
3670
3827
 
3671
- if "d" in output_format.lower() or "d" in sort_order.lower():
3672
- # calculate distance for each node (override previous val)
3673
- for c in ct:
3674
- c['distance'] = distance_between(mc.self_info, c)
3828
+ args=args[1:]
3675
3829
 
3676
- if filter_flag > 0:
3677
- ct = [x for x in ct if x.get("flags", 0) & filter_flag]
3830
+ if not quiet:
3831
+ res = mc.contacts
3832
+ ct = list(res.values())
3678
3833
 
3679
- if display_types != []:
3680
- ct = [x for x in ct if x.get("type") in display_types]
3834
+ if "d" in output_format.lower() or "d" in sort_order.lower():
3835
+ # calculate distance for each node (override previous val)
3836
+ for c in ct:
3837
+ c['distance'] = distance_between(mc.self_info, c)
3681
3838
 
3682
- for s in reversed(sort_order):
3683
- if s not in SORTING_CRITERIA:
3684
- continue
3685
- keyfunc, reverse = SORTING_CRITERIA[s]
3686
- ct.sort(key=keyfunc, reverse=reverse)
3839
+ if filter_flag > 0:
3840
+ ct = [x for x in ct if x.get("flags", 0) & filter_flag]
3687
3841
 
3688
- if json_output : # json output historically prints the whole dict ...
3689
- # if there were no args, print the dict else the list
3690
- if argnum == 0:
3691
- output_str += json.dumps(res, indent=4) + end
3692
- else:
3693
- output_str += json.dumps(ct, indent=4) + end
3694
- else :
3842
+ if display_types != []:
3843
+ ct = [x for x in ct if x.get("type") in display_types]
3844
+
3845
+ for s in reversed(sort_order):
3846
+ if s not in SORTING_CRITERIA:
3847
+ continue
3848
+ keyfunc, reverse = SORTING_CRITERIA[s]
3849
+ ct.sort(key=keyfunc, reverse=reverse)
3695
3850
 
3696
- for c in ct:
3697
- if c['out_path_len'] == -1:
3698
- path_str = "Flood"
3699
- elif c['out_path_len'] == 0:
3700
- path_str = "0 hop"
3851
+ if json_output : # json output historically prints the whole dict ...
3852
+ # if there were no args, print the dict else the list
3853
+ if argnum == 0:
3854
+ output_str += json.dumps(res, indent=4) + end
3701
3855
  else:
3702
- phs = c['out_path_hash_mode'] + 1
3703
- plen = c['out_path_len']
3704
- path_str_in = c['out_path']
3705
- path_str = path_str_in[:2*phs]
3706
- for i in range(1,plen):
3707
- path_str = path_str + "," + path_str_in[i*phs*2:(i+1)*2*phs]
3708
- #path_str = f"{c[1]['out_path']}:{c[1]['out_path_hash_mode']}"
3709
- output_str += f"{c['adv_name']:30} "
3710
- output_str += f"{ANSI_START}34G"
3711
- for i in output_format.lower():
3712
- if i == "t":
3713
- output_str += f" {CONTACT_TYPENAMES[c['type']]:4}"
3714
- elif i == "k":
3715
- output_str += f" {c['public_key'][:12]}"
3716
- elif i == "h":
3717
- output_str += f" {path_str:12}"
3718
- elif i == "a":
3719
- output_str += f" {time_ago_from_timestamp(c['last_advert']):>4}"
3720
- elif i == "m":
3721
- output_str += f" {time_ago_from_timestamp(c['lastmod']):>4}"
3722
- elif i == "b":
3723
- output_str += f" {c['flags']:02x}"
3724
- elif i == "d":
3725
- output_str += f" {c['distance']:7.2f}km"
3726
- output_str += "\n"
3727
- output_str += f"> {len(ct)} from {len(mc.contacts)} contacts in device{end}"
3856
+ output_str += json.dumps(ct, indent=4) + end
3857
+ else :
3858
+
3859
+ for c in ct:
3860
+ if c['out_path_len'] == -1:
3861
+ path_str = "Flood"
3862
+ elif c['out_path_len'] == 0:
3863
+ path_str = "0 hop"
3864
+ else:
3865
+ phs = c['out_path_hash_mode'] + 1
3866
+ plen = c['out_path_len']
3867
+ path_str_in = c['out_path']
3868
+ path_str = path_str_in[:2*phs]
3869
+ for i in range(1,plen):
3870
+ path_str = path_str + "," + path_str_in[i*phs*2:(i+1)*2*phs]
3871
+ #path_str = f"{c[1]['out_path']}:{c[1]['out_path_hash_mode']}"
3872
+ output_str += f"{c['adv_name']:30} "
3873
+ output_str += f"{ANSI_START}34G"
3874
+ for i in output_format.lower():
3875
+ if i == "t":
3876
+ output_str += f" {CONTACT_TYPENAMES[c['type']]:4}"
3877
+ elif i == "k":
3878
+ output_str += f" {c['public_key'][:12]}"
3879
+ elif i == "h":
3880
+ output_str += f" {path_str:12}"
3881
+ elif i == "a":
3882
+ output_str += f" {time_ago_from_timestamp(c['last_advert']):>4}"
3883
+ elif i == "m":
3884
+ output_str += f" {time_ago_from_timestamp(c['lastmod']):>4}"
3885
+ elif i == "b":
3886
+ output_str += f" {c['flags']:02x}"
3887
+ elif i == "d":
3888
+ output_str += f" {c['distance']:7.2f}km"
3889
+ output_str += "\n"
3890
+ if display_total:
3891
+ output_str += f"> {len(ct)} from {len(mc.contacts)} contacts in device{end}"
3892
+ # we may have an issue with display total if end is empty ...
3728
3893
 
3729
3894
  case "pending_contacts":
3730
3895
  if json_output:
@@ -3832,6 +3997,17 @@ async def next_cmd(mc, cmds, json_output=False, sink=sys.stdout, end="\n"):
3832
3997
  except ValueError:
3833
3998
  output_str += f"Error ! Command format add_contact key type name{end}"
3834
3999
 
4000
+ case "reset_advert_time":
4001
+ argnum = 1
4002
+ contact = await get_contact_from_arg(mc, cmds[1])
4003
+ contact['last_advert'] = 0
4004
+ res = await mc.commands.update_contact(contact)
4005
+ logger.debug(res)
4006
+ if res.type == EventType.ERROR:
4007
+ output_str += f"Error while reseting last advert for: {cmds[1]}{end}"
4008
+ elif json_output :
4009
+ output_str += json.dumps(res.payload, indent=4)+end
4010
+
3835
4011
  case "change_path" | "cp":
3836
4012
  argnum = 2
3837
4013
  contact = await get_contact_from_arg(mc, cmds[1])
@@ -4219,7 +4395,7 @@ async def next_cmd(mc, cmds, json_output=False, sink=sys.stdout, end="\n"):
4219
4395
  process = None
4220
4396
 
4221
4397
  try:
4222
- if not htype in ["msgs", "rxlog"]:
4398
+ if not htype in ["msgs", "rxlog", "chan_data"]:
4223
4399
  raise ValueError (f"Unknown handler type {htype}")
4224
4400
  process = await asyncio.create_subprocess_exec(
4225
4401
  *shlex.split(cmd, posix=True),
@@ -4257,7 +4433,7 @@ async def next_cmd(mc, cmds, json_output=False, sink=sys.stdout, end="\n"):
4257
4433
  case "handler_detach":
4258
4434
  argnum = 1
4259
4435
  nb = int(cmds[1])
4260
- handlers = HANDLERS["msgs"]|HANDLERS["rxlog"]
4436
+ handlers = HANDLERS["msgs"]|HANDLERS["rxlog"]|HANDLERS["chan_data"]
4261
4437
  handler = handlers[nb]
4262
4438
  handler["closed"] = True
4263
4439
  for task_name in ("writer_task", "output_task"):
@@ -4470,6 +4646,7 @@ def get_help_for (cmdname, context="line") :
4470
4646
  Filter is constructed with comma separated fields :
4471
4647
  - u, matches modification time < or > than a timestamp
4472
4648
  (can also be days hours or minutes ago if followed by d,h or m)
4649
+ - a, same as u but for advert time
4473
4650
  - t, matches the type (1: client, 2: repeater, 3: room, 4: sensor)
4474
4651
  - h, matches number of hops
4475
4652
  - d, direct, similar to h>-1
@@ -4488,15 +4665,18 @@ def get_help_for (cmdname, context="line") :
4488
4665
  """)
4489
4666
 
4490
4667
  elif cmdname == "node_discover" or cmdname == "nd" :
4491
- print("""node_discover <filter> : discovers 0-hop nodes and displays signal info
4668
+ print("""node_discover [-t<filter>] [-f] : discovers 0-hop nodes and displays signal info
4492
4669
 
4493
- filter can be "all" for all types or nodes or a comma separated list consisting of :
4670
+ `-t` asks for nodes regarding filter.
4671
+ filter can be an integer value or "all" for all types or nodes or a comma separated list consisting of :
4494
4672
  - cli or comp for companions
4495
4673
  - rep for repeaters
4496
4674
  - sens for sensors
4497
4675
  - room for chat rooms
4498
4676
 
4499
- nd can be used with no filter parameter ... !!! BEWARE WITH CHAINING !!!
4677
+ `-f` or `-full`: will ask for the full key of the node
4678
+
4679
+ BEWARE: filter option have changed since v1.6.4, using -t is now mandatory !!!
4500
4680
  """)
4501
4681
 
4502
4682
  elif cmdname == "get" :
File without changes
File without changes
File without changes
File without changes