meshcore-cli 1.6.2__tar.gz → 1.6.4__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.2
3
+ Version: 1.6.4
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.9
14
+ Requires-Dist: meshcore>=2.3.11
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.9";
20
+ version = "2.3.11";
21
21
  pyproject = true;
22
22
 
23
23
  src = python3Packages.fetchPypi {
24
24
  inherit pname version;
25
- sha256 = "sha256-sX0ozXspS6kGKp46RseoYdpBgQ8dfCBXBgO9GO3aXr0=";
25
+ sha256 = "sha256-eBu8VzOyVuGrxK1pfGzDjxxPx8zFORHeyslxehYgeWE=";
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.2"
7
+ version = "1.6.4"
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.9",
20
+ dependencies = [ "meshcore >= 2.3.11",
21
21
  "bleak >= 0.22",
22
22
  "prompt_toolkit >= 3.0.50",
23
23
  "requests >= 2.28.0" ]
@@ -4,7 +4,7 @@
4
4
  """
5
5
 
6
6
  import asyncio
7
- import os, sys, io, platform
7
+ import os, sys, io, platform, shutil
8
8
  import string
9
9
  import time, datetime
10
10
  import getopt, json, shlex, re
@@ -14,6 +14,7 @@ import serial.tools.list_ports
14
14
  from pathlib import Path
15
15
  import traceback
16
16
  import subprocess
17
+ import math
17
18
  from prompt_toolkit.shortcuts import PromptSession
18
19
  from prompt_toolkit.shortcuts import CompleteStyle
19
20
  from prompt_toolkit.completion import NestedCompleter, PathCompleter
@@ -34,7 +35,7 @@ except ImportError:
34
35
  from meshcore import MeshCore, EventType, logger
35
36
 
36
37
  # Version
37
- VERSION = "v1.6.2"
38
+ VERSION = "v1.6.4"
38
39
 
39
40
  # default ble address is stored in a config file
40
41
  MCCLI_CONFIG_DIR = os.path.expanduser("~/.config/meshcore/")
@@ -48,9 +49,14 @@ SCOPES = {}
48
49
  if os.path.exists(MCCLI_SCOPES_FILE) :
49
50
  with open(MCCLI_SCOPES_FILE, "r") as lines:
50
51
  for line in lines:
51
- line = line.strip()
52
- channel, scope = line.split()
53
- SCOPES[channel] = scope
52
+ try:
53
+ line = line.strip()
54
+ if line == "" or line.startswith(";"):
55
+ continue
56
+ channel, scope = line.split()
57
+ SCOPES[channel] = scope
58
+ except ValueError as e:
59
+ logger.error(f"while reading scope file {MCCLI_SCOPES_FILE}: {e} ... proceeding")
54
60
 
55
61
  PAYLOAD_TYPENAMES = ["REQ", "RESPONSE", "TEXT_MSG", "ACK", "ADVERT", "GRP_TXT", "GRP_DATA", "ANON_REQ", "PATH", "TRACE", "MULTIPART", "CONTROL"]
56
62
  ROUTE_TYPENAMES = ["TC_FLOOD", "FLOOD", "DIRECT", "TC_DIRECT"]
@@ -117,6 +123,82 @@ HANDLER_QUEUE_SIZE = 100
117
123
  # is the companion supposed to have cli
118
124
  HAS_CLI_CMD = False
119
125
 
126
+ # for sorting and filtering in lc could be used elsewhere
127
+ SORTING_CRITERIA = {
128
+ "a": (lambda x: x.get("last_advert", 0), False),
129
+ "A": (lambda x: x.get("last_advert", 0), True),
130
+ "n": (lambda x: x.get("adv_name", ""), False),
131
+ "N": (lambda x: x.get("adv_name", ""), True),
132
+ "t": (lambda x: x.get("type" , 0), False),
133
+ "T": (lambda x: x.get("type" , 0), True),
134
+ "m": (lambda x: x.get("lastmod" , 0), False),
135
+ "M": (lambda x: x.get("lastmod" , 0), True),
136
+ "h": (lambda x: x.get("out_path_len" , 0), False),
137
+ "H": (lambda x: x.get("out_path_len" , 0), True),
138
+ "d": (lambda x: x.get("distance" , 0), False),
139
+ "D": (lambda x: x.get("distance" , 0), True),
140
+ "f": (lambda x: bool(x.get("flags" , 0) & 1), True),
141
+ "F": (lambda x: bool(x.get("flags" , 0) & 1), False),
142
+ }
143
+
144
+ TYPE_MAP = {
145
+ "1": 1, "c": 1, # client
146
+ "2": 2, "r": 2, # repeater
147
+ "3": 3, "o": 3, # room
148
+ "4": 4, "s": 4, # sensor
149
+ }
150
+
151
+ LC_DISPLAY_TYPES = [1, 2, 3, 4]
152
+ LC_OUTPUT_FORMAT = "tkah"
153
+ LC_SORT_ORDER = ""
154
+
155
+ def time_ago_from_timestamp (timestamp):
156
+ duration = int(time.time()) - timestamp
157
+ if duration / 86400 >= 1 : # result in days
158
+ days_ago = int(duration/86400)
159
+ if days_ago >= 365:
160
+ time_ago = f"{int(days_ago/365)}y"
161
+ else:
162
+ time_ago = f"{days_ago}d"
163
+ elif duration / 3600 >= 1 : # result in days
164
+ time_ago = f"{int(duration/3600)}h"
165
+ elif duration / 60 >= 1 : # result in min
166
+ time_ago = f"{int(duration/60)}m"
167
+ else :
168
+ time_ago = f"{int(duration)}s"
169
+ return time_ago
170
+
171
+ def haversine_distance(coord1, coord2):
172
+ # Radius of the Earth in kilometers (use 3958.8 for miles)
173
+ R = 6371.0
174
+
175
+ lat1, lon1 = coord1
176
+ lat2, lon2 = coord2
177
+
178
+ # Convert latitude and longitude to radians
179
+ lat1_rad = math.radians(lat1)
180
+ lon1_rad = math.radians(lon1)
181
+ lat2_rad = math.radians(lat2)
182
+ lon2_rad = math.radians(lon2)
183
+
184
+ # Differences
185
+ dlat = lat2_rad - lat1_rad
186
+ dlon = lon2_rad - lon1_rad
187
+
188
+ # Haversine formula computation
189
+ a = (math.sin(dlat / 2) ** 2 +
190
+ math.cos(lat1_rad) * math.cos(lat2_rad) * math.sin(dlon / 2) ** 2)
191
+ a = min(1.0, max(0.0, a))
192
+ c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
193
+
194
+ return R * c
195
+
196
+ def distance_between(contact1, contact2):
197
+ # calculate distance between two contacts (can be mc.self_info)
198
+ coord1 = (contact1['adv_lat'], contact1['adv_lon'])
199
+ coord2 = (contact2['adv_lat'], contact2['adv_lon'])
200
+ return haversine_distance(coord1, coord2)
201
+
120
202
  def enqueue_handler_event(handler_type, payload):
121
203
  message = json.dumps(payload) + "\n"
122
204
  for handler in HANDLERS[handler_type].values():
@@ -170,8 +252,16 @@ def strip_outer_quotes(text):
170
252
 
171
253
  def split_pipeline(pipeline):
172
254
  lines, buf, quote = [], [], None
255
+ escaped = False
256
+
173
257
  for c in pipeline:
174
- if quote:
258
+ if escaped:
259
+ buf.append(c)
260
+ escaped = False
261
+ elif c == "\\" and quote != "'":
262
+ buf.append(c)
263
+ escaped = True
264
+ elif quote:
175
265
  buf.append(c)
176
266
  if c == quote:
177
267
  quote = None
@@ -330,7 +420,7 @@ async def handle_log_rx(event):
330
420
  message = "-- unhandled --"
331
421
 
332
422
  if chan_name != "" :
333
- width = os.get_terminal_size().columns
423
+ width = shutil.get_terminal_size(fallback=(80, 24)).columns
334
424
  cars = width - 13 - len(event.payload["path"]) - len(chan_name) - 1
335
425
  dispmsg = message.replace("\n","")[0:cars]
336
426
  txt = f"{ANSI_LIGHT_GRAY}{chan_name} {ANSI_DGREEN}{dispmsg+(cars-len(dispmsg))*' '} {ANSI_START}{width-11-len(event.payload['path'])}G{ANSI_YELLOW}[{event.payload['path']}]{ANSI_LIGHT_GRAY}{event.payload['snr']:6,.2f}{event.payload['rssi']:4}{ANSI_END}"
@@ -594,6 +684,7 @@ def make_completion_dict(contacts, pending=None, to=None, channels=None):
594
684
  "change_path" : contact_list,
595
685
  "change_flags" : contact_list,
596
686
  "remove_contact" : contact_list,
687
+ "add_contact" : {"key type name":None},
597
688
  "import_contact" : {"meshcore://":None},
598
689
  "reload_contacts" : None,
599
690
  "aliases" : None,
@@ -637,6 +728,8 @@ def make_completion_dict(contacts, pending=None, to=None, channels=None):
637
728
  "print_timestamp" : {"on":None, "off": None, "%Y:%M":None},
638
729
  "json_msgs" : {"on":None, "off": None},
639
730
  "color" : {"on":None, "off":None},
731
+ "lc_output_format":None,
732
+ "lc_sort_order":None,
640
733
  "print_adverts" : {"on":None, "off":None},
641
734
  "json_log_rx" : {"on":None, "off":None},
642
735
  "channel_echoes" : {"on":None, "off":None},
@@ -673,6 +766,8 @@ def make_completion_dict(contacts, pending=None, to=None, channels=None):
673
766
  "print_timestamp":None,
674
767
  "json_msgs":None,
675
768
  "color":None,
769
+ "lc_output_format":None,
770
+ "lc_sort_order":None,
676
771
  "print_adverts":None,
677
772
  "json_log_rx":None,
678
773
  "channel_echoes":None,
@@ -709,6 +804,7 @@ def make_completion_dict(contacts, pending=None, to=None, channels=None):
709
804
  "?contact_info":None,
710
805
  "?apply_to":None,
711
806
  "?at":None,
807
+ "?lc":None,
712
808
  "?node_discover":None,
713
809
  "?nd":None,
714
810
  "?pending_contacts":None,
@@ -724,6 +820,7 @@ def make_completion_dict(contacts, pending=None, to=None, channels=None):
724
820
  "?change_path":None,
725
821
  "?trace":None,
726
822
  "?alias":None,
823
+ "?add_contact":None
727
824
  }
728
825
 
729
826
  contact_completion_list = {
@@ -1361,7 +1458,7 @@ async def process_line(mc, line, contact=None, scope="*", prev_contact=None, pre
1361
1458
  args = shlex.split(line, posix=True)
1362
1459
  res = await process_cmds(mc, args, json_output=json_output, sink=sink,end=end)
1363
1460
  if not res and HAS_CLI_CMD: # if command was not found, try cli
1364
- args = ["cli", line[1:].strip()]
1461
+ args = ["cli", line.strip()]
1365
1462
  res = await process_cmds(mc, args, json_output=json_output, sink=sink,end=end)
1366
1463
  if not res :
1367
1464
  logger.error(f"Problem while running {args}")
@@ -2201,6 +2298,7 @@ async def next_cmd(mc, cmds, json_output=False, sink=sys.stdout, end="\n"):
2201
2298
  returns (following, output_str)
2202
2299
  """
2203
2300
  global ARROW_HEAD, SLASH_START, SLASH_END, INVERT_SLASH, LAST_HANDLER_ID
2301
+ global LC_DISPLAY_TYPES, LC_OUTPUT_FORMAT, LC_SORT_ORDER
2204
2302
  output_str = ""
2205
2303
  try :
2206
2304
  argnum = 0
@@ -2259,12 +2357,13 @@ async def next_cmd(mc, cmds, json_output=False, sink=sys.stdout, end="\n"):
2259
2357
  output_str += f"Time synced{end}"
2260
2358
  else:
2261
2359
  res = await mc.commands.get_time()
2262
- timestamp = res.payload["time"]
2263
- if res.type == EventType.ERROR:
2360
+ if res is None or res.type == EventType.ERROR:
2264
2361
  output_str += f"Error getting time: {res}{end}"
2265
2362
  elif json_output :
2363
+ timestamp = res.payload["time"]
2266
2364
  output_str += json.dumps(res.payload, indent=4)+end
2267
2365
  else :
2366
+ timestamp = res.payload["time"]
2268
2367
  output_str += 'Current time :'\
2269
2368
  + f' {datetime.datetime.fromtimestamp(timestamp).strftime("%Y-%m-%d %H:%M:%S")}'\
2270
2369
  + f' ({timestamp})'\
@@ -2313,6 +2412,10 @@ async def next_cmd(mc, cmds, json_output=False, sink=sys.stdout, end="\n"):
2313
2412
  case "help" :
2314
2413
  argnum = 1
2315
2414
  get_help_for("set")
2415
+ case "lc_output_format":
2416
+ LC_OUTPUT_FORMAT=cmds[2]
2417
+ case "lc_sort_order":
2418
+ LC_SORT_ORDER=cmds[2]
2316
2419
  case "max_flood_attempts":
2317
2420
  msg_ack.max_flood_attempts=int(cmds[2])
2318
2421
  case "max_attempts":
@@ -2599,6 +2702,16 @@ async def next_cmd(mc, cmds, json_output=False, sink=sys.stdout, end="\n"):
2599
2702
  match cmds[1]:
2600
2703
  case "help":
2601
2704
  get_help_for("get")
2705
+ case "lc_output_format":
2706
+ if json_output :
2707
+ output_str += json.dumps({"lc_output_format": LC_OUTPUT_FORMAT})+end
2708
+ else:
2709
+ output_str += f"lc_output_format: {LC_OUTPUT_FORMAT}{end}"
2710
+ case "lc_sort_order":
2711
+ if json_output :
2712
+ output_str += json.dumps({"lc_sort_order": LC_SORT_ORDER})+end
2713
+ else:
2714
+ output_str += f"lc_sort_order: \"{LC_SORT_ORDER}\"{end}"
2602
2715
  case "max_flood_attempts":
2603
2716
  if json_output :
2604
2717
  output_str += json.dumps({"max_flood_attempts" : msg_ack.max_flood_attempts})+end
@@ -2903,13 +3016,13 @@ async def next_cmd(mc, cmds, json_output=False, sink=sys.stdout, end="\n"):
2903
3016
  case "self_telemetry" | "t":
2904
3017
  res = await mc.commands.get_self_telemetry()
2905
3018
  logger.debug(res)
2906
- if res.type == EventType.ERROR:
2907
- output_str += f"Error while requesting telemetry{end}"
2908
- elif res is None:
3019
+ if res is None:
2909
3020
  if json_output :
2910
3021
  output_str += json.dumps({"error" : "Timeout waiting telemetry"})+end
2911
3022
  else:
2912
3023
  output_str += "Timeout waiting telemetry" + end
3024
+ elif res.type == EventType.ERROR:
3025
+ output_str += f"Error while requesting telemetry{end}"
2913
3026
  else :
2914
3027
  output_str += json.dumps(res.payload, indent=4)+end
2915
3028
 
@@ -3467,7 +3580,7 @@ async def next_cmd(mc, cmds, json_output=False, sink=sys.stdout, end="\n"):
3467
3580
  if json_output:
3468
3581
  output_str += json.dumps(res, indent=4)+end
3469
3582
  else:
3470
- width = os.get_terminal_size().columns
3583
+ width = shutil.get_terminal_size(fallback=(80, 24)).columns
3471
3584
  output_str += f"Got {res['results_count']} neighbours out of {res['neighbours_count']} from {contact['adv_name']}:\n"
3472
3585
  first = True
3473
3586
  for n in res['neighbours']:
@@ -3518,40 +3631,100 @@ async def next_cmd(mc, cmds, json_output=False, sink=sys.stdout, end="\n"):
3518
3631
  else :
3519
3632
  output_str += json.dumps(res)+end
3520
3633
 
3521
- case "contacts" | "list" | "lc":
3522
- await mc.ensure_contacts(follow=True)
3634
+ case "contacts" | "list" | "lc" | "reload_contacts" | "rc" :
3635
+ argnum = 0
3636
+
3637
+ if cmd == "rc" or cmd == "reload_contacts" :
3638
+ await mc.commands.get_contacts()
3639
+ else:
3640
+ await mc.ensure_contacts(follow=True)
3641
+
3642
+ sort_order = LC_SORT_ORDER
3643
+ display_types = LC_DISPLAY_TYPES
3644
+ output_format = LC_OUTPUT_FORMAT
3645
+ filter_flag = 0
3646
+
3647
+ args = cmds[1:]
3648
+ while len(args) > 0 and args[0][0] == "-":
3649
+ argnum += 1
3650
+ if len(args[0]) <= 1: # just a dash
3651
+ args=args[1:]
3652
+ continue
3653
+ a = args[0][1:]
3654
+ if a[0] == "s": # sorting options
3655
+ sort_order = a[1:]
3656
+
3657
+ elif a[0] == "f": # output format
3658
+ output_format = a[1:]
3659
+
3660
+ elif a[0] == "t": # type
3661
+ display_types = {TYPE_MAP[t] for t in a[1:] if t in TYPE_MAP}
3662
+
3663
+ elif a[0] == "b": # flag
3664
+ filter_flag = int(a[1:], 0)
3665
+
3666
+ args=args[1:]
3667
+
3523
3668
  res = mc.contacts
3524
- if json_output :
3525
- output_str += json.dumps(res, indent=4) + end
3669
+ ct = list(res.values())
3670
+
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)
3675
+
3676
+ if filter_flag > 0:
3677
+ ct = [x for x in ct if x.get("flags", 0) & filter_flag]
3678
+
3679
+ if display_types != []:
3680
+ ct = [x for x in ct if x.get("type") in display_types]
3681
+
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)
3687
+
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
3526
3694
  else :
