-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathbasler_backend.py
More file actions
1287 lines (1056 loc) · 45.7 KB
/
Copy pathbasler_backend.py
File metadata and controls
1287 lines (1056 loc) · 45.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
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
"""Basler camera backend implemented with :mod:`pypylon`."""
# dlclivegui/cameras/backends/basler_backend.py
from __future__ import annotations
import logging
import time
from typing import ClassVar
import numpy as np
from ...config import BASLER_DO_LOG_TIMING, CameraTriggerSettings
from ...utils.stats import WorkerTimingStats
from ..base import CameraBackend, SupportLevel, register_backend
LOG = logging.getLogger(__name__)
# NOTE @C-Achard: This could be added in settings eventually
# Forces pypylon to create N emulation virtual cameras,
# mostly for testing. This should not be enabled for release.
ENABLE_PYLON_EMU = True
if ENABLE_PYLON_EMU:
import os
os.environ["PYLON_CAMEMU"] = "4"
try: # pragma: no cover - optional dependency
from pypylon import pylon
except Exception: # pragma: no cover - optional dependency
pylon = None # type: ignore
@register_backend("basler")
class BaslerCameraBackend(CameraBackend):
"""Capture frames from Basler cameras using the Pylon SDK."""
OPTIONS_KEY: ClassVar[str] = "basler"
# Keep RetrieveResult calls short enough that controller shutdown can stop
# worker threads promptly while waiting for external hardware triggers.
_MAX_HARDWARE_TRIGGER_RETRIEVE_TIMEOUT_MS: ClassVar[int] = 1000
def __init__(self, settings):
super().__init__(settings)
self._props: dict = settings.properties if isinstance(settings.properties, dict) else {}
self._preserve_mono: bool = bool(
getattr(settings, "preserve_mono", False) or self.ns.get("preserve_mono", False)
)
self._camera_pixel_format: str | None = None
self._logged_first_frame: bool = False
# Optional fast-start hint for probe workers
# (may skip StartGrabbing and converter setup for faster capability probing; not suitable for normal capture)
self._fast_start: bool = bool(self.ns.get("fast_start", False))
self._retrieve_timeout_ms: int = 100 # default; may be overridden by trigger settings
# ---- Trigger settings ----
raw_trigger = self.ns.get("trigger", self._props.get("trigger"))
raw_trigger_strict = isinstance(raw_trigger, dict) and bool(raw_trigger.get("strict", False))
try:
self._trigger = CameraTriggerSettings.from_any(raw_trigger)
except Exception as exc:
if raw_trigger_strict:
raise ValueError(f"Strict mode failure - Invalid Basler trigger configuration: {exc}") from exc
LOG.warning(
"Invalid Basler trigger config; falling back to trigger role=off: %s. "
"Enable strict mode to force this to raise.",
exc,
)
self._trigger = CameraTriggerSettings()
trigger_timeout = self._positive_float(self._trigger_attr(self._trigger, "timeout", None))
if trigger_timeout is not None:
# pypylon RetrieveResult timeout is milliseconds.
self._retrieve_timeout_ms = max(1, int(float(trigger_timeout) * 1000.0))
else:
self._retrieve_timeout_ms = 100
if self.waits_for_hardware_trigger:
self._retrieve_timeout_ms = min(
self._retrieve_timeout_ms,
self._MAX_HARDWARE_TRIGGER_RETRIEVE_TIMEOUT_MS,
)
# Stable identity (serial-based). Prefer new namespace; fall back to legacy keys read-only.
self._device_id: str | None = None
dev_id = self.ns.get("device_id")
if dev_id:
self._device_id = str(dev_id)
else:
# legacy fallback (read-only)
legacy_serial = None
try:
legacy_serial = self._props.get("serial") or self._props.get("serial_number")
except Exception:
legacy_serial = None
if legacy_serial:
self._device_id = str(legacy_serial)
self._requested_resolution: tuple[int, int] | None = self._get_requested_resolution_or_none()
# ---- Runtime handles (set during open) ----
self._camera: pylon.InstantCamera | None = None
self._converter: pylon.ImageFormatConverter | None = None
# ---- Actuals for GUI telemetry ----
self._actual_width: int | None = None
self._actual_height: int | None = None
self._actual_fps: float | None = None
self._actual_exposure: float | None = None
self._actual_gain: float | None = None
# ---- Timing stats for logging (optional) ----
msg = self._device_id or f"index:{getattr(settings, 'index', '?')}"
timing_id = f"Basler {msg}"
self._timing = WorkerTimingStats(
timing_id,
logger=LOG,
log_interval=1.0,
enabled=BASLER_DO_LOG_TIMING,
)
@property
def actual_resolution(self) -> tuple[int, int] | None:
if self._actual_width and self._actual_height:
return (self._actual_width, self._actual_height)
return None
@property
def actual_fps(self) -> float | None:
return self._actual_fps
@property
def actual_exposure(self) -> float | None:
return self._actual_exposure
@property
def actual_gain(self) -> float | None:
return self._actual_gain
@property
def actual_pixel_format(self) -> str | None:
"""Camera/native pixel format reported by Basler, e.g. 'Mono8'."""
return self._camera_pixel_format
@property
def actual_output_format(self) -> str | None:
"""Backend output frame format emitted to the app, e.g. 'Mono8' or 'BGR8'."""
if not self._camera_pixel_format:
return None
return "Mono8" if self._should_output_mono() else "BGR8"
@property
def recommended_preserve_mono(self) -> bool | None:
if not self._camera_pixel_format:
return None
return self._is_camera_mono()
@classmethod
def is_available(cls) -> bool:
return pylon is not None
@classmethod
def static_capabilities(cls) -> dict[str, SupportLevel]:
caps = super().static_capabilities()
caps.update(
{
"set_resolution": SupportLevel.SUPPORTED,
"set_fps": SupportLevel.SUPPORTED,
"set_exposure": SupportLevel.SUPPORTED,
"set_gain": SupportLevel.SUPPORTED,
"device_discovery": SupportLevel.BEST_EFFORT,
"stable_identity": SupportLevel.SUPPORTED,
"hardware_trigger": SupportLevel.BEST_EFFORT,
"preserve_mono": SupportLevel.SUPPORTED,
}
)
return caps
@property
def ns(self) -> dict:
"""Basler namespace view (read-only). Always derived from current settings.properties."""
return self.__class__._ns_from_settings(self.settings)
@classmethod
def _ns_from_settings(cls, settings) -> dict:
"""Return basler namespace dict from a settings object (read-only, safe)."""
props = settings.properties if isinstance(settings.properties, dict) else {}
ns = props.get(cls.OPTIONS_KEY, {})
return ns if isinstance(ns, dict) else {}
def _ensure_mutable_ns(self) -> dict:
"""Ensure settings.properties and its basler namespace dict exist; return the namespace."""
if not isinstance(self.settings.properties, dict):
self.settings.properties = {}
ns = self.settings.properties.get(self.OPTIONS_KEY)
if not isinstance(ns, dict):
ns = {}
self.settings.properties[self.OPTIONS_KEY] = ns
return ns
def _read_camera_pixel_format(self) -> str:
pixel_format = self._feature_value(self._feature("PixelFormat"), "")
self._camera_pixel_format = str(pixel_format or "")
return self._camera_pixel_format
def _is_camera_mono(self) -> bool:
return bool(self._camera_pixel_format and self._camera_pixel_format.startswith("Mono"))
def _should_output_mono(self) -> bool:
return bool(self._preserve_mono and self._is_camera_mono())
@classmethod
def _enumerate_devices_cls(cls):
"""Enumerate DeviceInfo entries (unit-testable via monkeypatch)."""
if pylon is None:
return []
factory = pylon.TlFactory.GetInstance()
return factory.EnumerateDevices()
@classmethod
def get_device_count(cls) -> int:
"""Return the number of Basler devices visible to Pylon."""
try:
return len(cls._enumerate_devices_cls())
except Exception:
return 0
@classmethod
def quick_ping(cls, index: int, *args, **kwargs) -> bool:
"""Best-effort presence check; avoids opening the device."""
try:
devices = cls._enumerate_devices_cls()
idx = int(index)
return 0 <= idx < len(devices)
except Exception:
return False
@classmethod
def discover_devices(
cls,
*,
max_devices: int = 10,
should_cancel=None,
progress_cb=None,
):
"""
Return a rich list of DetectedCamera with stable identity (serial).
Best-effort: works for USB3/GigE; fields depend on SDK/device.
"""
if pylon is None:
return []
from ..factory import DetectedCamera # local import to keep module load light
devices = cls._enumerate_devices_cls()
out = []
# Bound by max_devices to match factory expectations
n = min(len(devices), int(max_devices) if max_devices is not None else len(devices))
for i in range(n):
if should_cancel and should_cancel():
break
if progress_cb:
progress_cb(f"Reading Basler device info ({i + 1}/{n})…")
di = devices[i]
# Best-effort getters; not all are present on all transports
serial = None
try:
serial = di.GetSerialNumber()
except Exception:
serial = None
# Friendly label: Vendor Model (Serial)
vendor = model = friendly = full_name = None
try:
vendor = di.GetVendorName()
except Exception:
pass
try:
model = di.GetModelName()
except Exception:
pass
try:
friendly = di.GetFriendlyName()
except Exception:
pass
try:
full_name = di.GetFullName()
except Exception:
pass
label_parts = []
if vendor:
label_parts.append(str(vendor))
if model:
label_parts.append(str(model))
if not label_parts and friendly:
label_parts.append(str(friendly))
label = " ".join(label_parts) if label_parts else f"Basler #{i}"
if serial:
label = f"{label} ({serial})"
out.append(
DetectedCamera(
index=i,
label=label,
device_id=str(serial) if serial else None, # <-- stable identity
path=str(full_name) if full_name else None,
)
)
return out
@classmethod
def rebind_settings(cls, settings):
"""
If settings.properties['basler']['device_id'] (serial) exists,
update settings.index to match the current device list order.
"""
if pylon is None:
return settings
dc = settings.model_copy(deep=True)
ns = cls._ns_from_settings(dc)
serial = ns.get("device_id") or ns.get("serial") # allow legacy-in-namespace
# Legacy top-level fallback (read-only compatibility)
if not serial:
props = dc.properties if isinstance(dc.properties, dict) else {}
serial = props.get("serial") or props.get("serial_number")
if not serial:
return dc
try:
devices = cls._enumerate_devices_cls()
for i, di in enumerate(devices):
try:
if di.GetSerialNumber() == serial:
dc.index = int(i)
# Ensure we persist stable ID in the basler namespace
if not isinstance(dc.properties, dict):
dc.properties = {}
bns = dc.properties.get(cls.OPTIONS_KEY)
if not isinstance(bns, dict):
bns = {}
dc.properties[cls.OPTIONS_KEY] = bns
bns["device_id"] = str(serial) # canonical
# optional friendly name cache (nice for UI)
try:
bns["device_name"] = str(di.GetFriendlyName())
except Exception:
pass
try:
bns["device_path"] = str(di.GetFullName())
except Exception:
pass
return dc
except Exception:
continue
except Exception:
pass
return dc
@classmethod
def sanitize_for_probe(cls, settings):
"""
Keep only basler namespace + set all requested controls to Auto
so probing is fast and doesn't force modes.
"""
dc = settings.model_copy(deep=True)
# Keep only backend namespace dict
ns = cls._ns_from_settings(dc)
dc.properties = {cls.OPTIONS_KEY: dict(ns)} # shallow copy ok
# Force Auto for probe; do NOT set heavy parameters
dc.width = 0
dc.height = 0
dc.fps = 0.0
dc.exposure = 0
dc.gain = 0.0
dc.rotation = 0
dc.crop_x0 = dc.crop_y0 = dc.crop_x1 = dc.crop_y1 = 0
return dc
@staticmethod
def _positive_float(value) -> float | None:
"""Return float(value) if > 0 else None."""
try:
v = float(value)
return v if v > 0 else None
except Exception:
return None
def trigger_once(self) -> None:
if self._camera is None:
raise RuntimeError("Basler camera not opened")
# pypylon commonly exposes ExecuteSoftwareTrigger on InstantCamera.
method = getattr(self._camera, "ExecuteSoftwareTrigger", None)
if method is not None:
method()
return
command = self._feature("TriggerSoftware")
if command is not None:
try:
command.Execute()
return
except Exception as exc:
raise RuntimeError(f"Failed to execute Basler software trigger: {exc}") from exc
raise RuntimeError("Basler software trigger command is not available")
def _configure_frame_rate(self) -> None:
if self._camera is None:
return
fps = self._positive_float(getattr(self.settings, "fps", 0.0))
if fps is None:
LOG.info("[Basler] FPS: auto/free-run, not forcing AcquisitionFrameRate")
return
enable = self._feature("AcquisitionFrameRateEnable")
rate = self._feature("AcquisitionFrameRate")
try:
if enable is not None:
enable.SetValue(True)
if rate is None:
LOG.warning("[Basler] AcquisitionFrameRate node not available; cannot set FPS=%s", fps)
return
try:
min_v = rate.GetMin()
max_v = rate.GetMax()
LOG.info("[Basler] AcquisitionFrameRate range: min=%s max=%s requested=%s", min_v, max_v, fps)
except Exception:
pass
rate.SetValue(float(fps))
except Exception as exc:
LOG.warning("[Basler] Failed to set AcquisitionFrameRate=%s: %s", fps, exc, exc_info=True)
# Readbacks
readbacks = {}
for name in (
"AcquisitionFrameRateEnable",
"AcquisitionFrameRate",
"ResultingFrameRate",
"ResultingAcquisitionFrameRate",
"AcquisitionResultingFrameRate",
"BslResultingAcquisitionFrameRate",
"ExposureAuto",
"ExposureTime",
"Width",
"Height",
"PixelFormat",
"TestImageSelector",
"ImageFileMode",
):
feature = self._feature(name)
if feature is not None:
readbacks[name] = self._feature_value(feature, None)
LOG.info("[Basler] FPS readback requested=%s values=%s", fps, readbacks)
try:
self._actual_fps = float(readbacks.get("AcquisitionFrameRate"))
except Exception:
self._actual_fps = None
def _configure_converter(self) -> None:
"""Configure pypylon image converter.
Default behavior remains BGR8 for compatibility.
If preserve_mono=True and the camera PixelFormat is Mono*,
return Mono8 frames as 2D arrays to avoid 3x BGR expansion.
"""
if self._camera is None:
return
camera_pixel_format = self._camera_pixel_format or self._read_camera_pixel_format()
self._converter = pylon.ImageFormatConverter()
self._converter.OutputBitAlignment = pylon.OutputBitAlignment_MsbAligned
if self._should_output_mono():
self._converter.OutputPixelFormat = pylon.PixelType_Mono8
LOG.info(
"[Basler] Converter configured for Mono8 output (camera PixelFormat=%s preserve_mono=%s)",
camera_pixel_format,
self._preserve_mono,
)
else:
self._converter.OutputPixelFormat = pylon.PixelType_BGR8packed
LOG.info(
"[Basler] Converter configured for BGR8 output (camera PixelFormat=%s preserve_mono=%s)",
camera_pixel_format,
self._preserve_mono,
)
def open(self) -> None:
if pylon is None:
raise RuntimeError("pypylon is required for the Basler backend but is not installed")
# ----------------------------
# Device enumeration & selection
# ----------------------------
devices = self._enumerate_devices()
if not devices:
raise RuntimeError("No Basler cameras detected")
device = self._select_device(devices)
self._camera = pylon.InstantCamera(pylon.TlFactory.GetInstance().CreateDevice(device))
self._camera.Open()
# Exposure
if getattr(self.settings, "exposure", 0) > 0:
try:
if hasattr(self._camera, "ExposureAuto"):
self._camera.ExposureAuto.SetValue("Off")
self._camera.ExposureTime.SetValue(float(self.settings.exposure))
LOG.info("[Basler] Exposure set to %s us (auto off)", self.settings.exposure)
except Exception as exc:
LOG.warning("[Basler] Failed to set exposure: %s", exc)
# Gain
if getattr(self.settings, "gain", 0.0) > 0.0:
try:
if hasattr(self._camera, "GainAuto"):
self._camera.GainAuto.SetValue("Off")
self._camera.Gain.SetValue(float(self.settings.gain))
LOG.info("[Basler] Gain set to %s dB (auto off)", self.settings.gain)
except Exception as exc:
LOG.warning("[Basler] Failed to set gain: %s", exc)
# ----------------------------
# Resolution (None → device default)
# ----------------------------
# Re-evaluate in case settings were rebound before open()
self._requested_resolution = self._get_requested_resolution_or_none()
self._configure_resolution()
# ----------------------------
# Frame rate (0.0 = Auto → do not set)
# ----------------------------
self._configure_frame_rate()
# ----------------------------
# Trigger configuration
# ----------------------------
self._debug_trigger_nodes(context="before configuration")
self._configure_trigger()
self._debug_trigger_nodes(context="after configuration")
try:
ns = self._ensure_mutable_ns()
ns["trigger_actual"] = self._trigger_to_dict(self._trigger)
except Exception:
pass
# ----------------------------
# Read back actual values (telemetry for GUI / probe)
# ----------------------------
try:
self._actual_fps = float(self._camera.AcquisitionFrameRate.GetValue())
except Exception:
self._actual_fps = None
try:
self._actual_width = int(self._camera.Width.GetValue())
self._actual_height = int(self._camera.Height.GetValue())
except Exception:
pass
try:
self._actual_exposure = float(self._camera.ExposureTime.GetValue())
except Exception:
self._actual_exposure = None
try:
self._actual_gain = float(self._camera.Gain.GetValue())
except Exception:
self._actual_gain = None
self._read_camera_pixel_format()
# ----------------------------
# Start acquisition (skip for fast probe)
# ----------------------------
if not self._fast_start:
# --- HARD RESET of stream state (critical after fast-start probe) ---
try:
if hasattr(self._camera, "StopGrabbing") and self._camera.IsGrabbing():
self._camera.StopGrabbing()
except Exception:
pass
# Converter BEFORE StartGrabbing
self._configure_converter()
# Force stream configuration reset
try:
if hasattr(self._camera, "MaxNumBuffer"):
self._camera.MaxNumBuffer.SetValue(10)
except Exception:
pass
self._camera.StartGrabbing(
pylon.GrabStrategy_LatestImageOnly,
)
LOG.info(
"[Basler] grabbing=%s max_buffers=%s",
self._camera.IsGrabbing(),
self._camera.MaxNumBuffer.GetValue() if hasattr(self._camera, "MaxNumBuffer") else "N/A",
)
else:
LOG.debug("Fast-start probe: skipping StartGrabbing and converter")
LOG.info(
"[Basler] open device_id=%s index=%s fast_start=%s requested=(%sx%s @ %s fps exp=%s gain=%s)",
getattr(self, "_device_id", None),
getattr(self.settings, "index", None),
getattr(self, "_fast_start", None),
getattr(self.settings, "width", None),
getattr(self.settings, "height", None),
getattr(self.settings, "fps", None),
getattr(self.settings, "exposure", None),
getattr(self.settings, "gain", None),
)
# ----------------------------
# Persist stable identity into namespace (migration-safe)
# ----------------------------
try:
serial = device.GetSerialNumber()
if serial:
ns = self._ensure_mutable_ns()
ns["device_id"] = str(serial)
try:
ns["device_name"] = str(device.GetFriendlyName())
except Exception:
pass
except Exception:
pass
def read(self) -> tuple[np.ndarray, float]:
if self._camera is None:
raise RuntimeError("Basler camera not opened")
if self._converter is None:
raise RuntimeError("Basler camera opened in fast-start probe mode; cannot read frames")
grab_result = None
try:
with self._timing.measure("Basler.retrieve"):
grab_result = self._camera.RetrieveResult(
int(getattr(self, "_retrieve_timeout_ms", 100)),
pylon.TimeoutHandling_ThrowException,
)
with self._timing.measure("Basler.check_result"):
if not grab_result.GrabSucceeded():
grab_result.Release()
grab_result = None
self._timing.note_error()
self._timing.maybe_log()
raise RuntimeError("Basler camera did not return an image")
with self._timing.measure("Basler.convert"):
image = self._converter.Convert(grab_result)
with self._timing.measure("Basler.get_array"):
frame = image.GetArray()
if not self._logged_first_frame:
self._logged_first_frame = True
LOG.info(
"[Basler] first frame device_id=%s shape=%s dtype=%s nbytes=%.2f MB "
"camera_pixel_format=%s output_format=%s preserve_mono=%s",
self._device_id,
frame.shape,
frame.dtype,
frame.nbytes / (1024 * 1024),
self._camera_pixel_format,
self.actual_output_format,
self._preserve_mono,
)
with self._timing.measure("Basler.release"):
grab_result.Release()
grab_result = None
if self._actual_width is None or self._actual_height is None:
h, w = frame.shape[:2]
self._actual_width = int(w)
self._actual_height = int(h)
self._timing.note_frame()
self._timing.maybe_log()
return frame, time.time()
except Exception as exc:
if grab_result is not None:
try:
grab_result.Release()
except Exception:
pass
if self.waits_for_hardware_trigger:
self._timing.note_timeout()
self._timing.maybe_log()
raise TimeoutError(f"Basler timeout while waiting for hardware trigger: {exc}") from exc
self._timing.note_error()
self._timing.maybe_log()
raise RuntimeError("Failed to retrieve image from Basler camera.") from exc
def close(self) -> None:
LOG.info(
"[Basler] close called camera_exists=%s grabbing=%s open=%s",
self._camera is not None,
bool(self._camera and self._camera.IsGrabbing()),
bool(self._camera and self._camera.IsOpen()),
)
if self._camera is not None:
if self._camera.IsGrabbing():
try:
self._camera.StopGrabbing()
except Exception:
pass
if self._camera.IsOpen():
try:
self._restore_trigger_idle()
except Exception:
pass
self._camera.Close()
self._camera = None
self._converter = None
def stop(self) -> None:
if self._camera is not None and self._camera.IsGrabbing():
try:
self._camera.StopGrabbing()
except Exception:
pass
def _enumerate_devices(self):
return self.__class__._enumerate_devices_cls()
def _select_device(self, devices):
# 1) Namespaced / cached stable identity (preferred)
serial = self._device_id
if serial:
for device in devices:
try:
if device.GetSerialNumber() == serial:
return device
except Exception:
continue
# 2) Legacy top-level fallback (read-only compatibility)
legacy = None
try:
legacy = self._props.get("serial") or self._props.get("serial_number")
except Exception:
legacy = None
if legacy:
for device in devices:
try:
if device.GetSerialNumber() == legacy:
return device
except Exception:
continue
# 3) Index fallback
index = int(self.settings.index)
if index < 0 or index >= len(devices):
raise RuntimeError(f"Camera index {index} out of range for {len(devices)} Basler device(s)")
return devices[index]
@staticmethod
def _snap_to_node(value: int, node) -> int:
"""
Best-effort clamp/snap for Basler integer nodes (Width/Height).
Works with real Pylon nodes and is unit-testable with fakes.
If node lacks GetMin/GetMax/GetInc, returns value unchanged.
"""
v = int(value)
try:
vmin = int(node.GetMin())
vmax = int(node.GetMax())
v = max(vmin, min(v, vmax))
except Exception:
# Node doesn't support min/max querying; keep as-is
return v
try:
inc = int(node.GetInc())
if inc > 1:
# snap down to nearest valid increment
v = vmin + ((v - vmin) // inc) * inc
except Exception:
pass
return int(v)
@property
def waits_for_hardware_trigger(self) -> bool:
role = str(self._trigger_attr(getattr(self, "_trigger", None), "role", "off") or "off").lower()
return role in {"external", "follower"}
@staticmethod
def _trigger_attr(trigger, name: str, default=None):
if isinstance(trigger, dict):
return trigger.get(name, default)
return getattr(trigger, name, default)
@staticmethod
def _trigger_to_dict(trigger) -> dict:
if trigger is None:
return {}
if isinstance(trigger, dict):
return dict(trigger)
if hasattr(trigger, "model_dump"):
try:
return trigger.model_dump(exclude_none=True)
except Exception:
pass
return {}
def _feature(self, name: str):
if self._camera is None:
return None
try:
return getattr(self._camera, name)
except Exception:
return None
@staticmethod
def _feature_value(feature, default=None):
if feature is None:
return default
try:
return feature.GetValue()
except Exception:
return default
@staticmethod
def _feature_symbolics(feature) -> list[str]:
if feature is None:
return []
for method_name in ("GetSymbolics", "GetEntries"):
try:
method = getattr(feature, method_name, None)
if method is None:
continue
values = method()
out = []
for value in values:
try:
if hasattr(value, "GetSymbolic"):
out.append(str(value.GetSymbolic()))
else:
out.append(str(value))
except Exception:
continue
return [v for v in out if v]
except Exception:
continue
return []
def _set_enum_feature(self, name: str, value: str, *, strict: bool = False) -> bool:
feature = self._feature(name)
if feature is None:
if strict:
raise RuntimeError(f"Basler feature '{name}' is not available")
LOG.debug("Basler feature '%s' is not available; skipping", name)
return False
symbolics = self._feature_symbolics(feature)
if symbolics and value not in symbolics:
if strict:
raise RuntimeError(f"Basler feature '{name}' does not support '{value}'. Available: {symbolics}")
LOG.warning("Basler feature '%s' does not support '%s'. Available: %s", name, value, symbolics)
return False
try:
feature.SetValue(value)
return True
except Exception as exc:
if strict:
raise RuntimeError(f"Failed to set Basler feature '{name}' to '{value}': {exc}") from exc
LOG.warning("Failed to set Basler feature '%s' to '%s': %s", name, value, exc)
return False
def _set_numeric_feature(self, name: str, value, *, strict: bool = False) -> bool:
feature = self._feature(name)
if feature is None:
if strict:
raise RuntimeError(f"Basler feature '{name}' is not available")
LOG.debug("Basler feature '%s' is not available; skipping", name)
return False
try:
feature.SetValue(value)
return True
except Exception as exc:
if strict:
raise RuntimeError(f"Failed to set Basler feature '{name}' to '{value}': {exc}") from exc
LOG.warning("Failed to set Basler feature '%s' to '%s': %s", name, value, exc)
return False
def _debug_trigger_nodes(self, *, context: str = "") -> None:
if not LOG.isEnabledFor(logging.DEBUG):
return
names = (
"TriggerSelector",
"TriggerMode",
"TriggerSource",
"TriggerActivation",
"TriggerDelay",
"TriggerDelayAbs",
"AcquisitionMode",
"LineSelector",
"LineMode",
"LineSource",
"LineInverter",
)
label = f"Basler trigger debug {context}".strip()
for name in names:
feature = self._feature(name)
if feature is None:
continue
value = self._feature_value(feature, None)
symbolics = self._feature_symbolics(feature)
extras = []
if symbolics:
extras.append(f"symbolics={symbolics}")
for method_name in ("IsReadable", "IsWritable"):
try:
method = getattr(feature, method_name, None)
if method is not None:
extras.append(f"{method_name}={method()}")
except Exception:
pass
LOG.debug("%s: %s=%r %s", label, name, value, " ".join(extras))
def _resolve_trigger_source(self, requested: str, *, strict: bool) -> tuple[str, bool]:
requested = str(requested or "auto").strip()
feature = self._feature("TriggerSource")
available = self._feature_symbolics(feature)
if not available:
if strict:
raise RuntimeError("Basler feature 'TriggerSource' is not available or has no symbolics")
LOG.warning("Basler feature 'TriggerSource' is not available; disabling trigger input.")
return requested, False