Light sources
A light source is a subtype of LightSource and carries properties::LightSourceProperties: the power unit, the requested power, whether it is on, and the allowed range. setpower sets the level, light_on and light_off switch it, and lights_off calls light_off on every light in a set, even after one fails, then reports every failure in one LightsOffError (a light whose switch-off failed may still be on).
A regulated laser diode is a DiodeLaser, typed by the quantity its controller holds: ConstantCurrent or ConstantPhotocurrent, fixed at construction. It is set with setcurrent! (mA), setoutputpower! (mW at the laser output) or setlevel! (0 to 1 of the declared range), and read back with measured_current, measured_photocurrent, indicated_output_power and loop_status. setpower is deprecated on a DiodeLaser: on a ConstantCurrent laser it forwards to setcurrent! (the value in mA) after a deprecation warning that Julia shows only under --depwarn=yes (under --depwarn=error it throws instead, before forwarding), and on a ConstantPhotocurrent laser it throws. The closed-loop calibration procedure of the TCube driver is in src/hardware_implementations/tcube_laser/CALIBRATION.md in the repository.
A light can take a modulator::AbstractModulationControl, which puts its level on an analog input as a voltage; NIDAQModulator, on the DAQ and FPGA boards page, is the DAQ implementation.
Light source interface
MicroscopeControl.HardwareInterfaces.LightSourceInterface — Module
This builds a generic interface for light sources: Laser, LED and Lamps
MicroscopeControl.HardwareInterfaces.LightSourceInterface.AbstractModulationControl — Type
AbstractModulationControlSomething that puts a LEVEL on a light's analogue input, in the light's own unit (mW in ConstantPhotocurrent, mA in ConstantCurrent, whatever a plain setpower takes), by driving a voltage: a DAQ analogue output (NIDAQModulator) or a recorder (RecordingModulator). (A Triggerscope DAC modulator follows in a later release.) It holds the scale (per_volt, the light's unit per volt), so setpower(modulator, p) is the whole conversation.
It is not an AbstractInstrument and has no panel. A modulator is built for one pairing of an output and a light; the claim in open_modulator! refuses a second light on the same output.
The four methods a modulator defines
[guarantee] of a type that <: AbstractModulationControl (checked by test/contract.jl):
setpower(mc, p::Float64): put levelpon the output;p = 0is 0 V. ThrowsArgumentErrorBEFORE any write whenpis out of the output's reach; any other throw leaves the output unknown.initialize(mc): open the output, leaving 0 V; or throw having released what it took.shutdown(mc): write 0 V, then release.output_id(mc)::String: names the physical output, for the claim.
export_state(mc) has a fallback (the type and output_id) and is a child of the light's.
How a light takes one
See LightSource and modulation_violations.
MicroscopeControl.HardwareInterfaces.LightSourceInterface.ConstantCurrent — Type
ConstantCurrent <: RegulationModeThe loop holds the diode DRIVE CURRENT constant (open loop, in Thorlabs' terms). Optical power follows diode efficiency, which drifts with temperature and age. Commanded with setcurrent!, in mA.
MicroscopeControl.HardwareInterfaces.LightSourceInterface.ConstantPhotocurrent — Type
ConstantPhotocurrent <: RegulationModeThe loop holds the MONITOR PHOTOCURRENT constant (closed loop, "constant power" in Thorlabs' terms). Optical power follows photodiode responsivity, which is temperature dependent: without a TEC-stabilised mount the delivered power drifts against a still setpoint. Commanded with setoutputpower!, in mW at the laser output, through the calibration held in PhotodiodeLoop.
There is deliberately no ConstantPower: the loop does not hold optical power anywhere, and the name would say it did.
MicroscopeControl.HardwareInterfaces.LightSourceInterface.DiodeLaser — Type
DiodeLaser <: LightSourceA laser diode driven by a controller that REGULATES something: drive current, or monitor photocurrent under photodiode feedback. Every DiodeLaser declares which, as a type parameter fixed at construction; see RegulationMode.
A light that is only modulated by an analogue voltage (CrystaLaser, VortranLaser, DaqTrLight) is NOT a DiodeLaser. It has no controller, no loop and no readback, and none of the generics in this file are defined for it.
A DiodeLaser carries, by name, the fields the shared panels and setlevel! read: unique_id, properties, min_current, max_current, threshold_current, drive_current and pd.
[guarantee] setpower(laser, mA) on a ConstantCurrent DiodeLaser forwards to setcurrent! with a deprecation warning, and means what it always did; the mode is a type parameter fixed at construction, so a forwarded call can never change unit. On a ConstantPhotocurrent DiodeLaser it throws, and setoutputpower! and the unit-free setlevel! replace it.
[limitation] InteractiveUtils.subtypes is one level deep, so subtypes(LightSource) lists DiodeLaser and not the drivers beneath it. Walk the hierarchy to its non-abstract leaves to enumerate devices.
MicroscopeControl.HardwareInterfaces.LightSourceInterface.LightSource — Type
LightSource is an abstract type that defines the interface for a light source.
A light that takes a modulator
[guarantee] TCubeLaser, SimDiodeLaser and SimLight carry modulator::Union{Nothing,AbstractModulationControl} (keyword modulator = nothing). With nothing every method runs the code it always did. With a modulator the light's level goes out as a voltage on an analogue input, through setpower(modulator, p) in the light's own unit; the modulator holds the scale (per_volt). [limitation] CrystaLaser, VortranLaser and DaqTrLight take none: their native path is already a DAQ voltage.
A light with a modulator follows this convention, and a new driver that takes one must:
- end
initializewithopen_modulator!, the output off (it claims the modulator'soutput_id, so a second light object cannot drive the same output, then opens it at 0 V); callclose_modulator!fromshutdown, after switching off; light_on: write level 0 BEFORE the enable (a throw enables nothing), do its own steps, thensetpower(modulator, request); every throw after the enable, anArgumentErrorincluded, switches the light off;light_off: write level 0 first, logging a failure, and always switch off, even for anInterruptExceptionin the write (switch off, then pass the interrupt on);- a level setter validates as it always did, then, only while the light is on, calls
setpower(modulator, p): the output holds 0 V while the light is off. AnArgumentError(the modulator refused before writing) changes nothing; any other throw leaves the output unknown, so level 0 is tried, the light is switched off, and the error is rethrown; - never use its native level path while it has a modulator.
MicroscopeControl.modulation_violations(light; set!, expect) checks 1 to 5 against a MicroscopeControl.RecordingModulator; a downstream package runs @test isempty(MicroscopeControl.modulation_violations(light; set! = l -> setpower(l, 2.0), expect = 2.0)) on an initialized light with its native side faked. See AbstractModulationControl for what a modulator defines.
MicroscopeControl.HardwareInterfaces.LightSourceInterface.LightSourceProperties — Type
LightSourcePropertiesGeneric properties for a light source.
Fields
power_unit::String: The unit of the power of the light source.power::Float64: The current power of the light source.is_on::Bool: Whether the light source is on or off.min_power::Float64: The minimum power of the light source.max_power::Float64: The maximum power of the light source.
MicroscopeControl.HardwareInterfaces.LightSourceInterface.LightsOffError — Type
LightsOffError(failures)Every failed switch-off, as light name => caught exception pairs in failures. showerror prints one line per failed light. Public as MicroscopeControl.LightsOffError, not exported.
MicroscopeControl.HardwareInterfaces.LightSourceInterface.PhotodiodeLoop — Type
PhotodiodeLoopState of a monitor-photodiode regulation loop. Present on a ConstantPhotocurrent laser and on no other (laser.pd === nothing).
The loop regulates PHOTOCURRENT. wa_calibration converts photocurrent into a power NUMBER at the LASER OUTPUT – the plane where it was measured with a power meter – and it does not make the loop hold optical power anywhere. Without a TEC-stabilised mount the photodiode's responsivity drifts with temperature, so delivered power drifts while photocurrent is held steady. That is why tec_stabilised has no default and may be missing.
Fields
wa_calibration::Float64: W/A at the laser output, rig-measured with a power meter. Conversion and display only.tia_range::Float64: A, full scale of the photodiode amplifier. The rig's STATEMENT of the controller's range setting (a rear-panel DIP switch on the TLD001);initializethrows if the controller disagrees.tec_stabilised::Union{Bool,Missing}: rig fact.missingis legitimate and is the only honest answer before it has been checked.max_current_clamp::Float64: mA. The drive-current clampinitializeprogrammed, as READ BACK from the controller, never as requested.NaNuntilinitializehas programmed and verified it; a laser whose clamp isNaNrefusessetoutputpower!.output_power_requested::Float64: mW at the laser output, the last requestsetoutputpower!completed.NaNbefore the first.photocurrent_requested::Float64: A. The DECODED setpoint the loop was actually given, which the downward-rounding encoding makes differ fromoutput_power_requested / wa_calibration.NaNbefore the first command.ramp_step_mW::Float64:Inf(the default) sends every setpoint as one write, ~10 ms. A finite value in mW makes the driver walk any larger upward step in increments of that size,ramp_step_sapart; downward steps are always one write. History (642 nm rig's TLD001, 2026-09-28/29): on one night a setpoint jumped from 0 to 10 mW locked the loop at ~90 mA / ~21 mW whatever the request, 3 times out of 3, while the same target reached in steps settled at 78 mA / 9.3 mW, as the Kinesis application does. Later the same night, after a Kinesis CONST P session, the jump worked 4 times out of 4 (9.30-9.31 mW). Ramped runs never failed (10 of 10, 10-70 mW). The cause is not known. The jump is the default because it is the fastest and was reliable when last tested; if the lock recurs (the symptom: ~90 mA and ~21 mW whatever is requested) construct the laser withramp_step_mW = 3.0, ramp_step_s = 0.01, which were verified on the rig: 1 mW steps worked at 2 s, 50, 20, 10 and 5 ms spacing; below ~10 ms the USB round trip per write (~15 ms) sets the pace; 3 mW steps at 10 ms reached 40 mW in 0.22 s (38.74 mW) and 70 mW in 0.38 s (68.59 mW).ramp_step_s::Float64: seconds between ramp steps. Default0.01.lock_check_s::Float64: seconds the driver waits after sending a setpoint before it compares the measured photocurrent with the request. Default0.2; at leastLOCK_CHECK_MIN_S.lock_ratio::Float64: the measured photocurrent may exceed the request by this factor before the driver reports a suspected loop lock. Default1.5.[limitation]this threshold and wait are unvalidated on hardware: the one lock observed measured about 98 uA for 44.6 uA requested (2.2x). A false trip refuses, which is the safe direction.ref_current_mA::Float64,ref_photocurrent_A::Float64: the calibration reference. The open-loop drive current, and the photocurrent in A the controller read at it, decoded with the sametia_rangeas the config states, recorded in the same session and on the same range and gain aswa_calibration(CALIBRATION.md). With one, the first power-modelight_onafter eachinitializere-measures it and refuses on a mismatch.NaN(both) means none: thatlight_onwarns once andcheck_lockis the only guard. The reference is in amps, decoded withtia_range, so a range the reading does not follow, or atia_rangerelabelled with W/A kept (the 642 nm rig's observation of 2026-09-29), fails the re-check. Re-measure W/A and the reference whenever the DIP switch moves.ref_ratio::Float64: the re-measured photocurrent must be within this factor ofref_photocurrent_A, either way. Default1.5: a 10x change in counts is caught with a wide margin, a scale drop under 1.5x passes, and the reading is proportional to (I - I_th), so a small margin above threshold is sensitive to ordinary drift. Choose the reference at least 20 mA above threshold.scale_checked::Bool: state,trueonce this initialize's re-check passed or was skipped for want of a reference.scale_refused::Bool: state,trueonce this initialize's re-check found a mismatch. Every later power-modelight_onrefuses without lighting the diode until the nextinitialize.zero_failed::Bool: state,trueonce a setpoint zero failed, until a zero lands (one that succeeds while the output is recorded on; the controller ignores a zero sent with the output off) orinitialize. The next power-modelight_onwarns that the controller's stored setpoint may be stale.
Construct it with the keyword form, which fills the last thirteen fields.
MicroscopeControl.HardwareInterfaces.LightSourceInterface.PhotodiodeLoop — Method
PhotodiodeLoop(; wa_calibration, tia_range, tec_stabilised,
ramp_step_mW=Inf, ramp_step_s=0.01, lock_check_s=0.2, lock_ratio=1.5,
ref_current_mA=nothing, ref_photocurrent_A=nothing, ref_ratio=1.5)The first three are required, and none has a default: a power-mode laser cannot be built without a measured calibration, a stated amplifier range and an answer (possibly missing) to whether the diode's temperature is stabilised. The rest are documented on PhotodiodeLoop.
MicroscopeControl.HardwareInterfaces.LightSourceInterface.RecordingModulator — Type
RecordingModulator(; id = "RecordingModulator", reach = Inf, sink = nothing)A test aid: an AbstractModulationControl that writes nothing and records everything. writes holds every level it accepted, attempts every level it was asked for (accepted or not), opened and closed count initialize and shutdown. Set failure to an exception to make every setpower, initialize and shutdown throw it; reach is the largest level it accepts (ArgumentError above it, before any write). sink, if given, is called with each accepted level, so a test can drive a faked device from it. Public, not exported; use it with modulation_violations.
MicroscopeControl.HardwareInterfaces.LightSourceInterface.RegulationMode — Type
RegulationModeThe quantity a DiodeLaser's controller holds constant: a type, not a flag, so that it is fixed per instance and can be dispatched on. The two modes are ConstantCurrent and ConstantPhotocurrent.
MicroscopeControl.HardwareInterfaces.LightSourceInterface.close_modulator! — Method
close_modulator!(light)shutdown light.modulator (0 V, then release), then release the claim. A failed shutdown keeps the claim and rethrows, so the next call retries it and no other light can take the output meanwhile. A no-op when there is no modulator or light holds no claim. A light calls it from its own shutdown, after switching off. Public, not exported.
MicroscopeControl.HardwareInterfaces.LightSourceInterface.indicated_output_power — Method
indicated_output_power(laser::DiodeLaser)measured_photocurrent x wa_calibration, in mW at the laser output. The inverse of setoutputpower!'s conversion, so a caller never recomputes it.
It is INDICATED, not measured: a conversion through a one-time bench calibration. With a drifting photodiode responsivity it stays flat while the light moves. Defined only for ConstantPhotocurrent lasers.
MicroscopeControl.HardwareInterfaces.LightSourceInterface.light_off — Method
light_off(lightsource::LightSource)Turn off the light source.
The DAQ voltage lights write before recording off; a failed switch-off throws and records is_on = true because emission cannot be ruled out. CrystaLaser and DaqTrLight keep the requested level for metadata and any staged request for a later enable. On a failed Vortran DO switch-off, AO 0 is also attempted, but the DO failure still throws and is_on stays true. AO 0 lowers the output rather than extinguishing it: measured output was 0.964 mW with DO on at 0 V, versus 13.53 nW with DO off (MicroscopeAdapt dev/test_laser.jl:25-26). Use lights_off to attempt every light during teardown even when one fails. Closing a control panel does not switch off its light.
Arguments
lightsource::LightSource: A LightSource type.
MicroscopeControl.HardwareInterfaces.LightSourceInterface.light_on — Method
light_on(lightsource::LightSource)Turn on the light source.
The stub used to take a second ipower::Float64 argument that no driver implemented. It was removed in 0.2.5 rather than implemented: "on at a power" has no definable unit across lights. Level setting and enabling remain separate operations with driver-specific units.
On CrystaLaser and DaqTrLight, setpower without a successful enable stages a voltage for the next successful light_on, which then clears level_staged. Without a staged request, light_on writes 1.0 V clamped to the voltage range, recording that default in level_requested and in properties.power when its unit is "V". A live setpower does not stage the next enable. light_off preserves the requested level and staging flag; shutdown and initialize preserve the level but cancel the stage: after a live 2.5 V command and switch-off, the export still reports 2.5 V, while the next unstaged enable writes 1.0 V. VortranLaser only enables DO and leaves AO unchanged.
Arguments
lightsource::LightSource: A LightSource type.
MicroscopeControl.HardwareInterfaces.LightSourceInterface.lights_off — Method
lights_off(lights)
lights_off(l1::LightSource, l2::LightSource, ...)Attempt light_off on every light, even after an exception (including an InterruptException). Return nothing on success; otherwise throw one LightsOffError retaining every named failure. Pass a tuple or vector of lights. An iterator or generator that throws during iteration stops the loop before its remaining lights can be attempted.
MicroscopeControl.HardwareInterfaces.LightSourceInterface.loop_status — Method
loop_status(laser::DiodeLaser)One consistent snapshot of the controller, as a NamedTuple:
word::UInt32: the raw status word;output_enabled,key,interlock,closed_loop,psu_ok:Bool;current_mA:[limitation]with the output OFF this is not a measurement: the 642 nm rig's TLD001 reported a "drive current" equal to its limit after a potentiometer change, with no current flowing (2026-09-28).saturated::Bool: the drive current is at its limit (bit0x400), reported only while the output is enabled (the raw bit is still inword). InConstantPhotocurrentmode this means the loop is at the clamp and the power is not being held;open_circuit,tia_over,tia_under:Bool. Either TIA flag invalidates the photocurrent reading;tia_range_A::Float64: the amplifier range the controller reports,NaNunless exactly one range bit is set;current_mA::Float64,photocurrent_A::Float64: the two readings;below_threshold::Union{Bool,Missing}:truewhen the output is enabled, a level has been commanded and the drive current sits below the declaredthreshold_current, i.e. the diode is not lasing and every power number is junk – a fault distinct fromsaturated.falsewhen the output is off or nothing has been commanded.missingwhenthreshold_currentis unknown (NaN): a skipped check must not read as a passed one.
It is the only place the status bits are decoded, so panels, fault checks and a rig's logger share one definition. [policy] a rig running unattended polls this and treats a sustained saturated as a fault: the driver reports, the system decides. The TCube driver also refuses at each power-mode setpoint when 0x400 is set (check_lock, 0.2.6); after that check, nothing watches it.
MicroscopeControl.HardwareInterfaces.LightSourceInterface.measured_current — Method
measured_current(laser::DiodeLaser)The diode drive current the controller reports, in mA. A reading, not a request. In ConstantPhotocurrent mode it is the diagnostic: a drive current climbing at a still setpoint is a blocked photodiode or an ageing diode.
MicroscopeControl.HardwareInterfaces.LightSourceInterface.measured_photocurrent — Method
measured_photocurrent(laser::DiodeLaser)The monitor photodiode current the controller reports, in A. The regulated quantity in ConstantPhotocurrent mode.
MicroscopeControl.HardwareInterfaces.LightSourceInterface.modulation_violations — Method
modulation_violations(light; set!, expect) -> Vector{String}Check that an INITIALIZED light, whose modulator is a RecordingModulator, follows the convention a light with a modulator keeps; an empty result means it does. A downstream package runs
@test isempty(MicroscopeControl.modulation_violations(light; set! = l -> setpower(l, 2.0), expect = 2.0))with its native side faked, where set! sets a level (in the light's own unit) and expect is what the modulator should then be asked for. It leaves the light off and the recorder cleared. It checks that:
- the light has a
modulatorfield that admitsnothing, holding aRecordingModulator; - a level set while the light is off writes nothing but 0;
light_onwrites level 0 first, then the levelexpect(a recorded request);- a level set while on reaches the modulator as
expect; - an
ArgumentErrorfrom the modulator reaches the caller and changes nothing (the light stays on, no 0 written); - any other throw from the modulator reaches the caller, level 0 is tried, and the light is off;
light_onwith a failing modulator throws and leaves the light off, andlight_offwith one does not throw;light_onwith a recorded level the modulator refuses (ArgumentErrorafter the enable) leaves the light off.
Public, not exported.
MicroscopeControl.HardwareInterfaces.LightSourceInterface.open_modulator! — Method
open_modulator!(light)Claim output_id(light.modulator) for light (refused if another light object holds it), then initialize the modulator, which leaves 0 V. If the initialize throws, the error is rethrown and the claim is released, unless the modulator still holds_resources (a task it could not delete): the claim, whether taken by this call or an earlier initialize, then stays until close_modulator! releases it. A no-op when light.modulator === nothing. A light calls it at the end of its own initialize, with its output off. Public, not exported.
MicroscopeControl.HardwareInterfaces.LightSourceInterface.output_id — Method
output_id(mc::AbstractModulationControl) -> StringNames the physical output ("NIDAQ Dev1/ao1"), the key of the claim that lets only one light object drive it. Public, not exported.
MicroscopeControl.HardwareInterfaces.LightSourceInterface.regulation_mode — Method
regulation_mode(laser::DiodeLaser)The laser's RegulationMode, as an instance: ConstantCurrent() or ConstantPhotocurrent(). To ask "do I command power here", write regulation_mode(laser) isa ConstantPhotocurrent.
There is no LightSource fallback: a light with no loop has no honest answer, and "is this a regulated diode" is answered by isa DiodeLaser.
MicroscopeControl.HardwareInterfaces.LightSourceInterface.setcurrent! — Method
setcurrent!(laser::DiodeLaser, current_mA::Float64)Command the diode DRIVE CURRENT, in mA. Defined only for ConstantCurrent lasers: where a loop owns the current this has no meaning, and the interface stub throws.
MicroscopeControl.HardwareInterfaces.LightSourceInterface.setlevel! — Method
setlevel!(light::LightSource, frac::Float64)Set the light to frac of its own declared operating range, frac in 0..1. Unit-free BY CONSTRUCTION: the endpoints come from the device, so no caller names a unit it cannot check.
For a DiodeLaser the mapping is LINEAR IN THE REGULATED QUANTITY:
ConstantCurrent:min_current + frac * (effective_max_current - min_current)mA, throughsetcurrent!;ConstantPhotocurrent:min_power + frac * (max_power - min_power)mW at the laser output, fromproperties, throughsetoutputpower!. The mW-to-photocurrent conversion is linear, so this is linear in the regulated photocurrent too.
frac = 0.0 is the bottom of the declared range, which is NOT off: use light_off. Code that must survive a switch between the two modes should drive the laser through this, not through the unit-true setters.
[limitation] Methods ship only for DiodeLaser. The voltage-modulated lights have no setlevel! method yet, and this stub throws for them.
MicroscopeControl.HardwareInterfaces.LightSourceInterface.setoutputpower! — Method
setoutputpower!(laser::DiodeLaser, power_mW::Float64)Command the optical power at the laser output, in mW – the plane where the wa_calibration of PhotodiodeLoop was measured with a power meter.
This is NOT power at the sample. Everything between the laser output and the sample – splitters, attenuators, fibres, objectives – belongs to the system that owns those parts, and no driver holds a field describing any of it.
Defined only for ConstantPhotocurrent lasers, where the number is the driver's own arithmetic over the photodiode calibration: a command, not a measurement.
MicroscopeControl.HardwareInterfaces.LightSourceInterface.setpower — Method
setpower(mc::AbstractModulationControl, p::Float64)Put level p, in the light's unit, on the modulator's output. p = 0 is 0 V. Throws ArgumentError before any write when p is out of the output's reach (not finite, below 0, or needing a voltage the output cannot make); any other throw leaves the output's level unknown, and the light darkens.
MicroscopeControl.HardwareInterfaces.LightSourceInterface.setpower — Method
setpower(laser::DiodeLaser, x::Float64)Deprecated for a ConstantCurrent laser, where it forwards to setcurrent! (x in mA, as it always was on a TCube) with a Base.depwarn. Julia shows that warning only when run with --depwarn=yes (as Pkg.test does), and with --depwarn=error the call throws before forwarding. The mode is a type parameter fixed at construction, so a forwarded call can never change unit. It throws for a ConstantPhotocurrent laser: an mA call must not become an mW one, so use setoutputpower! there, or the unit-free setlevel! on either.
MicroscopeControl.HardwareInterfaces.LightSourceInterface.setpower — Method
setpower(lightsource::LightSource,power::Float64)Set the power of the lightsource.
Arguments
lightsource::LightSource: A LightSource type.power::Float64: The power to set the lightsource to.
MicroscopeControl.HardwareInterfaces.LightSourceInterface.supported_modes — Method
supported_modes(::Type{<:DiodeLaser})The concrete RegulationMode types this device may be constructed in, as a tuple of types. The contract test expands a parametric device into its instantiations through this – a type parameter cannot be enumerated any other way – and a driver's inner constructor rejects a mode absent from it.
MicroscopeControl.export_state — Method
export_state(mc::AbstractModulationControl)The fallback: the modulator's type and its output_id. A driver adds what it knows (the scale, the range). A child of the light's export_state.
MicroscopeControl.gui — Method
gui(laser::DiodeLaser)Open the control panel for a regulated laser diode, chosen by its RegulationMode: current_panel for ConstantCurrent, power_panel for ConstantPhotocurrent.
[guarantee] opening either panel issues no command and no read. The readout is filled by its Read button, or by the Poll toggle, which starts off.
MicroscopeControl.gui — Method
gui(light::LightSource)Open a panel in the light's own unit and range, without issuing a command, and return its GLMakie.Screen. Text submissions issue one command even when the slider position does not change; invalid entries are refused at the box. Command failures are shown in the panel and the toggle follows the driver's state. Closing the panel does not switch off the light.
MicroscopeControl.initialize — Method
initialize(mc::AbstractModulationControl)Open the modulator's output leaving 0 V, or throw having released whatever it took. Called by open_modulator!, not by user code.
MicroscopeControl.shutdown — Method
shutdown(mc::AbstractModulationControl)Write 0 V, then release the output. Called by close_modulator!, not by user code.
Simulated light
MicroscopeControl.HardwareImplementations.SimulatedLight — Module
The simulated light source, SimLight, for tests and examples without hardware.
MicroscopeControl.HardwareImplementations.SimulatedLight.SimLight — Type
`SimLight` A SimulatedLight type inherited from `LightSource`.Fields
unique_id::String: A unique identifier for the light source.properties::LightSourceProperties: The properties of the light source.modulator::Union{Nothing,AbstractModulationControl}: What puts the level on the light's output, ornothing(the default: every method runs as it always did). With one,initializeopens it and leaves the light OFF (a light without one is on afterinitialize),light_onwrites level 0, then the recordedproperties.power,light_offandshutdownwrite 0 first, andsetpowerrecords and writes the level only while the light is on. AnArgumentErrorfrom the modulator changes nothing; any other throw darkens the light and is rethrown.SimLightis the plain-setpowerreference for the convention inLightSource.
MicroscopeControl.export_state — Method
export_state(light::SimLight)Simulated laser diode
MicroscopeControl.HardwareImplementations.SimulatedDiodeLaser — Module
SimulatedDiodeLaserA simulated twin of a regulated laser diode, SimDiodeLaser, on the same abstract type as the hardware driver, so a system field typed ::DiodeLaser accepts either.
MicroscopeControl.HardwareImplementations.SimulatedDiodeLaser.SimDiodeLaser — Type
SimDiodeLaser{M<:RegulationMode} <: DiodeLaserA simulated laser diode on a TLD001-like controller, in either mode. It carries the field names the shared panels and setlevel! read (unique_id, properties, min_current, max_current, threshold_current, drive_current, pd), reports the same loop_status layout as TCubeLaser, throws on every command and read before initialize and after shutdown (leaving every *_requested field unchanged), and records each call in log as a (verb, value) tuple – reads as well as commands, so a test can assert that something issued neither.
The diode model is three lines of physics, and is the point of the type:
P_true = efficiency * max(0, I - threshold_current) # mW at the laser output
photocurrent = responsivity * (1 + responsivity_drift) * P_true / 1000 # A
loop : I rises until photocurrent reaches the setpoint, or I reaches the clampIn ConstantCurrent mode I is the commanded current, limited by the clamp. In ConstantPhotocurrent mode the loop settles instantly. true_output_power returns P_true: the test oracle, on the simulation only, never an interface generic.
Model and fault fields
efficiency(mW/mA above threshold),responsivity(A/W at the monitor photodiode; defaults to1 / wa_calibration, so the calibration starts true),responsivity_drift(fractional; nonzero models a warming photodiode whose photocurrent the loop still holds while the light moves).tia_range_A: the simulated rear-panel DIP switch, in A. Defaults to the statedpd.tia_range(or 1 mA); set it differently to model a moved switch.key,interlock: the two interlocksinitializechecks in power mode.pd_blocked: the photodiode sees nothing, so the loop drives the current straight to the clamp.tia_over_fault,tia_under_fault: force the amplifier flags.settle_s: realsleepafter each command.modulator::Union{Nothing,AbstractModulationControl}: as onTCubeLaser, keyword defaultnothing. With one,initializeopens it,light_onwrites level 0, enables, then puts the request on it,light_offandshutdownwrite 0 first, and the level setters check and record as always but write only while the light is on (anArgumentErrorfrom the modulator changes nothing; any other throw darkens the light and is rethrown). The model's setpoint then follows the level the modulator was given, so the physics (true_output_power) shows what the output would; nothing else about the twin's model changes.[limitation]The twin has no MOD IN register, no settle window and no confirm.
MicroscopeControl.HardwareImplementations.SimulatedDiodeLaser.SimDiodeLaser — Method
SimDiodeLaser(; mode = ConstantCurrent(), kwargs...)Takes the mode and diode keywords of TCubeLaser, with the same meanings (both build the photodiode loop through diode_loop_from_keywords), but TCubeLaser checks some of them further against its controller, so a configuration the simulation accepts can still be refused by the hardware driver. The shared keywords: mode, unique_id, properties, min_current, max_current, threshold_current, the photodiode-loop keywords below and modulator. It does not take the serial number or TCubeLaser's controller and DAQ keywords (laser_color, controller_max_current, max_setcurrent, max_setpoint, drive_current, task_mod, daq, daq_device, ao_channel), and it adds its own model and fault keywords, documented on the type; so a system's construction line and its twin's share the diode keywords but are not the same line. mode defaults to ConstantCurrent(). In ConstantPhotocurrent mode wa_calibration, tia_range, tec_stabilised, properties and max_current are required, and the loop keywords ramp_step_mW, ramp_step_s, lock_check_s, lock_ratio, ref_current_mA, ref_photocurrent_A and ref_ratio are accepted into the PhotodiodeLoop. [limitation] the simulation neither ramps, checks for a loop lock, nor re-checks a calibration reference; it only stores them. threshold_current defaults to 65 mA and, in ConstantCurrent mode, max_current to 160 mA (the 642 nm diode's numbers); the model fields are documented on the type.
Unlike TCubeLaser, whose default properties are 0.2.4's "mW" labels, the default properties here are labeled "mA", as they have been since the type was added, because its values are mA.
MicroscopeControl.export_state — Method
export_state(sim::SimDiodeLaser)The same attribute names as export_state(::TCubeLaser), from field reads only.
Thorlabs TLD001 laser diode controller (T-Cube)
MicroscopeControl.HardwareImplementations.TCubeLaserControl — Module
TCubeLaserControlA Module for controlling a laser through a TCube Laser Controller. To power cotrol this laser, the module uses the Thorlabs Kinesis library. First, measure the optical power of the laser using a power meter before the laser beam gets coupled into the fiber. This is because the coupling efficiency might vary over time and it is not reliable to use the power meter after the fiber.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.TCubeLaser — Type
TCubeLaser{M<:RegulationMode} <: DiodeLaserA laser diode on a Thorlabs TLD001 T-Cube controller, in one of two regulation modes fixed at construction:
TCubeLaser{ConstantCurrent}: open loop. The controller holds the drive current; command it withsetcurrent!, in mA.TCubeLaser{ConstantPhotocurrent}: closed loop. The controller holds the monitor photodiode current; command it withsetoutputpower!, in mW at the laser output, converted throughpd.wa_calibration. SeeCALIBRATION.mdbeside this file for how that number is measured.
setpower(laser, mA) still works on a ConstantCurrent laser: it forwards to setcurrent! and is deprecated. On a ConstantPhotocurrent laser it throws, so that an 80 mA call can never become an 80 mW one.
Fields
unique_id::String: A unique identifier for the light source.properties::LightSourceProperties:is_onis the requested output state. InConstantPhotocurrentmodemin_power/max_powerare the ENFORCED bounds ofsetoutputpower!, in mW at the laser output, and the endpoints ofsetlevel!. InConstantCurrentmodepropertiesis labels only: nothing checks or enforcesmin_power/max_power. The default is 0.2.4'sLightSourceProperties("mW", 0.0, false, 0.0, 100.0), kept for compatibility although this driver's values are mA, so passLightSourceProperties("mA", ...)to label them truthfully.poweris deprecated: an open-loopsetcurrent!writes it as 0.2.4's figuredrive_current * properties.max_power / <controller limit>, an uncalibrated guess that is NOT inpower_unit's unit, and with the defaultpropertiesit is the same figure 0.2.4 gave;drive_currentis the number to read. AConstantPhotocurrentlaser never writespower.laser_color::String: The color of the laser.min_current::Float64: The lowest drive current this rig will command, in mA:setcurrent!'s floor andsetlevel!'s zero. Defaults to0.0. It is a lower bound, so it protects nothing on its own – the ceiling does.max_current::Float64: The caller's current ceiling in mA, i.e. the rig's own limit for this diode. Never overwritten byinitialize. InConstantPhotocurrentmode it is also the clampinitializeprograms into the controller's max-current potentiometer, because there the loop raises the current by itself.max_setcurrent::Float64: Full-scale current of the setpoint DAC, in mA.max_setpoint::Float64: Full-scale value of the setpoint DAC.serialNo::String: Thorlabs Kinesis serial number of the controller.task_mod: The NI-DAQmx task driving the analogue modulation input, or0beforesetupIOruns.daq::NIdaq: The DAQ carrying that modulation channel.controller_max_current::Float64: The controller's own diode current limit in mA, read fromLD_GetLaserDiodeMaxCurrentLimitbyinitialize.NaNuntilinitializeruns.daq_device::Union{Nothing,String}: DAQ device namesetupIOshould use.nothingkeeps the historical discovery behaviour (seesetupIO).ao_channel::Union{Nothing,String}: AO channel namesetupIOshould use.nothingkeeps the historical discovery behaviour (seesetupIO).drive_current::Float64: The drive current in mA thatsetcurrent!last accepted: the last accepted request, not what reached the wire (a request below one setpoint code encodes to zero).NaNbefore the first. It staysNaNfor the life of aConstantPhotocurrentlaser: the loop owns the current there, and a requested value would be a fiction. Readmeasured_currentfor what the controller reports.threshold_current::Float64: The diode's lasing threshold in mA, declared by the rig from a bench sweep (the controller cannot report it).NaNwhen unknown. Used by the panel marker and byloop_status'sbelow_thresholdcheck; never as a bound.pd::Union{Nothing,PhotodiodeLoop}: The photodiode loop's calibration and state; aPhotodiodeLoopexactly whenM === ConstantPhotocurrent,nothingotherwise.modulator::Union{Nothing,AbstractModulationControl}: What puts the level on the controller's rear MOD IN, ornothing(the default: every method then runs as it always did). Fixed at construction, because its claim, its output and the control source it needs belong to one modulator for life. See "With a modulator" below.source_before::Union{Nothing,Int}: State. The control sourceinitializefound, to restore atshutdown;nothingoutside an open/close cycle of a modulator.connected::Bool: State. Whetherinitializehas opened the Kinesis handle andshutdownhas not closed it. With a modulator, ashutdownretried after the handle closed touches no closed-handle call.generation::Threads.Atomic{Int},lock::ReentrantLock,arming::Bool: State of a light with a modulator, see "Locking" below;closing::Bool: ashutdownhas begun (no activation may arm or enable) until the nextinitialize.disable_pending::Bool: State. ALD_DisableOutputfailed and has not been retried; ashutdownretried after the handle closed reopens it to retry the disable.
The first fourteen fields are in the order they have always been in, and the two added in 0.2.5 and the two added since are at the end, so the pre-0.2.5 positional forms still construct: they build a TCubeLaser{ConstantCurrent} with all of them defaulted.
Locking (with a modulator)
[guarantee] Two locks. lock serializes the writes and state changes of initialize, a second light_on, the level setters and the MOD IN writes. usb_lock serializes only the Kinesis enable and disable commands, each a single call. light_on arms under lock (a generation bump, 0 V, the preflight, then the enable under usb_lock after a generation check, then USB 0), releases lock to sleep MOD_SETTLE_S, applies the CURRENT request under it, and polls the read-back and the lock check WITHOUT it, re-checking the generation before each write. A light_off or shutdown bumps generation, then disables under usb_lock right away, with no wait for lock and so none for a MOD IN write that is blocked on its transport; the MOD IN zero follows. No enable can follow a disable that superseded it. An activation that finds generation moved throws "superseded" and writes nothing more. [guarantee] shutdown is final: it sets closing before it disables, an activation that reaches the lock or the enable gate afterwards is refused, and shutdown disables again as its last hardware step before it closes; initialize clears closing. light_off is not final: a light_on that is linearized after it (it takes the lock later) may legitimately turn the light on again, and light_off's own disable is prompt either way. [limitation] With ONE Julia thread, a vendor call that blocks (a DAQmx scalar write stalled on its transport) blocks the thread that would run light_off too, up to the write's timeout (NIDAQModulator: 0.5 s by default). Issue light_off from another thread (julia -t 2, Threads.@spawn) to be independent of it. While arming, level setters record only (the activation applies the latest request); while on, they write MOD IN under lock. A USB setpoint is written only when the MOD IN zero succeeded in the same critical section, and never when the modulator is not open: then it is skipped and the output disabled. A light without a modulator takes no lock and runs as it always did.
With a modulator
TCubeLaser(serialNo; modulator = NIDAQModulator(...)) drives the setpoint through MOD IN instead of USB: a level change is one analogue write, not a USB setpoint and a lock check. [guarantee] With modulator = nothing none of this applies. With one:
initializeis as always (never enables; zeroes and disables first), then, with the output off, opens the modulator (0 V), records the control source (once per open/close cycle, so a secondinitializekeeps the first) and sets source 3 (software + external). Never 5 or 7: the front knob adds an offset.shutdownrestores the recorded source.light_onwrites 0 V, enables, sends USB setpoint 0 and reads it back, waitsMOD_SETTLE_S(1.3 s), puts the request on MOD IN, then CONFIRMS that the controller's setpoint register shows the request withinmax(30 words, 3 %). It refuses (output off, 0 V) otherwise: that catches a wrongper_volt, a dead cable, an unarmed control source and a MOD IN change the controller lost.[limitation]It costs 1.3 s more perlight_on, plus a read-back.setcurrent!,setoutputpower!(sosetlevel!and the panels' sliders) check and record as always, and, while the output is on, write the level to MOD IN: one write, no USB call, no fresh read, no lock check, no ramp. While off they write nothing. AnArgumentErrorfrom the modulator changes nothing; any other throw darkens the light and is rethrown.[limitation]Betweenlight_ons nothing watches the level; pollloop_status.light_off,shutdownand every failure path DISABLE FIRST (at once, without waiting for a MOD IN write) and then write 0 V (a failure is logged). No USB zero is sent after a modulated off: the controller ignores one with the output off, and the nextlight_onwrites USB 0 at 0 V after its enable. (initializeand the calibration-reference check still zero the USB setpoint before they disable, when the MOD IN level is known to be 0.)[limitation]The controller has ONE setpoint register: a USB write sets it outright (taking the MOD IN voltage then as reference) and MOD IN changes add their difference. So no USB setpoint is sent while the modulator holds a level: only 0, and the calibration reference, each at 0 V. A setpoint from other software (Kinesis) absorbs the voltage until the nextlight_on.
The setpoint only takes while the output is on
The Thorlabs TLD001 ignores LD_SetLaserSetPoint while its output is disabled and, on the next LD_EnableOutput, runs on whatever setpoint it had stored (observed on the 642 nm rig's TLD001 64849775, 2026-09-28). So a requested setpoint (setcurrent!, setoutputpower!) reaches the diode only because light_on sends it right after enabling, and light_off and shutdown zero the setpoint before disabling, so the next enable starts dark. (With a modulator they disable first and send no USB zero; see "With a modulator". The stored setpoint then stays at the 0 the last light_on wrote, and the register's MOD IN part is back at 0 V before the next enable.)
[limitation] Between the enable and the setpoint that follows it (one USB round trip) the controller runs on its stored setpoint: 0 after this driver's light_off or shutdown (with a modulator: 0 because every light_on wrote USB 0, after a failed disable-first cleanup possibly not), but anything up to the controller's current limit if other software left it there. In that window the current-limit potentiometer is the only hardware bound; set it at or below the diode's rating.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.TCubeLaser — Method
TCubeLaser(serialNo::String; kwargs...)Construct a TCubeLaser for the Kinesis device serialNo. Pure: it opens nothing, so every keyword is a declaration that initialize and setupIO later act on. The keywords match the field names documented on TCubeLaser.
mode defaults to ConstantCurrent(), which is exactly the 0.2.x behaviour, so no existing construction line changes meaning. Closed loop is chosen explicitly with mode = ConstantPhotocurrent(). The default will not change.
# 642 nm rig, closed loop. Calibration: see CALIBRATION.md beside this file.
laser = TCubeLaser("00000000";
mode = ConstantPhotocurrent(),
wa_calibration = 224.2, # W/A, measured with a power meter before the fibre
tia_range = 1e-3, # A: the rear-panel DIP switch, as set
tec_stabilised = missing, # honest until checked
threshold_current = 65.0, # mA, from a bench sweep
max_current = 150.0, # mA, your diode's rating: programmed as the loop's clamp
properties = LightSourceProperties("mW", 0.0, false, 1.0, 70.0)) # max_power 70.0 mW: your diode's rating
# The same diode in open loop.
laser = TCubeLaser("00000000"; mode = ConstantCurrent(), # mode is optional here: the default
min_current = 70.0, max_current = 150.0) # max_current: your diode's ratingIn ConstantPhotocurrent mode wa_calibration, tia_range, tec_stabilised, max_current and properties (whose min_power/max_power become the enforced mW bounds) are required: a rig cannot reach power mode without a measured calibration, a stated amplifier range, an answer to the temperature question and an explicit clamp. In ConstantCurrent mode passing any of the first three throws, and properties defaults to 0.2.4's LightSourceProperties("mW", 0.0, false, 0.0, 100.0): labels only in this mode, nothing enforces them (see the properties field).
max_currentis your ceiling for this diode and is never overwritten. InConstantCurrentmode it defaults to160.0; inConstantPhotocurrentmode it has no default, because it is the clampinitializeprograms and the only real protection while the loop raises the current by itself;initializerecords the controller's own limit separately incontroller_max_current, andsetcurrent!enforces the smaller of the two.ramp_step_mW,ramp_step_s,lock_check_s,lock_ratio,ref_current_mA,ref_photocurrent_Aandref_ratio(closed loop only; passing one in open loop throws; seePhotodiodeLoopand CALIBRATION.md) set the fields of the same names onPhotodiodeLoop, which documents them: an optional ramp of upward setpoint steps and the loop-lock check.min_currentdefaults to0.0. A non-zero default would reject safe small currents without protecting against large ones.modulatordefaults tonothing; see "With a modulator" onTCubeLaser.initializeopens it andshutdowncloses it.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.tcube_get_current — Method
tcube_get_current(light::TCubeLaser)Read the diode current the controller reports, in mA, with an explicit LD_RequestReadings and wait rather than the polled cache. Slower than measured_current, and independent of whether polling refreshes the cache.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.tcube_refresh — Method
tcube_refresh(light::TCubeLaser)Removed in v0.2.3. Always throws; reaches no hardware.
It used to open the device, enable the output, drive a hardcoded 90 mA, sleep a second, then disable and close – a bench procedure whose name warned nobody, and the one function here that could raise the current on a diode without being asked for a number. It is kept as a throwing stub rather than deleted so that using MicroscopeControl; tcube_refresh(laser) still resolves and explains itself, instead of failing with an UndefVarError that says nothing about what the call used to do.
MicroscopeControl.HardwareInterfaces.LightSourceInterface.indicated_output_power — Method
indicated_output_power(light::TCubeLaser{ConstantPhotocurrent})measured_photocurrent x pd.wa_calibration, in mW at the laser output. A conversion through a one-time calibration, not a measurement.
MicroscopeControl.HardwareInterfaces.LightSourceInterface.light_off — Method
light_off(light::TCubeLaser)Zero the setpoint while the output is still on, then disable the output, then record it (zero_then_disable). A failed zero is logged and does not throw, since the output is still turned off; a failed disable throws and leaves properties.is_on unchanged. The recorded request (drive_current, or pd.output_power_requested) is kept, so light_on returns to it. With a modulator the output is disabled first, at once, without waiting for the light's lock or a MOD IN write, and level 0 is written after (a failure is logged and does not stop the switch-off); no USB zero is sent.
MicroscopeControl.HardwareInterfaces.LightSourceInterface.light_on — Method
light_on(light::TCubeLaser)Enable the controller's output, then immediately send the setpoint the driver's recorded request asks for (intended_code) and confirm it, then record properties.is_on. The setpoint has to follow the enable: the controller ignores setpoints while its output is off (send_setpoint). Called while the output is already on, this re-sends the recorded request, replacing any lower value set from Kinesis or the front panel. If nothing has been requested yet, setpoint 0 is sent, with a warning. In ConstantCurrent mode drive_current is checked against the current ceiling before the enable, so nothing is sent if that throws.
If the setpoint cannot be sent or confirmed after the enable, the setpoint is zeroed, the output is disabled again and the original error rethrown (disable_after_failure). properties.is_on is then what the cleanup left: false if the disable succeeded, true if it failed too (both failures are logged), so a failed light_on never records a lit diode as off. In ConstantPhotocurrent mode the setpoint is ramped from 0 when the laser was built with a finite ramp_step_mW, and check_lock then runs; a suspected loop lock is a failure after the enable like any other, so the output is disabled and the error rethrown. check_lock is two-sided: it also refuses when the controller reports its current limit reached (0x400) or the photocurrent is below 1/lock_ratio of the request.
The first power-mode light_on after each initialize also runs the calibration-reference re-check (check_scale!): with a reference it drives the diode in open loop at ref_current_mA for about REFERENCE_DWELL_S + 2 x REQUEST_WAIT_S plus the setpoint confirm (not tied to lock_check_s), reads the photodiode and refuses on a mismatch, leaving the output off; a mismatch latches until the next initialize, and later light_on calls refuse without lighting the diode again. Without a reference it warns once and carries on.
A safety check that refuses while the output may be on zeroes and disables it first.
[limitation] Between the enable and the setpoint the controller runs on its stored setpoint, bounded in hardware only by its current-limit potentiometer; see TCubeLaser.
[limitation] Called while the output is already on with a finite ramp_step_mW, the ramp starts from 0 again, so the output dips to one step and ramps back up. That is deliberate: the ramp starts only from what the driver knows the controller holds, and a value set from the front panel would make any other starting point a jump.
A ConstantPhotocurrent laser refuses until initialize has programmed and verified its clamp (pd.max_current_clamp is not NaN), and re-checks the controller before it emits: a fresh status read must report closed loop and the photodiode range tia_range states, and a fresh read of the controller's limit must not exceed max_current, or the programmed clamp by more than 0.5 mA, about half a potentiometer step (a controller power cycle can restore the pot).
[limitation] those checks add two fresh reads (about 4 x REQUEST_WAIT_S), and check_lock adds lock_check_s plus about 4 x REQUEST_WAIT_S, to every closed-loop light_on and setoutputpower!; unvalidated on hardware.
With a modulator
Under the light's lock: write level 0 to the modulator (a throw enables nothing); require_clamp and check_scale! as above; enable (after a generation check); send USB setpoint 0 and read it back; arm. Unlocked: wait MOD_SETTLE_S (1.3 s). Under the lock again: if light_off, initialize, shutdown or another light_on took over meanwhile, throw and write nothing; else put the CURRENT request on the modulator. Then, unlocked, confirm that the setpoint register shows it (confirm_modulated_setpoint) and run check_lock in closed loop, re-checking the generation. A throw disables first and then writes 0, sending no USB zero, and rethrows. [limitation] One light_on costs 1.3 s more and a read-back; a second light_on while on reruns all of it, dark meanwhile. See light_on_modulated.
MicroscopeControl.HardwareInterfaces.LightSourceInterface.loop_status — Method
loop_status(light::TCubeLaser)One snapshot of the controller: the status word and both readings, all polled cache reads. See the interface's loop_status for the fields.
MicroscopeControl.HardwareInterfaces.LightSourceInterface.measured_current — Method
measured_current(light::TCubeLaser)The diode drive current the controller reports, in mA: a polled cache read (see POLL_INTERVAL_MS), decoded by setpoint_current. The reading is signed; -32768..32767 represents -220..+220 mA (Kinesis header).
MicroscopeControl.HardwareInterfaces.LightSourceInterface.measured_photocurrent — Method
measured_photocurrent(light::TCubeLaser)The monitor photodiode current the controller reports, in A: a polled cache read, scaled over the amplifier range – pd.tia_range in ConstantPhotocurrent mode, and in ConstantCurrent mode the range the status word reports (NaN if it reports none). The reading is signed (a small negative offset at idle); a raw value outside ±32767 is a protocol error and throws.
Available in both modes. In open loop it is what a W/A calibration is measured against; see CALIBRATION.md.
MicroscopeControl.HardwareInterfaces.LightSourceInterface.setcurrent! — Method
setcurrent!(light::TCubeLaser{ConstantCurrent}, current::Float64)Set the diode drive current, in mA.
Validates through check_current, so an out-of-range request throws before anything reaches the controller, and encodes through setpoint_code, whose guarantee is that the decoded current never exceeds the requested one. With the output on – the driver recorded it on, or a fresh status read reports it (not the polled word, which can lag a light_off by one poll) – the setpoint is sent and confirmed from the controller's read-back. A stale status bit can no longer drop a request silently: the send is attempted and confirmed, or it throws. With the output off, it is recorded and light_on applies it right after enabling – the controller would ignore it now (send_setpoint).
The bottom of the range commands nothing
Because the encoding only ever rounds down, a positive request smaller than one code encodes to code 0: at the default scale that is any request below 220 / 32767 ≈ 0.006714 mA, so a zero current setpoint is sent. That is not the same as turning the laser off: this path does not disable the output and does not touch properties.is_on. Use light_off to stop emission. Rounding such a request up would command more current than was asked for, which is the rule this driver will not break – but drive_current records the requested current, not the zero that was commanded.
On success, light.drive_current holds the accepted current, in mA, and the deprecated properties.power holds legacy_power's figure, as it did in 0.2.4.
[limitation] With the output on, a setpoint the controller does not confirm throws and leaves the output on, at a setpoint that may be the new or the old one. There is no cleanup: 0.2.4's setpower never disabled on a failed write.
With a modulator, the same checks run, and then, with the output on (the driver's record), the level is written to the modulator: one write, no USB call, no read-back, no wait. With the output off nothing is written. An ArgumentError from the modulator changes nothing (the old level stays recorded); any other throw writes 0 (tried), disables the output and rethrows.
MicroscopeControl.HardwareInterfaces.LightSourceInterface.setoutputpower! — Method
setoutputpower!(light::TCubeLaser{ConstantPhotocurrent}, power_mW::Float64)Command the optical power at the laser output, in mW – the plane where pd.wa_calibration was measured. Not the power at the sample.
- Refuse unless
initializeprogrammed the clamp, and re-check the controller: a fresh status read must report closed loop and the photodiode rangetia_rangestates, and a fresh limit read must not exceedmax_current, or the programmed clamp by more than 0.5 mA, about half a potentiometer step.[limitation]this adds two fresh reads (about 4 xREQUEST_WAIT_S), andcheck_lock(step 6) addslock_check_splus about 4 xREQUEST_WAIT_S, to every call; unvalidated on hardware. check_poweragainstproperties.min_power..max_power.- Decide on the fresh status word step 1 returned: refuse unless it reports closed loop, or if the photodiode amplifier is over range (the status flag, or, with the output on, a fresh photocurrent word of -32768). An under-range flag with the output on only warns (the resolution is reduced; the loop still regulates, as seen at 1 mW on the 642 nm rig); with the output off it is expected and ignored.
- Convert: photocurrent
= power_mW / 1000 / wa_calibrationA, encoded byphotocurrent_code, rounding DOWN; above full scale it throws naming the DIP switch. - With the output on (the driver recorded it on, or the fresh status word reports it; a stale status bit cannot drop the send silently, it is attempted and confirmed or it throws), send and confirm the setpoint (
send_setpoint_ramped, ramping from the code of the previous request,0if none); with it off, leave it forlight_on(send_setpoint). - With the output on,
check_lockafter sending. A send or confirm failure, a suspected lock, a current limit reached (0x400) or a photocurrent below 1/lock_ratioof the request zeroes and disables the output, logs, and rethrows (disable_after_failure);properties.is_onistrueafterwards only if the disable failed. The request is not recorded. - Record
pd.output_power_requestedand the DECODEDpd.photocurrent_requested.
A safety check that refuses while the output may be on zeroes and disables it first.
[limitation] the lock check's threshold and wait are unvalidated on hardware (see check_lock).
It never touches drive_current: the loop owns the current. Whether the light at the output matches is a question for a power meter; see indicated_output_power and loop_status.
With a modulator
Steps 2 and 4 run (the clamp must have been programmed; the request is checked against properties and the amplifier's full scale), and then, with the output on (the driver's record), the level is written to the modulator: one write, with no USB call, no fresh read, no check_lock and no ramp (a MOD IN jump from 0 V never locked the loop, 15 of 15). With the output off nothing is written. An ArgumentError from the modulator changes nothing; any other throw writes 0 (tried), disables the output and rethrows. [limitation] Between light_ons nothing watches the level; poll loop_status.
MicroscopeControl.export_state — Method
export_state(light::TCubeLaser, ignored)Deprecated forwarder to export_state(::TCubeLaser). Warns once per session and ignores its second argument, which was never read.
It is kept because removing it would be a break for no benefit. The bug was the absence of the 1-argument method – export_state(laser) matched nothing on this type and fell through to the throwing instrument-level stub – so adding that method is the whole fix, and a caller that had to pass a second argument to get anything at all keeps working. The forwarder is scheduled for removal at the next breaking release.
MicroscopeControl.export_state — Method
export_state(light::TCubeLaser)Snapshot for HDF5 serialization. Pure field reads: no transport call, so its cost and failure modes do not depend on the controller. It records what was COMMANDED and configured, not what was measured – evidence that the loop held its setpoint comes from loop_status, which a rig logs with its own timestamps.
Every laser: regulation_mode ("ConstantCurrent"/"ConstantPhotocurrent"), setpoint_unit ("mA"/"mW"), min_current_mA, max_current_mA, controller_max_current, threshold_current_mA, drive_current, is_on and the identifiers and DAQ names.
ConstantPhotocurrent also: power_reference ("laser output"), min_output_power_mW, max_output_power_mW, wa_calibration_W_per_A, tia_range_A, tec_stabilised ("true"/"false"/"unknown"), max_current_clamp_mA, output_power_requested_mW, photocurrent_requested_A.
0.2.4's keys are kept in both modes, with 0.2.4's values: min_current, max_current (the fields, in mA), power_unit, power, min_power and max_power (from properties). power is the deprecated uncalibrated linear guess described in legacy_power, written only by open-loop setcurrent!; read drive_current instead.
MicroscopeControl.initialize — Method
initialize(light::TCubeLaser)Open the controller, start background polling (POLL_INTERVAL_MS), put it in the laser's RegulationMode, and record the controller's own diode current limit in light.controller_max_current. It never enables the output, and it leaves it OFF: in both modes, right after polling starts and before the mode command is sent, it zeroes the setpoint and disables the output (zero_then_disable), so the mode command is never sent while the diode is lit and properties.is_on is false afterwards. Polling starts first because the setpoint read-back that every verified write depends on only refreshes through it (see SETPOINT_CONFIRM_TIMEOUT_S).
ConstantCurrent: LD_SetOpenLoopMode, then a fresh status read that confirms open loop (it throws if the controller still reports closed loop), then the limit read. If the controller's limit is above max_current, the potentiometer is then lowered until it is not (lower_open_loop_clamp!) and controller_max_current is the limit that results; if it is at or below max_current the potentiometer is never touched, so a limit a rig set lower by hand stays. If lowering fails, it warns the same way and goes on, so initialize never fails here where 0.2.4 did not; light_on then refuses while the current limit stored in the controller is above max_current. [limitation] the open-loop potentiometer lowering is unvalidated on hardware beyond the 642 nm rig's closed-loop sequence; not yet run on hardware in open loop.
ConstantPhotocurrent – the closed-loop entry sequence. Every step is a refusal that cannot be retrofitted after a diode is damaged, so none may be simplified away:
- Read the status bits. Require the key switch (
0x2) and the interlock (0x8); throw naming which is missing. - Decode the photodiode amplifier range from
0x10-0x80: exactly one bit, or throw; and throw if it disagrees withpd.tia_range, naming both and the rear-panel switch. A range moved between sessions is a silent factor-of-ten error in every commanded power.[limitation]the check reads the status bits; on the 642 nm rig the photodiode words did not follow a DIP switch move that the bits did (2026-09-29, rig check R4). The calibration reference is the check that does not depend on the bits. - Program the clamp, the only real protection in power mode, because the loop raises current by itself to hold its setpoint (and a blocked photodiode drives it straight to the clamp):
program_clamp!leaves the max-current potentiometer at the highest position whose limit, as the controller itself reports it after leaving adjust mode, is<= max_current.pd.max_current_clamprecords that reported limit, never a request or a value computed from a position (the header's position scale is wrong on the rig's controller; seeDIGPOT_STEP_ESTIMATE_mA). LD_SetClosedLoopMode, then re-read the bits and require0x4.LD_SetWACalibFactor(pd.wa_calibration)and read it back withinCfloattolerance, so the front panel and this driver display the same number. The factor scales the controller's display only; the driver does its own conversion.
The calibration-reference re-check is not run here: initialize never emits. It runs at the first power-mode light_on after each initialize.
If any step after LD_Open fails, the handle is closed before the error propagates – a half-open controller refuses the next LD_Open and so blocks the retry – and the original error is the one raised. If the initial disable itself fails, properties.is_on is set true, since the diode may still be lit, and the same cleanup stops polling and closes. A power-mode failure leaves the output off. It sets pd.max_current_clamp to NaN first, so a failed re-initialize cannot leave a stale clamp.
It deliberately does not touch light.max_current: that field is the caller's ceiling for this diode, and overwriting it with the controller's (typically 160-220 mA) limit silently widened the range setcurrent! validates against, so a rig that asked for an 80 mA ceiling got the controller's instead.
With a modulator the sequence ends, the output still off, with begin_modulation!: the modulator is opened (its output claimed, 0 V), the control source is recorded (once per open/close cycle: a second initialize keeps the first) and set to 3, software + external (never 5 or 7: the front knob adds an offset). A failure there releases the modulator, closes the handle as for any other failed step and is the error raised.
Hardware-verified on the 642 nm rig's TLD001 (64849775, 2026-09-28), output off: polling refreshes the setpoint cache; a plain potentiometer set is ignored and adjust mode is required, with a pause before leaving it; the limit the controller reports is the truth, not the header's scale; entering closed loop sets status bit 0x4; the W/A factor reads back. [limitation] the second flag of LD_EnableMaxCurrentAdjust (always passed false) is not verified.
MicroscopeControl.red_laser_gui — Function
red_laser_gui(laser) -> GLMakie.ScreenThe same function as gui, under the name this module exports for the TCubeLaser. A TCubeLaser is a DiodeLaser, so the call opens the panel for its regulation mode (ConstantCurrent or ConstantPhotocurrent) and issues no command and no read; the readout fills from the panel's Read button or its Poll toggle. Needs a display (GLMakie).
MicroscopeControl.shutdown — Method
shutdown(light::TCubeLaser)Zero the setpoint and disable the output (zero_then_disable), stop polling and close the connection. A failed zero is logged; a failed disable throws, but the connection is closed either way: leaving the Kinesis handle open would also block the reconnection a caller needs in order to retry the disable.
With a modulator: the output is disabled first, at once; then level 0 is written and, only if the disable succeeded, the control source recorded by initialize is restored and the modulator closed (0 V, then its output is released). A failure there is thrown after the connection is closed, and the output stays claimed until the next shutdown retries it. A disable that failed stays pending: the source and the claim are kept, and the next shutdown reopens the handle to retry it.
CrystaLaser 561 nm
MicroscopeControl.HardwareImplementations.CrystaLaserControl — Module
CrystaLaserControlA Module for controlling a laser through a NIDAQ card.
MicroscopeControl.HardwareImplementations.CrystaLaserControl.CrystaLaser — Type
CrystaLaser(; daq=NIdaq(), channel=nothing, properties, ...)A single AO line controls both level and emission. setpower takes volts and stages the request unless line_enabled permits a write. The next successful light_on applies a staged request and clears level_staged. With no staged request, light_on writes 1.0 V clamped to the voltage range and records that default. initialize, light_off and shutdown write 0 V before recording off. All preserve the requested level (initially NaN); only light_off preserves a pending stage. A failed off records possible emission (is_on = true) but revokes permission to write levels (line_enabled = false).
A named channel skips discovery. Otherwise the legacy device/channel selection applies. Default properties use volts and the voltage bounds. A supplied properties object is kept unchanged; accepted commands update its power only when its unit is "V".
MicroscopeControl.laser_561_gui — Function
laser_561_gui(light::LightSource) -> GLMakie.ScreenThe same function as gui, under the name this module exports for its light. For a CrystaLaser it opens a panel in the light's own power unit and range and returns its GLMakie.Screen; opening the panel issues no command. Closing the panel does not switch the light off. Needs a display (GLMakie).
MicroscopeControl.nidaq_gui — Function
nidaq_gui(device)Another name for gui, the one function every device's control panel is a method of. CrystaLaserControl, VortranLaserControl and TransmissionDaqControl each export it next to their light type, so nidaq_gui(card) on an NIdaq opens the DAQ card's panel and nidaq_gui(light) opens the light's. Needs a display (GLMakie).
Vortran 488 nm
MicroscopeControl.HardwareImplementations.VortranLaserControl — Module
LaserDaqControlA Module for controlling a laser through a NIDAQ card.
MicroscopeControl.HardwareImplementations.VortranLaserControl.VortranLaser — Type
VortranLaser(; daq=NIdaq(), ao_channel=nothing, do_channel=nothing, properties, ...)The AO line sets the requested level in volts; the DO line enables emission. Named channels skip discovery for those outputs. Unnamed channels retain the legacy selection: device 1, AO index 2, DO index 12. The initial AO request is NaN (unknown); initialize only disables DO. shutdown attempts both DO 0 and AO 0, recording each successful command and reporting every failure.
Default properties use volts and the voltage bounds. A supplied properties object is kept unchanged; accepted commands update its power only when its unit is "V".
MicroscopeControl.laser_488_gui — Function
laser_488_gui(light::LightSource) -> GLMakie.ScreenThe same function as gui, under the name this module exports for its light. For a VortranLaser it opens a panel in the light's own power unit and range and returns its GLMakie.Screen; opening the panel issues no command. Closing the panel does not switch the light off. Needs a display (GLMakie).
Transmitted light on a DAQ output
MicroscopeControl.HardwareImplementations.TransmissionDaqControl — Module
TransmissionDaqControlA Module for controlling transmission light through a NIDAQ card. Citation: Ali Kazemi Nasaban Shotorban & Sheng Liu, Lidke Lab, UNM
MicroscopeControl.HardwareImplementations.TransmissionDaqControl.DaqTrLight — Type
DaqTrLight(; daq=NIdaq(), channel=nothing, properties, ...)A single AO line controls both level and emission. setpower takes volts and stages the request unless line_enabled permits a write. The next successful light_on applies a staged request and clears level_staged. With no staged request, light_on writes 1.0 V clamped to the voltage range and records that default. initialize, light_off and shutdown write 0 V before recording off. All preserve the requested level (initially NaN); only light_off preserves a pending stage. A failed off records possible emission (is_on = true) but revokes permission to write levels (line_enabled = false).
A named channel skips discovery. Otherwise the legacy device/channel selection applies. Default properties use volts and the voltage bounds. A supplied properties object is kept unchanged; accepted commands update its power only when its unit is "V".
MicroscopeControl.tr_light_gui — Function
tr_light_gui(light::LightSource) -> GLMakie.ScreenThe same function as gui, under the name this module exports for its light. For a DaqTrLight it opens a panel in the light's own power unit and range and returns its GLMakie.Screen; opening the panel issues no command. Closing the panel does not switch the light off. Needs a display (GLMakie).
Light source internals
Helpers the interface and the drivers define but do not make public: the diode-loop checks, the modulator helpers other than the public lifecycle functions (open_modulator!, close_modulator! and the rest are in the interface section above), and the Kinesis SDK bindings of the TCube driver.
MicroscopeControl.HardwareInterfaces.LightSourceInterface.LOCK_CHECK_MIN_S — Constant
LOCK_CHECK_MIN_SThe shortest lock_check_s a PhotodiodeLoop accepts, in s: 0.1. The floor gives the loop time to settle before check_lock reads; check_lock makes its own reads and does not depend on polling. Below it the photodiode is read before the loop has answered a new setpoint. At 0, before 0.2.6, the lock check read the polled cache before the loop moved and could never trip; with the two-sided check it would trip on every upward step.
MicroscopeControl.HardwareInterfaces.LightSourceInterface.STATUS_BITS — Constant
STATUS_BITSThe controller status-word layout the DiodeLaser drivers in this package report, which is the Thorlabs TLD001's (LD_GetStatusBits, from the Kinesis header): one definition, shared by the TCube driver and its simulated twin so that loop_status reads the same from both.
MicroscopeControl.HardwareInterfaces.LightSourceInterface.TIA_RANGE_BITS — Constant
TIA_RANGE_BITSPhotodiode amplifier range, in A of full scale, for each range bit of STATUS_BITS.
MicroscopeControl.HardwareInterfaces.LightSourceInterface._attach_output_toggle! — Method
_attach_output_toggle!(fig, row, laser, message)On/off toggle, initialised from properties.is_on so opening the panel does not impose a state. The slider's lowest position is not "off"; this is.
The label follows the driver, not the click: after every command it shows properties.is_on, whatever the command did, and if the toggle disagrees (a failed light_off leaves the diode on) the toggle is put back, under a guard that keeps the correction from firing light_on/light_off again. Returns (; toggle, status, poll_task), including the label's Observable{String} and the polling task. Every 0.5 s that sticky task refreshes the driver's report on the thread that built the panel, without commanding the light. Refresh failures are logged and retried; closing the window stops polling.
MicroscopeControl.HardwareInterfaces.LightSourceInterface._attach_readout! — Method
_attach_readout!(fig, row, laser)The shared readout block: a status text, a Read button and a Poll toggle that is off at construction. Polling reads loop_status twice a second and stops when the toggle is turned off or the window closes.
MicroscopeControl.HardwareInterfaces.LightSourceInterface._attach_setpoint! — Method
_attach_setpoint!(fig, laser, range, startvalue, command!, describe)The slider and textbox share one guarded command path. A slider change calls command!(x) once. A textbox submission moves the slider under a guard and then commands once, even when the selected value did not change. The textbox follows slider changes. The "commanded" line is refreshed from describe() only after the command returned, so a refused request shows as refused instead of as a value the device does not hold.
The textbox accepts only a number within [first(range), last(range)], the same bounds the driver enforces; anything else is not applied and the box's border turns red until it is corrected. The bounds are printed beside it.
MicroscopeControl.HardwareInterfaces.LightSourceInterface._format_tia — Method
Human-readable amplifier range: 1e-3 -> 1 mA.
MicroscopeControl.HardwareInterfaces.LightSourceInterface._panel_message — Method
First line of an exception's message, for showing inside a panel.
MicroscopeControl.HardwareInterfaces.LightSourceInterface._readout_text — Method
_readout_text(laser, s)Format a loop_status snapshot for a panel.
MicroscopeControl.HardwareInterfaces.LightSourceInterface.apply_level! — Method
apply_level!(light, p, darken!; darken_argument_errors = false, zero_first = true)Put level p on light.modulator. For a level setter whose light is on, an ArgumentError (the modulator refused before writing) is rethrown and changes nothing; with darken_argument_errors = true (an activation, where the light is already enabled) it darkens like any other throw. Any other throw, an InterruptException included, leaves the output unknown: level 0 is written (tried; a failure is logged), darken!() switches the light off, and the error is rethrown. With zero_first = false the caller's darken! is run first and is itself responsible for the level-0 write (a driver whose off must not wait for a MOD write). Public, not exported.
MicroscopeControl.HardwareInterfaces.LightSourceInterface.check_diode_config — Method
check_diode_config(M, pd, properties, max_current, name)The construction-time invariants every DiodeLaser shares, for a driver's inner constructor to call. Throws an ArgumentError naming the field at fault:
pdis aPhotodiodeLoopexactly whenM === ConstantPhotocurrent;- in that mode
properties.min_power/max_powerare the ENFORCED bounds ofsetoutputpower!, so they must be finite with0 <= min_power < max_power, andmax_powermust fit the amplifier's full scale (max_power / 1000 / wa_calibration <= tia_range): a range the loop cannot reach is refused here rather than at the first command; - in that mode
max_currentis finite and positive, because it becomes the clamp the loop is held under; - in that mode a calibration reference, if given, has
ref_current_mA <= max_current: the re-check drives the diode at it in open loop.
MicroscopeControl.HardwareInterfaces.LightSourceInterface.claim_output! — Method
Claim id for light, or refuse (ErrorException) when another light object holds it. Returns true when this call took the claim and false when light already held it.
MicroscopeControl.HardwareInterfaces.LightSourceInterface.current_panel — Method
current_panel(laser::DiodeLaser)Control panel for a ConstantCurrent laser: a slider in mA over min_current .. effective_max_current(laser), calling setcurrent!, the declared threshold, an on/off toggle, and a loop_status readout. The slider's lowest position is min_current, which still emits if the rig set it above threshold; the toggle is the off control.
MicroscopeControl.HardwareInterfaces.LightSourceInterface.diode_loop_from_keywords — Method
diode_loop_from_keywords(mode::RegulationMode, name; wa_calibration, tia_range,
tec_stabilised, properties, max_current, ramp_step_mW, ramp_step_s,
lock_check_s, lock_ratio, ref_current_mA, ref_photocurrent_A, ref_ratio)The keyword rules a DiodeLaser constructor applies, in one place so TCubeLaser(serialNo; ...) and SimDiodeLaser(; ...) cannot drift apart. Every keyword is nothing when the caller did not pass it. In ConstantPhotocurrent mode wa_calibration, tia_range, tec_stabilised, properties and max_current are required and the PhotodiodeLoop is returned, built from them and from whichever of the loop keywords (ramp_step_mW, ramp_step_s, lock_check_s, lock_ratio, ref_current_mA, ref_photocurrent_A, ref_ratio) were passed. In any other mode passing a loop keyword throws and nothing is returned. Throws ArgumentErrors prefixed with name.
MicroscopeControl.HardwareInterfaces.LightSourceInterface.effective_max_current — Method
effective_max_current(laser::DiodeLaser)The highest drive current, in mA, this laser will accept or report as the top of its range: the ceiling setlevel! maps frac = 1.0 to in ConstantCurrent mode. The fallback is laser.max_current; a driver that knows further ceilings (a controller limit, a DAC full scale) extends this to the smallest of them.
MicroscopeControl.HardwareInterfaces.LightSourceInterface.holds_resources — Method
holds_resources(mc::AbstractModulationControl) -> BoolWhether mc still holds something that a shutdown must release (an open task whose cleanup failed). false by default. open_modulator! keeps the claim while this is true, so a later shutdown can still release it.
MicroscopeControl.HardwareInterfaces.LightSourceInterface.power_panel — Method
power_panel(laser::DiodeLaser)Control panel for a ConstantPhotocurrent laser: a slider in mW at the laser output over properties.min_power .. max_power, calling setoutputpower!; a basis line saying what that number is built from; an on/off toggle; and a loop_status readout of what a power-mode user must see – the photocurrent with its range and over/under flags, the drive current (a climbing current at a still setpoint is a blocked photodiode or an ageing diode), and the saturated flag.
MicroscopeControl.HardwareInterfaces.LightSourceInterface.propagate_interrupt — Method
propagate_interrupt(err)Throw err if it is an InterruptException, else return nothing. A switch-off path calls it AFTER it has switched the light off, with what zero_modulator! returned, so an interrupted 0 V write never skips the disable.
MicroscopeControl.HardwareInterfaces.LightSourceInterface.release_output! — Method
Release id if light holds it.
MicroscopeControl.HardwareInterfaces.LightSourceInterface.status_snapshot — Method
status_snapshot(word, current_mA, photocurrent_A; threshold_current, commanded)Build loop_status's NamedTuple from a raw status word and the two readings. commanded says whether a level has been commanded since the laser was constructed, which the below_threshold check needs.
MicroscopeControl.HardwareInterfaces.LightSourceInterface.tia_range_from_word — Method
tia_range_from_word(word)The amplifier range in A that word reports, or NaN unless exactly one range bit is set.
MicroscopeControl.HardwareInterfaces.LightSourceInterface.zero_modulator! — Method
zero_modulator!(light) -> Nothing or the exceptionWrite level 0 to light.modulator, never throwing: a failure is logged (@error) and returned. The switch-off paths call it first and must go on to switch the light off whatever happens here. An InterruptException is returned like any other failure, so the caller can switch the light off first; it then passes it on with propagate_interrupt. Public, not exported.
MicroscopeControl.HardwareImplementations.SimulatedDiodeLaser._current — Method
Drive current in mA the simulated controller is passing.
MicroscopeControl.HardwareImplementations.SimulatedDiodeLaser.true_output_power — Method
true_output_power(sim::SimDiodeLaser)The simulated optical power at the laser output, in mW: the model's ground truth, which no driver can report. A test oracle only, not an interface generic – compare it with indicated_output_power to see what the calibration does and does not guarantee.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.CLAMP_WAIT_S — Constant
CLAMP_WAIT_SSeconds to wait around each step of a potentiometer change. A Ref so the test suite can set it to zero. On the rig's TLD001, leaving adjust mode immediately after LD_SetMaxCurrentDigPot left the limit unchanged; with 0.5 s between the steps it latched.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.DIGPOT_MIN_POS — Constant
DIGPOT_MIN_POS, DIGPOT_MAX_POS, DIGPOT_STEP_ESTIMATE_mAThe TLD001's max-current potentiometer: positions 20..255. The manual gives a step of about 0.863 mA per position (the header's step, 220/255), used only to choose the next position. The header's scale, position * 220 / 255 mA, is not the limit: the controller does not follow it. On the 642 nm rig's TLD001 (64849775, 2026-09-28) position 204 gave a limit of 160.74 mA and 194 gave 152.43 mA – about 0.83 mA per step. So no clamp value is ever computed from a position. The estimate is at least the measured step, so estimated moves fall short and the search approaches max_current from below: moves approach max_current from below. Since 0.863 mA is slightly more than the measured ~0.83 mA/step, an upward search can stop one position short of the highest position under max_current, which errs safe (a lower ceiling). The manual's ~0.7 mA per position (p.28, p.38) would overshoot upward, so it is not used. program_clamp! reads the controller's own limit after each setting, and that readback decides every position.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.EXPORT_STATE_2ARG_WARNED — Constant
EXPORT_STATE_2ARG_WARNEDWhether the deprecated 2-argument export_state has already attempted its warning in this session. Not @warn's maxlog=1, so that the warning is testable more than once per process; Threads.Atomic rather than a plain Ref because a check followed by a store lets two concurrent callers both warn and is a data race besides. Reset it with [] = false in a test.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.LD_SOURCE_SOFTWARE — Constant
Control-source flags of LD_SetControlSource (Kinesis LD_InputSourceFlags); they add.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.MODULATED_SOURCE — Constant
The control source a light with a modulator runs in: software + external (3).
MicroscopeControl.HardwareImplementations.TCubeLaserControl.MOD_CONFIRM_WORDS — Constant
MOD_CONFIRM_WORDS, MOD_CONFIRM_FRACTIONHow far the setpoint register may be from the code the request asks for when light_on confirms a MOD IN level: max(MOD_CONFIRM_WORDS, MOD_CONFIRM_FRACTION * code) words. Wide enough for the DAC's own offset, the readback's rounding and per_volt's measured precision; far narrower than the 3.2x the manual's scale was off in closed loop on 64865766.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.MOD_SETTLE_S — Constant
MOD_SETTLE_SSeconds after a setpoint write (LD_SetLaserSetPoint) during which a MOD IN change is NOT safe. Measured on TLD001 64849775 in closed loop (2026-10-14): a change up to about 0.95 s after the last write was LOST, entirely or in part. At 1.0 s a change was often partly lost; from 1.1 s every change was applied, at bases of 2 to 60 mW with steps of 1 to 10 mW. On TLD001 64865766 (2026-10-19): lost up to 0.91 s, applied from 1.00 s, 117 of 117. Status and photocurrent reads do not cause it, and MOD IN changes alone were applied at every rate tried (up to 2 kHz). 1.3 s leaves about 0.2 s of margin over 1.1 s. A Ref, so tests can shorten it.
With a modulator, light_on waits this long between its USB zero and the first level it puts on MOD IN. Every later level change is a MOD IN change alone, so none of them waits.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.PHOTOCURRENT_OVER_RANGE — Constant
PHOTOCURRENT_OVER_RANGEThe raw photocurrent word the controller reports when the photodiode channel is over range: 0x8000, i.e. -32768 read signed. Observed on the 642 nm rig's TLD001 (2026-09-28) at 110 mA and above, where the reading jumped from about 3200 counts straight to this value. Decoded as Inf, and reported by loop_status as tia_over.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.POLL_INTERVAL_MS — Constant
POLL_INTERVAL_MSThe Kinesis background polling period initialize starts, in ms (20 Hz), so that measured_current, measured_photocurrent and loop_status are single cache reads, at most this old. A documented constant rather than a keyword: 20 Hz covers the 1-10 Hz a rig logs at.
[limitation] that LD_StartPolling refreshes the reading caches at this period is read from the Kinesis header, not observed on hardware. If it does not, those getters return stale values; tcube_get_current issues its own request and is the fallback. check_lock does not depend on it: it makes its own requests (0.2.6). Whether polling refreshes the readings is rig check R2.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.REFERENCE_DWELL_S — Constant
REFERENCE_DWELL_SHow long the calibration-reference re-check holds the diode at ref_current_mA before it reads the photodiode. Fixed and short, so the reference emission does not grow with lock_check_s. The diode current settles far faster.
[limitation] unvalidated on hardware (rig check R2).
MicroscopeControl.HardwareImplementations.TCubeLaserControl.REQUEST_WAIT_S — Constant
REQUEST_WAIT_SSeconds to wait between each LD_Request* call and the next request or the LD_Get* that reads its answer. The Kinesis getters return a value cached by the DLL, and the request refreshes it asynchronously; 0.1 s is what this driver has always waited. A Ref so the test suite can set it to zero. Not hardware-verified.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.SETPOINT_CONFIRM_TIMEOUT_S — Constant
SETPOINT_CONFIRM_TIMEOUT_S, SETPOINT_READBACK_TOLERANCEHow long send_setpoint waits for the polled setpoint to show the code it sent, in seconds (a Ref so the test suite can shorten it), and how many codes the read-back may differ by: the rig's TLD001 reported 10424 for 10425.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.SETPOINT_PROTOCOL_MAX — Constant
SETPOINT_PROTOCOL_MAXLargest setpoint the controller accepts. LD_SetLaserSetPoint takes a 0-32767 value: it is transported as a UInt16, but only that range is a legal setpoint, so the protocol admits half of what the storage type can hold.
That distinction is the reason max_setcurrent has to be one of the ceilings effective_max_current enforces. UInt16 storage would not have forced it: at the default 220 mA full scale, 300 mA encodes to 44682 and 400 mA to 59576, both of which fit a UInt16 and neither of which is a setpoint this controller can be given.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.TLD001_TIA_RANGES — Constant
TLD001_TIA_RANGESThe TLD001's photodiode amplifier ranges, full scale in A: 10 µA, 100 µA, 1 mA and 10 mA. Selected only by the rear-panel DIP switches; software can read the range (status bits 0x10-0x80) but not set it. From the TLD001 manual and the Kinesis header; not hardware-verified.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.BOOL — Type
BOOLFour bytes. Retained for TLI_DeviceInfo's fields only, which nothing in this package calls — see that struct's docstring. Do not use it for a new binding: use KBOOL_ARG for an argument and KBOOL_RET for a return.
[limitation] The vendor headers do not declare BOOL for these fields. Two rigs have now read their own vendor-installed Thorlabs.MotionControl.TCube.LaserDiode.h — Kinesis 1.14.10 on the seq-sr rig and 1.14.47.22504 on quickbeam — and both declare lowercase C++ bool with #pragma pack(1) active. This Cuint is therefore wrong for TLI_DeviceInfo, and is left in place only because no single layout fits both versions anyway (they disagree on serialNo's length), so there is nothing to change it to.
History, because this was got wrong twice in opposite directions. v0.2.3 retyped both boolean roles to a one-byte Bool. A copy of the header on the lab NAS appeared to contradict that, carrying typedef unsigned int BOOL and no lowercase bool at all, and on its strength the change was reverted — but that file is a Clang.jl generation input, hand-edited to parse without the Windows SDK, and its typedefs are artefacts of the editing rather than the vendor's ABI. Splitting the two roles is the correct answer, and the vendor-installed headers since read off both rigs confirm it.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.KBOOL_ARG — Type
KBOOL_ARGThe type to pass a Kinesis C++ bool ARGUMENT: a zero-extended Cuint carrying exactly 0 or 1.
This is robust whichever width the callee really reads. A bool callee takes the low byte and sees 0 or 1; a BOOL callee takes all four and sees 0 or 1. Passing a 1-byte Bool is NOT robust in this direction: the upper three bytes of the register are undefined, so a false can arrive as true. That matters for LD_EnableMaxCurrentAdjust(serialNo, enableAdjust, enableDiode), whose second flag enables the laser diode during a max-current adjustment.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.KBOOL_RET — Type
KBOOL_RETThe type to read a Kinesis C++ bool RETURN: one byte.
The installed vendor header declares these bool, which on MSVC x86-64 returns in AL and leaves the rest of EAX undefined. Reading four bytes can therefore turn a false into a nonzero value — LD_CheckConnection reporting a disconnected controller as connected. Reading the low byte is correct under the bool ABI and still correct under a BOOL ABI returning 0 or 1.
History, because this was got wrong twice. v0.2.3 retyped both roles to a 1-byte Bool, which was right for returns and wrong for arguments. A copy of the header on the lab NAS appeared to contradict it — but that copy is a Clang.jl generation input, hand-edited to parse without Windows headers: its typedef unsigned int BOOL and its commented-out #pragma pack are artefacts of that editing, not the vendor's ABI. The installed header has 32 lowercase bool, zero BOOL, and an active #pragma pack(1). Splitting the two roles is what is actually correct, and is safe under either reading.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.TLI_DeviceInfo — Type
TLI_DeviceInfo[limitation] This layout does not match either Kinesis version we have looked at, and it is left alone deliberately, because there is no single layout that would match both.
Two rigs read their installed headers and reported different declarations:
| Kinesis 1.14.10 (seq-sr rig) | Kinesis 1.14.47.22504 (quickbeam) | |
|---|---|---|
serialNo | char serialNo[9] | char serialNo[16] |
| flags | 1-byte C++ bool | 1-byte C++ bool |
#pragma pack(1) | ACTIVE (lines 63-125) | ACTIVE |
| reported size | — | 100 bytes, PID at 85 |
This declaration uses NTuple{16,Cchar}, 4-byte BOOL flags and default alignment, measuring 120 bytes with PID at offset 88 (verified by execution). It is wrong for both, and the field that differs between the two vendor versions is an array LENGTH, so no reinterpretation fixes both at once.
[policy] Do not call TLI_GetDeviceInfo through this declaration. Nothing in this package does — initialize uses only TLI_BuildDeviceList and TLI_GetDeviceListSize, both of which return counts and touch no struct (verified). If a caller ever needs device info, declare the struct for the SDK version in use, assert sizeof, and keep it beside the header it was read from.
One copy of this header on the lab NAS contradicts all of the above; do not trust it. Personal Folders/Sheng/code/generate_lib/lib/ holds a Clang.jl generation input, hand-edited to parse without Windows headers: local typedefs including typedef unsigned int BOOL, OaIdl.h and __declspec stripped, both pack pragmas commented out, every lowercase bool rewritten. Those are artefacts of the editing. This docstring briefly asserted, on the strength of that file, that our layout was correct; it is not, and the round trip cost two wrong rulings in opposite directions.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.begin_modulation! — Method
begin_modulation!(light::TCubeLaser)End of initialize for a light with a modulator, the output off: open the modulator (claim its output, 0 V), record the control source (once per open/close cycle, so a second initialize keeps the first) and set source 3.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.bump_generation! — Method
Count an event that supersedes a light_on in progress (see light_on_modulated); returns the new count.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.check_current — Method
check_current(light::TCubeLaser, current::Float64)Validate a requested drive current in mA, throwing an ArgumentError naming the request and both bounds if it is out of range. Returns current.
This is the whole of setcurrent!'s safety check, kept as its own function so it can be exercised without a controller attached. It runs before any setpoint is computed or sent: the code before v0.2.3 logged @error and then carried on to call LD_SetLaserSetPoint anyway. What that cost depended on the request. 500 mA on a 160 mA diode never reached the controller – it logged, continued, and then died in the conversion, UInt16(round(...)) with an InexactError. 200 mA did: over the same 160 mA ceiling, but inside the setpoint DAC's range, so it converted cleanly and was sent. A log line was the only thing separating the two.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.check_err — Method
check_err(err, operation::AbstractString, serialNo::AbstractString)Throw unless a Kinesis call reported success. The TCube LaserDiode calls used here return a Cshort status where 0 is success and anything else is a Thorlabs error code; every call site below used to assign that status to an err local and never read it, so a failed open, a failed mode change and a failed setpoint were all indistinguishable from success.
Never point this at a boolean return (KBOOL_RET): those are success FLAGS where false means failure, the opposite sense. See check_flag.
Not hardware-verified (no TCube on the build machine): the 0 == success convention is the documented Kinesis one, not something this repo has observed.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.check_flag — Method
check_flag(ok, operation::AbstractString, serialNo::AbstractString)Throw unless a Kinesis call that returns a C++ bool success flag returned true. The counterpart of check_err for the opposite convention.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.check_lock — Method
check_lock(light::TCubeLaser{ConstantPhotocurrent}, code)After a setpoint, wait pd.lock_check_s, then make its own fresh reads: the photocurrent word (read_photocurrent_word), then the status word (read_status_fresh), and compare them with what code requests. It throws on the first of these that holds, in this order:
- the measured photocurrent exceeds
pd.lock_ratiotimes the request: the loop has probably locked at a high current whatever is requested (the failure the ramp works around; seePhotodiodeLoop). This is tested before the status read, so a lock trips about 2 xREQUEST_WAIT_Ssooner; - the status reports the current limit reached (
0x400): the loop is at the clamp and the power is not being held; - the measured photocurrent is below the request divided by
pd.lock_ratio: the loop is not holding its setpoint.
The test is two-sided because a loop driven to the clamp, by a request the clamp cannot reach or by a photodiode giving fewer counts per mW than at calibration, reads low. code is the final code its caller confirmed (after any ramp); intermediate ramp steps are not checked. At code == 0 it waits lock_check_s and runs only the 0x400 test (no photocurrent read): a zero request has no lock and no deficit, but a controller at its current limit is still a fault. Its own reads cost about lock_check_s + 4 x REQUEST_WAIT_S (+ 2 x at code == 0). It never disables the output by itself; its callers do. A no-op in open loop.
[limitation] the thresholds and the wait are unvalidated on hardware (one night's lock measured about 98 uA for 44.6 uA requested, 2.2x) and need the 642 nm rig check. A false trip refuses, which is the safe direction.
[limitation] that 0x400 sets when the closed loop saturates is read from the Kinesis header, not observed.
[limitation] a loop slower than lock_check_s to reach 2/3 of an upward step false-trips, which refuses (the safe direction).
MicroscopeControl.HardwareImplementations.TCubeLaserControl.check_power — Method
check_power(light::TCubeLaser{ConstantPhotocurrent}, power_mW::Float64)Validate a requested output power against properties.min_power..max_power, throwing an ArgumentError naming the request and both bounds. Returns power_mW. The power-mode counterpart of check_current.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.check_scale! — Method
check_scale!(light::TCubeLaser{ConstantPhotocurrent})The calibration-reference re-check: runs at most once per initialize (pd.scale_checked and pd.scale_refused, both cleared by every initialize, successful or failed), from light_on right after require_clamp. A no-op in open loop.
With no reference (pd.ref_current_mA is NaN) it logs one @warn, sets scale_checked and makes no SDK calls. With one, it checks ref_current_mA against the current ceiling (nothing is sent if that throws), zeroes and disables the output, enters open loop (set_open_loop!, which confirms it from a fresh status read before the enable), enables, sends the setpoint for ref_current_mA (after the enable: a setpoint sent with the output off is ignored), waits REFERENCE_DWELL_S, reads the photocurrent, zeroes and disables again, and restores closed loop (set_closed_loop!). It then compares the reading, decoded with pd.tia_range, with pd.ref_photocurrent_A: it passes iff the reading is within a factor pd.ref_ratio of it, either way. The output is off afterwards, and light_on continues with its own enable.
Any failure inside the re-check (a set_open_loop! refusal, a command error, or a mismatch) latches the refusal until the next initialize: scale_refused is set before the check starts and cleared only on a pass, so every later light_on refuses at once, without lighting the diode again. A command failure is also cleaned up (disable_after_failure) and rethrown; a mismatch leaves the output off and closed loop restored. Whatever it throws (that latched refusal, a reference above the ceiling, a failure or a mismatch), light_on first switches the output off (disable_after_failure) when it may be on, as for a require_clamp refusal, then rethrows; the log says whether that switch-off worked.
The reference is in amps, decoded with tia_range. A range the reading does not follow, or a tia_range relabelled with W/A kept (the 642 nm rig's fact 6), fails the re-check. A correct range change, where the words do follow, passes.
[limitation] the reference emission (open loop at ref_current_mA for about REFERENCE_DWELL_S + 2 x REQUEST_WAIT_S plus the setpoint confirm, no longer tied to lock_check_s) happens before the user's request at the first light_on.
[limitation] unvalidated on hardware.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.confirm_modulated_setpoint — Method
confirm_modulated_setpoint(light::TCubeLaser, code)Poll the controller's setpoint register (LD_GetLaserSetPoint, which reads the sum of the USB word and MOD IN's contribution) until it is within max(MOD_CONFIRM_WORDS, MOD_CONFIRM_FRACTION * code) words of code, the code the request asks for, or SETPOINT_CONFIRM_TIMEOUT_S; throw if it never is. This is the check on the modulator's per_volt: a scale that disagrees with the laser's own (the manual's, 3.2x too high in closed loop on 64865766), a dead cable, an unarmed control source and a MOD IN change the controller lost all leave the register elsewhere. It also catches interleavings: a light_off during the wait leaves a stale read-back (65530), a level change from another task is lost and the register shows the old level.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.control_source — Method
control_source(light::TCubeLaser) -> IntThe controller's control-source flags (1 software, 2 external SMA, 4 front potentiometer; they add), from a fresh read. [limitation] On the TLD001s tested a source of 2 or 3 reads back as 1 while the external input works, so the read-back cannot confirm the external flag, and a cube found at 3 is restored to 1; 5 reads back as 5.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.disable_after_failure — Method
disable_after_failure(light::TCubeLaser, what)Cleanup after what failed while the output may be lit: zero the setpoint, then disable the output, never throwing. properties.is_on becomes false if the disable succeeded and true if it failed, since the diode may still be lit. One @error names what and every cleanup failure. The caller rethrows its own error. The zero comes first for the reason zero_then_disable gives: the next enable must start dark, not on a stale setpoint.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.disable_after_failure_modulated — Method
disable_after_failure_modulated(light::TCubeLaser, what)disable_after_failure for a light with a modulator, never throwing: disable at once (disable_now!; no wait for a MOD IN write), then write level 0. No USB zero is sent (the output is off, so the controller would ignore it, and one at a MOD IN level would absorb it). properties.is_on is false only after the disable succeeded.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.disable_now! — Method
disable_now!(light::TCubeLaser)LD_DisableOutput under usb_lock, at once: it needs neither lock nor a MOD IN write. The output is recorded off only after it succeeds; a failure leaves disable_pending set and throws.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.enable_output! — Method
enable_output!(light::TCubeLaser)LD_EnableOutput. With a modulator it runs under usb_lock after checking that the activation that calls it is still current (arm_gen == generation), so no enable follows a light_off, shutdown, initialize or newer light_on.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.end_modulation! — Method
end_modulation!(light::TCubeLaser) -> Nothing or the exceptionRestore the control source begin_modulation! recorded (restore_control_source!), then close_modulator!. Both are attempted; failures are logged and the first returned, so a caller can finish closing the handle before it throws. A failed close_modulator! keeps the claim for the next call.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.has_request — Method
Whether a setpoint has been requested since construction: what light_on sends if not is 0.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.intended_code — Method
intended_code(light::TCubeLaser)The setpoint the driver's recorded request asks for: setpoint_code(drive_current) in ConstantCurrent mode, photocurrent_code(output_power_requested) in ConstantPhotocurrent mode, and 0 when nothing has been requested. What light_on sends right after enabling the output.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.legacy_power — Method
legacy_power(light::TCubeLaser, current::Float64)The value properties.power has held since before v0.2.3: the requested current scaled linearly onto properties.max_power. Deprecated, and scheduled for removal at the next breaking release – read light.drive_current instead.
It is a guess, not a measurement. The controller reports no optical power in the open-loop mode this driver uses, and the bench table in CALIBRATION.md shows the real curve is not this line. It is reproduced here only so that a rig reading properties.power across an upgrade reads the same number it read before.
Reproducing it exactly needs one step the old expression did not: it divided by light.max_current, and initialize used to overwrite that field with the controller's limit. max_current is now the caller's and stays so, so the divisor is controller_max_current once initialize has read it and max_current before that – which is the same quantity the old field held at each of those two moments.
One case where this deliberately does not reproduce 0.2.2. If a caller assigns max_current after initialize, 0.2.2 divided by the newly assigned value; this divides by the controller's limit still. With max_current = 80.0 and a 40 mA request after a controller limit of 23830, 0.2.2 gave 50.0 and this gives 25.000572235150496. Reproducing it would mean intercepting writes to the field, which is not worth doing for a number the driver invents and which the next breaking release removes. Read drive_current instead; it is exact and has no lifecycle.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.light_off_modulated — Method
light_off_modulated(light::TCubeLaser)light_off for a light with a modulator: bump generation (so an activation in flight throws "superseded" and no enable can follow), disable at once under usb_lock (disable_now!) without waiting for light.lock or a MOD IN write, then take lock to clear arming and write level 0. No USB zero is sent: the controller ignores one with the output off, and the next light_on writes USB 0 at 0 V after its enable. A failed disable throws after the level-0 write, and stays pending; an interrupted 0 V write passes on after the disable.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.light_on_modulated — Method
light_on_modulated(light::TCubeLaser)light_on for a light with a modulator, in three stages around two waits (see "Locking" on TCubeLaser):
- Arm, under
light.lock: bumpgenerationand record it (arm_gen); write level 0 to the modulator and require that write to succeed;require_clampandcheck_scale!(now at 0 V, so their USB setpoints act as plain USB); the enable underusb_lockafter a generation check (enable_output!); USB setpoint 0 and its read-back (a setpoint sent while off is ignored, so the base is known only after a write made while on); setarming. - Sleep
MOD_SETTLE_S, unlocked. A level setter meanwhile only records.light_offandshutdowndisable at once;initializeand anotherlight_ontake the lock; all of them bumpgeneration. - Apply, under
light.lock: ifgenerationmoved, throw "superseded" and touch nothing (whoever bumped it owns the hardware). Otherwise read the CURRENT request and put it on the modulator. Then, unlocked, poll the read-back (confirm_modulated_setpoint) and runcheck_lock(closed loop), re-checkinggenerationat each step. Last, under the lock, apply a request a setter recorded meanwhile and cleararming: the light is on.
A throw while this activation is still current writes level 0, sends no USB zero (the output is disabled first), disables and rethrows; if generation moved, it throws "superseded" and touches nothing. An interrupt in the sleep ends dark the same way. light_off waits for neither lock before it disables.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.lower_open_loop_clamp! — Method
lower_open_loop_clamp!(light::TCubeLaser)Open loop only, run by initialize after the controller's limit is recorded: if light.controller_max_current > light.max_current, lower the potentiometer with program_clamp! and store the limit it returns in light.controller_max_current. If the controller's limit is at or below max_current the potentiometer is not touched: a rig that lowered it by hand keeps it. Closed loop programs its clamp in enter_mode! and this does nothing.
If no potentiometer position gives a limit at or below max_current (the 642 nm rig's reads 16.74 mA at the lowest), the search fails and it warns as below; light_on then refuses while the current limit stored in the controller is above max_current (see light_on). The search runs with raise = false, so no position above the starting one is ever set.
If the search fails – adjust mode refused, a position that does not read back, or even the lowest position reading above max_current – it warns the same way and records the limit the controller then reports, and initialize goes on: the search has only ever lowered the potentiometer, so the controller is no less safe than before it ran, and no configuration that initialized in 0.2.4 fails here. If that re-read fails too, the limit read before the search is kept, which is an upper bound for the same reason.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.mod_zero! — Method
mod_zero!(light::TCubeLaser) -> Nothing or the exceptionWrite level 0 to the modulator if the light has one; never throws (an InterruptException is returned). nothing means the MOD IN level is known to be 0, or the light has no modulator. A modulator that is not open (the light holds no claim) is NOT known to be at 0: an error is returned. A caller sends a USB setpoint only when this returned nothing: a USB write at a MOD IN level would absorb the level.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.modulated_request — Method
The level light_on puts on MOD IN: the recorded request, 0 when nothing was requested.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.modulator_open — Method
Whether light holds its modulator's output, i.e. the modulator is open from an earlier initialize.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.photocurrent_code — Method
photocurrent_code(light::TCubeLaser{ConstantPhotocurrent}, photocurrent_A)Encode a photocurrent in A as the closed-loop setpoint, with the same guarantee as setpoint_code: the decoded photocurrent never exceeds the request. Throws, naming the DIP switch, if the request is above the amplifier's full scale: no software setting can reach it.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.photocurrent_from_code — Method
photocurrent_from_code(light::TCubeLaser{ConstantPhotocurrent}, code)Decode a closed-loop setpoint or photocurrent reading to amps: 0..max_setpoint spans 0..pd.tia_range. The one definition setoutputpower!, measured_photocurrent and photocurrent_code share.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.program_clamp! — Method
program_clamp!(light::TCubeLaser; raise::Bool=true)Leave the controller's diode current limit at the highest potentiometer position (or one position below it: see DIGPOT_STEP_ESTIMATE_mA) whose limit, as the controller reports it, does not exceed light.max_current, and return that limit in mA.
The search starts from the current position. It moves by the header's step estimate (DIGPOT_STEP_ESTIMATE_mA), which is larger than the real step on the rig's controller, so moves fall short and approach the ceiling from one side. It reads the controller's limit after each setting and keeps the best position under the ceiling and the lowest over it, so it settles in a few settings, and none if the present position already qualifies. Throws if even the lowest position is above the ceiling, or if it cannot settle. Output must be off (it is, in initialize).
In ConstantPhotocurrent mode initialize calls it to program the clamp. In ConstantCurrent mode initialize calls it through lower_open_loop_clamp! only when the controller's limit is above max_current, and with raise = false: the upper bound of the search is the starting position, so no position above it is ever set, whatever the reads return. It never raises the potentiometer in that mode. The default, raise = true, is closed loop's search, which may move up toward the ceiling.
[limitation] lowering the open-loop potentiometer is not validated on hardware beyond the 642 nm rig's closed-loop sequence; not yet run on hardware in open loop.
[limitation] that the controller clamps to the limit it reports (manual p.41, p.50; header :711), and not to the header's position scale, is inferred, not measured (rig check R3).
MicroscopeControl.HardwareImplementations.TCubeLaserControl.read_digpot — Method
Fresh read of the potentiometer position.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.read_limit_mA — Method
Fresh read of the controller's diode current limit, in mA.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.read_photocurrent_word — Method
Fresh read of the raw photocurrent word, signed: two LD_RequestReadings, then the reading.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.read_status_fresh — Method
Request twice, wait, then read the status word: a fresh read, not the polled cache.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.record_controller_limit! — Method
record_controller_limit!(light::TCubeLaser, raw)Scale the controller's raw diode current limit reading to mA and store it in light.controller_max_current, returning the scaled value.
Split out of initialize so the property that matters here – that reading the controller's limit leaves the caller's max_current alone – is testable without a controller attached.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.reopened — Method
reopened(f, light::TCubeLaser)Run f() with the Kinesis handle open: as it is when light.connected, else opened for the one call and closed again, deliberately (a shutdown retried after the handle closed, with a restore or a disable still pending).
MicroscopeControl.HardwareImplementations.TCubeLaserControl.request_twice — Method
request_twice(request, name, serialNo)Send request (an LD_Request* wrapper) twice, waiting REQUEST_WAIT_S after each, so the LD_Get* that follows returns the controller's state at the first request. The 642 nm rig's TLD001 answers one request behind (2026-09-29): the first request after a change returned the state before it, even 0.5 s later, and the next one was current. Every fresh read in this driver goes through here.
[limitation] whether this driver's polling already hides the lag for the limit and the status word after a change is not measured (rig check R1); the second request is kept either way, at REQUEST_WAIT_S per read.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.require_clamp — Method
require_clamp(mode::RegulationMode, light::TCubeLaser, op)The pre-enable safety check of mode (_require_clamp). A safety check that refuses while the output may be on zeroes and disables it first, then rethrows (#74 review M1).
MicroscopeControl.HardwareImplementations.TCubeLaserControl.restore_control_source! — Method
restore_control_source!(light::TCubeLaser)Put back the control source begin_modulation! recorded (software only if it did not include software) and forget it. With the handle closed, it is reopened for the one command (reopened).
MicroscopeControl.HardwareImplementations.TCubeLaserControl.send_setpoint — Method
send_setpoint(light::TCubeLaser, code::UInt16)Send a setpoint with the output on and wait for the controller to report it back within SETPOINT_READBACK_TOLERANCE codes, throwing if it does not. Only call it with the output enabled. Nothing is recorded by this function.
The setpoint only takes while the output is ON
Hardware-verified on the 642 nm rig's TLD001 (64849775, 2026-09-28), and the single most important fact about this controller:
LD_SetLaserSetPointsent while the output is disabled is ignored. On the nextLD_EnableOutputthe controller runs on whatever setpoint it had stored – on the rig, a word above full scale, so the diode went straight to its current limit (~160 mA, 85-88 mW measured) whatever had been "set".- Sent while the output is enabled, it takes within about one poll: 70 mA commanded, 70.0 mA on the front display, no limit flag.
LD_GetLaserSetPointreports the controller's setpoint only while the output is enabled (it read back 10424 for 10425 sent, one code low). With the output off it returns a stale word unrelated to anything sent.
So this driver never sends a setpoint with the output off. setcurrent! and setoutputpower! record the request and, if the output is on, send and confirm it; if it is off, the request is applied by light_on immediately after it enables the output. light_off zeroes the setpoint BEFORE disabling, so the controller's stored setpoint is 0 and the next enable starts dark rather than at a stale value.
[limitation] between LD_EnableOutput and the setpoint that follows it (a few ms, one USB round trip) the controller runs on its stored setpoint. After a light_off from this driver that is 0; on a controller last left by other software it may be anything up to full scale, bounded only by the current limit (the max-current clamp in power mode).
MicroscopeControl.HardwareImplementations.TCubeLaserControl.send_setpoint_ramped — Method
send_setpoint_ramped(light::TCubeLaser, code::UInt16, from::Integer)Send a setpoint with the output on. In ConstantPhotocurrent mode, if pd.ramp_step_mW is finite (see PhotodiodeLoop, which also records why the ramp exists) an upward step of more than that many mW is walked up from from, one step every pd.ramp_step_s; the final code is confirmed by send_setpoint. from is what the DRIVER knows the controller holds (light_on passes 0; setoutputpower! passes the code of its previous request), never LD_GetLaserSetPoint, which returns a stale word right after an enable (65530 on the rig). Downward steps, ramp_step_mW = Inf and open loop are one write, and open loop ignores from.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.set_closed_loop! — Method
LD_SetClosedLoopMode, then a fresh status read must report closed loop (0x4).
MicroscopeControl.HardwareImplementations.TCubeLaserControl.set_control_source! — Method
set_control_source!(light::TCubeLaser, flags::Integer)Set the control-source flags (see control_source). The software flag is required: this driver's setpoints must keep reaching the diode. Not persisted to the controller (LD_PersistSettings is not called), so a power cycle restores the stored source.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.set_digpot! — Method
set_digpot!(light::TCubeLaser, position)Set the potentiometer and return the controller's resulting limit in mA: LD_EnableMaxCurrentAdjust(true, false), wait, LD_SetMaxCurrentDigPot, wait, confirm the position reads back, LD_EnableMaxCurrentAdjust(false, false), wait, read the limit. Adjust mode is always left, even on failure. The diode flag is always false. The output must already be off: entering adjust mode drops the limit to its minimum until the position is set.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.set_level_modulated! — Method
set_level_modulated!(light::TCubeLaser, p::Float64) -> BoolThe level setters' common tail for a light with a modulator, called with the light's lock held. While the light is on (and not arming), put p on the modulator: one write, no USB call, no fresh read, no lock check, no ramp. While it is off or arming nothing is written (an arming light_on applies the latest recorded request). An ArgumentError from the modulator changes nothing; any other throw writes 0 (tried), disables and rethrows. Returns whether a level was written.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.set_open_loop! — Method
set_open_loop!(light::TCubeLaser)LD_SetOpenLoopMode, then a fresh status read must report open loop (0x4 clear). Used by open-loop initialize and by the reference re-check.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.setpoint_code — Method
setpoint_code(light::TCubeLaser, current::Float64)Encode a drive current in mA as the controller's integer setpoint.
Validates the conversion itself, which the range check cannot: check_current compares a request against ceilings and says nothing about whether the scale factors that encode it are usable. Requests that passed the check used to die here in UInt16(...) with an InexactError – max_setcurrent of 0.0 or NaN, a max_setpoint outside the protocol range, a negative min_current admitting a negative current. Each now throws an ArgumentError naming the field at fault, still before anything is sent.
The guarantee
setpoint_current(light, setpoint_code(light, c)) <= c for every c this function accepts. That is the whole of it, and it is worth reading narrowly: the decoded current is bounded by the request, by this driver's own arithmetic. What the controller does with the code – its DAC, its own rounding, its calibration – is not something this repo has observed, so no claim is made about the current at the diode.
Truncation alone does not deliver that. Rounding was the first thing it ruled out: at the default scale the 160 mA ceiling rounds to code 23831, which decodes to 160.00305 mA, so the one request sitting exactly on the enforced limit would be the one to breach it at the wire. But floor is applied to current / max_setcurrent * max_setpoint, and that division and multiplication can each round up: a request one ulp below a code boundary can be carried to the boundary itself, leaving floor nothing to cut. A scan of the predecessor of every code boundary in the default 0-160 mA range found 1794 such requests, the first at prevfloat(9 / 32767 * 220) = 0.06042664876247444, which encodes to code 9 and decodes back to 0.060426648762474444 – above the request. The excesses are single ulps, not overcurrent; the guarantee was still false.
So the candidate code is corrected downward while it decodes above the request. The comparison is > against setpoint_current – the same decode the guarantee is stated in, not an equivalent-looking expression – and the loop terminates because code 0 decodes to 0.0 and current is validated non-negative. In practice it runs at most once.
The cost of the whole rule is an undershoot of approximately one code, about 0.0067 mA at the default scale – "approximately" because the downward correction can take a boundary predecessor a hair past one code width. At the bottom of the range that undershoot is the entire request: see setcurrent!.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.setpoint_current — Method
setpoint_current(light::TCubeLaser, code)Decode a controller setpoint back to a current in mA, the inverse of setpoint_code's scaling.
One definition, used by every place in this driver that turns a raw controller word into mA – the setpoint check in setpoint_code, the limit read in record_controller_limit! and the readings in measured_current and tcube_get_current. setpoint_code's guarantee is stated in terms of this function, so it has to be the same arithmetic in every one of them and not several copies of the same expression.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.setupIO — Method
setupIO(light::TCubeLaser)Create the NI-DAQmx analogue-output task that drives this laser's modulation input, and store it in light.task_mod.
Pass daq_device= and ao_channel= to the constructor to name the device and channel explicitly. When they are nothing the historical behaviour is kept – the second discovered device and its second AO channel – because changing which analogue output a working rig drives is not something a driver should do quietly. What changed is that the discovery path now validates: where it used to raise a bare BoundsError on a single-device rig, it says what it found and what to pass instead.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.shutdown_disconnected — Method
shutdown_disconnected(light::TCubeLaser)A shutdown of a light with a modulator whose Kinesis handle is already closed (the first shutdown could not release the modulator, restore the control source, or disable the output): retry only what is pending, with no closed-handle call. A disable or source still pending reopens the handle for those commands (reopened); the output is recorded off only after LD_DisableOutput succeeds.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.shutdown_modulated — Method
shutdown_modulated(light::TCubeLaser)shutdown for a light with a modulator: bump generation, disable at once, then (under lock) write level 0 and, only if the disable succeeded, restore the control source and release the modulator; stop polling and close the handle either way. A disable that failed stays pending with the claim and the source kept, and the next shutdown reopens the handle to retry it. With the handle already closed it retries only what is pending (shutdown_disconnected).
MicroscopeControl.HardwareImplementations.TCubeLaserControl.usb_locked — Method
usb_locked(f, light::TCubeLaser)Run f() (one Kinesis enable or disable call) holding light.usb_lock when the light has a modulator; without one f() runs as it always did. Nothing else is called under it, and it is never held while light.lock is taken.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.with_light_lock — Method
with_light_lock(f, light::TCubeLaser)Run f() holding the light's lock when it has a modulator; without one there is no lock and f() runs as it always did.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.zero_setpoint — Method
zero_setpoint(light::TCubeLaser)Send setpoint 0 while the output is still on, so the controller does not keep the last current for its next enable. Never throws: returns nothing on success, otherwise the failure (a status code or an exception) for the caller to report.
MicroscopeControl.HardwareImplementations.TCubeLaserControl.zero_then_disable — Method
zero_then_disable(light::TCubeLaser)Send setpoint 0, then disable the output, then record properties.is_on = false. The controller keeps its setpoint across a disable and ignores setpoints while its output is off, so the zero has to come first: the next enable then starts dark rather than on a stale value. The zero is one write (zero_setpoint) with no status read and no read-back wait: commands to the controller are handled in order, so it lands before the disable. A failed zero is logged, before the disable, and never prevents it; a failed disable throws and leaves properties.is_on unchanged. The driver's recorded request is kept, and light_on re-applies it.
MicroscopeControl.HardwareInterfaces.LightSourceInterface.effective_max_current — Method
effective_max_current(light::TCubeLaser)The ceiling setcurrent! enforces, in mA: the smallest of the caller's max_current, the controller's controller_max_current (skipped while it is NaN, i.e. before initialize) and max_setcurrent, the full-scale current of the setpoint DAC.
max_setcurrent is in the list because a current above full scale has no legal setpoint: see SETPOINT_PROTOCOL_MAX for why the bound is the controller's 0-32767 protocol range and not UInt16 storage. Without it, setcurrent! would carry a request the range check had already passed into a conversion that cannot express it.