-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
393 lines (337 loc) · 14.7 KB
/
Copy pathmain.py
File metadata and controls
393 lines (337 loc) · 14.7 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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
"""ONEVO Local Connector entrypoint.
Flow: (optional ONVIF query) -> register (once) ->
start admin UI + uploader + heartbeat threads ->
capture loop cuts event clips -> clips enqueued to durable SQLite queue ->
uploaded to the cloud via short-lived signed URLs.
ONVIF mode: if --onvif-host (or CONNECTOR_ONVIF_HOST env) is set the connector
auto-discovers the RTSP URL and device info from the camera before starting
capture  no manual rtsp:// URL needed.
Installer modes:
--wizard first-run setup UI (setup code + RTSP / MP4)
--service Windows service: load ProgramData config and monitor continuously
"""
import sys
import threading
import time
from .admin import start_admin
from .backend_client import BackendClient
from .capture import CapturePipeline, validate_rtsp_stream
from .clip_settings import ClipSettings, load_clip_settings, save_clip_settings
from .config import load_config
from .paths import apply_pending_source_update, load_wizard_config,save_wizard_config
from .instance_lock import InstanceLock
from .runtime import RuntimeState
from .store import LocalStore
from .workers import run_heartbeat, run_uploader
# ---------------------------------------------------------------------------
# ONVIF startup helper
# ---------------------------------------------------------------------------
def _resolve_via_onvif(cfg, state: RuntimeState) -> None:
"""If onvif_host is configured, fetch RTSP URL + device info via ONVIF.
Updates cfg.source in-place and populates state ONVIF fields.
Non-fatal: on any error the connector falls back to cfg.source as-is.
"""
if not cfg.onvif_host:
return # ONVIF not configured  use --source as-is
try:
from .onvif_client import OnvifCamera
except ImportError:
state.log("WARNING: onvif_client not available  using --source as-is")
return
state.log(
f"ONVIF: connecting to {cfg.onvif_host}:{cfg.onvif_port} "
f"as '{cfg.onvif_user}' …"
)
try:
cam = OnvifCamera()
cam.connect(
host=cfg.onvif_host,
port=cfg.onvif_port,
username=cfg.onvif_user,
password=cfg.onvif_pass,
)
# ---- Device info ----
info = cam.get_device_info()
state.camera_manufacturer = info.manufacturer
state.camera_model = info.model
state.camera_serial = info.serial
state.camera_firmware = info.firmware
state.log(
f"ONVIF device: {info.manufacturer} {info.model} "
f"[S/N {info.serial}] fw={info.firmware}"
)
# ---- Stream profiles ----
profiles = cam.get_profiles()
state.onvif_profiles = [
{"token": p.token, "name": p.name,
"encoding": p.encoding, "width": p.width, "height": p.height}
for p in profiles
]
# ---- RTSP URL ----
profile_token = None if cfg.onvif_profile == "auto" else cfg.onvif_profile
rtsp_url = cam.get_rtsp_url(profile_token)
state.log(f"ONVIF RTSP URL → {rtsp_url}")
cfg.source = rtsp_url # override --source with the auto-fetched URL
except Exception as exc: # noqa: BLE001
state.log(f"ONVIF error (falling back to --source): {exc}")
def _ensure_registered(cfg, client: BackendClient, store: LocalStore, state: RuntimeState) -> bool:
"""Load or register connector credentials. Returns False on hard failure."""
cid = store.get_cred("connector_id")
key = store.get_cred("api_key")
if cid and key:
client.set_credentials(cid, key)
state.log(f"Loaded existing connector credentials ({cid})")
state.connector_id = client.connector_id
return True
if not cfg.store_id:
state.log("ERROR: first run needs --store-id (or complete the setup wizard).")
return False
try:
cid, key = client.register(cfg.store_id, cfg.connector_name, cfg.version, cfg.bootstrap_key)
except Exception as e: # noqa: BLE001
state.log(f"ERROR: registration failed: {e}")
return False
store.set_cred("connector_id", cid)
store.set_cred("api_key", key)
state.log(f"Registered connector {cid}")
state.connector_id = client.connector_id
return True
def _run_capture(cfg, client: BackendClient, store: LocalStore, state: RuntimeState, stop: threading.Event) -> int:
if cfg.camera_id:
_resolve_via_onvif(cfg, state)
state.source = cfg.source
state.camera_id = cfg.camera_id
if state.camera_model and cfg.camera_id:
try:
client.update_device_info(cfg.camera_id, {
"manufacturer": state.camera_manufacturer,
"model": state.camera_model,
"serial": state.camera_serial,
"firmware": state.camera_firmware,
"onvifHost": cfg.onvif_host,
"onvifPort": cfg.onvif_port,
"rtspUrl": cfg.source,
})
state.log("Device info pushed to backend")
except Exception as exc: # noqa: BLE001
state.log(f"WARNING: could not push device info: {exc}")
pipeline = CapturePipeline(cfg, state)
state.pipeline = pipeline
def on_clip(path: str, duration: float, trigger: str) -> None:
store.enqueue(path, cfg.camera_id, duration, trigger)
state.queue_depth = store.pending_count()
try:
pipeline.run(on_clip)
except KeyboardInterrupt:
state.log("Shutting down (Ctrl-C)")
finally:
stop.set()
pipeline.stop()
else:
from .orchestrator import StoreOrchestrator
orch = StoreOrchestrator(cfg, state, client, store)
try:
orch.run()
except KeyboardInterrupt:
state.log("Shutting down (Ctrl-C)")
finally:
stop.set()
orch.stop()
return 0
def _run_wizard_only(cfg, state: RuntimeState, store: LocalStore) -> int:
from .wizard import open_wizard_browser, start_wizard
state.log(f"Setup wizard on http://127.0.0.1:{cfg.admin_port}/")
start_wizard(state, cfg, store, cfg.admin_port)
open_wizard_browser(cfg.admin_port)
try:
while True:
time.sleep(1)
w = load_wizard_config()
if w and w.setup_complete:
state.log("Wizard complete  you can close this window; the service will monitor.")
# Let the browser receive the final response before the installer continues.
time.sleep(2)
break
except KeyboardInterrupt:
state.log("Wizard closed")
return 0
def _preflight_rtsp(rtsp_url: str, source_name: str, state: RuntimeState) -> None:
"""Validate that an RTSP URL is reachable before registering the camera."""
state.log(f"Preflight: validating RTSP for {source_name} …")
ok, msg = validate_rtsp_stream(rtsp_url)
if not ok:
raise ValueError(f"{source_name}: {msg}")
state.log(f"Preflight: {source_name} — {msg}")
def _persist_provision_failure(
wizard,
claim_succeeded: bool,
error: Exception,
state: RuntimeState,
) -> None:
"""Clear a consumed setup code so the shop tech can retry via /setup."""
message = str(error) or "Installer activation failed"
wizard.activation_error = message
err_lower = message.lower()
if claim_succeeded or any(token in err_lower for token in ("invalid", "expired", "used")):
wizard.setup_code = ""
save_wizard_config(wizard)
state.degraded_reason = (
f"{message}. Generate a new setup code in the ONEVO dashboard, "
"then open http://localhost:8099/setup to retry."
)
def _provision_native_installer(cfg, wizard, client: BackendClient, store: LocalStore, state: RuntimeState) -> bool:
"""Claim native-installer setup and create its configured camera sources once."""
if not wizard or wizard.setup_complete:
return False
claim_succeeded = False
try:
from .provisioning import claim_setup, complete_setup, provision_sources
if wizard.setup_code:
cid, _ = claim_setup(client, store, wizard, cfg.version)
claim_succeeded = True
else:
cid = store.get_cred("connector_id")
api_key = store.get_cred("api_key")
if not (cid and api_key):
raise RuntimeError("pending setup has no connector credentials")
client.set_credentials(cid, api_key)
def checkpoint(sources):
wizard.sources = sources
wizard.setup_complete = False
save_wizard_config(wizard)
if wizard.sources:
created = provision_sources(
client, wizard.sources, state, checkpoint=checkpoint
)
client.finalize_setup([source.source_key for source in created])
else:
# Installer may skip camera setup; pair connector and add sources later.
created = []
complete_setup(wizard, created)
state.connector_id = store.get_cred("connector_id")
state.log(f"Native installer provisioned {len(created)} camera source(s)")
return True
except Exception as exc: # noqa: BLE001
state.log(f"ERROR: native installer activation failed: {exc}")
_persist_provision_failure(wizard, claim_succeeded, exc, state)
if claim_succeeded:
cid = store.get_cred("connector_id")
key = store.get_cred("api_key")
if cid and key:
client.set_credentials(cid, key)
state.connector_id = cid
return False
# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------
def main() -> int:
cfg = load_config()
clip_tuning = load_clip_settings(
ClipSettings(
pre_seconds=cfg.pre_seconds,
post_seconds=cfg.post_seconds,
cooldown_seconds=cfg.cooldown_seconds,
)
)
clip_tuning.apply_to_config(cfg)
state = RuntimeState()
state.source = cfg.source
state.camera_id = cfg.camera_id
store = LocalStore(cfg.state_dir)
if cfg.wizard_mode:
return _run_wizard_only(cfg, state, store)
instance_lock = InstanceLock(cfg.state_dir)
if not instance_lock.acquire():
state.log("ERROR: connector state is locked or unavailable")
return 3
client = BackendClient(cfg.backend_url)
# Native installer writes a pending setup config before starting the service.
# It must take precedence over credentials left by an older installation.
wizard = load_wizard_config()
if wizard and apply_pending_source_update(wizard):
wizard = load_wizard_config()
state.log("Installer source update applied; activation is pending")
stop = threading.Event()
wizard_ready = threading.Event()
pending_setup = bool(wizard and not wizard.setup_complete)
def _on_wizard_configured(_wizard_cfg) -> None:
wizard_ready.set()
# Keep localhost:8099 reachable while backend activation is pending.
start_admin(
state,
cfg,
cfg.admin_port,
store=store,
enable_setup_wizard=pending_setup,
on_wizard_configured=_on_wizard_configured if pending_setup else None,
)
state.log(f"Admin UI on http://localhost:{cfg.admin_port}")
if cfg.service_mode and wizard and not wizard.setup_complete:
while not _provision_native_installer(cfg, wizard, client, store, state):
state.degraded_reason = (
"Setup pending: check the backend connection or setup code."
)
state.log("Installer activation pending; retrying in 15 seconds")
time.sleep(15)
wizard = load_wizard_config()
if wizard is None:
break
cfg = load_config()
state.source = cfg.source
state.camera_id = cfg.camera_id
client = BackendClient(cfg.backend_url)
state.degraded_reason = None
activation_failed = False
if cfg.service_mode and wizard and not wizard.setup_complete and wizard.setup_code:
if not _provision_native_installer(cfg, wizard, client, store, state):
activation_failed = True
state.log(
"ERROR: installer activation failed; admin UI stays up for troubleshooting "
"and setup retry at /setup"
)
wizard = load_wizard_config()
else:
cfg = load_config()
state.source = cfg.source
state.camera_id = cfg.camera_id
client = BackendClient(cfg.backend_url)
# Service / normal: register if needed (wizard may already have claimed).
if not activation_failed and not (store.get_cred("connector_id") and store.get_cred("api_key")):
if not _ensure_registered(cfg, client, store, state):
# Not registered yet  if installed, open wizard instead of failing hard.
if cfg.service_mode or (wizard is None or not wizard.setup_complete):
state.degraded_reason = "Connector pairing is incomplete."
state.log("Not configured yet; local admin remains available")
while True:
time.sleep(15)
return 2
elif not activation_failed:
client.set_credentials(store.get_cred("connector_id"), store.get_cred("api_key"))
state.connector_id = client.connector_id
state.log(f"Loaded existing connector credentials ({client.connector_id})")
if activation_failed:
try:
while not wizard_ready.is_set():
time.sleep(1)
current = load_wizard_config()
if current and current.setup_complete:
wizard_ready.set()
break
except KeyboardInterrupt:
stop.set()
return 0
cfg = load_config()
state.source = cfg.source
state.camera_id = cfg.camera_id
state.degraded_reason = None
client = BackendClient(cfg.backend_url)
client.set_credentials(store.get_cred("connector_id"), store.get_cred("api_key"))
state.connector_id = client.connector_id
state.log("Setup completed via /setup — starting monitoring")
up = threading.Thread(target=run_uploader, args=(cfg, client, store, state, stop), daemon=True)
hb = threading.Thread(target=run_heartbeat, args=(cfg, client, store, state, stop), daemon=True)
up.start()
hb.start()
return _run_capture(cfg, client, store, state, stop)
if __name__ == "__main__":
sys.exit(main())