-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbosch_camera.py
More file actions
executable file
·6440 lines (5755 loc) · 273 KB
/
bosch_camera.py
File metadata and controls
executable file
·6440 lines (5755 loc) · 273 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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Bosch Smart Home Camera — All-in-one Standalone Tool
Version: 7.0.0
=====================================================
No hardcoded camera IDs or credentials.
All configuration is stored in bosch_config.json (created on first run).
First run:
1. Creates bosch_config.json with empty credentials
2. Prompts for Bearer token (via mitmproxy — see README)
3. Auto-discovers all cameras from the API
4. Saves cameras + token to config file
Subsequent runs:
• Reads cameras from config (no repeated discovery needed)
• If token is expired → prompts for a fresh one → saves to config
Snapshot methods (newest → fastest, tried in order):
1. Cloud proxy live snap — proxy-NN.live.cbs.boschsecurity.com snap.jpg
(only if a live connection has been opened)
2. Local camera snap — https://<local_ip>/snap.jpg (Digest auth)
(only if local_ip + credentials are set in config)
3. Latest event snapshot — most recent motion-triggered JPEG from cloud events API
(always available, but only updates on motion)
Usage (interactive menu):
python3 bosch_camera.py
Usage (CLI):
python3 bosch_camera.py status
python3 bosch_camera.py snapshot [<cam-name>] [--live] # --live: prefer live methods
python3 bosch_camera.py liveshot [<cam-name>] # alias: forces live methods
python3 bosch_camera.py live [<cam-name>] # open RTSP stream in VLC
python3 bosch_camera.py download [<cam-name>] [--limit N] [--snaps-only] [--clips-only]
python3 bosch_camera.py events [<cam-name>] [--limit N] [--clip EVENT_ID]
python3 bosch_camera.py privacy-sound [<cam-name>] [on|off]
python3 bosch_camera.py rules [<cam-name>] [add|edit|delete]
python3 bosch_camera.py friends [invite|share|unshare|resend|remove]
python3 bosch_camera.py rename <cam-name> "New Name"
python3 bosch_camera.py profile [edit --display-name NAME --marketing on|off]
python3 bosch_camera.py account # feature flags, contracts, purchases
python3 bosch_camera.py config # show current config
python3 bosch_camera.py rescan # re-discover cameras
"""
import os
import sys
import json
import time
import shutil
import signal
import datetime
import argparse
import threading
import subprocess
import urllib3
import requests
from requests.adapters import HTTPAdapter
from typing import Optional
# Suppress InsecureRequestWarning only for local camera calls (self-signed certs).
# Cloud API and Keycloak calls use verify=True and do not trigger this warning.
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
# ─────────────────────────────────────────────────────────────────────────────
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
CONFIG_FILE = os.path.join(BASE_DIR, "bosch_config.json")
CLOUD_API = "https://residential.cbs.boschsecurity.com"
VERSION = "10.2.1"
DELAY = 0.5 # seconds between download requests (rate-limit protection)
# Human-readable display names for camera hardware versions
HW_DISPLAY_NAMES = {
"INDOOR": "360 Innenkamera",
"OUTDOOR": "Eyes Außenkamera",
"CAMERA_360": "360 Innenkamera",
"CAMERA_EYES": "Eyes Außenkamera",
"HOME_Eyes_Outdoor": "Eyes Außenkamera II",
"HOME_Eyes_Indoor": "Eyes Innenkamera II",
"CAMERA_OUTDOOR_GEN2": "Eyes Außenkamera II",
"CAMERA_INDOOR_GEN2": "Eyes Innenkamera II",
}
# ConnectionType enum — confirmed working values (discovered 2026-03-19)
# REMOTE = cloud proxy snap.jpg (fast ~1.5s, no credentials needed)
# LOCAL = direct LAN snap.jpg (slow ~15s Digest auth, same quality)
# Use REMOTE first for all operations — it is faster than LOCAL despite going via cloud.
LIVE_TYPE_CANDIDATES = [
"REMOTE", # ✅ cloud proxy — faster (1.5s vs 15s for LOCAL)
"LOCAL", # ✅ LAN direct — fallback if cloud unavailable
]
DEFAULT_CONFIG = {
"account": {
"username": "",
"password": "",
"bearer_token": "",
"refresh_token": "",
"_note": (
"Set username (your Bosch SingleKey ID email). "
"Run 'python3 get_token.py' to get tokens automatically via browser login. "
"After first login the refresh_token enables silent renewal forever."
),
},
"cameras": {
# Auto-populated on first run. Example entry:
# "MyCam": {
# "id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
# "name": "MyCam",
# "model": "CAMERA_EYES",
# "firmware": "...",
# "mac": "xx:xx:xx:xx:xx:xx",
# "download_folder": "MyCam",
# "local_ip": "", ← optional: set for local snap.jpg access
# "local_username": "", ← local camera Digest auth username
# "local_password": "", ← local camera Digest auth password
# "last_live": { "rtsp_url": "", "proxy_url": "", "cookie": "" }
# }
},
"settings": {
"download_base_path": "",
"scan_interval_seconds": 30,
"request_delay_seconds": 0.5,
"_note": (
"download_base_path: folder for downloaded events. "
"Empty = use this script's directory. "
"local_ip / local_username / local_password per camera: "
"enables direct local snap.jpg (HTTP Digest auth). "
"local_ip and credentials are optional — cloud API works without them."
),
},
}
# ─────────────────────────────────────────────────────────────────────────────
# ══════════════════════════ CONFIG MANAGEMENT ═════════════════════════════════
def load_config() -> dict:
"""Load config from file. Creates default config if it doesn't exist."""
if not os.path.exists(CONFIG_FILE):
_create_default_config()
with open(CONFIG_FILE, "r") as f:
cfg = json.load(f)
# Merge in any missing keys from DEFAULT_CONFIG (forward-compat)
_merge_defaults(cfg, DEFAULT_CONFIG)
return cfg
def save_config(cfg: dict) -> None:
"""Save config to file.
Serialized via _CONFIG_LOCK so concurrent writes (main thread saving a fresh
bearer token + FCM credentials-update callback firing from a background
thread) cannot interleave. Written via tmpfile + os.replace so readers
never see a half-written JSON — process crash mid-write leaves the
previous file intact instead of a truncated one.
"""
with _CONFIG_LOCK:
tmp_path = f"{CONFIG_FILE}.tmp.{os.getpid()}"
try:
with open(tmp_path, "w") as f:
json.dump(cfg, f, indent=2)
f.flush()
os.fsync(f.fileno())
os.chmod(tmp_path, 0o600)
os.replace(tmp_path, CONFIG_FILE)
except Exception:
try:
os.remove(tmp_path)
except OSError:
pass
raise
def _create_default_config() -> None:
"""Create a new config file with defaults and print instructions."""
save_config(DEFAULT_CONFIG)
print(f"\n✅ Created config file: {CONFIG_FILE}")
print(" Edit it to add your credentials, or continue — the script will prompt you.\n")
def _merge_defaults(cfg: dict, defaults: dict) -> None:
"""Recursively add missing keys from defaults into cfg (in-place)."""
for key, val in defaults.items():
if key not in cfg:
cfg[key] = val
elif isinstance(val, dict) and isinstance(cfg[key], dict):
_merge_defaults(cfg[key], val)
# ══════════════════════════ TOKEN MANAGEMENT ══════════════════════════════════
def _is_token_expired(token: str) -> bool:
"""Return True if the JWT bearer token is expired or expiring within 60s."""
import base64 as _b64, json as _json
try:
parts = token.split(".")
if len(parts) >= 2:
pad = len(parts[1]) % 4
body = _b64.urlsafe_b64decode(parts[1] + "=" * pad)
exp = _json.loads(body).get("exp", 0)
return exp > 0 and (exp - time.time()) < 60
except Exception:
pass
return False
def _is_token_near_expiry(token_str: str, buffer_secs: int = 60) -> bool:
"""Return True if the JWT bearer token expires within buffer_secs seconds.
Fail-safe: returns True (treat as near-expiry) if decoding fails.
Uses only stdlib: base64, json, time.
"""
import base64 as _b64, json as _json
try:
parts = token_str.split(".")
if len(parts) >= 2:
pad = len(parts[1]) % 4
body = _b64.urlsafe_b64decode(parts[1] + "=" * pad)
exp = _json.loads(body).get("exp", 0)
return exp == 0 or (exp - time.time()) < buffer_secs
except Exception:
pass
return True
def get_token(cfg: dict) -> str:
"""
Return a valid Bearer token. Tries in order:
1. Saved bearer_token in config (if not expired)
2. Silent renewal via refresh_token (auto, no user interaction)
3. Browser login via get_token.py (auto-opens browser)
4. Manual paste as last resort
"""
token = cfg["account"].get("bearer_token", "").strip()
if token and not _is_token_expired(token):
return token
# Token expired or missing — try silent renewal first
refresh = cfg["account"].get("refresh_token", "").strip()
if refresh:
try:
from get_token import _do_refresh
if token: # only print if we had a token (i.e. it expired)
print(" 🔄 Token expired — renewing automatically via refresh_token...")
tokens = _do_refresh(refresh)
if tokens:
new_token = tokens.get("access_token", "")
new_refresh = tokens.get("refresh_token", refresh)
cfg["account"]["bearer_token"] = new_token
cfg["account"]["refresh_token"] = new_refresh
save_config(cfg)
print(" ✅ Token renewed silently.")
return new_token
except ImportError:
pass
except Exception as e:
print(f" ⚠️ Silent renewal failed: {e}")
if token:
return token # Expired but renewal failed — return as-is and let the API reject it
# Try get_token.py auto-flow (refresh + browser login)
try:
from get_token import get_token_auto
print(" 🔑 No token in config — trying automatic token retrieval...")
new_token = get_token_auto(cfg)
if new_token:
return new_token
except ImportError:
# get_token.py not in path — fall through to manual
pass
except Exception as e:
print(f" ⚠️ Auto-token failed: {e}")
# Manual fallback
print("\n ⚠️ Could not obtain token automatically.")
print(" Options:")
print(" • Run: python3 get_token.py (browser login, saves token automatically)")
print(" • Or paste a Bearer token captured from the Bosch Smart Home Camera app")
print(" (See README.md for mitmproxy instructions)\n")
token = input(" Paste Bearer token (or press Enter to exit): ").strip()
if not token:
print(" ❌ No token. Exiting.")
sys.exit(1)
cfg["account"]["bearer_token"] = token
save_config(cfg)
print(f" 💾 Token saved.")
return token
def check_token_age(cfg: dict) -> str:
"""Return human-readable token expiry decoded from JWT claims."""
import base64 as _b64, json as _json
token = cfg["account"].get("bearer_token", "").strip()
if not token:
return "no token"
try:
parts = token.split(".")
if len(parts) >= 2:
pad = len(parts[1]) % 4
body = _b64.urlsafe_b64decode(parts[1] + "=" * pad)
info = _json.loads(body)
exp = info.get("exp", 0)
if exp:
exp_dt = datetime.datetime.fromtimestamp(exp)
diff = exp_dt - datetime.datetime.now()
mins = int(diff.total_seconds() / 60)
if mins > 5:
return f"valid, expires in ~{mins}m ✅"
elif mins > 0:
return f"expires in ~{mins}m ⚠️"
else:
return f"EXPIRED {abs(mins)}m ago ❌ — run: python3 bosch_camera.py token fix"
except Exception:
pass
# Fallback to file mtime
mtime = os.path.getmtime(CONFIG_FILE)
age = datetime.datetime.now() - datetime.datetime.fromtimestamp(mtime)
mins = int(age.total_seconds() / 60)
if mins < 60:
return f"~{mins} min old ✅"
elif mins < 120:
return f"~{mins} min old ⚠️ (may be expired)"
else:
return f"~{mins} min old ❌ — run: python3 bosch_camera.py token fix"
def handle_401(cfg: dict) -> str:
"""Called when API returns 401. Clears token, prompts for a new one."""
print("\n ❌ Bearer token expired (HTTP 401).")
cfg["account"]["bearer_token"] = ""
return get_token(cfg)
# ══════════════════════════ SESSION ═══════════════════════════════════════════
# Cached global session — reuses a single TCP/TLS connection pool across all API
# calls (avoids handshake-per-request). Token updates only touch the Authorization
# header, so the underlying pool stays warm.
_HTTP_SESSION: Optional[requests.Session] = None
def make_session(token: str) -> requests.Session:
"""Return the cached module-level session, updating the Bearer token header.
On first call, creates a requests.Session with a connection-pooled HTTPAdapter
(pool_connections=10, pool_maxsize=20, max_retries=0 — retries are handled
explicitly by _request_with_retry). Subsequent calls just swap the token on
the existing session so connections are reused.
"""
global _HTTP_SESSION
if _HTTP_SESSION is None:
s = requests.Session()
adapter = HTTPAdapter(pool_connections=10, pool_maxsize=20, max_retries=0)
s.mount("https://", adapter)
s.mount("http://", adapter)
s.verify = False
_HTTP_SESSION = s
_HTTP_SESSION.headers.update({
"Authorization": f"Bearer {token}",
"Accept": "application/json",
})
return _HTTP_SESSION
# Lock serializing bosch_config.json writes (FCM creds-update callback may fire
# from a background thread while the main thread is also saving tokens).
_CONFIG_LOCK = threading.Lock()
# Set by SIGTERM/SIGINT handlers so long-running loops (watch, FCM) can exit
# cleanly instead of relying solely on KeyboardInterrupt propagation.
_STOP_REQUESTED = threading.Event()
def _install_stop_handlers() -> None:
"""Install SIGINT/SIGTERM handlers that flip _STOP_REQUESTED.
Safe to call multiple times — later calls just re-install the same handler.
Only installs in the main thread (signal.signal() raises otherwise).
"""
if threading.current_thread() is not threading.main_thread():
return
def _handler(signum, frame):
_STOP_REQUESTED.set()
try:
signal.signal(signal.SIGINT, _handler)
signal.signal(signal.SIGTERM, _handler)
except (ValueError, OSError):
# signal.signal() can fail in odd embedding contexts — ignore.
pass
def _request_with_retry(session: requests.Session, method: str, url: str,
max_attempts: int = 3, **kwargs) -> requests.Response:
"""Issue an HTTP request with exponential backoff on transient failures.
Retries only on HTTP 5xx responses and on requests.exceptions.Timeout /
ConnectionError. Auth/client errors (401/403/404, etc.) pass through on the
first attempt — the caller decides how to react.
Backoff: 1s, 2s, 4s between attempts (max_attempts=3 → up to 2 retries).
"""
last_exc: Optional[BaseException] = None
for attempt in range(max_attempts):
try:
r = session.request(method, url, **kwargs)
except (requests.exceptions.Timeout, requests.exceptions.ConnectionError) as e:
last_exc = e
if attempt == max_attempts - 1:
raise
time.sleep(2 ** attempt)
continue
# Retry only on server-side errors.
if 500 <= r.status_code < 600 and attempt < max_attempts - 1:
time.sleep(2 ** attempt)
continue
return r
# Unreachable — loop either returns a response or re-raises. Keep for safety.
if last_exc is not None:
raise last_exc
raise RuntimeError("unreachable: _request_with_retry loop exited without result")
# ══════════════════════════ CAMERA DISCOVERY ══════════════════════════════════
def discover_cameras(cfg: dict, session: requests.Session) -> dict:
"""
GET /v11/video_inputs → discover all cameras.
Returns dict keyed by camera name (title):
{
"MyCam": { "id": "...", "name": "MyCam", "model": "...",
"firmware": "...", "mac": "...", "download_folder": "MyCam" },
...
}
Saves discovered cameras to config.
"""
r = session.get(f"{CLOUD_API}/v11/video_inputs", timeout=15)
if r.status_code == 401:
return {}
r.raise_for_status()
cam_list = r.json()
cameras = {}
for cam in cam_list:
name = cam.get("title", cam.get("id", "unknown"))
# Keep existing local config if camera already known
existing = cfg.get("cameras", {}).get(name, {})
feat = cam.get("featureSupport", {})
cameras[name] = {
"id": cam.get("id", ""),
"name": name,
"model": cam.get("hardwareVersion", "CAMERA"),
"firmware": cam.get("firmwareVersion", ""),
"mac": cam.get("macAddress", ""),
"download_folder": name,
"local_ip": existing.get("local_ip", ""),
"local_username": existing.get("local_username", ""),
"local_password": existing.get("local_password", ""),
"has_light": feat.get("light", False),
"pan_limit": feat.get("panLimit", 0),
}
# Ask for local IP if not already set
if not cameras[name]["local_ip"]:
print(f"\n 📷 Camera: {name}")
ip = input(f" Local IP address (e.g. 192.168.1.100) — press Enter to skip: ").strip()
if ip:
cameras[name]["local_ip"] = ip
cfg["cameras"] = cameras
save_config(cfg)
print(f" 💾 Discovered {len(cameras)} camera(s) → saved to {CONFIG_FILE}")
return cameras
def get_cameras(cfg: dict, session: requests.Session) -> dict:
"""Return cameras from config; auto-discover if none are saved yet."""
if not cfg.get("cameras"):
print(" 🔍 No cameras in config — auto-discovering...")
return discover_cameras(cfg, session)
return cfg["cameras"]
def resolve_cam(cfg: dict, key: str | None) -> dict:
"""
Resolve a partial camera name to the full cameras dict entry.
If key is None → return all cameras.
If key matches exactly or case-insensitively → return that single camera dict.
"""
cameras = cfg.get("cameras", {})
if not key:
return cameras
# Exact match
if key in cameras:
return {key: cameras[key]}
# Case-insensitive partial match
key_lower = key.lower()
matches = {k: v for k, v in cameras.items() if key_lower in k.lower()}
if len(matches) == 1:
return matches
if len(matches) > 1:
names = ", ".join(matches.keys())
print(f" ⚠️ Ambiguous camera name '{key}' — matches: {names}")
sys.exit(1)
print(f" ❌ Camera '{key}' not found in config. Known: {', '.join(cameras.keys())}")
print(f" Run 'python3 bosch_camera.py rescan' to re-discover cameras.")
sys.exit(1)
# ══════════════════════════ API HELPERS ═══════════════════════════════════════
def api_ping(session: requests.Session, cam_id: str) -> str:
try:
r = session.get(f"{CLOUD_API}/v11/video_inputs/{cam_id}/ping", timeout=10)
if r.status_code == 200:
return r.text.strip().strip('"')
return f"HTTP {r.status_code}"
except Exception as e:
return f"ERROR: {e}"
def api_get_events(session: requests.Session, cam_id: str, limit: int = 400) -> list:
r = _request_with_retry(
session, "GET",
f"{CLOUD_API}/v11/events?videoInputId={cam_id}&limit={limit}",
timeout=30,
)
if r.status_code == 401:
return []
r.raise_for_status()
return r.json()
def api_mark_events_read(session: requests.Session, event_ids: list[str]) -> bool:
"""Mark events as read on the Bosch cloud via PUT /v11/events.
The /v11/events/bulk endpoint only supports `{ids, action: "DELETE"}` —
there is no bulk mark-as-read. Returns True if at least one PUT succeeded.
"""
if not event_ids:
return True
success = False
for eid in event_ids:
try:
r = session.put(
f"{CLOUD_API}/v11/events",
json={"id": eid, "isRead": True},
timeout=5,
)
if r.status_code in (200, 204):
success = True
except Exception:
pass
return success
def api_get_camera(session: requests.Session, cam_id: str) -> dict | None:
"""
GET /v11/video_inputs/{cam_id} — fetch a single camera object by ID.
Returns the camera dict or None on error.
"""
try:
r = session.get(f"{CLOUD_API}/v11/video_inputs/{cam_id}", timeout=15)
if r.status_code == 200:
return r.json()
except Exception:
pass
return None
# ══════════════════════════ OPEN FILE / VLC ═══════════════════════════════════
def open_file(path: str) -> None:
if sys.platform == "darwin":
subprocess.Popen(["open", path])
elif sys.platform.startswith("linux"):
subprocess.Popen(["xdg-open", path])
else:
os.startfile(path)
def open_vlc(url: str, user: str = "", password: str = "", token: str = "") -> None:
# Prefer ffplay/mpv for RTSP — they support custom headers for Bearer auth.
# VLC does not support Authorization headers for RTSP.
if url.startswith("rtsp://"):
players = [
shutil.which("ffplay"),
shutil.which("mpv"),
shutil.which("vlc"),
"/Applications/VLC.app/Contents/MacOS/VLC",
]
else:
players = [
shutil.which("vlc"),
"/Applications/VLC.app/Contents/MacOS/VLC",
shutil.which("mpv"),
shutil.which("ffplay"),
]
player = next((p for p in players if p and os.path.exists(p)), None)
if not player:
print(f"\n ❌ No media player found (VLC / mpv / ffplay).")
print(f" Install: brew install ffmpeg # or brew install --cask vlc")
print(f" Stream URL: {url}")
return
print(f"\n ▶️ Opening in {os.path.basename(player)}: {url}")
name = os.path.basename(player).lower()
if "ffplay" in name:
cmd = [player, "-rtsp_transport", "tcp"]
if token:
cmd += ["-headers", f"Authorization: Bearer {token}\r\n"]
cmd += [url]
elif "mpv" in name:
cmd = [player]
if token:
cmd += [f"--http-header-fields=Authorization: Bearer {token}"]
cmd += [url]
else:
# VLC — embed creds in URL if provided, otherwise try as-is
open_url = url
if user and password and url.startswith("rtsp://"):
from urllib.parse import quote
host_part = url[len("rtsp://"):]
open_url = f"rtsp://{quote(user, safe='')}:{quote(password, safe='')}@{host_part}"
cmd = [player, open_url]
if token and "vlc" in name:
cmd += ["--http-cookie", f"HcsoB={token[:20]}"]
if user:
print(f" 🔑 Using credentials: {user}")
subprocess.Popen(cmd)
# ══════════════════════════ COMMANDS ══════════════════════════════════════════
def cmd_status(cfg: dict, args) -> None:
"""Show all cameras with ONLINE/OFFLINE status."""
token = get_token(cfg)
session = make_session(token)
cameras = get_cameras(cfg, session)
print(f"\n── Bosch Smart Home Cameras ────────────────────────────────")
print(f" Token age: {check_token_age(cfg)}\n")
for name, cam_info in cameras.items():
status = api_ping(session, cam_info["id"])
if status == "ONLINE":
icon = "🟢"
elif status.startswith("UPDATING"):
icon = "🔄"
status = "UPDATING (firmware)"
else:
icon = "🔴"
print(f" {icon} {name}")
print(f" ID: {cam_info['id']}")
print(f" Model: {cam_info['model']} FW: {cam_info['firmware']}")
print(f" MAC: {cam_info['mac']}")
print(f" Status: {status}")
print()
def cmd_events(cfg: dict, args) -> None:
"""Show latest events — removed (cloud event listing no longer available)."""
print(" ⚠️ Events command has been removed.")
return
# ══════════════════════════ LIVE SNAPSHOT METHODS ═══════════════════════════
def snap_from_proxy(cam_info: dict, token: str, hq: bool = False,
cfg: Optional[dict] = None) -> bytes | None:
"""
Live snapshot via PUT /connection.
Tries LOCAL first (faster on home network), then REMOTE (cloud proxy).
If snap.jpg returns 404 (proxy session expired), automatically re-requests
a fresh connection and retries once.
hq=True requests highQualityVideo in the connection payload.
If cfg is provided and we receive a 401 on PUT /connection, refresh the
token once and retry. On second 401 we fail hard with a clear message.
Returns JPEG bytes or None.
"""
cam_id = cam_info.get("id", "")
# Mutable list so the inner closure can update the header after a token refresh.
headers_box = [{"Authorization": f"Bearer {token}", "Content-Type": "application/json"}]
def _put_connection(conn_type: str) -> requests.Response:
"""PUT /connection with one-shot token refresh on 401."""
r = requests.put(
f"{CLOUD_API}/v11/video_inputs/{cam_id}/connection",
headers=headers_box[0],
json={"type": conn_type, "highQualityVideo": hq},
timeout=15,
)
if r.status_code == 401 and cfg is not None:
print(" 🔄 Token expired (401) — refreshing once...")
try:
new_token = get_token(cfg)
except Exception as e:
print(f" ❌ Token refresh failed: {e}")
print(" Run `bosch-camera login` (or `python3 get_token.py`).")
return r
headers_box[0] = {"Authorization": f"Bearer {new_token}",
"Content-Type": "application/json"}
# Also update the cached session so subsequent calls use the new token.
make_session(new_token)
r = requests.put(
f"{CLOUD_API}/v11/video_inputs/{cam_id}/connection",
headers=headers_box[0],
json={"type": conn_type, "highQualityVideo": hq},
timeout=15,
)
if r.status_code == 401:
print(" ❌ Still 401 after refresh — token could not be refreshed. "
"Run `bosch-camera login`.")
return r
def _fetch_snap(conn_type: str) -> bytes | None:
label = "local" if conn_type == "LOCAL" else "cloud proxy"
print(f" 🌐 Opening {label} connection...")
r = _put_connection(conn_type)
if r.status_code != 200:
return None
data = r.json()
urls = data.get("urls", [])
scheme = data.get("imageUrlScheme", "https://{url}/snap.jpg")
api_user = data.get("user") or ""
api_pass = data.get("password") or ""
if not urls:
return None
snap_url = scheme.replace("{url}", urls[0])
snap_timeout = 5 if conn_type == "LOCAL" else 15
# snap.jpg may come from local camera (self-signed cert) — verify=False required
if api_user and api_pass:
from requests.auth import HTTPDigestAuth
snap_r = requests.get(snap_url, auth=HTTPDigestAuth(api_user, api_pass),
verify=False, timeout=snap_timeout)
else:
snap_r = requests.get(snap_url, verify=False, timeout=snap_timeout)
if snap_r.status_code == 200 and snap_r.headers.get("Content-Type", "").startswith("image"):
print(f" ✅ Live snapshot ({label}): {len(snap_r.content):,} bytes")
return snap_r.content
elif snap_r.status_code == 404:
print(f" ⚠️ Proxy session expired (404) — re-requesting connection...")
# Retry once with a fresh connection (reuses the refreshed token if
# the first PUT already triggered a token renewal).
r2 = _put_connection(conn_type)
if r2.status_code == 200:
data2 = r2.json()
urls2 = data2.get("urls", [])
scheme2 = data2.get("imageUrlScheme", "https://{url}/snap.jpg")
api_user2 = data2.get("user") or ""
api_pass2 = data2.get("password") or ""
if urls2:
snap_url2 = scheme2.replace("{url}", urls2[0])
if api_user2 and api_pass2:
from requests.auth import HTTPDigestAuth
snap_r2 = requests.get(snap_url2, auth=HTTPDigestAuth(api_user2, api_pass2),
verify=False, timeout=snap_timeout)
else:
snap_r2 = requests.get(snap_url2, verify=False, timeout=snap_timeout)
if snap_r2.status_code == 200 and snap_r2.headers.get("Content-Type", "").startswith("image"):
print(f" ✅ Live snapshot ({label}, retry): {len(snap_r2.content):,} bytes")
return snap_r2.content
print(f" ⚠️ {label} snap retry also failed")
return None
else:
print(f" ⚠️ {label} snap returned HTTP {snap_r.status_code}")
return None
for conn_type in LIVE_TYPE_CANDIDATES:
try:
result = _fetch_snap(conn_type)
if result:
return result
except Exception as e:
label = "local" if conn_type == "LOCAL" else "cloud proxy"
print(f" ⚠️ {label} error: {e}")
return None
def snap_from_local(cam_info: dict) -> bytes | None:
"""
Method 2 — Local camera snap.jpg via HTTP Digest authentication.
Direct access to the camera at https://<local_ip>/snap.jpg
Returns 1920×1080 JPEG bytes or None.
Credentials are randomly generated by the SHC at pairing time.
Capture via mitmproxy and store in config under local_ip / local_username / local_password.
WARNING: Excessive requests to the local camera IP can break the connection,
causing the SHC to regenerate random credentials. Use sparingly.
"""
local_ip = cam_info.get("local_ip", "")
username = cam_info.get("local_username", "")
password = cam_info.get("local_password", "")
if not local_ip or not username or not password:
return None
# Append ?JpegSize=1206 — without it the camera triggers a slow on-demand
# full-sensor capture (~6–10 s when idle). With it, the cached path serves
# in ~1.4 s. Verified empirically; matches HA integration v10.4.5 fix.
url = f"https://{local_ip}/snap.jpg?JpegSize=1206"
print(f" 🏠 Trying local camera snapshot: {url}")
try:
from requests.auth import HTTPDigestAuth
r = requests.get(
url,
auth=HTTPDigestAuth(username, password),
timeout=10,
verify=False,
)
if r.status_code == 200 and r.headers.get("Content-Type", "").startswith("image"):
print(f" ✅ Local snapshot: {len(r.content):,} bytes (1920×1080)")
return r.content
else:
print(f" ⚠️ Local camera returned {r.status_code}")
except Exception as e:
print(f" ⚠️ Local camera error: {e}")
return None
def snap_from_events(session, cam_info: dict) -> tuple[bytes | None, str]:
"""
Method 3 — Latest event snapshot (cloud API, motion-triggered).
Returns (jpeg_bytes, timestamp_str) or (None, "").
Only updates when the camera detects motion — not a live view.
"""
events = api_get_events(session, cam_info["id"], limit=10)
for ev in events:
img_url = ev.get("imageUrl")
if not img_url:
continue
try:
r = session.get(img_url, timeout=20)
if r.status_code == 200:
ts = ev.get("timestamp", "")[:19]
return r.content, ts
except Exception:
pass
return None, ""
def _save_and_open(data: bytes, name: str, ts: str, method: str) -> str:
"""Save image bytes to file and open in Preview. Returns file path."""
safe_name = name.replace(" ", "_")
ts_safe = ts.replace(":", "-").replace("T", "_") if ts else \
datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
fn = f"snapshot_{safe_name}_{ts_safe}_{method}.jpg"
path = os.path.join(BASE_DIR, fn)
with open(path, "wb") as f:
f.write(data)
print(f" 💾 {path} ({len(data):,} bytes)")
open_file(path)
return path
# ─────────────────────────────────────────────────────────────────────────────
def cmd_snapshot(cfg: dict, args) -> None:
"""
Fetch and open the best available snapshot for a camera.
Without --live: shows latest event snapshot (cloud events API).
With --live: tries methods in order:
1. Cloud proxy live snap (if live connection previously opened)
2. Local camera snap.jpg (if local_ip + credentials in config)
3. Latest event snapshot (fallback)
--hq: request highQualityVideo=true in PUT /connection (higher resolution).
"""
token = get_token(cfg)
session = make_session(token)
session.headers["Accept"] = "*/*"
cameras = get_cameras(cfg, session)
cams = resolve_cam(cfg, getattr(args, "cam", None))
live = getattr(args, "live", False)
quality = getattr(args, "quality", None)
if quality == "high":
hq = True
elif quality is not None:
hq = False
else:
hq = getattr(args, "hq", False)
for name, cam_info in cams.items():
mode_str = "Live Snapshot" if live else "Latest Event Snapshot"
print(f"\n── {mode_str}: {name} ──────────────────────────────────────")
if live:
# ── Method 1: Cloud proxy live snap ───────────────────────────────
data = snap_from_proxy(cam_info, token, hq=hq, cfg=cfg)
if data:
_save_and_open(data, name, "", "proxy_live")
continue
# ── Method 2: Local camera snap.jpg ───────────────────────────────
data = snap_from_local(cam_info)
if data:
_save_and_open(data, name, "", "local_live")
continue
print(" ℹ️ Live methods unavailable:")
if not cam_info.get("last_live", {}).get("proxy_url"):
print(" • Cloud proxy: no live connection opened yet")
print(" → Press 'Open Live Stream' button in HA, or run: live " + name)
if not cam_info.get("local_ip"):
print(" • Local: no local_ip set in config")
print(f" → Edit {CONFIG_FILE} and set local_ip, local_username, local_password")
print(" ↩️ Falling back to latest event snapshot...\n")
# ── Method 3 (or default): Latest event snapshot ──────────────────────
data, ts = snap_from_events(session, cam_info)
if data:
_save_and_open(data, name, ts, "event")
if not live:
print(f" ℹ️ This is a motion-triggered snapshot from {ts[:10]},")
print(f" not a live view. Use '--live' for live snapshot methods.")
else:
print(" ⚠️ No snapshot available (token expired or no events).")
def _live_snap_loop(snap_url: str, cam_name: str, interval: float = 1.0) -> None:
"""
Live view: serves snap.jpg frames as a local MJPEG stream, then opens ffplay on it.
ffplay connects to http://localhost:PORT and receives a continuous MJPEG feed.
Press Q in the ffplay window or Ctrl+C in the terminal to stop.
"""
import threading
import http.server
import socket
ffplay = shutil.which("ffplay") or "/opt/homebrew/bin/ffplay"
if not os.path.exists(ffplay):
ffplay = None
if not ffplay:
print(f"\n ❌ ffplay not found. Install with: brew install ffmpeg\n")
return
# Find a free port
with socket.socket() as s:
s.bind(("127.0.0.1", 0))
port = s.getsockname()[1]
stop_event = threading.Event()
frame_lock = threading.Lock()
current_frame: list = [None] # [bytes | None]
# ── Fetcher thread: polls snap.jpg ────────────────────────────────────────
def fetcher():
count = 0
while not stop_event.is_set():
t0 = time.time()
try:
r = requests.get(snap_url, verify=False, timeout=10)
if r.status_code == 200 and r.headers.get("Content-Type", "").startswith("image"):
with frame_lock:
current_frame[0] = r.content
count += 1
print(f"\r 🖼️ Frame {count} {len(r.content):,} bytes", end="", flush=True)
elif r.status_code == 404:
print(f"\n ⏰ Proxy session expired after {count} frames.")
stop_event.set()
break
except Exception:
pass
elapsed = time.time() - t0
remaining = interval - elapsed
if remaining > 0:
stop_event.wait(remaining)
# ── MJPEG HTTP server ─────────────────────────────────────────────────────
class MJPEGHandler(http.server.BaseHTTPRequestHandler):
def log_message(self, *args): pass # silence request logs
def do_GET(self):
self.send_response(200)
self.send_header("Content-Type", "multipart/x-mixed-replace; boundary=--frame")
self.end_headers()
try:
while not stop_event.is_set():
with frame_lock:
frame = current_frame[0]
if frame:
header = (
f"--frame\r\n"
f"Content-Type: image/jpeg\r\n"
f"Content-Length: {len(frame)}\r\n\r\n"
).encode()
self.wfile.write(header)
self.wfile.write(frame)
self.wfile.write(b"\r\n")
self.wfile.flush()
time.sleep(interval)
except (BrokenPipeError, ConnectionResetError):