meshcore-cli 1.6.12__tar.gz → 1.6.14__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.12
3
+ Version: 1.6.14
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
@@ -14,6 +14,7 @@ Requires-Dist: bleak>=0.22
14
14
  Requires-Dist: meshcore>=2.3.22
15
15
  Requires-Dist: prompt-toolkit>=3.0.50
16
16
  Requires-Dist: requests>=2.28.0
17
+ Requires-Dist: zeroconf>=0.131
17
18
  Description-Content-Type: text/markdown
18
19
 
19
20
  # meshcore-cli
@@ -79,8 +80,8 @@ Arguments mostly deals with connection to the node
79
80
  -j : json output (disables init file)
80
81
  -D : debug
81
82
  -S : scan for devices and show a selector
82
- -l : list available ble/serial devices and exit
83
- -T <timeout> : timeout for the ble scan (-S and -l) default 2s
83
+ -l : list available ble/tcp (mDNS)/serial devices and exit
84
+ -T <timeout> : timeout for the ble/mDNS scan (-S and -l) default 2s
84
85
  -a <address> : specifies device address (can be a name)
85
86
  -d <name> : filter meshcore devices with name or address
86
87
  -P : forces pairing via the OS
@@ -253,11 +254,13 @@ Will print out the content of `rx_log` as it comes in.
253
254
 
254
255
  #### Timers
255
256
 
256
- `timer [-j] [-c<contact>] [-s<scope>] <s> <line>` runs `line` every `s` seconds.
257
+ `timer [-j] [-x] [-n<count>] [-c<contact>] [-s<scope>] <s> <line>` runs `line` every `s` seconds.
257
258
 
258
259
  - `-c` sets the contact the line is run from (`~` for root).
259
260
  - `-s` sets the scope for the line (default is the current scope of the node).
260
261
  - `-j` forces json output for the timed line.
262
+ - `-x` executes the line immediately instead of waiting `s` seconds for the first run.
263
+ - `-n` runs the line `count` times and then disarms the timer (default: runs until cancelled). For instance `timer -x -n3 10m "chan 1 hi"` sends the message right away, then 2 more times at 10 minute intervals.
261
264
 
262
265
  `timers` lists the running timers and `timer_cancel <n>` cancels timer `n`.
263
266
 
@@ -61,8 +61,8 @@ Arguments mostly deals with connection to the node
61
61
  -j : json output (disables init file)
62
62
  -D : debug
63
63
  -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
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
66
66
  -a &lt;address&gt; : specifies device address (can be a name)
67
67
  -d &lt;name&gt; : filter meshcore devices with name or address
68
68
  -P : forces pairing via the OS
@@ -235,11 +235,13 @@ Will print out the content of `rx_log` as it comes in.
235
235
 
236
236
  #### Timers
237
237
 
238
- `timer [-j] [-c<contact>] [-s<scope>] <s> <line>` runs `line` every `s` seconds.
238
+ `timer [-j] [-x] [-n<count>] [-c<contact>] [-s<scope>] <s> <line>` runs `line` every `s` seconds.
239
239
 
240
240
  - `-c` sets the contact the line is run from (`~` for root).
241
241
  - `-s` sets the scope for the line (default is the current scope of the node).
242
242
  - `-j` forces json output for the timed line.
243
+ - `-x` executes the line immediately instead of waiting `s` seconds for the first run.
244
+ - `-n` runs the line `count` times and then disarms the timer (default: runs until cancelled). For instance `timer -x -n3 10m "chan 1 hi"` sends the message right away, then 2 more times at 10 minute intervals.
243
245
 
244
246
  `timers` lists the running timers and `timer_cancel <n>` cancels timer `n`.
245
247
 
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "meshcore-cli"
7
- version = "1.6.12"
7
+ version = "1.6.14"
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,14 +11,14 @@ 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
18
17
  from prompt_toolkit.shortcuts import PromptSession
19
18
  from prompt_toolkit.shortcuts import CompleteStyle
20
- from prompt_toolkit.completion import NestedCompleter, PathCompleter
19
+ from prompt_toolkit.completion import NestedCompleter, PathCompleter, Completer, Completion
21
20
  from prompt_toolkit.history import FileHistory
21
+ from prompt_toolkit.document import Document
22
22
  from prompt_toolkit.formatted_text import ANSI
23
23
  from prompt_toolkit.key_binding import KeyBindings
24
24
  from prompt_toolkit.shortcuts import radiolist_dialog