3527
- for c in res.items():
3528
- if c[1]['out_path_len'] == -1:
3695
+
3696
+ for c in ct:
3697
+ if c['out_path_len'] == -1:
3529
3698
  path_str = "Flood"
3530
- elif c[1]['out_path_len'] == 0:
3699
+ elif c['out_path_len'] == 0:
3531
3700
  path_str = "0 hop"
3532
3701
  else:
3533
- phs = c[1]['out_path_hash_mode'] + 1
3534
- plen = c[1]['out_path_len']
3535
- path_str_in = c[1]['out_path']
3702
+ phs = c['out_path_hash_mode'] + 1
3703
+ plen = c['out_path_len']
3704
+ path_str_in = c['out_path']
3536
3705
  path_str = path_str_in[:2*phs]
3537
3706
  for i in range(1,plen):
3538
3707
  path_str = path_str + "," + path_str_in[i*phs*2:(i+1)*2*phs]
3539
3708
  #path_str = f"{c[1]['out_path']}:{c[1]['out_path_hash_mode']}"
3540
- output_str += f"{c[1]['adv_name']:30} "
3709
+ output_str += f"{c['adv_name']:30} "
3541
3710
  output_str += f"{ANSI_START}34G"
3542
- output_str += f"{CONTACT_TYPENAMES[c[1]['type']]:4} "
3543
- output_str += f"{c[1]['public_key'][:12]}  {path_str}\n"
3544
- output_str += f"> {len(mc.contacts)} contacts in device{end}"
3545
-
3546
- case "reload_contacts" | "rc":
3547
- await mc.commands.get_contacts()
3548
- res = mc.contacts
3549
- if json_output :
3550
- output_str += json.dumps(res, indent=4)+end
3551
- else :
3552
- for c in res.items():
3553
- output_str += c[1]["adv_name"]
3554
- output_str += f"> {len(mc.contacts)} contacts in device{end}"
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}"
3555
3728
 
