-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
348 lines (276 loc) · 11.6 KB
/
cli.py
File metadata and controls
348 lines (276 loc) · 11.6 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
#!/usr/bin/env python
# SPDX-License-Identifier: MIT
#
# Copyright (c) 2025 OpenMV, LLC.
# OpenMV CLI Tool
# Command-line interface for OpenMV cameras. Provides live video
# streaming, script execution, and camera management capabilities.
import sys
import os
import argparse
import time
import logging
import pygame
import signal
import atexit
from openmv.camera import Camera
from openmv.profiler import draw_profile_overlay
# Benchmark script for throughput testing
bench_script = """
import csi, image, time
csi0 = csi.CSI()
csi0.reset()
csi0.pixformat(csi.RGB565)
csi0.framesize(csi.QVGA)
img = csi0.snapshot().compress()
while(True):
img.flush()
"""
# Default test script for csi-based cameras
test_script = """
import time
import protocol
import csi
import image
class TicksChannel:
def __init__(self):
pass
def size(self):
return 10
def read(self, offset, size):
return f'{time.ticks_ms():010d}'
def poll(self):
return True
ch1 = protocol.register(name='ticks', backend=TicksChannel())
csi0 = csi.CSI()
csi0.reset()
csi0.pixformat(csi.RGB565)
csi0.framesize(csi.QVGA)
clock = time.clock()
while(True):
clock.tick()
img = csi0.snapshot()
print(clock.fps(), " FPS")
"""
def cleanup_and_exit():
"""Force cleanup pygame and exit"""
try:
pygame.quit()
except Exception:
pass
os._exit(0)
def signal_handler(signum, frame):
cleanup_and_exit()
def str2bool(v):
"""Convert string to boolean for argparse"""
if isinstance(v, bool):
return v
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise argparse.ArgumentTypeError('Boolean value expected.')
def main():
parser = argparse.ArgumentParser(description='OpenMV CLI Tool')
parser.add_argument('--port',
action='store', default='/dev/ttyACM0',
help='Serial port (default: /dev/ttyACM0)')
parser.add_argument("--script",
action="store", default=None,
help="Script file")
parser.add_argument('--poll', action='store',
default=4, type=int,
help='Poll rate in ms (default: 4)')
parser.add_argument('--scale', action='store',
default=4, type=int,
help='Display scaling factor (default: 4)')
parser.add_argument('--bench',
action='store_true', default=False,
help='Run throughput benchmark')
parser.add_argument('--raw',
action='store_true', default=False,
help='Enable raw streaming mode')
parser.add_argument('--timeout',
action='store', type=float, default=1.0,
help='Protocol timeout in seconds')
parser.add_argument('--debug',
action='store_true',
help='Enable debug logging')
parser.add_argument('--baudrate',
type=int, default=921600,
help='Serial baudrate (default: 921600)')
parser.add_argument('--crc',
type=str2bool, nargs='?', const=True, default=True,
help='Enable CRC validation (default: true)')
parser.add_argument('--seq',
type=str2bool, nargs='?', const=True, default=True,
help='Enable sequence number validation (default: true)')
parser.add_argument('--ack',
type=str2bool, nargs='?', const=True, default=True,
help='Enable packet acknowledgment (default: false)')
parser.add_argument('--events',
type=str2bool, nargs='?', const=True, default=True,
help='Enable event notifications (default: true)')
parser.add_argument('--max-retry',
type=int, default=3,
help='Maximum number of retries (default: 3)')
parser.add_argument('--max-payload',
type=int, default=4096,
help='Maximum payload size in bytes (default: 4096)')
parser.add_argument('--drop-rate',
type=float, default=0.0,
help='Packet drop simulation rate (0.0-1.0, default: 0.0)')
parser.add_argument('--firmware',
action='store', default=None,
help='Firmware ELF file for symbol resolution')
parser.add_argument('--quiet',
action='store_true',
help='Suppress script output text')
parser.add_argument('--channel',
action='store', default=None,
help='Custom channel to poll and read')
args = parser.parse_args()
# Register signal handlers for clean exit
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
atexit.register(cleanup_and_exit)
# Configure logging
if args.debug:
log_level = logging.DEBUG
elif not args.quiet:
log_level = logging.INFO
else:
log_level = logging.ERROR
logging.basicConfig(
format="%(relativeCreated)010.3f - %(message)s",
level=log_level,
)
# Load script
if args.script is not None:
with open(args.script, 'r') as f:
script = f.read()
logging.info(f"Loaded script from {args.script}")
else:
script = bench_script if args.bench else test_script
logging.info("Using built-in script")
# Load profiler symbols if firmware provided
symbols = []
if args.firmware:
from openmv.profiler import load_symbols
symbols = load_symbols(args.firmware)
# Initialize pygame
pygame.init()
screen = None
clock = pygame.time.Clock()
fps_clock = pygame.time.Clock()
font = pygame.font.SysFont("monospace", 30)
if not args.bench:
pygame.display.set_caption("OpenMV Camera")
else:
pygame.display.set_caption("OpenMV Camera (Benchmark)")
screen = pygame.display.set_mode((640, 120), pygame.DOUBLEBUF, 32)
# Profiler state
profile_view = 0 # Off
profile_mode = False # False = inclusive, True = exclusive
profile_enabled = False # Will be set if profile channel exists
profile_update_ms = 0
profile_data = None
try:
with Camera(args.port, baudrate=args.baudrate, crc=args.crc, seq=args.seq,
ack=args.ack, events=args.events,
timeout=args.timeout, max_retry=args.max_retry,
max_payload=args.max_payload, drop_rate=args.drop_rate) as camera:
logging.info(f"Connected to OpenMV camera on {args.port}")
# Configure profiler (if enabled)
if profile_enabled := camera.has_channel("profile"):
logging.info("Profiler channel detected - profiling enabled")
camera.profiler_reset(config=None)
# Stop any running script
camera.stop()
time.sleep(0.500)
# Execute script
camera.exec(script)
camera.streaming(True, raw=args.raw, resolution=(512, 512))
logging.info("Script executed, starting display...")
while True:
# Handle pygame events first to keep UI responsive
for event in pygame.event.get():
if event.type == pygame.QUIT:
raise KeyboardInterrupt
if event.type != pygame.KEYDOWN:
continue
if event.key == pygame.K_ESCAPE:
raise KeyboardInterrupt
elif event.key == pygame.K_p and profile_enabled:
profile_view = (profile_view + 1) % 3 # Cycle views
logging.info(f"Profile view: {profile_view}")
elif event.key == pygame.K_r and profile_enabled:
camera.profiler_reset()
logging.info("Profiler reset")
elif event.key == pygame.K_m and profile_enabled:
profile_mode = not profile_mode
camera.profiler_mode(exclusive=profile_mode)
logging.info(f"Profile mode: {'Exclusive' if profile_mode else 'Inclusive'}")
# Read camera status
status = camera.read_status()
# Read text output
if not args.quiet and not args.bench and status and status.get('stdout'):
if text := camera.read_stdout():
print(text, end='')
# Read custom channel
if args.channel and status and status.get(args.channel):
if size := camera.channel_size(args.channel):
data = camera.channel_read(args.channel, size=size)
preview = data[:10] if len(data) > 10 else data
logging.info(f"[{args.channel}] ({size} bytes) {preview}")
# Read profiler data if enabled (max 10Hz)
if profile_enabled and profile_view and screen is not None:
current_time = time.time()
if current_time - profile_update_ms >= 0.1: # 10Hz
if profile_data := camera.read_profile():
profile_update_ms = current_time
# Read frame data
if frame := camera.read_frame():
fps = fps_clock.get_fps()
w, h, data = frame['width'], frame['height'], frame['data']
# Create image from RGB888 data (always converted by camera module)
if not args.bench:
image = pygame.image.frombuffer(data, (w, h), 'RGB')
image = pygame.transform.smoothscale(image, (w * args.scale, h * args.scale))
# Create/resize screen if needed
if screen is None:
screen = pygame.display.set_mode((w * args.scale, h * args.scale), pygame.DOUBLEBUF, 32)
# Draw frame
if args.bench:
screen.fill((0, 0, 0))
else:
screen.blit(image, (0, 0))
# Draw FPS info with accurate data rate
current_mbps = (fps * frame['raw_size']) / 1024**2
if current_mbps < 1.0:
rate_text = f"{current_mbps * 1024:.2f} KB/s"
else:
rate_text = f"{current_mbps:.2f} MB/s"
fps_text = f"{fps:.2f} FPS {rate_text} {w}x{h} RGB888"
screen.blit(font.render(fps_text, True, (255, 0, 0)), (0, 0))
# Draw profiler overlay if enabled and data available
if profile_data is not None:
draw_profile_overlay(screen, profile_data, profile_mode,
profile_view, 1, symbols, alpha=200)
pygame.display.flip()
fps_clock.tick()
# Control main loop timing
clock.tick(1000 // args.poll)
except KeyboardInterrupt:
logging.info("Interrupted by user")
except Exception as e:
logging.error(f"Error: {e}")
if args.debug:
import traceback
logging.error(f"{traceback.format_exc()}")
sys.exit(1)
finally:
pygame.quit()
if __name__ == '__main__':
main()