-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_multi_device.py
More file actions
executable file
·225 lines (173 loc) · 6.36 KB
/
example_multi_device.py
File metadata and controls
executable file
·225 lines (173 loc) · 6.36 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
#!/usr/bin/env python3
"""
Multi-device example: Control multiple Nimbie devices concurrently.
This example demonstrates how to:
1. Discover multiple Nimbie devices
2. Select specific devices for operations
3. Use persistent identifiers (port_numbers) for reliable device selection
4. Process disks concurrently on multiple Nimbies
"""
import time
from threading import Thread
from nimbie import NimbieStateMachine, list_devices, print_devices
def discover_devices():
"""Discover and display all connected Nimbie devices."""
print("=" * 70)
print("DEVICE DISCOVERY")
print("=" * 70)
# Use the convenience function to display all devices
print_devices()
# Or get device information programmatically
devices = list_devices()
if len(devices) == 0:
print("\n⚠️ No Nimbie devices found!")
print("Please connect at least one Nimbie device to continue.")
return None
return devices
def process_disk_on_device(device_info, target_drive):
"""Process disks on a specific Nimbie device.
Args:
device_info: Device information dict from list_devices()
target_drive: CD/DVD drive index for this Nimbie
"""
device_id = device_info["index"]
port = device_info["port_numbers"]
print(f"\n[Device {device_id}] Starting processing thread...")
# Option 1: Select by port_numbers (STABLE across reboots)
# Recommended for production use
sm = NimbieStateMachine(
target_drive=target_drive,
port_numbers=port,
)
# Option 2: Select by index (SIMPLE but not stable)
# Good for single session use
# sm = NimbieStateMachine(
# target_drive=target_drive,
# device_index=device_id,
# )
try:
# Check if disks are available
if not sm.get_hardware_state()["disk_available"]:
print(f"[Device {device_id}] No disks available")
return
print(f"[Device {device_id}] Processing disks...")
def process_disk():
"""Simple processing function."""
print(f" [Device {device_id}] Processing disk...")
time.sleep(2) # Simulate some work
print(f" [Device {device_id}] Done!")
return True # Accept the disk
# Process all available disks
stats = sm.process_batch(process_fn=process_disk)
print(f"[Device {device_id}] Complete! Processed {stats['total']} disks.")
finally:
sm.close()
def example_sequential():
"""Example: Process disks sequentially on multiple devices."""
print("\n" + "=" * 70)
print("EXAMPLE 1: Sequential Processing")
print("=" * 70)
print("Process disks on each Nimbie one at a time\n")
devices = discover_devices()
if not devices:
return
# Process on each device sequentially
for device in devices:
print(f"\nProcessing on device {device['index']}...")
process_disk_on_device(device, target_drive="1")
def example_concurrent():
"""Example: Process disks concurrently on multiple devices."""
print("\n" + "=" * 70)
print("EXAMPLE 2: Concurrent Processing")
print("=" * 70)
print("Process disks on multiple Nimbies at the same time\n")
devices = discover_devices()
if not devices:
return
if len(devices) < 2:
print("\n⚠️ Only one Nimbie found. Connect multiple devices for concurrent processing.")
return
# Create threads for each device
threads = []
for device in devices:
thread = Thread(
target=process_disk_on_device,
args=(device, "1"), # Adjust target_drive per device as needed
)
threads.append(thread)
thread.start()
# Wait for all threads to complete
for thread in threads:
thread.join()
print("\n✅ All devices finished processing!")
def example_persistent_config():
"""Example: Using persistent port_numbers configuration."""
print("\n" + "=" * 70)
print("EXAMPLE 3: Persistent Device Configuration")
print("=" * 70)
print("Use port_numbers for reliable device identification across reboots\n")
devices = discover_devices()
if not devices:
return
# Save configuration (in practice, save to config file)
config = {
"devices": [
{
"name": f"Nimbie-{d['index']}",
"port_numbers": d["port_numbers"],
"target_drive": "1",
}
for d in devices
]
}
print("\nGenerated configuration:")
import json
print(json.dumps(config, indent=2))
print("\n💡 Save this configuration to reliably identify devices")
print(" even after reboots or USB re-enumeration!")
# Use the configuration
print("\nUsing saved configuration to connect to first device...")
first_device_config = config["devices"][0]
sm = NimbieStateMachine(
target_drive=first_device_config["target_drive"],
port_numbers=tuple(first_device_config["port_numbers"]),
)
print(f"✅ Connected to {first_device_config['name']}")
print(f" Port: {first_device_config['port_numbers']}")
sm.close()
def main():
"""Main function to run examples."""
print("\n" + "=" * 70)
print("NIMBIE MULTI-DEVICE CONTROL EXAMPLES")
print("=" * 70)
while True:
print("\nSelect an example:")
print("1. Sequential processing (one device at a time)")
print("2. Concurrent processing (multiple devices simultaneously)")
print("3. Persistent configuration (using port_numbers)")
print("4. Discover devices only")
print("0. Exit")
try:
choice = input("\nEnter choice (0-4): ").strip()
if choice == "1":
example_sequential()
elif choice == "2":
example_concurrent()
elif choice == "3":
example_persistent_config()
elif choice == "4":
discover_devices()
elif choice == "0":
print("\nGoodbye!")
break
else:
print("Invalid choice. Please enter 0-4.")
except KeyboardInterrupt:
print("\n\nInterrupted by user. Exiting...")
break
except Exception as e:
print(f"\n❌ Error: {e}")
import traceback
traceback.print_exc()
if __name__ == "__main__":
main()