@@ -32,10 +32,17 @@ try:
32
32
  except ImportError:
33
33
  BLEAK_AVAILABLE = False
34
34
 
35
+ try:
36
+ from zeroconf import ServiceStateChange
37
+ from zeroconf.asyncio import AsyncZeroconf, AsyncServiceBrowser, AsyncServiceInfo
38
+ ZEROCONF_AVAILABLE = True
39
+ except ImportError:
40
+ ZEROCONF_AVAILABLE = False
41
+
35
42
  from meshcore import MeshCore, EventType, logger
36
43
 
37
44
  # Version
38
- VERSION = "v1.6.12"
45
+ VERSION = "v1.6.14"
39
46
 
40
47
  # default ble address is stored in a config file
41
48
  MCCLI_CONFIG_DIR = os.path.expanduser("~/.config/meshcore/")
@@ -62,6 +69,9 @@ PAYLOAD_TYPENAMES = ["REQ", "RESPONSE", "TEXT_MSG", "ACK", "ADVERT", "GRP_TXT",
62
69
  ROUTE_TYPENAMES = ["TC_FLOOD", "FLOOD", "DIRECT", "TC_DIRECT"]
63
70
  CONTACT_TYPENAMES = ["NONE","CLI","REP","ROOM","SENS"]
64
71
 
72
+ # mDNS service type browsed to discover companion radios reachable over tcp
73
+ MDNS_SERVICE = "_meshcore._tcp.local."
74
+
65
75
  # Fallback address if config file not found
66
76
  # if None or "" then a scan is performed
67
77
  ADDRESS = ""
@@ -243,8 +253,12 @@ def enqueue_handler_event(handler_type, payload):
243
253
  logger.warning(f"Handler {handler['id']} queue is full; dropping event")
244
254
 
245
255
  async def run_timer(mc, timer):
256
+ first = timer["exec"] # -x: first run without waiting for the delay
246
257
  while True:
247
- await asyncio.sleep(timer["secs"])
258
+ if first:
259
+ first = False
260
+ else:
261
+ await asyncio.sleep(timer["secs"])
248
262
  async with CMD_LOCK:
249
263
  base = set_scope.current_scope
250
264
  if base is None:
@@ -259,6 +273,13 @@ async def run_timer(mc, timer):
259
273
  if timer["scope"] != base:
260
274
  await set_scope(mc, base)
261
275
 
276
+ # n given: count the run and disarm the timer once it is exhausted
277
+ if timer["remaining"] is not None:
278
+ timer["remaining"] -= 1
279
+ if timer["remaining"] <= 0:
280
+ TIMERS.pop(timer["id"], None)
281
+ return
282
+
262
283
  async def write_handler(handler):
263
284
  try:
264
285
  while True:
@@ -695,12 +716,38 @@ class MyNestedCompleter(NestedCompleter):
695
716
  else: # normal behavior for remainder
696
717
  yield from super().get_completions(document, complete_event)
697
718
 
719
+ class OptionsCompleter(Completer):
720
+ def __init__(self, options, then=None):
721
+ self.options = list(options)
722
+ if isinstance(then, dict):
723
+ then = NestedCompleter.from_nested_dict(then)
724
+ self.then = then
725
+
726
+ def get_completions(self, document, complete_event):
727
+ words = document.text_before_cursor.split(" ")
728
+ current = words[-1]
729
+ done = [w for w in words[:-1] if w]
730
+
731
+ n = 0 # leading words that are options
732
+ while n < len(done) and done[n].startswith("-"):
733
+ n += 1
734
+
735
+ if n == len(done) and (current == "" or current.startswith("-")):
736
+ used = {w[:2] for w in done}
737
+ for o in self.options:
738
+ if o[:2] not in used and o.startswith(current):
739
+ yield Completion(o, start_position=-len(current))
740
+
741
+ if self.then is not None and not current.startswith("-"):
742
+ rest = " ".join(done[n:] + [current])
743
+ yield from self.then.get_completions(Document(rest, len(rest)), complete_event)
744
+
698
745
 
699
746
  def make_completion_dict(contacts, pending=None, to=None, channels=None):
700
747
  pending = pending or {}
701
748
  contact_list = {}
702
749
  pending_list = {}
703
- discovered_list = {"-a":None}
750
+ discovered_list = {}
704
751
  to_list = {}
705
752
 
706
753
  to_list["~"] = None
@@ -741,7 +788,7 @@ def make_completion_dict(contacts, pending=None, to=None, channels=None):
741
788
  root_completion_list = {
742
789
  "public" : None,
743
790
  "chan" : None,
744
- "chan_data" : None,
791
+ "chan_data" : OptionsCompleter(["-p"]),
745
792
  "ver" : None,
746
793
  "infos" : None,
747
794
  "advert" : None,
@@ -754,7 +801,8 @@ def make_completion_dict(contacts, pending=None, to=None, channels=None):
754
801
  "reboot" : None,
755
802
  "card" : None,
756
803
  "upload_card" : None,
757
- "contacts": None,
804
+ "contacts": OptionsCompleter(["-s", "-f", "-t", "-b", "-q", "-l"]),
805
+ "lc": OptionsCompleter(["-s", "-f", "-t", "-b", "-q", "-l"]),
758
806
  "pending_contacts": None,
759
807
  "add_pending": pending_list,
760
808
  "flush_pending": None,
@@ -765,9 +813,9 @@ def make_completion_dict(contacts, pending=None, to=None, channels=None):
765
813
  "path": contact_list,
766
814
  "disc_path" : contact_list,
767
815
  "advert_path" : contact_list | pending_list,
768
- "node_discover": {"-tall":None, "-tsens":None, "-trep":None, "-tcomp":None, "-troom":None, "-tcli":None},
816
+ "node_discover": OptionsCompleter(["-f", "-tall", "-tsens", "-trep", "-tcomp", "-troom", "-tcli"]),
769
817
  "list_discovered": None,
770
- "add_discovered": discovered_list,
818
+ "add_discovered": OptionsCompleter(["-a", "-n"], then=discovered_list),
771
819
  "trace" : None,
772
820
  "reset_path" : contact_list,
773
821
  "change_path" : contact_list,
@@ -783,7 +831,7 @@ def make_completion_dict(contacts, pending=None, to=None, channels=None):
783
831
  "handler_attach": {"rxlog":None, "msgs":None, "chan_data":None, "telemetry":None},
784
832
  "handler_detach": None,
785
833
  "handlers": None,
786
- "timer": None,
834
+ "timer": OptionsCompleter(["-j", "-x", "-n", "-c", "-s"]),
787
835
  "timer_cancel": None,
788
836
  "timers": None,
789
837
  "login" : contact_list,
@@ -861,9 +909,9 @@ def make_completion_dict(contacts, pending=None, to=None, channels=None):
861
909
  "agc.reset.interval": None,
862
910
  "multi.acks": None,
863
911
  "pin": None,
864
- "wifi.status": None,
865
912
  "wifi.ssid": None,
866
913
  "wifi.pwd": None,
914
+ "wifi.enabled" : {"0": None, "1": None,},
867
915
  "ui.show_clock": None,
868
916
  "ui.auto_off_delay": None,
869
917
  "ui.backlight_delay": None,
@@ -932,6 +980,7 @@ def make_completion_dict(contacts, pending=None, to=None, channels=None):
932
980
  "wifi.status": None,
933
981
  "wifi.ssid": None,
934
982
  "wifi.pwd": None,
983
+ "wifi.enabled": None,
935
984
  "ui.show_clock": None,
936
985
  "ui.auto_off_delay": None,
937
986
  "ui.backlight_delay": None,
@@ -989,7 +1038,7 @@ def make_completion_dict(contacts, pending=None, to=None, channels=None):
989
1038
  "unsub_telemetry" : None,
990
1039
  "req_binary" : None,
991
1040
  "forget_password" : None,
992
- "timer" : None,
1041
+ "timer" : OptionsCompleter(["-j", "-x", "-n", "-s"]),
993
1042
  }
994
1043
 
995
1044
  client_completion_list = dict(contact_completion_list)
@@ -4648,18 +4697,30 @@ async def next_cmd(mc, cmds, json_output=False, sink=sys.stdout, end="\n"):
4648
4697
  output_str += json.dumps(HANDLERS, default=str)+end
4649
4698
 
4650
4699
  case "timer":
4651
- argnum = 2 # [-j] [-c<contact>] [-s<scope>] secs line
4700
+ argnum = 2 # [-j] [-x] [-n<count>] [-c<contact>] [-s<scope>] secs line
4652
4701
  t_contact = None
4653
4702
  t_scope = set_scope.current_scope
4654
4703
  if t_scope is None:
4655
4704
  t_scope = ""
4656
4705
  t_json = json_output
4706
+ t_count = None # None = runs until cancelled
4707
+ t_exec = False # -x : first run without delay
4657
4708
  valid = True
4658
4709
 
4659
4710
  args = cmds[1:]
4660
4711
  while len(args) > 0 and args[0][0] == "-":
4661
4712
  argnum += 1
4662
4713
 
4714
+ if args[0].startswith("-x"): # exec now, then every s seconds
4715
+ t_exec = True
4716
+
4717
+ if args[0].startswith("-n"): # number of runs before disarming
4718
+ if args[0][2:].isdigit() and int(args[0][2:]) > 0:
4719
+ t_count = int(args[0][2:])
4720
+ else:
4721
+ valid = False
4722
+ logger.error(f"Invalid count {args[0][2:]!r} for -n, expected a positive integer")
4723
+
4663
4724
  if args[0].startswith("-j"): # force json output for the timer
4664
4725
  t_json = True
4665
4726
 
@@ -4703,6 +4764,9 @@ async def next_cmd(mc, cmds, json_output=False, sink=sys.stdout, end="\n"):
4703
4764
  timer["scope"] = t_scope
4704
4765
  timer["contact"] = t_contact
4705
4766
  timer["json"] = t_json
4767
+ timer["exec"] = t_exec
4768
+ timer["count"] = t_count
4769
+ timer["remaining"] = t_count
4706
4770
  timer["task"] = asyncio.create_task(run_timer(mc, timer))
4707
4771
  TIMERS[LAST_TIMER_ID] = timer
4708
4772
  if json_output:
@@ -4713,7 +4777,10 @@ async def next_cmd(mc, cmds, json_output=False, sink=sys.stdout, end="\n"):
4713
4777
  case "timer_cancel":
4714
4778
  argnum = 1
4715
4779
  nb = int(cmds[1])
4716
- timer = TIMERS.pop(nb)
4780
+ timer = TIMERS.pop(nb, None)
4781
+ if timer is None:
4782
+ logger.error(f"No timer {nb} (unknown, cancelled or already finished)")
4783
+ return (cmds[argnum+1:], output_str)
4717
4784
  timer["task"].cancel()
4718
4785
  try:
4719
4786
  await timer["task"]
@@ -4809,7 +4876,7 @@ def command_help():
4809
4876
  aliases_load : load aliases from a file
4810
4877
  handler_attach <d> <c> : attach c as a handler for d
4811
4878
  handler_detach <n> : detach an handler (from its handle n)
4812
- timer <s> <c> : runs command c every s seconds
4879
+ timer [-x] [-n<k>] <s> <c> : runs command c every s seconds (k times if -n, now if -x)
4813
4880
  timer_cancel <n> : cancels a timer (from its handle n)
4814
4881
  timers : lists current timers
4815
4882
  Messaging
@@ -4895,8 +4962,8 @@ def command_usage() :
4895
4962
  -D : debug (sets logging to DEBUG)
4896
4963
  -q : quiet (sets logging to ERROR)
4897
4964
  -S : scan for devices and show a selector
4898
- -l : list available ble/serial devices and exit
4899
- -T <timeout> : timeout for the ble scan (-S and -l) default 2s
4965
+ -l : list available ble/tcp (mDNS)/serial devices and exit
4966
+ -T <timeout> : timeout for the ble/mDNS scan (-S and -l) default 2s
4900
4967
  -a <address> : specifies device address (can be a name)
4901
4968
  -d <name> : filter meshcore devices with name or address
4902
4969
  -P : forces pairing via the OS
@@ -5256,10 +5323,12 @@ meshcore-cli lets you attach shell process to msg rx_log chan_data or telemetry
5256
5323
  """)
5257
5324
 
5258
5325
  elif "timer" in cmdname:
5259
- print("""timer [-j] [-c<contact>] [-s<scope>] <s> <line>: runs line every s seconds (s can be postfixed with s, m, h or d)
5326
+ print("""timer [-j] [-x] [-n<count>] [-c<contact>] [-s<scope>] <s> <line>: runs line every s seconds (s can be postfixed with s, m, h or d)
5260
5327
 
5261
5328
  * args:
5262
5329
  - `-j` forces json output for the timed line.
5330
+ - `-x` executes the line immediately, then every `s` seconds (without it, the first run happens after `s` seconds).
5331
+ - `-n` runs the line `count` times, then disarms the timer (default: runs until cancelled).
5263
5332
  - `-c` sets the contact the line is run from (`~` for root).
5264
5333
  - `-s` sets the scope for the line, defaults to the current scope.
5265
5334
 
@@ -5710,6 +5779,67 @@ async def repeater_loop(ser):
5710
5779
  await process_repeater_line(ser, cmd, repeater_name=device_name)
5711
5780
 
5712
5781
 
5782
+ async def mdns_discover(timeout=2):
5783
+ """ Browse the network for MeshCore devices advertised through mDNS
5784
+
5785
+ Returns a list of dicts sorted by name, with keys :
5786
+ name : node name (txt record node-name, else instance name)
5787
+ host : mDNS hostname (e.g. "meshcore_mynode.local.") or None
5788
+ port : tcp port
5789
+ addresses : list of ip addresses (as strings)
5790
+ firmware : firmware version (txt record) or None
5791
+
5792
+ Returns an empty list if zeroconf is not available or if the
5793
+ network can't be browsed.
5794
+ """
5795
+ if not ZEROCONF_AVAILABLE:
5796
+ return []
5797
+
5798
+ found = {}
5799
+ pending = set()
5800
+
5801
+ async def resolve(zc, service_type, name):
5802
+ info = AsyncServiceInfo(service_type, name)
5803
+ if await info.async_request(zc, 2000):
5804
+ addresses = info.parsed_addresses()
5805
+ if info.port and addresses:
5806
+ # the instance name is sanitized by the firmware (meshcore_<name>),
5807
+ # the real node name is in the node-name txt record
5808
+ props = {k.decode(errors="replace"): v.decode(errors="replace")
5809
+ for k, v in (info.properties or {}).items() if v is not None}
5810
+ found[name] = {
5811
+ "name": props.get("node-name") or name.removesuffix("." + service_type),
5812
+ "host": info.server,
5813
+ "port": info.port,
5814
+ "addresses": addresses,
5815
+ "firmware": props.get("firmware-version"),
5816
+ }
5817
+
5818
+ def on_service_change(zeroconf, service_type, name, state_change):
5819
+ if state_change is ServiceStateChange.Added:
5820
+ task = asyncio.ensure_future(resolve(zeroconf, service_type, name))
5821
+ pending.add(task)
5822
+ task.add_done_callback(pending.discard)
5823
+
5824
+ aiozc = None
5825
+ browser = None
5826
+ try:
5827
+ aiozc = AsyncZeroconf()
5828
+ browser = AsyncServiceBrowser(aiozc.zeroconf, MDNS_SERVICE,
5829
+ handlers=[on_service_change])
5830
+ await asyncio.sleep(timeout)
5831
+ if pending:
5832
+ await asyncio.gather(*pending, return_exceptions=True)
5833
+ except OSError as e:
5834
+ logger.info(f"mDNS discovery not available: {e}")
5835
+ finally:
5836
+ if browser is not None:
5837
+ await browser.async_cancel()
5838
+ if aiozc is not None:
5839
+ await aiozc.async_close()
5840
+
5841
+ return sorted(found.values(), key=lambda s: s["name"])
5842
+
5713
5843
  async def main(argv):
5714
5844
  """ Do the job """
5715
5845
  global HAS_CLI_CMD
@@ -5787,7 +5917,11 @@ async def main(argv):
5787
5917
  case "-b" :
5788
5918
  baudrate = int(arg)
5789
5919
  case "-t" :
5790
- hostname = arg
5920
+ if arg.count(":") == 1:
5921
+ port = arg.split(":")[1]
5922
+ hostname = arg.split(":")[0]
5923
+ else:
5924
+ hostname = arg
5791
5925
  case "-p" :
5792
5926
  port = int(arg)
5793
5927
  case "-j" :
@@ -5808,6 +5942,10 @@ async def main(argv):
5808
5942
  case "-q": # quiet (turns logger to ERROR only)
5809
5943
  quiet = True
5810
5944
  case "-l" :
5945
+ # start mDNS browsing now so it overlaps with the BLE scan
5946
+ mdns_task = None
5947
+ if ZEROCONF_AVAILABLE and not repeater_mode:
5948
+ mdns_task = asyncio.ensure_future(mdns_discover(timeout=timeout))
5811
5949
  if BLEAK_AVAILABLE and not repeater_mode:
5812
5950
  print("BLE devices:")
5813
5951
  try :
@@ -5820,6 +5958,14 @@ async def main(argv):
5820
5958
  except (BleakError, BleakDBusError):
5821
5959
  print(" No BLE HW")
5822
5960
  print("")
5961
+ if mdns_task is not None:
5962
+ print("TCP devices (mDNS):")
5963
+ services = await mdns_task
5964
+ if len(services) == 0:
5965
+ print(" No mDNS device found")
5966
+ for s in services:
5967
+ print(f" {s['addresses'][0] + ':' + str(s['port']):<22} {s['name']}")
5968
+ print("")
5823
5969
  print("Serial ports:")
5824
5970
  ports = serial.tools.list_ports.comports()
5825
5971
  for port, desc, hwid in sorted(ports):
@@ -5827,7 +5973,10 @@ async def main(argv):
5827
5973
  return
5828
5974
  case "-S" :
5829
5975
  choices = []
5830
-
5976
+ # start mDNS browsing now so it overlaps with the BLE scan
5977
+ mdns_task = None
5978
+ if ZEROCONF_AVAILABLE and not repeater_mode:
5979
+ mdns_task = asyncio.ensure_future(mdns_discover(timeout=timeout))
5831
5980
  if BLEAK_AVAILABLE and not repeater_mode:
5832
5981
  try :
5833
5982
  devices = await BleakScanner.discover(timeout=timeout)
@@ -5836,7 +5985,10 @@ async def main(argv):
5836
5985
  choices.append(({"type":"ble","device":d}, f"{d.address:<22} {d.name}"))
5837
5986
  except (BleakError, BleakDBusError):
5838
5987
  logger.info("No BLE Device")
5839
-
5988
+ if mdns_task is not None:
5989
+ services = await mdns_task
5990
+ for s in services:
5991
+ choices.append(({"type":"tcp","address":s['addresses'][0],"port":s['port']}, f"{s['addresses'][0] + ':' + str(s['port']):<22} {s['name']}"))
5840
5992
  ports = serial.tools.list_ports.comports()
5841
5993
  for port, desc, hwid in sorted(ports):
5842
5994
  choices.append(({"type":"serial","port":port}, f"{port:<22} {desc}"))
@@ -5858,6 +6010,9 @@ async def main(argv):
5858
6010
  device = result["device"]
5859
6011
  elif result["type"] == "serial":
5860
6012
  serial_port = result["port"]
6013
+ elif result["type"] == "tcp":
6014
+ hostname = result["address"]
6015
+ port = result["port"]
5861
6016
  else:
5862
6017
  logger.error("Invalid choice")
5863
6018
  return
@@ -5889,7 +6044,39 @@ async def main(argv):
5889
6044
 
5890
6045
  mc = None
5891
6046
  if not hostname is None : # connect via tcp
5892
- mc = await MeshCore.create_tcp(host=hostname, port=port, debug=debug, only_error=json_output)
6047
+ try:
6048
+ mc = await MeshCore.create_tcp(host=hostname, port=port, debug=debug, only_error=json_output)
6049
+ except Exception as err:
6050
+ if ZEROCONF_AVAILABLE and not repeater_mode and hostname and not (':' in hostname or hostname.replace('.', '').isdigit()):
6051
+ logger.debug(f"Error trying to connect via TCP: {err} ... trying mDNS")
6052
+ services = await mdns_discover(timeout=timeout)
6053
+ mc = None
6054
+ name = hostname.lower()
6055
+ srv = None
6056
+ for s in services:
6057
+ if name == s['name'].lower(): # priorize exact match
6058
+ srv = s
6059
+ break
6060
+ if srv is None:
6061
+ for s in services:
6062
+ if name in s['name'].lower() or s['host'] and name in s['host'].lower():
6063
+ srv = s
6064
+ break
6065
+ if srv:
6066
+ hostname = srv['addresses'][0]
6067
+ port = srv['port']
6068
+ else:
6069
+ print(f"Could not find {hostname} with mDNS")
6070
+ return
6071
+
6072
+ try:
6073
+ mc = await MeshCore.create_tcp(host=hostname, port=port, debug=debug, only_error=json_output)
6074
+ except Exception:
6075
+ print("Could not connect via TCP")
6076
+ return
6077
+ else:
6078
+ print(f"Could not connect via TCP err:{err}")
6079
+ return
5893
6080
  elif not serial_port is None : # connect via serial port
5894
6081
  mc = await MeshCore.create_serial(port=serial_port, baudrate=baudrate, debug=debug, only_error=json_output, dtr=serial_dtr, rts=serial_rts)
5895
6082
  if mc is None: # did not connect
File without changes
File without changes
File without changes
File without changes