3556
3729
  case "pending_contacts":
3557
3730
  if json_output:
@@ -3640,7 +3813,7 @@ async def next_cmd(mc, cmds, json_output=False, sink=sys.stdout, end="\n"):
3640
3813
  "public_key": cmds[1],
3641
3814
  "type" : int (cmds[2]),
3642
3815
  "flags" : 0,
3643
- "out_path_len" : 0,
3816
+ "out_path_len" : -1,
3644
3817
  "out_path" : "",
3645
3818
  "out_path_hash_mode" : 0,
3646
3819
  "adv_name" : cmds[3],
@@ -3655,6 +3828,7 @@ async def next_cmd(mc, cmds, json_output=False, sink=sys.stdout, end="\n"):
3655
3828
  output_str += f"Error adding contact: {res}{end}"
3656
3829
  elif json_output :
3657
3830
  output_str += json.dumps(res.payload, indent=4)+end
3831
+ await mc.commands.get_contacts() # reload contacts
3658
3832
  except ValueError:
3659
3833
  output_str += f"Error ! Command format add_contact key type name{end}"
3660
3834
 
@@ -4020,9 +4194,9 @@ async def next_cmd(mc, cmds, json_output=False, sink=sys.stdout, end="\n"):
4020
4194
  else:
4021
4195
  file_name = await prompt_for_file()
