-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathrpc.py
More file actions
360 lines (304 loc) · 12.4 KB
/
rpc.py
File metadata and controls
360 lines (304 loc) · 12.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
from pathlib import Path
import time
from datetime import datetime
from typing import Optional
import synapse as syn
from synapse.api.query_pb2 import QueryRequest, QueryResponse, StreamQueryRequest
from synapse.api.status_pb2 import StatusCode
from google.protobuf import text_format
from google.protobuf.json_format import Parse
from rich.console import Console
from synapse.cli.query import StreamingQueryClient
from synapse.utils.log import log_entry_to_str
from synapse.cli.device_info_display import DeviceInfoDisplay
from synapse.utils.proto import load_device_config
def add_commands(subparsers):
a = subparsers.add_parser("info", help="Get device information")
a.set_defaults(func=info)
b = subparsers.add_parser("query", help="Execute a query on the device")
b.add_argument("query_file", type=str)
b.add_argument("--verbose", "-v", action="store_true", help="Verbose output")
b.add_argument("--stream", "-s", action="store_true", help="Stream the output")
b.set_defaults(func=query)
c = subparsers.add_parser("start", help="Start the device or an application")
c.add_argument(
"config_file",
nargs="?",
default=None,
help=(
"Optional path to a device configuration JSON file. If supplied, "
"the CLI first uploads the configuration, then starts the device. "
"Running `synapsectl start` with no argument simply starts the "
"device without re-configuring it."
),
)
c.set_defaults(func=start)
d = subparsers.add_parser("stop", help="Stop the device or an application")
d.add_argument(
"app_name",
nargs="?",
default=None,
help="Name of the application to stop (systemd service). If omitted, stops the whole device via RPC.",
)
d.set_defaults(func=stop)
e = subparsers.add_parser("configure", help="Write a configuration to the device")
e.add_argument("config_file", type=str)
e.set_defaults(func=configure)
f = subparsers.add_parser("logs", help="Get logs from the device")
f.add_argument("--output", "-o", type=str, help="Optional file to write logs to")
f.add_argument(
"--quiet",
"-q",
action="store_true",
help="Suppress output to stdout",
)
f.add_argument(
"--log-level",
"-l",
type=str,
choices=["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"],
default="INFO",
help="Log level to filter by",
)
f.add_argument(
"--follow",
"-f",
action="store_true",
help="Follow log output",
)
f.add_argument(
"--since",
"-S",
type=int,
help="Get logs from the last N milliseconds",
metavar="N",
)
f.add_argument(
"--start-time",
type=str,
help="Start time in ISO format (e.g., '2024-03-14T15:30:00')",
)
f.add_argument(
"--end-time",
type=str,
help="End time in ISO format (e.g., '2024-03-14T15:30:00')",
)
f.set_defaults(func=get_logs)
def info(args):
device = syn.Device(args.uri, args.verbose)
display = DeviceInfoDisplay()
display.summary(device)
def query(args):
def load_query_request(path_to_config):
try:
with open(path_to_config, "r") as f:
data = f.read()
proto = Parse(data, QueryRequest())
return proto
except FileNotFoundError:
console.print(f"[red]Failed to open {path_to_config}: File not found[/red]")
return None
except Exception as e:
console.print(f"[red]Failed to parse query file: {str(e)}[/red]")
return None
console = Console()
if args.stream:
client = StreamingQueryClient(args.uri, args.verbose)
query_proto = load_query_request(args.query_file)
if not query_proto:
return False
try:
return client.stream_query(StreamQueryRequest(request=query_proto))
except Exception as e:
console.print(f"[red]Error streaming query: {str(e)}[/red]")
return False
if Path(args.query_file).suffix != ".json":
console.print("[red]Query file must be a JSON file[/red]")
return False
try:
with open(args.query_file) as query_json:
query_proto = Parse(query_json.read(), QueryRequest())
console.print("Running query:")
console.print(query_proto)
result: QueryResponse = syn.Device(args.uri, args.verbose).query(
query_proto
)
if result:
console.print(text_format.MessageToString(result))
if result.HasField("impedance_response"):
measurements = result.impedance_response
# Write impedance measurements to a CSV file
timestamp = time.strftime("%Y%m%d-%H%M%S")
filename = f"impedance_measurements_{timestamp}.csv"
try:
with open(filename, "w") as f:
f.write(
"Electrode ID,Magnitude (Ohms),Phase (degrees),Status\n"
)
for measurement in measurements.measurements:
f.write(
f"{measurement.electrode_id},{measurement.magnitude},{measurement.phase},1\n"
)
console.print(
f"[green]Impedance measurements saved to {filename}[/green]"
)
except IOError as e:
console.print(
f"[red]Error writing impedance measurements: {str(e)}[/red]"
)
except Exception as e:
console.print(f"[red]Error executing query: {str(e)}[/red]")
return False
def start(args):
"""Start the Synapse device (and any application services managed by
*ApplicationControllerNode*). If an ``app_name`` is supplied we still just
issue the standard *Device.start* RPC – the controller node on-device will
decide which systemd service to launch.
"""
console = Console()
config_obj = None
cfg_path = getattr(args, "config_file", None)
if cfg_path:
if Path(cfg_path).suffix != ".json":
console.print("[bold red]Configuration file must be a JSON file (.json)")
return
if not Path(cfg_path).is_file():
console.print(f"[bold red]Configuration file {cfg_path} does not exist")
return
# Load the configuration proto and build Config object
try:
config_obj = load_device_config(cfg_path, console)
except Exception as e:
console.print(
f"[bold red]Failed to parse configuration file[/bold red]: {e}"
)
return
device = syn.Device(args.uri, args.verbose)
device_name = device.get_name()
# If we have a configuration, apply it first.
if config_obj is not None:
with console.status("Configuring device...", spinner="bouncingBall"):
cfg_ret = device.configure_with_status(config_obj)
if cfg_ret is None:
console.print("[bold red]Internal error configuring device")
return
if cfg_ret.code != StatusCode.kOk:
console.print(
f"[bold red]Error configuring device[/bold red]\nResponse from {device_name}:\n{cfg_ret.message}"
)
return
console.print("[green]Device configured")
with console.status("Starting device...", spinner="bouncingBall"):
start_ret = device.start_with_status()
if start_ret is None:
console.print("[bold red]Internal error starting device")
return
if start_ret.code != StatusCode.kOk:
console.print(
f"[bold red]Error starting device[/bold red]\nResponse from {device_name}:\n{start_ret.message}"
)
return
console.print("[green]Device started")
def stop(args):
"""Stop the Synapse device and, by extension, any application services
controlled by ApplicationControllerNode.
"""
console = Console()
if getattr(args, "app_name", None):
console.print(
f"[yellow]Stopping device; application '{args.app_name}' will be "
"shut down by the on-device ApplicationController.[/yellow]"
)
with console.status("Stopping device...", spinner="bouncingBall"):
stop_ret = syn.Device(args.uri, args.verbose).stop_with_status()
if not stop_ret:
console.print("[bold red]Internal error stopping device")
return
if stop_ret.code != StatusCode.kOk:
console.print(f"[bold red]Error stopping\n{stop_ret.message}")
return
console.print("[green]Device stopped")
def configure(args):
console = Console()
if Path(args.config_file).suffix != ".json":
console.print("[bold red]Configuration file must be a JSON file")
return False
config_obj = load_device_config(args.config_file, console)
console.print("Configuring device with the following configuration:")
console.print(config_obj.to_proto())
config_ret = syn.Device(args.uri, args.verbose).configure_with_status(config_obj)
if not config_ret:
console.print("[bold red]Internal error configuring device")
return
if config_ret.code != StatusCode.kOk:
console.print(f"[bold red]Error configuring\n{config_ret.message}")
return
console.print("[green]Device configured")
def get_logs(args):
def parse_datetime(time_str: Optional[str]) -> Optional[datetime]:
"""Parse an ISO format datetime string."""
if not time_str:
return None
try:
return datetime.fromisoformat(time_str)
except ValueError:
return None
console = Console()
output_file = open(args.output, "w") if args.output else None
try:
if args.follow:
with console.status("Tailing logs...", spinner="bouncingBall"):
device = syn.Device(args.uri, args.verbose)
for log in device.tail_logs(args.log_level):
line = log_entry_to_str(log)
if output_file:
output_file.write(line + "\n")
if not args.quiet:
print(line)
return
start_time = parse_datetime(args.start_time)
if args.start_time and not start_time:
console.print(
"[bold red]Invalid start time format. Use ISO format (e.g., '2024-03-14T15:30:00')"
)
return
end_time = parse_datetime(args.end_time)
if args.end_time and not end_time:
console.print(
"[bold red]Invalid end time format. Use ISO format (e.g., '2024-03-14T15:30:00')"
)
return
with console.status("Getting logs...", spinner="bouncingBall"):
res = syn.Device(args.uri, args.verbose).get_logs_with_status(
log_level=args.log_level,
since_ms=args.since,
start_time=start_time,
end_time=end_time,
)
if not res or not res.entries:
console.print("[yellow]No logs found for the specified criteria")
return
for log in res.entries:
line = log_entry_to_str(log)
if output_file:
output_file.write(line + "\n")
if not args.quiet:
print(line)
finally:
if output_file:
output_file.close()
def list_apps(args):
console = Console()
with console.status("Listing installed applications...", spinner="bouncingBall"):
device = syn.Device(args.uri, args.verbose)
response = device.list_apps()
if not response:
console.print("[bold red]Failed to list applications")
return
if not response.apps:
console.print("[yellow]No applications installed on the device")
return
console.print("[bold]Installed Applications:[/bold]")
for app in response.apps:
version_str = f" (v{app.version})" if app.version else ""
console.print(f" • {app.name}{version_str}")