Files
RadioPhotonic_PCB_PC_software/laser_control/example_usage.py
2026-02-18 19:01:28 +03:00

110 lines
3.5 KiB
Python

"""
Example: how to embed laser_control into any Python application.
Run:
python3 laser_control/example_usage.py
"""
import sys
import time
from laser_control import (
LaserController,
VariationType,
ValidationError,
CommunicationError,
)
def example_manual_mode(port: str = None):
"""Manual mode: set fixed temperatures and currents."""
with LaserController(port=port) as ctrl:
try:
ctrl.set_manual_mode(
temp1=25.0,
temp2=30.0,
current1=40.0,
current2=35.0,
)
print("Manual parameters sent.")
data = ctrl.get_measurements()
if data:
print(f" Temp1: {data.temp1:.2f} °C")
print(f" Temp2: {data.temp2:.2f} °C")
print(f" I1: {data.current1:.3f} mA")
print(f" I2: {data.current2:.3f} mA")
print(f" 3.3V: {data.voltage_3v3:.3f} V")
print(f" 5V: {data.voltage_5v1:.3f} V")
print(f" 7V: {data.voltage_7v0:.3f} V")
except ValidationError as e:
print(f"Parameter validation error: {e}")
except CommunicationError as e:
print(f"Communication error: {e}")
def example_variation_mode(port: str = None):
"""Variation mode: sweep current of laser 1."""
collected = []
def on_measurement(m):
collected.append(m)
print(f" t={m.timestamp.isoformat(timespec='milliseconds')} "
f"I1={m.current1:.3f} mA T1={m.temp1:.2f} °C")
with LaserController(port=port, on_data=on_measurement) as ctrl:
try:
ctrl.start_variation(
variation_type=VariationType.CHANGE_CURRENT_LD1,
params={
'min_value': 20.0, # mA
'max_value': 50.0, # mA
'step': 0.5, # mA
'time_step': 50, # µs
'delay_time': 5, # ms
'static_temp1': 25.0,
'static_temp2': 30.0,
'static_current1': 35.0,
'static_current2': 35.0,
}
)
print("Variation task started. Collecting data for 2 s...")
deadline = time.monotonic() + 2.0
while time.monotonic() < deadline:
ctrl.get_measurements()
time.sleep(0.15)
ctrl.stop_task()
print(f"Done. Collected {len(collected)} measurements.")
except ValidationError as e:
print(f"Parameter validation error: {e}")
except CommunicationError as e:
print(f"Communication error: {e}")
def example_embed_in_app():
"""
Minimal embedding pattern for use inside another application.
The controller can be created once and kept alive for the lifetime
of the host application. No GUI dependency whatsoever.
"""
ctrl = LaserController(port=None) # auto-detect port
try:
ctrl.connect()
except CommunicationError as e:
print(f"Cannot connect: {e}")
return ctrl
return ctrl # caller owns the controller; call ctrl.disconnect() when done
if __name__ == '__main__':
port = sys.argv[1] if len(sys.argv) > 1 else None
print("=== Manual mode example ===")
example_manual_mode(port)
print("\n=== Variation mode example ===")
example_variation_mode(port)