4022
4196
 
4023
- file_name = file_name.strip()
4024
- fn = file_name
4025
4197
  if not file_name is None:
4198
+ file_name = file_name.strip()
4199
+ fn = file_name
4026
4200
  file_name = os.path.expanduser(file_name)
4027
4201
  if not os.path.exists(file_name) :
4028
4202
  if os.path.exists(MCCLI_CONFIG_DIR + file_name) :
@@ -4230,6 +4404,7 @@ def command_help():
4230
4404
  export_contact <ct> : get a contact's URI ec
4231
4405
  import_contact <URI> : import a contact from its URI ic
4232
4406
  remove_contact <ct> : removes a contact from this node
4407
+ add_contact <k> <t> <n>: adds contact: key type name
4233
4408
  path <ct> : diplays path for a contact
4234
4409
  disc_path <ct> : discover new path and display dp
4235
4410
  reset_path <ct> : resets path to a contact to flood rp
@@ -4280,7 +4455,9 @@ def command_usage() :
4280
4455
  -P : forces pairing via the OS
4281
4456
  -t <hostname> : connects via tcp/ip
4282
4457
  -p <port> : specifies tcp port (default 5000)
4283
- -s <port> : use serial port <port>
4458
+ -s <port>[:opts]: use serial port <port>
4459
+ opts are comma separated options
4460
+ rts=, dtr=, baud=
4284
4461
  -b <baudrate> : specify baudrate
