meshcore-cli 1.6.0__tar.gz → 1.6.1__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.0
3
+ Version: 1.6.1
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
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "meshcore-cli"
7
- version = "1.6.0"
7
+ version = "1.6.1"
8
8
  authors = [
9
9
  { name="Florent de Lamotte", email="florent@frizoncorrea.fr" },
10
10
  ]
@@ -0,0 +1,144 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Get the current position (latitude, longitude, accuracy/precision) via GeoClue2.
4
+
5
+ Requirements:
6
+ sudo apt install gir1.2-geoclue-2.0 python3-gi
7
+ GeoClue2 daemon (package "geoclue-2.0") must be installed and running.
8
+ """
9
+
10
+ import argparse
11
+ import json
12
+ import sys
13
+
14
+ import gi
15
+ gi.require_version("Geoclue", "2.0")
16
+ from gi.repository import GLib, Geoclue
17
+
18
+ def get_current_position(app_id="my-python-app",
19
+ accuracy_level=Geoclue.AccuracyLevel.EXACT,
20
+ timeout_seconds=15,
21
+ max_accuracy_meters=None,
22
+ on_update=None):
23
+ loop = GLib.MainLoop()
24
+ result = {}
25
+ error_holder = {}
26
+ simple_holder = {}
27
+
28
+ def meets_threshold(location):
29
+ if max_accuracy_meters is None:
30
+ return True
31
+ accuracy = location.get_property("accuracy")
32
+ return accuracy is not None and accuracy <= max_accuracy_meters
33
+
34
+ def capture(location):
35
+ result["latitude"] = location.get_property("latitude")
36
+ result["longitude"] = location.get_property("longitude")
37
+ result["accuracy"] = location.get_property("accuracy")
38
+ if on_update is not None:
39
+ on_update(dict(result))
40
+
41
+ def on_location_notify(simple, param):
42
+ location = simple.get_location()
43
+ if location is None:
44
+ return
45
+ capture(location)
46
+ if meets_threshold(location):
47
+ loop.quit()
48
+
49
+ def on_client_ready(source, res, user_data=None):
50
+ try:
51
+ simple = Geoclue.Simple.new_finish(res)
52
+ except GLib.Error as e:
53
+ error_holder["error"] = e
54
+ loop.quit()
55
+ return
56
+
57
+ simple_holder["simple"] = simple
58
+
59
+ location = simple.get_location()
60
+ if location is not None:
61
+ capture(location)
62
+ if meets_threshold(location):
63
+ loop.quit()
64
+ return
65
+
66
+ simple.connect("notify::location", on_location_notify)
67
+
68
+ def on_timeout():
69
+ if "latitude" not in result:
70
+ error_holder["error"] = TimeoutError(
71
+ f"No location fix received within {timeout_seconds}s"
72
+ )
73
+ loop.quit()
74
+ return False
75
+
76
+ GLib.timeout_add_seconds(timeout_seconds, on_timeout)
77
+
78
+ Geoclue.Simple.new(app_id, accuracy_level, None, on_client_ready)
79
+
80
+ loop.run()
81
+
82
+ if "error" in error_holder:
83
+ raise error_holder["error"]
84
+
85
+ return result
86
+
87
+ def parse_args():
88
+ parser = argparse.ArgumentParser(
89
+ description="Get the current position via GeoClue2."
90
+ )
91
+ parser.add_argument(
92
+ "-t", "--timeout",
93
+ type=float,
94
+ default=15,
95
+ metavar="SECONDS",
96
+ help="max time to wait for a location fix (default: 15)",
97
+ )
98
+ parser.add_argument(
99
+ "-a", "--accuracy",
100
+ type=float,
101
+ default=600,
102
+ metavar="METERS",
103
+ help=("keep waiting for fixes until accuracy is reached"),
104
+ )
105
+ parser.add_argument(
106
+ "-v", "--verbose",
107
+ action="store_true",
108
+ help="print every position fix as it's acquired, not just the final one",
109
+ )
110
+ parser.add_argument(
111
+ "-vo", "--verbose-stdout",
112
+ action="store_true",
113
+ help=("print intermediate positions to stdout"),
114
+ )
115
+ return parser.parse_args()
116
+
117
+ def main():
118
+ args = parse_args()
119
+ if args.verbose_stdout:
120
+ args.verbose = True
121
+
122
+ def print_update(fix):
123
+ stream = sys.stdout if args.verbose_stdout else sys.stderr
124
+ print(json.dumps(fix), file=stream)
125
+
126
+ try:
127
+ loc = get_current_position(
128
+ accuracy_level=Geoclue.AccuracyLevel.EXACT,
129
+ timeout_seconds=args.timeout,
130
+ max_accuracy_meters=args.accuracy,
131
+ on_update=print_update if args.verbose else None,
132
+ )
133
+ except Exception as e:
134
+ print(f"Failed to get location: {e}", file=sys.stderr)
135
+ sys.exit(1)
136
+
137
+ print(json.dumps({
138
+ "lat": loc["latitude"],
139
+ "lon": loc["longitude"],
140
+ "accuracy": loc["accuracy"],
141
+ }))
142
+
143
+ if __name__ == "__main__":
144
+ main()
@@ -34,13 +34,23 @@ except ImportError:
34
34
  from meshcore import MeshCore, EventType, logger
35
35
 
36
36
  # Version
37
- VERSION = "v1.6.0"
37
+ VERSION = "v1.6.1"
38
38
 
39
39
  # default ble address is stored in a config file
40
40
  MCCLI_CONFIG_DIR = os.path.expanduser("~/.config/meshcore/")
41
41
  MCCLI_ADDRESS = MCCLI_CONFIG_DIR + "default_address"
42
42
  MCCLI_HISTORY_FILE = MCCLI_CONFIG_DIR + "history"
43
43
  MCCLI_INIT_SCRIPT = MCCLI_CONFIG_DIR + "init"
44
+ MCCLI_SCOPES_FILE = MCCLI_CONFIG_DIR + "scopes"
45
+
46
+ # Per channel scope overrides, one "<channel name> <scope>" per line.
47
+ SCOPES = {}
48
+ if os.path.exists(MCCLI_SCOPES_FILE) :
49
+ with open(MCCLI_SCOPES_FILE, "r") as lines:
50
+ for line in lines:
51
+ line = line.strip()
52
+ channel, scope = line.split()
53
+ SCOPES[channel] = scope
44
54
 
45
55
  PAYLOAD_TYPENAMES = ["REQ", "RESPONSE", "TEXT_MSG", "ACK", "ADVERT", "GRP_TXT", "GRP_DATA", "ANON_REQ", "PATH", "TRACE", "MULTIPART", "CONTROL"]
46
56
  ROUTE_TYPENAMES = ["TC_FLOOD", "FLOOD", "DIRECT", "TC_DIRECT"]
@@ -150,6 +160,29 @@ def split_first_token(line):
150
160
 
151
161
  return target, command
152
162
 
163
+ def strip_outer_quotes(text):
164
+ if len(text) >= 2 and text[0] in ("'", '"') and text[-1] == text[0]:
165
+ return text[1:-1]
166
+ return text
167
+
168
+ def split_pipeline(pipeline):
169
+ lines, buf, quote = [], [], None
170
+ for c in pipeline:
171
+ if quote:
172
+ buf.append(c)
173
+ if c == quote:
174
+ quote = None
175
+ elif c in ('"', "'"):
176
+ quote = c
177
+ buf.append(c)
178
+ elif c == "|":
179
+ lines.append("".join(buf).strip())
180
+ buf = []
181
+ else:
182
+ buf.append(c)
183
+ lines.append("".join(buf).strip())
184
+ return lines
185
+
153
186
  def escape_ansi(line):
154
187
  ansi_escape = re.compile(r'(?:\x1B[@-_]|[\x80-\x9F])[0-?]*[ -/]*[@-~]')
155
188
  return ansi_escape.sub('', line)
@@ -481,7 +514,7 @@ class MyNestedCompleter(NestedCompleter):
481
514
  opts = self.options.keys()
482
515
  completer = WordCompleter(
483
516
  opts, ignore_case=self.ignore_case,
484
- pattern=re.compile(r"([a-zA-Z0-9_\\/\#\?]+|[^a-zA-Z0-9_\s\#\?]+)"))
517
+ pattern=re.compile(r"([a-zA-Z0-9_\\/\#\?@]+|[^a-zA-Z0-9_\s\#\?@]+)"))
485
518
  yield from completer.get_completions(document, complete_event)
486
519
  else: # normal behavior for remainder
487
520
  yield from super().get_completions(document, complete_event)
@@ -1176,8 +1209,7 @@ async def process_redirected_line(mc, line, contact=None, scope="*", prev_contac
1176
1209
 
1177
1210
  async def process_pipeline(mc, pipeline, contact=None, scope="*", prev_contact=None, prev_scope="*", json_output=False, sink=sys.stdout, end="\n"):
1178
1211
 
1179
- pattern = r"""(?:\\.|"[^"\\]*(?:\\.[^"\\]*)*"|'[^'\\]*(?:\\.[^'\\]*)*'|[^|"\'])+"""
1180
- lines = [match.group(0).strip() for match in re.finditer(pattern, pipeline)]
1212
+ lines = split_pipeline(pipeline)
1181
1213
 
1182
1214
  last_ack = True
1183
1215
  for line in lines:
@@ -1236,6 +1268,8 @@ async def process_line(mc, line, contact=None, scope="*", prev_contact=None, pre
1236
1268
  if '%' in dest and scope!=None :
1237
1269
  dest_scope = dest.split("%")[-1]
1238
1270
  dest = dest[:-len(dest_scope)-1]
1271
+ elif dest in SCOPES.keys():
1272
+ dest_scope = SCOPES[dest]
1239
1273
  nc = await get_contact_from_arg(mc, dest)
1240
1274
  if nc is None:
1241
1275
  if dest == "public" :
@@ -1264,16 +1298,21 @@ async def process_line(mc, line, contact=None, scope="*", prev_contact=None, pre
1264
1298
  nc = {"adv_name": chan["channel_name"],
1265
1299
  "type": 0,
1266
1300
  "chan_nb": chan["channel_idx"],}
1267
- if nc != contact :
1268
- last_ack = True
1269
- prev_contact = contact
1270
- contact = nc
1271
- if dest_scope is None:
1301
+ if not contact is None and dest_scope is None \
1302
+ and contact["adv_name"] in SCOPES and scope == SCOPES[contact["adv_name"]]:
1303
+ # if the scope was associated with that channel
1304
+ # then reset scope to default
1305
+ dest_scope = ""
1306
+ if dest_scope is None: # still None ... keep it as it was
1272
1307
  dest_scope = scope
1273
- if not scope is None and dest_scope != scope:
1308
+ if not scope is None and dest_scope != scope: # has scope changed
1274
1309
  prev_scope = scope
1275
1310
  if not dest_scope is None:
1276
1311
  scope = await set_scope(mc, dest_scope)
1312
+ if nc != contact :
1313
+ last_ack = True
1314
+ prev_contact = contact
1315
+ contact = nc
1277
1316
 
1278
1317
  elif line == "to" or line == "/to" :
1279
1318
  if contact is None :
@@ -1327,16 +1366,15 @@ async def process_line(mc, line, contact=None, scope="*", prev_contact=None, pre
1327
1366
 
1328
1367
  elif line.startswith("send") or line.startswith("\"") :
1329
1368
  if line.startswith("send") :
1330
- line = line[5:]
1331
- if line.startswith("\"") :
1332
- line = line[1:]
1369
+ line = line[5:].strip()
1370
+ line = strip_outer_quotes(line)
1333
1371
  last_ack = await msg_ack(mc, contact, line)
1334
1372
 
1335
1373
  elif contact["type"] == 0 : # channel, send msg to channel
1336
- await send_chan_msg(mc, contact["chan_nb"], line)
1374
+ await send_chan_msg(mc, contact["chan_nb"], strip_outer_quotes(line))
1337
1375
 
1338
1376
  elif contact["type"] == 1 : # chat, send to recipient and wait ack
1339
- last_ack = await msg_ack(mc, contact, line)
1377
+ last_ack = await msg_ack(mc, contact, strip_outer_quotes(line))
1340
1378
 
1341
1379
  elif contact["type"] == 2 or\
1342
1380
  contact["type"] == 3 or\
@@ -1636,7 +1674,10 @@ async def process_contact_chat_line(mc, contact, line, inside=False, json_output
1636
1674
  cmds[0] == "cf" or cmds[0] == "change_flags" or\
1637
1675
  cmds[0] == "req_binary" or\
1638
1676
  cmds[0] == "login" :
1639
- args = [cmds[0], contact['adv_name'], cmds[1]]
1677
+ text = cmds[1]
1678
+ if cmds[0] == "msg":
1679
+ text = strip_outer_quotes(text)
1680
+ args = [cmds[0], contact['adv_name'], text]
1640
1681
  await process_cmds(mc, args, json_output=json_output, sink=sink)
1641
1682
  return True
1642
1683
 
@@ -1773,10 +1814,8 @@ async def apply_command_to_contacts(mc, contact_filter, line, json_output=False,
1773
1814
 
1774
1815
  elif line.startswith("send") or line.startswith("\"") :
1775
1816
  if line.startswith("send") :
1776
- line = line[5:]
1777
- if line.startswith("\"") :
1778
- line = line[1:]
1779
- await msg_ack(mc, contact, line)
1817
+ line = line[5:].strip()
1818
+ await msg_ack(mc, contact, strip_outer_quotes(line))
1780
1819
 
1781
1820
  elif contact["type"] == 2 or\
1782
1821
  contact["type"] == 3 or\
@@ -1,20 +0,0 @@
1
- #!/usr/bin/python
2
- # queries geoclue for current position of a linux device and print coordinates
3
-
4
- import gi
5
- gi.require_version('Geoclue', '2.0')
6
- from gi.repository import Geoclue
7
-
8
- # Initialisation du client Geoclue simple
9
- clue = Geoclue.Simple.new_sync('mon-app-id', Geoclue.AccuracyLevel.EXACT, None)
10
-
11
- # Récupération de l'objet de localisation (proxy D-Bus)
12
- loc = clue.get_location()
13
-
14
- # Extraction des propriétés réelles de l'objet
15
- latitude = loc.get_property('latitude')
16
- longitude = loc.get_property('longitude')
17
- altitude = loc.get_property('altitude')
18
-
19
- # Affichage des coordonnées numériques
20
- print(f"{latitude},{longitude}")
File without changes
File without changes
File without changes
File without changes
File without changes