0
# Context & Device Management
1
2
Device discovery, enumeration, and management capabilities for fine-grained control over RealSense devices. Provides low-level access to device features, hotplug detection, and multi-device scenarios.
3
4
## Capabilities
5
6
### Context
7
8
Central hub for device discovery and management.
9
10
```python { .api }
11
class context:
12
def __init__(json_settings=None):
13
"""
14
Create a context for device management.
15
16
Args:
17
json_settings (str, optional): JSON configuration string
18
"""
19
20
def query_devices() -> device_list:
21
"""
22
Query all connected RealSense devices.
23
24
Returns:
25
device_list: Collection of available devices
26
"""
27
28
def query_devices(product_line) -> device_list:
29
"""
30
Query devices from specific product line.
31
32
Args:
33
product_line (product_line): Device family filter
34
35
Returns:
36
device_list: Filtered device collection
37
"""
38
39
def query_all_sensors() -> list[sensor]:
40
"""
41
Get all sensors from all devices.
42
43
Returns:
44
list[sensor]: All available sensors
45
"""
46
47
@property
48
def devices(self) -> device_list:
49
"""All connected devices."""
50
51
@property
52
def sensors(self) -> list[sensor]:
53
"""All sensors from all devices."""
54
55
def load_device(filename) -> device:
56
"""
57
Load recorded device from file.
58
59
Args:
60
filename (str): Path to .bag file
61
62
Returns:
63
device: Playback device
64
"""
65
66
def unload_device(filename):
67
"""
68
Unload previously loaded device.
69
70
Args:
71
filename (str): Path to .bag file
72
"""
73
74
def unload_tracking_module():
75
"""Unload tracking module if loaded."""
76
77
def get_sensor_parent(sensor) -> device:
78
"""
79
Get device that owns a sensor.
80
81
Args:
82
sensor (sensor): Sensor instance
83
84
Returns:
85
device: Parent device
86
"""
87
88
def set_devices_changed_callback(callback_function):
89
"""
90
Set callback for device connect/disconnect events.
91
92
Args:
93
callback_function: Called when devices change
94
"""
95
```
96
97
### Device List
98
99
Collection of discovered devices.
100
101
```python { .api }
102
class device_list:
103
def __len__() -> int:
104
"""Number of devices in list."""
105
106
def __getitem__(index) -> device:
107
"""Get device by index."""
108
109
def __iter__():
110
"""Iterate over devices."""
111
112
def size() -> int:
113
"""Number of devices in list."""
114
115
def contains(device) -> bool:
116
"""
117
Check if device is in list.
118
119
Args:
120
device (device): Device to check
121
122
Returns:
123
bool: True if device is present
124
"""
125
126
def front() -> device:
127
"""Get first device."""
128
129
def back() -> device:
130
"""Get last device."""
131
```
132
133
### Base Device
134
135
Core device interface with common functionality.
136
137
```python { .api }
138
class device:
139
def query_sensors() -> list[sensor]:
140
"""
141
Get all sensors on this device.
142
143
Returns:
144
list[sensor]: Device sensors
145
"""
146
147
@property
148
def sensors(self) -> list[sensor]:
149
"""All sensors on this device."""
150
151
def first_depth_sensor() -> depth_sensor:
152
"""
153
Get first depth sensor.
154
155
Returns:
156
depth_sensor: First depth sensor found
157
158
Raises:
159
rs.error: If no depth sensor available
160
"""
161
162
def first_roi_sensor() -> roi_sensor:
163
"""
164
Get first ROI sensor.
165
166
Returns:
167
roi_sensor: First ROI sensor found
168
"""
169
170
def first_pose_sensor() -> pose_sensor:
171
"""
172
Get first pose sensor.
173
174
Returns:
175
pose_sensor: First pose sensor found
176
"""
177
178
def first_color_sensor() -> color_sensor:
179
"""
180
Get first color sensor.
181
182
Returns:
183
color_sensor: First color sensor found
184
"""
185
186
def first_motion_sensor() -> motion_sensor:
187
"""
188
Get first motion sensor.
189
190
Returns:
191
motion_sensor: First motion sensor found
192
"""
193
194
def first_fisheye_sensor() -> fisheye_sensor:
195
"""
196
Get first fisheye sensor.
197
198
Returns:
199
fisheye_sensor: First fisheye sensor found
200
"""
201
202
def supports(camera_info) -> bool:
203
"""
204
Check if device supports specific information field.
205
206
Args:
207
camera_info (camera_info): Information field to check
208
209
Returns:
210
bool: True if information is available
211
"""
212
213
def get_info(camera_info) -> str:
214
"""
215
Get device information string.
216
217
Args:
218
camera_info (camera_info): Information field to retrieve
219
220
Returns:
221
str: Information value
222
223
Raises:
224
rs.error: If information not supported
225
"""
226
227
def hardware_reset():
228
"""Perform hardware reset of device."""
229
230
def is_connected() -> bool:
231
"""
232
Check if device is currently connected.
233
234
Returns:
235
bool: True if device is connected
236
"""
237
238
def is_metadata_enabled() -> bool:
239
"""
240
Check if metadata is enabled for frames.
241
242
Returns:
243
bool: True if metadata is enabled
244
"""
245
246
# Type checking methods
247
def is_updatable() -> bool:
248
"""Check if device supports firmware updates."""
249
250
def is_update_device() -> bool:
251
"""Check if device is in update mode."""
252
253
def is_auto_calibrated_device() -> bool:
254
"""Check if device supports auto-calibration."""
255
256
def is_playback() -> bool:
257
"""Check if device is a playback device."""
258
259
def is_recorder() -> bool:
260
"""Check if device is a recorder."""
261
262
# Type casting methods
263
def as_updatable() -> updatable:
264
"""Cast to updatable device."""
265
266
def as_update_device() -> update_device:
267
"""Cast to update device."""
268
269
def as_auto_calibrated_device() -> auto_calibrated_device:
270
"""Cast to auto-calibrated device."""
271
272
def as_playback() -> playback:
273
"""Cast to playback device."""
274
275
def as_recorder() -> recorder:
276
"""Cast to recorder device."""
277
```
278
279
### Specialized Device Types
280
281
#### Updatable Device
282
283
```python { .api }
284
class updatable(device):
285
def enter_update_state():
286
"""Enter firmware update mode."""
287
288
def create_flash_backup() -> bytes:
289
"""
290
Create backup of device firmware.
291
292
Returns:
293
bytes: Firmware backup data
294
"""
295
296
def create_flash_backup(progress_callback) -> bytes:
297
"""
298
Create firmware backup with progress callback.
299
300
Args:
301
progress_callback: Function called with progress updates
302
303
Returns:
304
bytes: Firmware backup data
305
"""
306
307
def update_unsigned(fw_image, update_mode=rs.update_mode.UPDATE):
308
"""
309
Update firmware with unsigned image.
310
311
Args:
312
fw_image (bytes): Firmware image data
313
update_mode (update_mode): Update mode flags
314
"""
315
316
def update_unsigned(fw_image, progress_callback, update_mode=rs.update_mode.UPDATE):
317
"""
318
Update firmware with progress callback.
319
320
Args:
321
fw_image (bytes): Firmware image data
322
progress_callback: Function called with progress updates
323
update_mode (update_mode): Update mode flags
324
"""
325
326
def check_firmware_compatibility(fw_image) -> bool:
327
"""
328
Check if firmware image is compatible.
329
330
Args:
331
fw_image (bytes): Firmware image to check
332
333
Returns:
334
bool: True if compatible
335
"""
336
```
337
338
#### Update Device
339
340
```python { .api }
341
class update_device(device):
342
def update(fw_image):
343
"""
344
Apply firmware update.
345
346
Args:
347
fw_image (bytes): Firmware image data
348
"""
349
350
def update(fw_image, progress_callback):
351
"""
352
Apply firmware update with progress.
353
354
Args:
355
fw_image (bytes): Firmware image data
356
progress_callback: Function called with progress updates
357
"""
358
```
359
360
#### Auto-Calibrated Device
361
362
```python { .api }
363
class auto_calibrated_device(device):
364
def write_calibration():
365
"""Write calibration data to device."""
366
367
def run_on_chip_calibration(json_content, timeout_ms) -> tuple[bytes, tuple[float, float]]:
368
"""
369
Run on-chip calibration.
370
371
Args:
372
json_content (str): Calibration configuration JSON
373
timeout_ms (int): Operation timeout
374
375
Returns:
376
tuple: (calibration_table, (health, accuracy))
377
"""
378
379
def run_on_chip_calibration(json_content, progress_callback, timeout_ms) -> tuple[bytes, tuple[float, float]]:
380
"""
381
Run on-chip calibration with progress.
382
383
Args:
384
json_content (str): Calibration configuration JSON
385
progress_callback: Function called with progress updates
386
timeout_ms (int): Operation timeout
387
388
Returns:
389
tuple: (calibration_table, (health, accuracy))
390
"""
391
392
def run_tare_calibration(ground_truth_mm, json_content, timeout_ms) -> tuple[bytes, tuple[float, float]]:
393
"""
394
Run tare calibration.
395
396
Args:
397
ground_truth_mm (float): Ground truth distance in mm
398
json_content (str): Calibration configuration JSON
399
timeout_ms (int): Operation timeout
400
401
Returns:
402
tuple: (calibration_table, (health1, health2))
403
"""
404
405
def process_calibration_frame(frame, timeout_ms) -> tuple[bytes, tuple[float, float]]:
406
"""
407
Process single calibration frame.
408
409
Args:
410
frame (frame): Calibration frame
411
timeout_ms (int): Operation timeout
412
413
Returns:
414
tuple: (calibration_table, (health1, health2))
415
"""
416
```
417
418
#### Device Calibration
419
420
Device with calibration trigger capabilities.
421
422
```python { .api }
423
class device_calibration(device):
424
def trigger_device_calibration(calibration_type) -> float:
425
"""
426
Trigger device calibration process.
427
428
Args:
429
calibration_type (calibration_type): Type of calibration to perform
430
431
Returns:
432
float: Calibration result value
433
"""
434
435
def register_calibration_change_callback(callback_function):
436
"""
437
Register callback for calibration changes.
438
439
Args:
440
callback_function: Function called when calibration changes
441
"""
442
```
443
444
#### Calibration Change Device
445
446
Device that can notify about calibration changes.
447
448
```python { .api }
449
class calibration_change_device(device):
450
def register_calibration_change_callback(callback_function):
451
"""
452
Register callback for calibration state changes.
453
454
Args:
455
callback_function: Function called when calibration state changes
456
"""
457
```
458
459
#### Debug Protocol
460
461
Low-level device communication interface.
462
463
```python { .api }
464
class debug_protocol:
465
def build_command(opcode, param1=0, param2=0, param3=0, param4=0, data=None) -> bytes:
466
"""
467
Build debug command packet.
468
469
Args:
470
opcode (int): Operation code
471
param1-param4 (int): Command parameters
472
data (bytes, optional): Additional data payload
473
474
Returns:
475
bytes: Command packet
476
"""
477
478
def send_and_receive_raw_data(command) -> tuple[int, bytes]:
479
"""
480
Send raw command and receive response.
481
482
Args:
483
command (bytes): Command packet
484
485
Returns:
486
tuple: (status_code, response_data)
487
"""
488
```
489
490
### Event Information
491
492
Device hotplug event data.
493
494
```python { .api }
495
class event_information:
496
def was_removed(device) -> bool:
497
"""
498
Check if device was removed.
499
500
Args:
501
device (device): Device to check
502
503
Returns:
504
bool: True if device was removed
505
"""
506
507
def was_added(device) -> bool:
508
"""
509
Check if device was added.
510
511
Args:
512
device (device): Device to check
513
514
Returns:
515
bool: True if device was added
516
"""
517
518
def get_new_devices() -> list[device]:
519
"""
520
Get list of newly added devices.
521
522
Returns:
523
list[device]: New devices
524
"""
525
```
526
527
## Usage Examples
528
529
### Device Discovery
530
531
```python
532
import pyrealsense2 as rs
533
534
# Create context and discover devices
535
ctx = rs.context()
536
devices = ctx.query_devices()
537
538
print(f"Found {len(devices)} RealSense device(s)")
539
540
for i, device in enumerate(devices):
541
print(f"\nDevice {i}:")
542
print(f" Name: {device.get_info(rs.camera_info.name)}")
543
print(f" Serial: {device.get_info(rs.camera_info.serial_number)}")
544
print(f" Firmware: {device.get_info(rs.camera_info.firmware_version)}")
545
print(f" Product Line: {device.get_info(rs.camera_info.product_line)}")
546
547
# List sensors
548
sensors = device.query_sensors()
549
print(f" Sensors: {len(sensors)}")
550
for j, sensor in enumerate(sensors):
551
if sensor.supports(rs.camera_info.name):
552
print(f" {j}: {sensor.get_info(rs.camera_info.name)}")
553
```
554
555
### Device Information
556
557
```python
558
import pyrealsense2 as rs
559
560
ctx = rs.context()
561
devices = ctx.query_devices()
562
563
if len(devices) == 0:
564
print("No devices found")
565
exit()
566
567
device = devices[0]
568
569
# Check all available information
570
info_types = [
571
rs.camera_info.name,
572
rs.camera_info.serial_number,
573
rs.camera_info.firmware_version,
574
rs.camera_info.physical_port,
575
rs.camera_info.debug_op_code,
576
rs.camera_info.advanced_mode,
577
rs.camera_info.product_id,
578
rs.camera_info.camera_locked,
579
rs.camera_info.usb_type_descriptor,
580
rs.camera_info.product_line
581
]
582
583
print("Device Information:")
584
for info_type in info_types:
585
if device.supports(info_type):
586
value = device.get_info(info_type)
587
print(f" {info_type.name}: {value}")
588
```
589
590
### Hotplug Detection
591
592
```python
593
import pyrealsense2 as rs
594
import time
595
596
def device_changed_callback(info):
597
devices = info.get_new_devices()
598
599
for device in devices:
600
if info.was_added(device):
601
print(f"Device connected: {device.get_info(rs.camera_info.serial_number)}")
602
elif info.was_removed(device):
603
print(f"Device disconnected: {device.get_info(rs.camera_info.serial_number)}")
604
605
ctx = rs.context()
606
ctx.set_devices_changed_callback(device_changed_callback)
607
608
print("Monitoring device connections. Press Ctrl+C to stop.")
609
try:
610
while True:
611
time.sleep(1)
612
except KeyboardInterrupt:
613
print("Stopping device monitoring")
614
```
615
616
### Multi-Device Setup
617
618
```python
619
import pyrealsense2 as rs
620
621
ctx = rs.context()
622
devices = ctx.query_devices()
623
624
if len(devices) < 2:
625
print("Need at least 2 devices for this example")
626
exit()
627
628
# Configure pipeline for each device
629
pipelines = []
630
configs = []
631
632
for i, device in enumerate(devices[:2]): # Use first 2 devices
633
serial = device.get_info(rs.camera_info.serial_number)
634
635
config = rs.config()
636
config.enable_device(serial)
637
config.enable_stream(rs.stream.depth, 640, 480, rs.format.z16, 30)
638
639
pipeline = rs.pipeline(ctx)
640
641
pipelines.append(pipeline)
642
configs.append(config)
643
644
print(f"Configured device {i}: {serial}")
645
646
# Start all pipelines
647
for i, (pipeline, config) in enumerate(zip(pipelines, configs)):
648
pipeline.start(config)
649
print(f"Started pipeline {i}")
650
651
try:
652
for frame_count in range(100):
653
for i, pipeline in enumerate(pipelines):
654
frames = pipeline.poll_for_frames()
655
if frames:
656
depth = frames.get_depth_frame()
657
if depth:
658
print(f"Device {i} frame {depth.get_frame_number()}")
659
660
finally:
661
for pipeline in pipelines:
662
pipeline.stop()
663
```
664
665
### Device Capabilities Detection
666
667
```python
668
import pyrealsense2 as rs
669
670
ctx = rs.context()
671
devices = ctx.query_devices()
672
673
for device in devices:
674
serial = device.get_info(rs.camera_info.serial_number)
675
print(f"\nDevice {serial} capabilities:")
676
677
# Check device types
678
capabilities = []
679
if device.is_updatable():
680
capabilities.append("Firmware Update")
681
if device.is_auto_calibrated_device():
682
capabilities.append("Auto-Calibration")
683
684
print(f" Device Types: {', '.join(capabilities) if capabilities else 'Basic'}")
685
686
# Check sensor types
687
sensor_types = []
688
try:
689
device.first_depth_sensor()
690
sensor_types.append("Depth")
691
except:
692
pass
693
694
try:
695
device.first_color_sensor()
696
sensor_types.append("Color")
697
except:
698
pass
699
700
try:
701
device.first_motion_sensor()
702
sensor_types.append("Motion")
703
except:
704
pass
705
706
try:
707
device.first_pose_sensor()
708
sensor_types.append("Pose")
709
except:
710
pass
711
712
print(f" Sensor Types: {', '.join(sensor_types)}")
713
714
# List stream capabilities
715
sensors = device.query_sensors()
716
for i, sensor in enumerate(sensors):
717
if sensor.supports(rs.camera_info.name):
718
sensor_name = sensor.get_info(rs.camera_info.name)
719
profiles = sensor.get_stream_profiles()
720
print(f" Sensor {i} ({sensor_name}): {len(profiles)} stream profiles")
721
```
722
723
### Firmware Update Example
724
725
```python
726
import pyrealsense2 as rs
727
728
ctx = rs.context()
729
devices = ctx.query_devices()
730
731
# Find updatable device
732
updatable_device = None
733
for device in devices:
734
if device.is_updatable():
735
updatable_device = device.as_updatable()
736
break
737
738
if not updatable_device:
739
print("No updatable devices found")
740
exit()
741
742
print(f"Found updatable device: {updatable_device.get_info(rs.camera_info.serial_number)}")
743
744
# Read firmware file
745
try:
746
with open("firmware.bin", "rb") as f:
747
fw_image = f.read()
748
749
print("Checking firmware compatibility...")
750
if updatable_device.check_firmware_compatibility(fw_image):
751
print("Firmware is compatible")
752
753
# Create backup first
754
print("Creating firmware backup...")
755
backup = updatable_device.create_flash_backup()
756
757
with open("firmware_backup.bin", "wb") as f:
758
f.write(backup)
759
print("Backup saved")
760
761
# Update firmware (commented out for safety)
762
# print("Updating firmware...")
763
# updatable_device.update_unsigned(fw_image)
764
# print("Firmware update complete")
765
766
else:
767
print("Firmware is not compatible with this device")
768
769
except FileNotFoundError:
770
print("Firmware file 'firmware.bin' not found")
771
except Exception as e:
772
print(f"Error: {e}")
773
```