4285
4462
  -C : toggles classic mode for prompt
4286
4463
  -c <on/off> : disables most of color output if off
@@ -4418,7 +4595,7 @@ Managing Flood Scope in interactive mode
4418
4595
  - contact_type (ct)
4419
4596
  """)
4420
4597
 
4421
- elif cmdname == "pending_contacts" or cmdname == "flush_pending" or cmdname == "add_pending" or cmdname == "autoadd":
4598
+ elif cmdname == "pending_contacts" or cmdname == "flush_pending" or cmdname == "add_pending" or cmdname == "autoadd" or cmdname == "add_contact":
4422
4599
  print("""Contact management
4423
4600
 
4424
4601
  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).
@@ -4442,6 +4619,8 @@ You can also set autoadd_config flag to filter contacts that are automatically a
4442
4619
 
4443
4620
  Instead of an int you can use can make a string containing keys which can be (ov, cli, rep, room or sen), parser will look for keys in the string.
4444
4621
 
4622
+ Contacts can also be added manually by using `add_contact` command, which takes key, type and name as parameters.
4623
+
4445
4624
  Note: There is also an auto_update_contacts setting that has nothing to do with adding contacts, it permits to automatically sync contact lists between device and meshcore-cli (when there is an update in name, location or path).
4446
4625
  """)
4447
4626
 
@@ -4555,6 +4734,37 @@ The alias command takes two parameters, alias name and value. Value can contain
4555
4734
  You can list all aliases using `aliases` command and so using `.> <filename> aliases` will save the alias dict in a file (`alias` with no parameter will act as `aliases`).
4556
4735
 
4557
4736
  To recall an alias dict from a file use `aliases_load`, with a name it will try to load aliases from a file by the given name (searching also in mccli config dir), with no name it will prompt you for a file (with a file completer).
4737
+ """)
4738
+
4739
+ elif cmdname=="lc" or cmdname=="contacts" or cmdname=="list" :
4740
+ print("""lc: displays contact list from the the node
4741
+
4742
+ lc supports four parameters:
4743
+ sort order : -s
4744
+ output format : -f
4745
+ filter by type: -t
4746
+ filter by flag: -b
4747
+
4748
+ Sort order is given as a string with different criterias (lowercase for ascending, uppercase for descending order):
4749
+ n: sorts by name
4750
+ t: sorts by type
4751
+ a: sorts by last advert
4752
+ m: sorts by modification time
4753
+ h: sorts by path len
4754
+ d: sorts by distance
4755
+ f: starts with favorites
4756
+ If several criteria are used, they are evaluated from right to left, so the leftmost one has more priority `-stfn` first sorts by name, then puts the favorites first and finally orders by type.
4757
+ Use get/set lc_sort_order to get or set default value
4758
+
4759
+ Output format is given as a string with one character by field. Name is always displayed first but you can tailor the rest of the output:
4760
+ t: type
4761
+ k: key prefix
4762
+ a: last advert
4763
+ m: last modification
4764
+ h: hop count
4765
+ d: distance (in km)
4766
+ b: flag bits (as hex)
4767
+ Use get/set lc_output_format to get or set default value
4558
4768
  """)
