meshcore-cli 1.6.12__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,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: meshcore-cli
3
- Version: 1.6.12
3
+ Version: 1.6.13
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
@@ -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 <timeout> : timeout for the ble scan (-S and -l) default 2s
64
+ -l : list available ble/tcp (mDNS)/serial devices and exit
65
+ -T <timeout> : timeout for the ble/mDNS scan (-S and -l) default 2s
66
66
  -a <address> : specifies device address (can be a name)
67
67
  -d <name> : filter meshcore devices with name or address
68
68
  -P : forces pairing via the OS
@@ -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.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.12"
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 = ""
@@ -861,9 +870,9 @@ def make_completion_dict(contacts, pending=None, to=None, channels=None):
861
870
  "agc.reset.interval": None,
862
871
  "multi.acks": None,
863
872
  "pin": None,
864
- "wifi.status": None,
865
873
  "wifi.ssid": None,
866
874
  "wifi.pwd": None,
875
+ "wifi.enabled" : {"0": None, "1": None,},
867
876
  "ui.show_clock": None,
868
877
  "ui.auto_off_delay": None,
869
878
  "ui.backlight_delay": None,
@@ -932,6 +941,7 @@ def make_completion_dict(contacts, pending=None, to=None, channels=None):
932
941
  "wifi.status": None,
933
942
  "wifi.ssid": None,
934
943
  "wifi.pwd": None,
944
+ "wifi.enabled": None,
935
945
  "ui.show_clock": None,
936
946
  "ui.auto_off_delay": None,
937
947
  "ui.backlight_delay": None,
@@ -4895,8 +4905,8 @@ def command_usage() :
4895
4905
  -D : debug (sets logging to DEBUG)
4896
4906
  -q : quiet (sets logging to ERROR)
4897
4907
  -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
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
4900
4910
  -a <address> : specifies device address (can be a name)
4901
4911
  -d <name> : filter meshcore devices with name or address
4902
4912
  -P : forces pairing via the OS
@@ -5710,6 +5720,67 @@ async def repeater_loop(ser):
5710
5720
  await process_repeater_line(ser, cmd, repeater_name=device_name)
5711
5721
 
5712
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
+
5713
5784
  async def main(argv):
5714
5785
  """ Do the job """
5715
5786
  global HAS_CLI_CMD
@@ -5787,7 +5858,11 @@ async def main(argv):
5787
5858
  case "-b" :
5788
5859
  baudrate = int(arg)
5789
5860
  case "-t" :
5790
- hostname = arg
5861
+ if arg.count(":") == 1:
5862
+ port = arg.split(":")[1]
5863
+ hostname = arg.split(":")[0]
5864
+ else:
5865
+ hostname = arg
5791
5866
  case "-p" :
5792
5867
  port = int(arg)
5793
5868
  case "-j" :
@@ -5808,6 +5883,10 @@ async def main(argv):
5808
5883
  case "-q": # quiet (turns logger to ERROR only)
5809
5884
  quiet = True
5810
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))
5811
5890
  if BLEAK_AVAILABLE and not repeater_mode:
5812
5891
  print("BLE devices:")
5813
5892
  try :
@@ -5820,6 +5899,14 @@ async def main(argv):
5820
5899
  except (BleakError, BleakDBusError):
5821
5900
  print(" No BLE HW")
5822
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("")
5823
5910
  print("Serial ports:")
5824
5911
  ports = serial.tools.list_ports.comports()
5825
5912
  for port, desc, hwid in sorted(ports):
@@ -5827,7 +5914,10 @@ async def main(argv):
5827
5914
  return
5828
5915
  case "-S" :
5829
5916
  choices = []
5830
-
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))
5831
5921
  if BLEAK_AVAILABLE and not repeater_mode:
5832
5922
  try :
5833
5923
  devices = await BleakScanner.discover(timeout=timeout)
@@ -5836,7 +5926,10 @@ async def main(argv):
5836
5926
  choices.append(({"type":"ble","device":d}, f"{d.address:<22} {d.name}"))
5837
5927
  except (BleakError, BleakDBusError):
5838
5928
  logger.info("No BLE Device")
5839
-
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']}"))
5840
5933
  ports = serial.tools.list_ports.comports()
5841
5934
  for port, desc, hwid in sorted(ports):
5842
5935
  choices.append(({"type":"serial","port":port}, f"{port:<22} {desc}"))
@@ -5858,6 +5951,9 @@ async def main(argv):
5858
5951
  device = result["device"]
5859
5952
  elif result["type"] == "serial":
5860
5953
  serial_port = result["port"]
5954
+ elif result["type"] == "tcp":
5955
+ hostname = result["address"]
5956
+ port = result["port"]
5861
5957
  else:
5862
5958
  logger.error("Invalid choice")
5863
5959
  return
@@ -5889,7 +5985,39 @@ async def main(argv):
5889
5985
 
5890
5986
  mc = None
5891
5987
  if not hostname is None : # connect via tcp
5892
- 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
5893
6021
  elif not serial_port is None : # connect via serial port
5894
6022
  mc = await MeshCore.create_serial(port=serial_port, baudrate=baudrate, debug=debug, only_error=json_output, dtr=serial_dtr, rts=serial_rts)
5895
6023
  if mc is None: # did not connect
File without changes
File without changes
File without changes
File without changes