-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontrol.py
More file actions
1596 lines (1393 loc) · 53.5 KB
/
Copy pathcontrol.py
File metadata and controls
1596 lines (1393 loc) · 53.5 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
"""Unified capture controller for light, turntable, and Sony camera.
Run from the repository root, usually through the Sony camera launcher::
sonycam control.py
Useful dry run for checking the capture plan and filenames::
python control.py --dry-run
Default plan:
lighting position: front
lighting intensities: 0, 10, 50, 300, 500, 700, 1000
views: 0, 90, 180, 270 degrees
apertures: F3.2
ISO: 800
shutter speeds: 1/80
"""
from __future__ import annotations
import argparse
import asyncio
import base64
import glob
import json
import os
import time
from datetime import datetime
from pathlib import Path
from typing import Optional
DEFAULT_OUTPUT_DIR = Path("dataset")
DEFAULT_TURNTABLE_PORT = "/dev/cu.usbmodem1101"
DEFAULT_CCT = 5600
DEFAULT_LIGHT_POSITION = "normal" # optional: normal, reflect, face, side
DEFAULT_LIGHT_INTENSITIES = [0, 10, 50, 300, 500, 700, 1000]
DEFAULT_APERTURES = [2.8, 4, 8, 11, 16, 22]
DEFAULT_ISOS = [100, 250, 800, 2000, 3200, 6400, 12800, 32000]
DEFAULT_SHUTTERS = ['0.5"', "1/3", "1/15", "1/60", "1/250", "1/1000"]
DEFAULT_SAVE_MEDIA = "host"
DEFAULT_START_DELAY_SECONDS = 10.0
PAD_WIDTH = 3
AUTO_PARAM_ID = 0
def parse_int_list(value: str) -> list[int]:
items = [item.strip() for item in value.split(",") if item.strip()]
if not items:
raise argparse.ArgumentTypeError("list cannot be empty")
return [int(item) for item in items]
def parse_float_list(value: str) -> list[float]:
items = [item.strip() for item in value.split(",") if item.strip()]
if not items:
raise argparse.ArgumentTypeError("list cannot be empty")
return [float(item) for item in items]
def parse_shutter_list(value: str) -> list[str]:
shutters = []
for item in [item.strip() for item in value.split(",") if item.strip()]:
if "/" in item:
shutters.append(item)
else:
shutters.append(f"1/{item}")
if not shutters:
raise argparse.ArgumentTypeError("list cannot be empty")
return shutters
def light_percent(intensity: int) -> float:
"""
This function is only for reading purpose
Real control still use the original intensity [0, 1000]
"""
return intensity / 10.0
def make_session_id() -> str:
return datetime.now().strftime("%Y%m%d_%H%M%S_%f")[:-3]
def timestamp() -> str:
return time.strftime("%Y-%m-%dT%H:%M:%S%z")
def format_id(prefix: str, value: int) -> str:
return f"{prefix}{value:0{PAD_WIDTH}d}"
def format_number(value: float | int | str) -> str:
if isinstance(value, float):
return f"{value:g}"
return str(value)
def format_duration(seconds: float) -> str:
minutes, remaining_seconds = divmod(max(0.0, seconds), 60.0)
return f"{int(minutes)}m {remaining_seconds:.1f}s"
def restore_owner(path: Path) -> None:
"""Make files created through sudo writable by the invoking user."""
uid_text = os.environ.get("SUDO_UID")
gid_text = os.environ.get("SUDO_GID")
if uid_text is None or gid_text is None:
return
os.chown(path, int(uid_text), int(gid_text))
def append_jsonl_record(path: Path, record: dict[str, object]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("a", encoding="utf-8") as handle:
handle.write(json.dumps(record, ensure_ascii=True, sort_keys=True) + "\n")
restore_owner(path)
def write_json_file(path: Path, data: dict[str, object]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(data, indent=2, sort_keys=True) + "\n", encoding="utf-8")
restore_owner(path)
def maps_dir(output_dir: Path) -> Path:
path = output_dir / "maps"
path.mkdir(parents=True, exist_ok=True)
restore_owner(path)
return path
def ensure_output_dir_for_mode(output_dir: Path, capture_mode: str) -> None:
if capture_mode == "fresh" and output_dir.exists() and any(output_dir.iterdir()):
raise RuntimeError(
f"--capture-mode fresh requires an empty output directory, got {output_dir}. "
"Use a new --output-dir or clear it manually."
)
output_dir.mkdir(parents=True, exist_ok=True)
restore_owner(output_dir)
def normalize_class_id(value: str) -> int:
class_id = value.strip()
if not class_id.isdigit():
raise ValueError(f"class_id must be a number, got {value!r}.")
return int(class_id)
def prompt_class_id() -> int | None:
while True:
value = input("\nClass ID (number, q to quit): ").strip()
if value.lower() in {"q", "quit", "exit"}:
return None
if value.isdigit():
return int(value)
print("Please enter a numeric class_id, or q to quit.")
def build_output_path(
output_dir: Path,
class_id: int,
sample_id: int,
light_id: int,
view_id: int,
param_id: int,
) -> Path:
return (
output_dir
/ format_id("l", light_id)
/ format_id("c", class_id)
/ format_id("s", sample_id)
/ format_id("v", view_id)
/ f"{format_id('p', param_id)}.jpg"
)
def build_capture_record(
*,
session_id: str,
sequence: int,
class_id: int,
sample_id: int,
light_id: int,
light_position: str,
light_intensity: int,
light_cct: int,
view_id: int,
angle_degrees: int,
param_id: int,
aperture: float | str,
iso: int | str,
shutter_speed: str,
exposure_mode: str,
output_dir: Path,
output_path: Path,
captured_at: str,
size_bytes: int,
) -> dict[str, object]:
image_path = str(output_path.relative_to(output_dir))
return {
"session_id": session_id,
"sequence": sequence,
"class_id": class_id,
"sample_id": sample_id,
"light_id": light_id,
"view_id": view_id,
"param_id": param_id,
"position": light_position,
"intensity": light_intensity,
"cct": light_cct,
"angle_degrees": angle_degrees,
"aperture": aperture,
"iso": iso,
"shutter_speed": shutter_speed,
"exposure_mode": exposure_mode,
"image_path": image_path,
"captured_at": captured_at,
"size_bytes": size_bytes,
}
def new_dataset_map() -> dict[str, object]:
now = timestamp()
return {
"schema_version": 1,
"created_at": now,
"updated_at": now,
"classes": [],
"samples": [],
"lights": [],
"views": [],
"params": [],
}
def load_dataset_map(path: Path) -> dict[str, object]:
if not path.exists() or path.stat().st_size == 0:
return new_dataset_map()
try:
data = json.loads(path.read_text(encoding="utf-8"))
except json.JSONDecodeError as exc:
raise ValueError(f"Dataset parameter map is not valid JSON: {path}: {exc}") from exc
if not isinstance(data, dict):
raise ValueError(f"Dataset parameter map must be a JSON object: {path}")
for key in ["classes", "samples", "lights", "views", "params"]:
if not isinstance(data.get(key), list):
data[key] = []
data.setdefault("schema_version", 1)
data.setdefault("created_at", timestamp())
data["updated_at"] = timestamp()
return data
def save_dataset_map(map_dir: Path, dataset_map: dict[str, object]) -> None:
dataset_map["updated_at"] = timestamp()
write_json_file(map_dir / "parameters.json", dataset_map)
def map_items(dataset_map: dict[str, object], key: str) -> list[dict[str, object]]:
items = dataset_map.setdefault(key, [])
if not isinstance(items, list):
raise ValueError(f"Dataset map field {key!r} must be a list.")
return items # type: ignore[return-value]
def next_map_id(items: list[dict[str, object]], key: str) -> int:
values = []
for item in items:
value = item.get(key)
if isinstance(value, int):
values.append(value)
elif isinstance(value, str) and value.isdigit():
values.append(int(value))
return max(values, default=0) + 1
def ensure_class_entry(dataset_map: dict[str, object], class_id: int) -> None:
classes = map_items(dataset_map, "classes")
for item in classes:
if int(item.get("class_id", -1)) == class_id:
return
classes.append(
{
"class_id": class_id,
"class_folder": format_id("c", class_id),
"created_at": timestamp(),
}
)
def sample_ids_from_dirs(output_dir: Path, light_id: int, class_id: int) -> list[int]:
new_class_dir = output_dir / format_id("l", light_id) / format_id("c", class_id)
sample_ids = []
if new_class_dir.exists():
for path in new_class_dir.iterdir():
if path.is_dir() and path.name.startswith("s") and path.name[1:].isdigit():
sample_ids.append(int(path.name[1:]))
return sample_ids
def sample_light_ids(sample: dict[str, object]) -> list[int]:
light_ids = sample.get("light_ids")
if isinstance(light_ids, list):
return [int(value) for value in light_ids if isinstance(value, int) or str(value).isdigit()]
light_id = sample.get("light_id")
if isinstance(light_id, int):
return [light_id]
if isinstance(light_id, str) and light_id.isdigit():
return [int(light_id)]
return []
def next_sample_id(
dataset_map: dict[str, object],
output_dir: Path,
class_id: int,
light_ids: list[int],
) -> int:
light_id_set = set(light_ids)
samples = map_items(dataset_map, "samples")
map_sample_ids = []
for item in samples:
if int(item.get("class_id", -1)) != class_id:
continue
if not str(item.get("sample_id", "")).isdigit():
continue
item_light_ids = set(sample_light_ids(item))
if item_light_ids and item_light_ids.isdisjoint(light_id_set):
continue
if not item_light_ids:
continue
map_sample_ids.append(int(item["sample_id"]))
dir_sample_ids = []
for light_id in light_ids:
dir_sample_ids.extend(sample_ids_from_dirs(output_dir, light_id, class_id))
return max([*map_sample_ids, *dir_sample_ids], default=0) + 1
def light_sample_dirs(output_dir: Path, light_ids: list[int], class_id: int, sample_id: int) -> list[Path]:
return [
output_dir / format_id("l", light_id) / format_id("c", class_id) / format_id("s", sample_id)
for light_id in light_ids
]
def sample_folder_text(output_dir: Path, light_ids: list[int], class_id: int, sample_id: int) -> str:
paths = light_sample_dirs(output_dir, light_ids, class_id, sample_id)
if len(paths) == 1:
return str(paths[0])
return ", ".join(str(path) for path in paths)
def append_sample_entry(
dataset_map: dict[str, object],
class_id: int,
sample_id: int,
light_ids: list[int],
session_id: str,
total_captures: int,
started_at: str,
) -> None:
entry = {
"class_id": class_id,
"sample_id": sample_id,
"light_ids": light_ids,
"light_folders": [format_id("l", light_id) for light_id in light_ids],
"class_folder": format_id("c", class_id),
"sample_folder": format_id("s", sample_id),
"session_id": session_id,
"created_at": started_at,
"started_at": started_at,
"total_captures": total_captures,
}
if len(light_ids) == 1:
entry["light_id"] = light_ids[0]
entry["light_folder"] = format_id("l", light_ids[0])
map_items(dataset_map, "samples").append(entry)
def validate_light_intensity(intensity: int) -> None:
if intensity < 0 or intensity > 1000:
raise ValueError(f"Light intensity must be in [0, 1000], got {intensity}.")
def update_sample_timing(
dataset_map: dict[str, object],
class_id: int,
sample_id: int,
session_id: str,
capture_started_at: str,
completed_at: str,
object_elapsed_seconds: float,
capture_elapsed_seconds: float,
) -> None:
for item in map_items(dataset_map, "samples"):
if (
int(item.get("class_id", -1)) == class_id
and int(item.get("sample_id", -1)) == sample_id
and item.get("session_id") == session_id
):
item.update(
{
"capture_started_at": capture_started_at,
"completed_at": completed_at,
"object_elapsed_seconds": round(object_elapsed_seconds, 3),
"capture_elapsed_seconds": round(capture_elapsed_seconds, 3),
}
)
return
raise RuntimeError(
f"Could not update timing for class {class_id}, sample {sample_id}, session {session_id}."
)
def get_or_create_light_id(
dataset_map: dict[str, object],
position: str,
intensity: int,
cct: int,
) -> int:
lights = map_items(dataset_map, "lights")
for item in lights:
if (
item.get("position") == position
and int(item.get("intensity", -1)) == intensity
and int(item.get("cct", -1)) == cct
):
return int(item["light_id"])
light_id = next_map_id(lights, "light_id")
lights.append(
{
"light_id": light_id,
"light_folder": format_id("l", light_id),
"position": position,
"intensity": intensity,
"light_percent": light_percent(intensity),
"cct": cct,
}
)
return light_id
def get_or_create_view_id(
dataset_map: dict[str, object],
view_index: int,
angle_degrees: int,
) -> int:
views = map_items(dataset_map, "views")
for item in views:
if (
int(item.get("view_index", -1)) == view_index
and int(item.get("angle_degrees", -1)) == angle_degrees
):
return int(item["view_id"])
view_id = next_map_id(views, "view_id")
views.append(
{
"view_id": view_id,
"view_folder": format_id("v", view_id),
"view_index": view_index,
"angle_degrees": angle_degrees,
}
)
return view_id
def get_or_create_param_id(
dataset_map: dict[str, object],
aperture: float,
iso: int,
shutter: str,
) -> int:
params = map_items(dataset_map, "params")
aperture_value = format_number(aperture)
for item in params:
try:
item_iso = int(item.get("iso", -1))
except (TypeError, ValueError):
continue
if (
str(item.get("aperture")) == aperture_value
and item_iso == iso
and item.get("shutter_speed") == shutter
):
return int(item["param_id"])
param_id = next_map_id(params, "param_id")
params.append(
{
"param_id": param_id,
"param_file": f"{format_id('p', param_id)}.jpg",
"aperture": aperture_value,
"iso": iso,
"shutter_speed": shutter,
}
)
return param_id
def ensure_auto_param_entry(dataset_map: dict[str, object]) -> None:
params = map_items(dataset_map, "params")
for item in params:
if int(item.get("param_id", -1)) == AUTO_PARAM_ID:
return
params.append(
{
"param_id": AUTO_PARAM_ID,
"param_file": f"{format_id('p', AUTO_PARAM_ID)}.jpg",
"aperture": "auto",
"iso": "auto",
"shutter_speed": "auto",
"exposure_mode": "auto",
}
)
def build_lighting_plan(
dataset_map: dict[str, object],
args: argparse.Namespace,
) -> list[dict[str, object]]:
plan = [
{
"position": args.light_position,
"intensity": intensity,
"cct": args.cct,
}
for intensity in args.light_intensities
]
for item in plan:
item["light_id"] = get_or_create_light_id(
dataset_map,
str(item["position"]),
int(item["intensity"]),
int(item["cct"]),
)
return plan
def build_view_plan(
dataset_map: dict[str, object],
args: argparse.Namespace,
) -> list[dict[str, object]]:
view_plan = []
for view_index in range(args.views):
angle = (view_index * args.view_step) % 360
view_plan.append(
{
"view_id": get_or_create_view_id(dataset_map, view_index, angle),
"view_index": view_index,
"angle_degrees": angle,
}
)
return view_plan
def build_param_plan(
dataset_map: dict[str, object],
args: argparse.Namespace,
) -> list[dict[str, object]]:
param_plan = []
for aperture in args.apertures:
for iso in args.isos:
for shutter in args.shutters:
param_plan.append(
{
"param_id": get_or_create_param_id(
dataset_map,
aperture,
iso,
shutter,
),
"aperture": aperture,
"iso": iso,
"shutter_speed": shutter,
}
)
return param_plan
class DryLightController:
def __init__(self):
self.current_cct = None
async def __aenter__(self) -> "DryLightController":
print("[dry-run] light connected")
return self
async def __aexit__(self, exc_type, exc_value, traceback) -> None:
print("[dry-run] light disconnected")
async def set_cct(self, cct: int) -> None:
if self.current_cct == cct:
return
self.current_cct = cct
print(f"[dry-run] set light CCT {cct}K")
async def set_intensity(self, intensity: int) -> None:
print(f"[dry-run] set light intensity {intensity}/1000 ({light_percent(intensity):g}%)")
class AmaranLightController:
def __init__(
self,
ws_url: str,
api_secret_key: str,
client_id: int,
cct: int,
settle_seconds: float,
):
self.ws_url = ws_url
self.api_secret_key = api_secret_key
self.client_id = client_id
self.cct = cct
self.settle_seconds = settle_seconds
self.ws = None
self.node_id = None
self.current_cct = None
self._last_request_id = 0
async def __aenter__(self) -> "AmaranLightController":
""" Connect to Amaran Light """
await self._connect()
self._ensure_ok(await self._send("get_protocol_versions"), "get_protocol_versions")
devices = self._extract_devices(
self._ensure_ok(await self._send("get_fixture_list"), "get_fixture_list")
)
if not devices:
devices = self._extract_devices(
self._ensure_ok(await self._send("get_device_list"), "get_device_list")
)
if not devices:
raise RuntimeError("No Amaran light found.")
# By default, we use the first light
light = devices[0]
self.node_id = light["node_id"]
print(f"Using light: {light.get('name')} ({self.node_id})")
self._ensure_ok(
await self._send("set_sleep", node_id=self.node_id, args={"sleep": False}),
"set_sleep",
)
await asyncio.sleep(self.settle_seconds)
await self.set_cct(self.cct)
return self
async def __aexit__(self, exc_type, exc_value, traceback) -> None:
if self.node_id is not None and self.ws is not None:
try:
self._ensure_ok(
await self._send(
"set_intensity",
node_id=self.node_id,
args={"intensity": 0},
),
"set_intensity",
)
self._ensure_ok(
await self._send(
"set_sleep",
node_id=self.node_id,
args={"sleep": True},
),
"set_sleep",
)
print("Light turned off and put to sleep.")
except Exception as exc:
print(f"Warning: failed to turn off light cleanly: {exc}")
await self._close_ws()
async def set_cct(self, cct: int) -> None:
if self.node_id is None:
raise RuntimeError("Light is not connected.")
if self.current_cct == cct:
return
self._ensure_ok(
await self._send("set_cct", node_id=self.node_id, args={"cct": cct}),
"set_cct",
)
self.current_cct = cct
print(f"Light CCT: {cct}K")
await asyncio.sleep(self.settle_seconds)
async def set_intensity(self, intensity: int) -> None:
if self.node_id is None:
raise RuntimeError("Light is not connected.")
self._ensure_ok(
await self._send(
"set_intensity",
node_id=self.node_id,
args={"intensity": intensity},
),
"set_intensity",
)
readback = self._ensure_ok(
await self._send("get_intensity", node_id=self.node_id),
"get_intensity",
)
print(f"Light intensity: {readback.get('data')} / 1000")
await asyncio.sleep(self.settle_seconds)
def _generate_token(self) -> str:
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
iv = os.urandom(12)
encryptor = Cipher(
algorithms.AES(base64.b64decode(self.api_secret_key)),
modes.GCM(iv),
backend=default_backend(),
).encryptor()
ciphertext = encryptor.update(str(int(time.time())).encode()) + encryptor.finalize()
return base64.b64encode(iv + encryptor.tag + ciphertext).decode()
def _next_request_id(self) -> int:
request_id = int(time.time() * 1000)
if request_id <= self._last_request_id:
request_id = self._last_request_id + 1
self._last_request_id = request_id
return request_id
async def _connect(self) -> None:
import websockets
await self._close_ws()
self.ws = await websockets.connect(self.ws_url)
async def _close_ws(self) -> None:
if self.ws is None:
return
try:
await self.ws.close()
except Exception:
pass
finally:
self.ws = None
async def _send(
self,
action: str,
node_id: Optional[str] = None,
args: Optional[dict] = None,
):
for attempt in range(2):
try:
return await self._send_once(action, node_id=node_id, args=args)
except Exception:
if attempt == 1:
raise
print(f"Light websocket disconnected during {action}; reconnecting and retrying...")
await self._connect()
async def _send_once(
self,
action: str,
node_id: Optional[str] = None,
args: Optional[dict] = None,
):
if self.ws is None:
raise RuntimeError("Light websocket is not connected.")
request_id = self._next_request_id()
request = {
"version": 2,
"type": "request",
"client_id": self.client_id,
"request_id": request_id,
"action": action,
"token": self._generate_token(),
}
if node_id is not None:
request["node_id"] = node_id
if args is not None:
request["args"] = args
await self.ws.send(json.dumps(request))
while True:
data = json.loads(await self.ws.recv())
if data.get("type") == "event":
continue
if data.get("type") == "response" and data.get("request_id") == request_id:
return data
@staticmethod
def _ensure_ok(resp: dict, action: str) -> dict:
if resp.get("code") != 0:
raise RuntimeError(f"{action} failed: {json.dumps(resp, indent=2)}")
return resp
@staticmethod
def _extract_devices(resp: dict) -> list[dict]:
data = resp.get("data", resp)
return data if isinstance(data, list) else []
class DryTurntableController:
def __enter__(self) -> "DryTurntableController":
print("[dry-run] turntable connected")
return self
def __exit__(self, exc_type, exc_value, traceback) -> None:
print("[dry-run] turntable disconnected")
def home(self) -> None:
print("[dry-run] turntable HOME")
def set_speed(self, rpm: float) -> None:
print(f"[dry-run] turntable SPEED {rpm}")
def rotate(self, degrees: float) -> None:
print(f"[dry-run] turntable ROT {degrees}")
def goto(self, degrees: float) -> None:
print(f"[dry-run] turntable GOTO {degrees}")
class TurntableController:
def __init__(self, port: str, speed_rpm: float, settle_seconds: float):
self.port = port
self.speed_rpm = speed_rpm
self.settle_seconds = settle_seconds
self._turntable = None
def __enter__(self) -> "TurntableController":
from turntable.turntable import Turntable
self._turntable = Turntable(self.port)
print("Set current turntable position as HOME")
print(self._turntable.home())
print(f"Set turntable speed: {self.speed_rpm} rpm")
print(self._turntable.set_speed(self.speed_rpm))
return self
def __exit__(self, exc_type, exc_value, traceback) -> None:
if self._turntable is not None:
self._turntable.close()
def rotate(self, degrees: float) -> None:
if self._turntable is None:
raise RuntimeError("Turntable is not connected.")
print(f"Rotate turntable by {degrees:g} degrees")
print(self._turntable.rotate(degrees))
time.sleep(self.settle_seconds)
def goto(self, degrees: float) -> None:
if self._turntable is None:
raise RuntimeError("Turntable is not connected.")
print(f"Move turntable to {degrees:g} degrees")
print(self._turntable.goto(degrees))
time.sleep(self.settle_seconds)
class DryCameraController:
def __enter__(self) -> "DryCameraController":
print("[dry-run] camera connected")
return self
def __exit__(self, exc_type, exc_value, traceback) -> None:
print("[dry-run] camera disconnected")
def capture(
self,
aperture: float,
iso: int,
shutter: str,
output_path: Path,
timeout: float,
save_media: str = DEFAULT_SAVE_MEDIA,
fast_shutter: bool = False,
) -> int:
print(f"[dry-run] capture ISO {iso}, F{aperture:g}, {shutter} -> {output_path.name}")
output_path.write_text("dry-run placeholder\n", encoding="utf-8")
restore_owner(output_path)
return output_path.stat().st_size
def capture_auto(
self,
output_path: Path,
timeout: float,
save_media: str = DEFAULT_SAVE_MEDIA,
fast_shutter: bool = False,
) -> int:
print(f"[dry-run] capture auto exposure -> {output_path.name}")
output_path.write_text("dry-run auto exposure placeholder\n", encoding="utf-8")
restore_owner(output_path)
return output_path.stat().st_size
class SonyCameraController:
def __init__(self):
self._context = None
self.camera = None
self.ExposureMode = None
self.DeviceProperty = None
self.SaveMedia = None
self.iso_table = None
self.aperture_table = None
self.shutter_table = None
self._last_exposure_mode = None
self._last_iso = None
self._last_aperture = None
self._last_shutter = None
def __enter__(self) -> "SonyCameraController":
from pysonycam import ExposureMode, SonyCamera
from pysonycam.constants import (
DeviceProperty,
F_NUMBER_TABLE,
ISO_TABLE,
SHOT_OBJECT_HANDLE,
SHUTTER_SPEED_TABLE,
SaveMedia,
)
self.ExposureMode = ExposureMode
self.DeviceProperty = DeviceProperty
self.SHOT_OBJECT_HANDLE = SHOT_OBJECT_HANDLE
self.SaveMedia = SaveMedia
self.iso_table = ISO_TABLE
self.aperture_table = F_NUMBER_TABLE
self.shutter_table = SHUTTER_SPEED_TABLE
self._context = SonyCamera()
self.camera = self._context.__enter__()
self.camera.authenticate()
self.camera.set_mode("still")
self._set_exposure_mode(ExposureMode.MANUAL, "manual exposure mode")
return self
def __exit__(self, exc_type, exc_value, traceback) -> None:
if self._context is not None:
self._context.__exit__(exc_type, exc_value, traceback)
def capture(
self,
aperture: float,
iso: int,
shutter: str,
output_path: Path,
timeout: float,
save_media: str = DEFAULT_SAVE_MEDIA,
fast_shutter: bool = False,
) -> int:
if self.camera is None:
raise RuntimeError("Camera is not connected.")
iso_code = self._iso_code(iso)
aperture_code = self._aperture_code(aperture)
shutter_code = self._shutter_code(shutter)
changed_to_manual = self._set_exposure_mode(
self.ExposureMode.MANUAL,
"manual exposure mode",
)
if self._last_iso != iso_code:
self.camera.set_iso(iso_code)
self._wait_for_setting(self.DeviceProperty.ISO, iso_code, "ISO")
self._last_iso = iso_code
if self._last_aperture != aperture_code:
self.camera.set_aperture(aperture_code)
self._wait_for_setting(self.DeviceProperty.F_NUMBER, aperture_code, "aperture")
self._last_aperture = aperture_code
if self._last_shutter != shutter_code:
self.camera.set_shutter_speed(shutter_code)
self._wait_for_setting(
self.DeviceProperty.SHUTTER_SPEED,
shutter_code,
"shutter speed",
)
self._last_shutter = shutter_code
capture_fast = fast_shutter and not changed_to_manual
if fast_shutter and changed_to_manual:
print("Using normal shutter for first manual capture after auto exposure; fast shutter resumes after this.")
try:
return self._capture_to_path(output_path, timeout, save_media, capture_fast)
except RuntimeError as exc:
if not changed_to_manual or "timed out waiting for image" not in str(exc):
raise
print("First manual capture after auto exposure timed out; retrying once with normal shutter.")
return self._capture_to_path(output_path, timeout, save_media, fast_shutter=False)
def capture_auto(
self,
output_path: Path,
timeout: float,
save_media: str = DEFAULT_SAVE_MEDIA,
fast_shutter: bool = False,
) -> int:
if self.camera is None:
raise RuntimeError("Camera is not connected.")
self._set_exposure_mode(self._auto_exposure_mode(), "auto exposure mode")
auto_iso_code = self._auto_iso_code()
if self._last_iso != auto_iso_code:
self.camera.set_iso(auto_iso_code)
self._wait_for_setting(self.DeviceProperty.ISO, auto_iso_code, "ISO AUTO")