4559
4769
 
4560
4770
  else:
@@ -5013,6 +5223,12 @@ async def main(argv):
5013
5223
  first_device = False
5014
5224
  quiet = False
5015
5225
  force_interactive = False
5226
+ serial_dtr = True
5227
+ serial_rts = False
5228
+
5229
+ # basic logger configuration (was removed from meshcore_py)
5230
+ logging.basicConfig(level=logging.INFO)
5231
+
5016
5232
  # If there is an address in config file, use it by default
5017
5233
  # unless an arg is explicitely given
5018
5234
  if os.path.exists(MCCLI_ADDRESS) :
@@ -5043,6 +5259,26 @@ async def main(argv):
5043
5259
  case "-P" : # pairing
5044
5260
  pin = True
5045
5261
  case "-s" : # serial port
5262
+ if ":" in arg:
5263
+ serial_opts=arg.split(":",1)[1].split(',')
5264
+ arg=arg.split(":")[0]
5265
+ for opt in serial_opts:
5266
+ try:
5267
+ name = opt.split('=')[0].lower().strip()
5268
+ if name == 'dtr':
5269
+ val = opt.split('=')[1].lower()
5270
+ serial_dtr = True if val == 'true' or val == '1' or val == 'on' else False
5271
+ elif name == 'rts':
5272
+ val = opt.split('=')[1].lower()
5273
+ serial_rts = True if val == 'true' or val == '1' or val == 'on' else False
5274
+ elif name == 'baudrate' or name == 'baud' or name == 'b':
5275
+ baudrate = int(opt.split('=')[1])
5276
+ else:
5277
+ logger.error(f"Unrecognized serial option {opt}")
5278
+ except ValueError as e:
5279
+ logger.error(f"Bad option format {opt}: {e}")
5280
+ except IndexError as e:
5281
+ logger.error(f"Bad option format {opt}: {e}")
5046
5282
  serial_port = arg
5047
5283
  case "-b" :
5048
5284
  baudrate = int(arg)
@@ -5151,7 +5387,7 @@ async def main(argv):
5151
5387
  if not hostname is None : # connect via tcp
5152
5388
  mc = await MeshCore.create_tcp(host=hostname, port=port, debug=debug, only_error=json_output)
5153
5389
  elif not serial_port is None : # connect via serial port
5154
- mc = await MeshCore.create_serial(port=serial_port, baudrate=baudrate, debug=debug, only_error=json_output)
5390
+ mc = await MeshCore.create_serial(port=serial_port, baudrate=baudrate, debug=debug, only_error=json_output, dtr=serial_dtr, rts=serial_rts)
5155
5391
  if mc is None: # did not connect
5156
5392
  logger.error("To connect to a repeater, use -r option.")
5157
5393
  elif BLEAK_AVAILABLE : # connect via ble
@@ -5261,11 +5497,12 @@ async def main(argv):
5261
5497
  if os.path.isdir(MCCLI_CONFIG_DIR) :
5262
5498
  log_message.file = MCCLI_CONFIG_DIR + (mc.self_info["name"].replace("/","")) + ".msgs"
5263
5499
 
5500
+ if res.payload["fw ver"] >= 14 :
5501
+ HAS_CLI_CMD = True
5502
+
5264
5503
  if (json_output or quiet) :
5265
5504
  logger.setLevel(logging.ERROR)
5266
5505
  else :
5267
- if res.payload["fw ver"] >= 14 :
5268
- HAS_CLI_CMD = True
5269
5506
  if res.payload["fw ver"] > 2 :
5270
5507
  logger.info(f"Connected to {mc.self_info['name']} running on a {res.payload['ver']} ({res.payload['fw ver']}) fw.")
5271
5508
  else :
File without changes
File without changes
File without changes
File without changes