Skip to content

Lablink

Use this module to connect to your lablink server, manage instruments, start experiments, and retrieve data.

Basic usage:

import asyncio

import pypalmsens as ps
from pypalmsens import lablink

async def main():
    method = ps.CyclicVoltammetry()

    local = lablink.Instance('https://127.0.0.1/')
    await local.fetch_metadata()
    session = await local.login('test', 'test')

    # Grab first instrument
    instrument, _* = session.instruments

    async with await session.claim(instrument) as claim:
        job = await session.start(claim, method=method)
        measurement = await job

    print(measurement)

    data = measurement[0].xarray()


if __name__ == '__main__':
    asyncio.run(main())

Connect, manage, and start measurements on Lablink instances.

Modules:

  • models –

Classes:

Functions:

  • discover –

    Browse the local network for LabLink devices for a fixed duration.

Instance

Instance(address: str = 'https://127.0.0.1', port: int = 5000)

A reference to a Lablink instance.

Exposes basic metadata through properties and provides get_info to refresh that information. Use login for an authenticated session.

Parameters:

  • address

    (str, default: 'https://127.0.0.1' ) –

    The address of the instance (default is 'https://127.0.0.1').

  • port

    (int, default: 5000 ) –

    Port to use on the instance (default is 5000).

Methods:

  • get_info –

    Fetch instance metadata from the lablink server.

  • login –

    Start an authenticated session with this lablink instance.

  • register_new_user –

    Register a new user account.

Attributes:

  • address (str) –

    The address of the instance.

  • info (LablinkInfo | None) –

    Last fetched metadata, or None if not yet fetched.

Source code in src/pypalmsens/lablink/_instance.py
35
36
37
38
def __init__(self, address: str = 'https://127.0.0.1', port: int = 5000):
    self._address = address.rstrip('/')
    self._http = HttpClient(f'{self._address}/api/v1')
    self._info: LablinkInfo | None = None

address property

address: str

The address of the instance.

info property

info: LablinkInfo | None

Last fetched metadata, or None if not yet fetched.

May be stale or empty.

See get_info to (re)populate this.

get_info async

get_info() -> LablinkInfo

Fetch instance metadata from the lablink server.

Returns:

  • LablinkInfo –

    Instance metadata including name, version and serial number.

Source code in src/pypalmsens/lablink/_instance.py
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
async def get_info(self) -> LablinkInfo:
    """
    Fetch instance metadata from the lablink server.

    Returns
    -------
    LablinkInfo
        Instance metadata including name, version and serial number.
    """
    data = await self._http.get('/Home/GetInfo')
    self._info = LablinkInfo.from_wire(data.json())
    if not self._info.is_supported:
        msg = (
            f'LabLink instance at {self.address} reports version {self._info.version}. '
            f'This version of pypalmsens supports {SUPPORTED}. '
            'Calls may fail or behave unexpectedly. '
            'Upgrade pypalmsens or the LabLink server.'
        )
        warnings.warn(msg, stacklevel=2)

    return self._info

login async

login(name: str, password: str) -> Session

Start an authenticated session with this lablink instance.

Parameters:

  • name
    (str) –

    The username for authentication.

  • password
    (str) –

    The password for authentication.

Returns:

  • Session –

    A new session object for this instance.

Source code in src/pypalmsens/lablink/_instance.py
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
async def login(self, name: str, password: str) -> Session:
    """Start an authenticated session with this lablink instance.

    Parameters
    ----------
    name : str
        The username for authentication.
    password : str
        The password for authentication.

    Returns
    -------
    Session
        A new session object for this instance.
    """
    payload = AuthRequestModel(UserName=name, Password=password).model_dump()

    data = await self._http.post('/Auth/ApiKey', json=payload)
    auth = AuthResponseModel.model_validate(data.json())
    assert auth.Token
    self._http.set_token(auth.Token)
    return Session._from_http(self._http)

register_new_user async

register_new_user(name: str, password: str) -> None

Register a new user account.

Parameters:

  • name
    (str) –

    The username for authentication.

  • password
    (str) –

    The password for authentication.

Source code in src/pypalmsens/lablink/_instance.py
86
87
88
89
90
91
92
93
94
95
96
97
98
99
async def register_new_user(self, name: str, password: str) -> None:
    """
    Register a new user account.

    Parameters
    ----------
    name : str
        The username for authentication.
    password : str
        The password for authentication.
    """
    payload = AuthRequestModel(UserName=name, Password=password).model_dump()

    await self._http.post('/Auth/Register', json=payload)

Instrument

Instrument(serial: str, session: Session)

A reference to an instrument.

Methods:

Attributes:

Source code in src/pypalmsens/lablink/_instrument.py
161
162
163
def __init__(self, serial: str, session: Session):
    self._serial: str = serial
    self._session: Session = session

info property

info: dict[str, Any]

The instrument info from the most recent get_info call.

May be stale or empty.

serial_number property

serial_number: str

The serial number of the instrument.

claim async

claim(*, auto_release: bool = False) -> InstrumentClaim

Claim this instrument.

The claim is held until you release it, or until the enclosing async with block exits.

Parameters:

  • auto_release
    (bool, default: False ) –

    If True, the server releases the claim after measurement ends.

Returns:

Source code in src/pypalmsens/lablink/_instrument.py
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
async def claim(self, *, auto_release: bool = False) -> InstrumentClaim:
    """Claim this instrument.

    The claim is held until you release it, or until the enclosing
    `async with` block exits.

    Parameters
    ----------
    auto_release: bool, optional
        If True, the server releases the claim after measurement ends.

    Returns
    -------
    claim : InstrumentClaim
        Claimed instrument
    """
    method = 'Claim' if auto_release else 'ManualClaim'
    await self._session._http.post(f'/Instrument/{self._serial}/{method}')
    return InstrumentClaim(self._serial, self._session)

get_active_measurement async

get_active_measurement() -> Measurement

Return the active measurement, if any.

Returns:

  • measurement ( Measurement ) –

    Reference to the active measurement

Raises:

Source code in src/pypalmsens/lablink/_instrument.py
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
async def get_active_measurement(self) -> Measurement:
    """Return the active measurement, if any.

    Returns
    -------
    measurement : Measurement
        Reference to the active measurement

    Raises
    ------
    NoActiveMeasurementError
        If there is no active measurement.
    """
    response = await self._session._http.get(
        f'/Instrument/{self._serial}/CurrentMeasurement'
    )
    data = response.json()
    guid = data['result']['id']
    return Measurement(guid=guid, session=self._session)

get_capabilities async

get_capabilities() -> dict[str, Any]

Fetch the capabilities of this instrument.

Returns:

  • dict[str, Any] –

    Dictionary with supported features.

Source code in src/pypalmsens/lablink/_instrument.py
109
110
111
112
113
114
115
116
117
118
119
async def get_capabilities(self) -> dict[str, Any]:
    """Fetch the capabilities of this instrument.

    Returns
    -------
    dict[str, Any]
        Dictionary with supported features.
    """
    response = await self._session._http.get(f'/Instrument/{self._serial}/Capabilities')
    data = response.json()
    return data['result']

get_configuration async

get_configuration() -> dict[str, Any]

Get the current configuration for this instrument.

Returns:

  • dict[str, Any] –

    Dictionary with current configuration.

Source code in src/pypalmsens/lablink/_instrument.py
 97
 98
 99
100
101
102
103
104
105
106
107
async def get_configuration(self) -> dict[str, Any]:
    """Get the current configuration for this instrument.

    Returns
    -------
    dict[str, Any]
        Dictionary with current configuration.
    """
    response = await self._session._http.get(f'/Instrument/{self._serial}/Configuration')
    data = response.json()
    return data['result']

get_info async

get_info() -> dict[str, Any]

Get info for instrument.

Returns:

  • info ( dict[str, Any] ) –

    Dictionary with instrument info.

Source code in src/pypalmsens/lablink/_instrument.py
74
75
76
77
78
79
80
81
82
83
async def get_info(self) -> dict[str, Any]:
    """Get info for instrument.

    Returns
    -------
    info : dict[str, Any]
        Dictionary with instrument info.
    """
    info = await self._session.get_instrument_info()
    return info[self._serial]

get_signalr_url async

get_signalr_url() -> str

Return the signal rate URL for this instrument.

Returns:

  • url ( str ) –

    Generated signalr url for this instrument.

Source code in src/pypalmsens/lablink/_instrument.py
85
86
87
88
89
90
91
92
93
94
95
async def get_signalr_url(self) -> str:
    """Return the signal rate URL for this instrument.

    Returns
    -------
    url : str
        Generated signalr url for this instrument.
    """
    response = await self._session._http.get(f'/Instrument/{self._serial}/GetSignalRUrl')
    data = response.json()
    return data['result']

get_state async

get_state() -> dict[str, Any]

Fetch the current state of this instrument.

Returns:

  • dict[str, Any] –

    dictionary describing the current device state.

Source code in src/pypalmsens/lablink/_instrument.py
141
142
143
144
145
146
147
148
149
150
151
async def get_state(self) -> dict[str, Any]:
    """Fetch the current state of this instrument.

    Returns
    -------
    dict[str, Any]
        dictionary describing the current device state.
    """
    response = await self._session._http.get(f'/Instrument/{self._serial}/State')
    data = response.json()
    return data['result']

InstrumentClaim

InstrumentClaim(serial: str, session: Session)

A reference to a claimed instrument.

Can also be used as a context manager for a claiming an instrument.

Methods:

Attributes:

Source code in src/pypalmsens/lablink/_instrument.py
209
210
211
def __init__(self, serial: str, session: Session):
    self._serial: str = serial
    self._session: Session = session

info property

info: dict[str, Any]

The instrument info from the most recent get_info call.

May be stale or empty.

serial_number property

serial_number: str

The serial number of the claimed instrument.

abort_measurement async

abort_measurement() -> None

Stop and release a running measurement.

The instrument resets to the pre-measurement state after aborting.

Source code in src/pypalmsens/lablink/_instrument.py
303
304
305
306
307
308
async def abort_measurement(self) -> None:
    """Stop and release a running measurement.

    The instrument resets to the pre-measurement state after aborting.
    """
    await self._session._http.post(f'/Instrument/{self._serial}/AbortMeasurement')

configure async

configure(mains_frequency: Literal['auto', 50, 60] | None = None, signal_train: Literal['lowspeed', 'highspeed', 'maximumrange'] | None = None, multichannel_role: Literal['standalone', 'main', 'follower'] | None = None) -> None

Configure this instrument.

Parameters:

  • mains_frequency
    (int or None, default: None ) –

    Set the DC mains frequency in to 50 or 60 Hz, depending on your region. Use 'auto' for automatic determination of the mains frequency.

    The mains frequency of the power grid couples into the measured current. The instrument filters sampling at that frequency.

  • signal_train
    (str or None, default: None ) –

    Speed of the analog input train (e.g. 'lowSpeed', 'highSpeed').

  • multichannel_role
    (str or None, default: None ) –

    Role for multi-channel mode ('standalone', 'main', 'follower').

Source code in src/pypalmsens/lablink/_instrument.py
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
async def configure(
    self,
    mains_frequency: Literal['auto', 50, 60] | None = None,
    signal_train: Literal['lowspeed', 'highspeed', 'maximumrange'] | None = None,
    multichannel_role: Literal['standalone', 'main', 'follower'] | None = None,
) -> None:
    """Configure this instrument.

    Parameters
    ----------
    mains_frequency : int or None, optional
        Set the DC mains frequency in to 50 or 60 Hz, depending on your region.
        Use 'auto' for automatic determination of the mains frequency.

        The mains frequency of the power grid couples into the measured current.
        The instrument filters sampling at that frequency.
    signal_train : str or None, optional
        Speed of the analog input train (e.g. 'lowSpeed', 'highSpeed').
    multichannel_role : str or None, optional
        Role for multi-channel mode ('standalone', 'main', 'follower').
    """
    if mains_frequency == 50:
        _mains_freq = 'Hz50'
    elif mains_frequency == 60:
        _mains_freq = 'Hz60'
    elif mains_frequency == 'auto':
        _mains_freq = 'Undefined'
    else:
        _mains_freq = None

    if multichannel_role == 'main':
        _role = 'Master'
    elif multichannel_role == 'follower':
        _role = 'Slave'
    elif multichannel_role == 'standalone':
        _role = 'Standalone'
    else:
        _role = None

    if signal_train:
        _signal_train = signal_train.capitalize()
    else:
        _signal_train = None

    config = ConfigureInstrumentsProperties.model_validate(
        {
            'MainsFrequency': _mains_freq,
            'SignalTrain': signal_train,
            'MultiChannelRole': _role,
        }
    )
    # TODO: How does the endpoint handle null?
    # If the endpoint treats this as a patch,
    # nulls may clear settings or be rejected
    payload = config.model_dump(exclude_none=True)

    await self._session._http.post(
        f'/Instrument/{self._serial}/ConfigureInstrument', json=payload
    )

get_active_measurement async

get_active_measurement() -> Measurement

Return the active measurement, if any.

Returns:

  • measurement ( Measurement ) –

    Reference to the active measurement

Raises:

Source code in src/pypalmsens/lablink/_instrument.py
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
async def get_active_measurement(self) -> Measurement:
    """Return the active measurement, if any.

    Returns
    -------
    measurement : Measurement
        Reference to the active measurement

    Raises
    ------
    NoActiveMeasurementError
        If there is no active measurement.
    """
    response = await self._session._http.get(
        f'/Instrument/{self._serial}/CurrentMeasurement'
    )
    data = response.json()
    guid = data['result']['id']
    return Measurement(guid=guid, session=self._session)

get_capabilities async

get_capabilities() -> dict[str, Any]

Fetch the capabilities of this instrument.

Returns:

  • dict[str, Any] –

    Dictionary with supported features.

Source code in src/pypalmsens/lablink/_instrument.py
109
110
111
112
113
114
115
116
117
118
119
async def get_capabilities(self) -> dict[str, Any]:
    """Fetch the capabilities of this instrument.

    Returns
    -------
    dict[str, Any]
        Dictionary with supported features.
    """
    response = await self._session._http.get(f'/Instrument/{self._serial}/Capabilities')
    data = response.json()
    return data['result']

get_configuration async

get_configuration() -> dict[str, Any]

Get the current configuration for this instrument.

Returns:

  • dict[str, Any] –

    Dictionary with current configuration.

Source code in src/pypalmsens/lablink/_instrument.py
 97
 98
 99
100
101
102
103
104
105
106
107
async def get_configuration(self) -> dict[str, Any]:
    """Get the current configuration for this instrument.

    Returns
    -------
    dict[str, Any]
        Dictionary with current configuration.
    """
    response = await self._session._http.get(f'/Instrument/{self._serial}/Configuration')
    data = response.json()
    return data['result']

get_info async

get_info() -> dict[str, Any]

Get info for instrument.

Returns:

  • info ( dict[str, Any] ) –

    Dictionary with instrument info.

Source code in src/pypalmsens/lablink/_instrument.py
74
75
76
77
78
79
80
81
82
83
async def get_info(self) -> dict[str, Any]:
    """Get info for instrument.

    Returns
    -------
    info : dict[str, Any]
        Dictionary with instrument info.
    """
    info = await self._session.get_instrument_info()
    return info[self._serial]

get_signalr_url async

get_signalr_url() -> str

Return the signal rate URL for this instrument.

Returns:

  • url ( str ) –

    Generated signalr url for this instrument.

Source code in src/pypalmsens/lablink/_instrument.py
85
86
87
88
89
90
91
92
93
94
95
async def get_signalr_url(self) -> str:
    """Return the signal rate URL for this instrument.

    Returns
    -------
    url : str
        Generated signalr url for this instrument.
    """
    response = await self._session._http.get(f'/Instrument/{self._serial}/GetSignalRUrl')
    data = response.json()
    return data['result']

get_state async

get_state() -> dict[str, Any]

Fetch the current state of this instrument.

Returns:

  • dict[str, Any] –

    dictionary describing the current device state.

Source code in src/pypalmsens/lablink/_instrument.py
141
142
143
144
145
146
147
148
149
150
151
async def get_state(self) -> dict[str, Any]:
    """Fetch the current state of this instrument.

    Returns
    -------
    dict[str, Any]
        dictionary describing the current device state.
    """
    response = await self._session._http.get(f'/Instrument/{self._serial}/State')
    data = response.json()
    return data['result']

pause_measurement async

pause_measurement() -> None

Pause a running measurement.

The instrument holds its current state and resumes later.

Source code in src/pypalmsens/lablink/_instrument.py
292
293
294
295
296
297
async def pause_measurement(self) -> None:
    """Pause a running measurement.

    The instrument holds its current state and resumes later.
    """
    await self._session._http.post(f'/Instrument/{self._serial}/PauseMeasurement')

release async

release() -> None

Release the instrument claim.

Source code in src/pypalmsens/lablink/_instrument.py
233
234
235
async def release(self) -> None:
    """Release the instrument claim."""
    await self._session._http.post(f'/Instrument/{self._serial}/Unclaim')

resume_measurement async

resume_measurement() -> None

Resume a previously paused measurement.

Source code in src/pypalmsens/lablink/_instrument.py
299
300
301
async def resume_measurement(self) -> None:
    """Resume a previously paused measurement."""
    await self._session._http.post(f'/Instrument/{self._serial}/ResumeMeasurement')

set_bipot_current_range async

set_bipot_current_range(current_range: AllowedCurrentRanges) -> None

Set the current range of the second working electrode (bipot, WE2).

Parameters:

Source code in src/pypalmsens/lablink/_instrument.py
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
async def set_bipot_current_range(self, current_range: AllowedCurrentRanges) -> None:
    """Set the current range of the second working electrode (bipot, WE2).

    Parameters
    ----------
    current_range : AllowedCurrentRanges
        Desired WE2 current range as a string (e.g. '1 mA').
    """
    # TODO: investigate intention behind MeasuringRange
    sig, exp = cr_string_to_sig_exp(current_range)
    config = MeasuringRange(Significant=sig, Exponent=exp)
    payload = config.model_dump()

    await self._session._http.post(
        f'/Instrument/{self._serial}/SetBiPotCurrentRange',
        json=payload,
    )

set_bipot_enabled async

set_bipot_enabled(state: bool) -> None

Enable or disable the second working electrode (bipot, WE2).

Parameters:

  • state
    (bool) –

    True = bipotentiostat on (WE2 active), False = off.

Source code in src/pypalmsens/lablink/_instrument.py
450
451
452
453
454
455
456
457
458
async def set_bipot_enabled(self, state: bool) -> None:
    """Enable or disable the second working electrode (bipot, WE2).

    Parameters
    ----------
    state : bool
        True = bipotentiostat on (WE2 active), False = off.
    """
    await self._session._http.post(f'/Instrument/{self._serial}/SetBiPotState', json=state)

set_bipot_mode async

set_bipot_mode(mode: Literal['constant', 'offset']) -> None

Set how the second working electrode (WE2) is coupled to WE1.

  • constant: WE2 is held at a fixed potential vs. the RE while WE1 is stepped or swept independently.
  • offset: WE2 tracks WE1, maintained at a fixed potential difference from WE1 as WE1 changes.

Parameters:

  • mode
    (str) –

    Coupling mode: 'constant' or 'offset'.

Source code in src/pypalmsens/lablink/_instrument.py
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
async def set_bipot_mode(self, mode: Literal['constant', 'offset']) -> None:
    """Set how the second working electrode (WE2) is coupled to WE1.

    - `constant`: WE2 is held at a fixed potential vs. the RE while
      WE1 is stepped or swept independently.
    - `offset`: WE2 tracks WE1, maintained at a fixed potential
      difference from WE1 as WE1 changes.

    Parameters
    ----------
    mode : str
        Coupling mode: 'constant' or 'offset'.
    """
    payload = CellMode[mode.capitalize()].value

    await self._session._http.post(f'/Instrument/{self._serial}/SetBiPotMode', json=payload)

set_bipot_potential async

set_bipot_potential(potential: float) -> None

Set the potential of the second working electrode (WE2).

Parameters:

  • potential
    (float) –

    WE2 setpoint in volts. Absolute vs. RE in constant mode, or the WE1-relative offset in offset mode.

Source code in src/pypalmsens/lablink/_instrument.py
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
async def set_bipot_potential(self, potential: float) -> None:
    """Set the potential of the second working electrode (WE2).

    Parameters
    ----------
    potential : float
        WE2 setpoint in volts. Absolute vs. RE in constant mode, or the
        WE1-relative offset in offset mode.
    """
    config = Volt(Value=potential)
    payload = config.model_dump()

    await self._session._http.post(
        f'/Instrument/{self._serial}/SetBiPotPotential',
        json=payload,
    )

set_cell_mode async

set_cell_mode(mode: Literal['potentiostatic', 'galvanostatic']) -> None

Set active measurement mode of the instrument.

Parameters:

  • mode
    (str) –

    One of 'potentiostatic' or 'galvanostatic'.

Source code in src/pypalmsens/lablink/_instrument.py
237
238
239
240
241
242
243
244
245
246
async def set_cell_mode(self, mode: Literal['potentiostatic', 'galvanostatic']) -> None:
    """Set active measurement mode of the instrument.

    Parameters
    ----------
    mode : str
        One of 'potentiostatic' or 'galvanostatic'.
    """
    payload = CellMode[mode.capitalize()].value
    await self._session._http.post(f'/Instrument/{self._serial}/SetCellMode', json=payload)

set_cell_state async

set_cell_state(state: Literal['off', 'on']) -> None

Sets the cell state.

Parameters:

  • state
    (str) –

    Set the cell 'on' or 'off'

Source code in src/pypalmsens/lablink/_instrument.py
248
249
250
251
252
253
254
255
256
257
async def set_cell_state(self, state: Literal['off', 'on']) -> None:
    """Sets the cell state.

    Parameters
    ----------
    state : str
        Set the cell 'on' or 'off'
    """
    payload = CellState[state.capitalize()].value
    await self._session._http.post(f'/Instrument/{self._serial}/SetCellState', json=payload)

set_current async

set_current(current: float) -> None

Set the cell current (galvanostatic mode).

Parameters:

  • current
    (float) –

    Current value in µA.

Source code in src/pypalmsens/lablink/_instrument.py
423
424
425
426
427
428
429
430
431
432
433
434
async def set_current(self, current: float) -> None:
    """Set the cell current (galvanostatic mode).

    Parameters
    ----------
    current : float
        Current value in µA.
    """
    await self._session._http.post(
        f'/Instrument/{self._serial}/SetCurrent',
        json=current,
    )

set_current_range async

set_current_range(current_range: AllowedCurrentRanges) -> None

Set the current measurement range.

Parameters:

Source code in src/pypalmsens/lablink/_instrument.py
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
async def set_current_range(self, current_range: AllowedCurrentRanges) -> None:
    """Set the current measurement range.

    Parameters
    ----------
    current_range : AllowedCurrentRanges
        The desired range as a string (e.g. '1 mA').
    """
    # TODO: investigate intention behind MeasuringRange
    sig, exp = cr_string_to_sig_exp(current_range)
    config = MeasuringRange(Significant=sig, Exponent=exp)
    payload = config.model_dump()
    await self._session._http.post(
        f'/Instrument/{self._serial}/SetCurrentRange',
        json=payload,
    )

set_custom_name async

set_custom_name(name: str) -> None

Set a custom display name for the instrument.

Parameters:

  • name
    (str) –

    Custom name to assign to the instrument

Source code in src/pypalmsens/lablink/_instrument.py
310
311
312
313
314
315
316
317
318
async def set_custom_name(self, name: str) -> None:
    """Set a custom display name for the instrument.

    Parameters
    ----------
    name : str
        Custom name to assign to the instrument
    """
    await self._session._http.post(f'/Instrument/{self._serial}/SetCustomName', json=name)

set_potential async

set_potential(potential: float) -> None

Set the working electrode (WE) potential relative to the reference electrode (RE).

Parameters:

  • potential
    (float) –

    WE potential in volts.

Source code in src/pypalmsens/lablink/_instrument.py
436
437
438
439
440
441
442
443
444
445
446
447
448
async def set_potential(self, potential: float) -> None:
    """Set the working electrode (WE) potential relative to the reference
    electrode (RE).

    Parameters
    ----------
    potential : float
        WE potential in volts.
    """
    await self._session._http.post(
        f'/Instrument/{self._serial}/SetPotential',
        json=potential,
    )

set_potential_range async

set_potential_range(potential_range: AllowedPotentialRanges) -> None

Set the potential measurement range.

Parameters:

Source code in src/pypalmsens/lablink/_instrument.py
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
async def set_potential_range(self, potential_range: AllowedPotentialRanges) -> None:
    """Set the potential measurement range.

    Parameters
    ----------
    potential_range : AllowedPotentialRanges
        The desired range as a string (e.g. '100 mV').
    """
    # TODO: investigate intention behind MeasuringRange
    sig, exp = pr_string_to_sig_exp(potential_range)
    config = MeasuringRange(Significant=sig, Exponent=exp)
    payload = config.model_dump()
    await self._session._http.post(
        f'/Instrument/{self._serial}/SetPotentialRange', json=payload
    )

skip_pre_measurement_stage async

skip_pre_measurement_stage() -> None

Skip the initial pre-measurement setup step.

Useful when you want to begin measuring without running through all calibration steps.

Source code in src/pypalmsens/lablink/_instrument.py
284
285
286
287
288
289
290
async def skip_pre_measurement_stage(self) -> None:
    """Skip the initial pre-measurement setup step.

    Useful when you want to begin measuring without running
    through all calibration steps.
    """
    await self._session._http.post(f'/Instrument/{self._serial}/SkipPreMeasurementStage')

start_measurement async

Start a measurement.

Parameters:

Returns:

Source code in src/pypalmsens/lablink/_instrument.py
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
async def start_measurement(self, method: MethodTypeCompatible) -> MeasurementJob:
    """Start a measurement.

    Parameters
    ----------
    method : MethodTypeCompatible
        The measurement technique and parameters to run.

    Returns
    -------
    job : MeasurementJob
        Reference to the measurement job
    """
    self.require_supports(method)

    payload = to_payload(method)

    response = await self._session._http.post(
        f'/Instrument/{self._serial}/StartMeasurement', json=payload
    )

    data = response.json()

    return MeasurementJob(guid=data['result'], claim=self)

start_workflow async

start_workflow(workflow: str) -> None

Start a workflow on the instrument.

Parameters:

  • workflow
    (str) –

    Name of the workfrow to execute on the instrument.

Source code in src/pypalmsens/lablink/_instrument.py
380
381
382
383
384
385
386
387
388
async def start_workflow(self, workflow: str) -> None:
    """Start a workflow on the instrument.

    Parameters
    ----------
    workflow : str
        Name of the workfrow to execute on the instrument.
    """
    await self._session._http.post(f'/Instrument/{self._serial}/SendScript', json=workflow)

InstrumentClaimBatch

InstrumentClaimBatch(claims: list[InstrumentClaim])

A batch of claimed instruments.

Use as an async context manager. All claims are released when the context exits.

Parameters:

  • claims

    (list of InstrumentClaim) –

    The list of instrument claims to manage.

Methods:

  • release –

    Release all instrument claims in this batch.

Source code in src/pypalmsens/lablink/_instrument.py
526
527
def __init__(self, claims: list[InstrumentClaim]):
    self.claims: list[InstrumentClaim] = claims

release async

release() -> None

Release all instrument claims in this batch.

Source code in src/pypalmsens/lablink/_instrument.py
553
554
555
556
async def release(self) -> None:
    """Release all instrument claims in this batch."""
    tasks = [claim.release() for claim in self.claims]
    _ = await asyncio.gather(*tasks)

LablinkApiError

LablinkApiError(message: str, *, status_code: int | None = None, resource_key: str | None = None, dictionary: str | None = None, serial: str | None = None, parameters: list[Any] | None = None, response: Any = None)

Base class for errors returned by the Lablink API.

Source code in src/pypalmsens/lablink/_errors.py
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
def __init__(
    self,
    message: str,
    *,
    status_code: int | None = None,
    resource_key: str | None = None,
    dictionary: str | None = None,
    serial: str | None = None,
    parameters: list[Any] | None = None,
    response: Any = None,
) -> None:
    super().__init__(message)
    self.status_code = status_code
    self.resource_key = resource_key
    self.dictionary = dictionary
    self.serial = serial
    self.parameters = parameters or []
    self.response = response

LablinkClientError

LablinkClientError(message: str, *, status_code: int | None = None, resource_key: str | None = None, dictionary: str | None = None, serial: str | None = None, parameters: list[Any] | None = None, response: Any = None)

4xx client error.

Source code in src/pypalmsens/lablink/_errors.py
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
def __init__(
    self,
    message: str,
    *,
    status_code: int | None = None,
    resource_key: str | None = None,
    dictionary: str | None = None,
    serial: str | None = None,
    parameters: list[Any] | None = None,
    response: Any = None,
) -> None:
    super().__init__(message)
    self.status_code = status_code
    self.resource_key = resource_key
    self.dictionary = dictionary
    self.serial = serial
    self.parameters = parameters or []
    self.response = response

LablinkServerError

LablinkServerError(message: str, *, status_code: int | None = None, resource_key: str | None = None, dictionary: str | None = None, serial: str | None = None, parameters: list[Any] | None = None, response: Any = None)

5xx server error.

Source code in src/pypalmsens/lablink/_errors.py
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
def __init__(
    self,
    message: str,
    *,
    status_code: int | None = None,
    resource_key: str | None = None,
    dictionary: str | None = None,
    serial: str | None = None,
    parameters: list[Any] | None = None,
    response: Any = None,
) -> None:
    super().__init__(message)
    self.status_code = status_code
    self.resource_key = resource_key
    self.dictionary = dictionary
    self.serial = serial
    self.parameters = parameters or []
    self.response = response

Measurement

Measurement(guid: str, *, session: Session | None = None)

A reference to a measurement.

Holds the GUID of a stored measurement and an optional session link.

Methods:

  • delete –

    Delete this measurement from the server.

  • get_data –

    Retrieve recorded data for this measurement.

  • get_info –

    Get metadata for this measurement (not yet implemented).

Attributes:

  • guid (str) –

    The unique identifier of the measurement.

Source code in src/pypalmsens/lablink/_measurement.py
32
33
34
def __init__(self, guid: str, *, session: Session | None = None):
    self._guid: str = guid
    self._session: Session | None = session

guid property

guid: str

The unique identifier of the measurement.

Returns:

  • str –

    Measurement GUID.

delete async

delete() -> None

Delete this measurement from the server.

Raises:

Source code in src/pypalmsens/lablink/_measurement.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
async def delete(self) -> None:
    """
    Delete this measurement from the server.

    Raises
    ------
    ConnectionError
        If this reference is detached from a session.
    """
    if self._session is None:
        raise ConnectionError(
            f'This {type(self).__name__} is detached. Reattach it via '
            '`ref = session.get_measurement(ref)` before fetching data.'
        )
    return await self._session._http.delete(f'/Measurements/{self.guid}/Delete')

get_data async

get_data() -> Dataset | DataTree

Retrieve recorded data for this measurement.

Returns:

  • Dataset or DataTree –

    Measurement data. A Dataset is returned for a single measurement, a DataTree when the measurement contains repeated/stacked runs.

Raises:

Source code in src/pypalmsens/lablink/_measurement.py
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
async def get_data(self) -> xr.Dataset | xr.DataTree:
    """
    Retrieve recorded data for this measurement.

    Returns
    -------
    xarray.Dataset or xarray.DataTree
        Measurement data. A `Dataset` is returned for a single
        measurement, a `DataTree` when the measurement contains
        repeated/stacked runs.

    Raises
    ------
    ConnectionError
        If this reference is detached from a session.
    """
    if self._session is None:
        raise ConnectionError(
            f'This {type(self).__name__} is detached. Reattach it via '
            'ref = session.get_measurement(ref) before fetching data.'
        )
    return await self._session.get_measurement(self)

get_info async

get_info() -> None

Get metadata for this measurement (not yet implemented).

Raises:

  • ConnectionError –

    If no session is attached. Reattach via session.get_measurement(ref) before calling.

Source code in src/pypalmsens/lablink/_measurement.py
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
async def get_info(self) -> None:
    """
    Get metadata for this measurement (not yet implemented).

    Raises
    ------
    ConnectionError
        If no session is attached. Reattach via
        `session.get_measurement(ref)` before calling.
    """
    if self._session is None:
        raise ConnectionError(
            f'This {type(self).__name__} is detached. Reattach it via '
            'ref = session.get_measurement(ref) before fetching data.'
        )
    raise NotImplementedError

MeasurementJob

MeasurementJob(guid: str, *, claim: InstrumentClaim)

A job representing an ongoing measurement.

Holds the GUID of a measurement in progress and its instrument claim.

Methods:

  • abort –

    Abort the measurement.

  • pause –

    Pause the measurement.

  • result –

    Wait for the measurement to finish and return a reference.

  • resume –

    Resume the measurement.

Attributes:

  • claim (InstrumentClaim) –

    The instrument claim associated with the measurement job.

  • guid (str) –

    The unique identifier of the measurement being performed.

  • is_finished (bool) –

    True if the measurement has finished.

  • serial_number (str) –

    Serial number of the instrument carrying out the measurement.

Source code in src/pypalmsens/lablink/_measurement.py
115
116
117
118
def __init__(self, guid: str, *, claim: InstrumentClaim) -> None:
    self._guid: str = guid
    self._claim: InstrumentClaim = claim
    self._is_finished: bool = False

claim property

The instrument claim associated with the measurement job.

guid property

guid: str

The unique identifier of the measurement being performed.

Returns:

  • str –

    Measurement GUID.

is_finished property

is_finished: bool

True if the measurement has finished.

serial_number property

serial_number: str

Serial number of the instrument carrying out the measurement.

abort async

abort() -> None

Abort the measurement.

Source code in src/pypalmsens/lablink/_measurement.py
216
217
218
async def abort(self) -> None:
    """Abort the measurement."""
    return await self._claim.abort_measurement()

pause async

pause() -> None

Pause the measurement.

Source code in src/pypalmsens/lablink/_measurement.py
220
221
222
async def pause(self) -> None:
    """Pause the measurement."""
    return await self._claim.pause_measurement()

result async

result(*, initial: float = 1.0, cap: float = 30.0, factor: float = 2.0, jitter: float = 0.15, timeout: float | None = None) -> Measurement

Wait for the measurement to finish and return a reference.

Polls claim.get_active_measurement() with exponential backoff so short jobs are caught quickly while long ones stay cheap.

Parameters:

  • initial
    (float, default: 1.0 ) –

    Delay before the first retry, in seconds. Defaults to 1.0.

  • cap
    (float, default: 30.0 ) –

    Maximum delay between polls, in seconds. Defaults to 30.0.

  • factor
    (float, default: 2.0 ) –

    Multiplier applied to the delay after each poll. Defaults to 2.0.

  • jitter
    (float, default: 0.15 ) –

    Fractional randomness added to each delay (e.g., 0.15 for +/-15%). Defaults to 0.15.

  • timeout
    (float or None, default: None ) –

    Total seconds to wait before giving up; None waits indefinitely. Defaults to None.

Returns:

  • MeasurementRef –

    A reference to the finished measurement.

Raises:

  • TimeoutError –

    If timeout is set and the measurement does not finish in time.

Source code in src/pypalmsens/lablink/_measurement.py
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
async def result(
    self,
    *,
    initial: float = 1.0,
    cap: float = 30.0,
    factor: float = 2.0,
    jitter: float = 0.15,
    timeout: float | None = None,
) -> Measurement:
    """
    Wait for the measurement to finish and return a reference.

    Polls `claim.get_active_measurement()` with exponential backoff so
    short jobs are caught quickly while long ones stay cheap.

    Parameters
    ----------
    initial : float, optional
        Delay before the first retry, in seconds. Defaults to 1.0.
    cap : float, optional
        Maximum delay between polls, in seconds. Defaults to 30.0.
    factor : float, optional
        Multiplier applied to the delay after each poll. Defaults to 2.0.
    jitter : float, optional
        Fractional randomness added to each delay (e.g., 0.15 for +/-15%).
        Defaults to 0.15.
    timeout : float or None, optional
        Total seconds to wait before giving up; None waits indefinitely.
        Defaults to None.

    Returns
    -------
    MeasurementRef
        A reference to the finished measurement.

    Raises
    ------
    TimeoutError
        If `timeout` is set and the measurement does not finish in time.
    """
    loop = asyncio.get_running_loop()
    deadline = loop.time() + timeout if timeout else None
    delay = initial

    while True:
        await asyncio.sleep(delay * (1 + random.uniform(-jitter, jitter)))
        delay = min(delay * factor, cap)

        try:
            active = await self._claim.get_active_measurement()
        except NoActiveMeasurementError:
            break

        if not active or active.guid != self.guid:
            break

        if deadline and loop.time() >= deadline:
            raise TimeoutError(f'measurement {self.guid} did not finish in {timeout}s')

    self._is_finished = True

    return Measurement(self.guid, session=self._claim._session)

resume async

resume() -> None

Resume the measurement.

Source code in src/pypalmsens/lablink/_measurement.py
224
225
226
async def resume(self) -> None:
    """Resume the measurement."""
    return await self._claim.resume_measurement()

NoActiveMeasurementError

NoActiveMeasurementError(message: str, *, status_code: int | None = None, resource_key: str | None = None, dictionary: str | None = None, serial: str | None = None, parameters: list[Any] | None = None, response: Any = None)

The instrument has no active measurement.

Source code in src/pypalmsens/lablink/_errors.py
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
def __init__(
    self,
    message: str,
    *,
    status_code: int | None = None,
    resource_key: str | None = None,
    dictionary: str | None = None,
    serial: str | None = None,
    parameters: list[Any] | None = None,
    response: Any = None,
) -> None:
    super().__init__(message)
    self.status_code = status_code
    self.resource_key = resource_key
    self.dictionary = dictionary
    self.serial = serial
    self.parameters = parameters or []
    self.response = response

Session

Session(host: str, token: str, port: int = 5000)

A session managing a connection to a Lablink instance.

Use Session.list_instruments to list instruments, Session.claim to claim them, and Session.start_measurement to run measurements.

Parameters:

  • host

    (str) –

    Base URL of the Lablink instance (e.g. 'lablink.example.com').

  • token

    (str) –

    Token used to authenticate API calls.

  • port

    (int, default: 5000 ) –

    Port for the API server, defaults to 5000.

Methods:

Attributes:

Source code in src/pypalmsens/lablink/_session.py
51
52
53
54
55
56
57
def __init__(
    self,
    host: str,
    token: str,
    port: int = 5000,
):
    self._init(HttpClient(f'{host}:{port}/api/v1', token=token))

info property

info: LablinkInfo | None

Last fetched metadata, or None if not yet fetched.

Use get_info to (re)populate this.

instrument_info property

instrument_info: dict[str, dict[str, Any]]

The instrument info from the most recent get_instrument_info call.

May be stale or empty. Use list_instruments or get_instrument_info to update the cache.

instruments property

instruments: list[Instrument]

The instruments from the most recent list_instruments call.

May be stale or empty. Use list_instruments or get_instrument_info update the cache.

abort_measurement async

abort_measurement(jobs: Sequence[MeasurementJob]) -> None

Abort a running measurement and cancel job.

Parameters:

Source code in src/pypalmsens/lablink/_session.py
383
384
385
386
387
388
389
390
391
392
393
394
395
396
async def abort_measurement(self, jobs: Sequence[MeasurementJob]) -> None:
    """Abort a running measurement and cancel job.

    Parameters
    ----------
    jobs : Sequence[MeasurementJob]
        The measurement to abort.
    """
    payload = {
        'AllInstrumentsMustSucceed': True,
        'InstrumentProperties': {job.serial_number: {} for job in jobs},
    }

    await self._http.post('/Instrument/AbortMeasurement', json=payload)

claim async

Claim multiple instruments.

The claim is held until you release it, or until the enclosing async with block exits.

Parameters:

  • instruments
    (Sequence[Instrument]) –

    The instruments to claim.

  • auto_release
    (bool, default: False ) –

    If True, the server releases the claims after measurement ends.

Returns:

  • claims ( ClaimBatch ) –

    A batch containing the instrument claims.

Source code in src/pypalmsens/lablink/_session.py
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
async def claim(
    self, instruments: Sequence[Instrument], *, auto_release: bool = False
) -> InstrumentClaimBatch:
    """Claim multiple instruments.

    The claim is held until you release it, or until the enclosing
    `async with` block exits.

    Parameters
    ----------
    instruments : Sequence[Instrument]
        The instruments to claim.
    auto_release : bool, optional
        If True, the server releases the claims after measurement ends.

    Returns
    -------
    claims : ClaimBatch
        A batch containing the instrument claims.
    """
    method = 'Claim' if auto_release else 'ManualClaim'

    props = {instrument.serial_number: EmptyProperty() for instrument in instruments}
    payload = SimpleInstrumentsCommand(
        InstrumentProperties=props, AllInstrumentsMustSucceed=True
    )

    await self._http.post(f'/Instruments/{method}', json=payload.model_dump())

    claims = [InstrumentClaim(instrument.serial_number, self) for instrument in instruments]
    return InstrumentClaimBatch(claims)

delete_measurements async

delete_measurements(measurements: list[Measurement | str]) -> None

Delete measurement data from Lablink.

Measurements are deleted by their unique identifier (GUID), either using the guid attribute from the Measurement instance or directly as a string.

Parameters:

  • measurements
    (list[Measurement | str]) –

    A list of measurements to delete. Each item in the list can be either an instance of Measurement or a GUID string.

Source code in src/pypalmsens/lablink/_session.py
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
async def delete_measurements(self, measurements: list[Measurement | str]) -> None:
    """Delete measurement data from Lablink.

    Measurements are deleted by their unique identifier (GUID),
    either using the `guid` attribute from the `Measurement` instance or
    directly as a string.

    Parameters
    ----------
    measurements : list[Measurement | str]
        A list of measurements to delete. Each item in the list can be
        either an instance of `Measurement` or a GUID string.
    """
    payload = [
        item.guid if isinstance(item, Measurement) else item for item in measurements
    ]

    await self._http.delete('/Measurements/BatchDelete', json=payload)

delete_user async

delete_user(user: UserInfo | str) -> None

Delete a user by their identifier.

Users are deleted using their unique identifier (GUID), either using the guid attribute from the UserInfo instance or directly as a string.

Parameters:

  • user
    (UserInfo | str) –

    The identifier for the user to delete. This can be either an instance of UserInfo, or a GUID string.

Source code in src/pypalmsens/lablink/_session.py
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
async def delete_user(self, user: UserInfo | str) -> None:
    """Delete a user by their identifier.

    Users are deleted using their unique identifier (GUID),
    either using the `guid` attribute from the `UserInfo` instance or
    directly as a string.

    Parameters
    ----------
    user: UserInfo | str
        The identifier for the user to delete. This can be either an instance
        of UserInfo, or a GUID string.
    """
    if isinstance(user, UserInfo):
        guid = user.guid
    else:
        guid = user

    await self._http.delete(f'/Users/{guid}')

get_info async

get_info() -> LablinkInfo

Fetch metadata for this instance.

Source code in src/pypalmsens/lablink/_session.py
82
83
84
85
86
async def get_info(self) -> LablinkInfo:
    """Fetch metadata for this instance."""
    data = await self._http.get('/Home/GetInfo')
    self._info = LablinkInfo.from_wire(data.json())
    return self._info

get_instrument_info async

get_instrument_info() -> dict[str, dict[str, Any]]

Get info dictionary for currently attached instruments.

Refreshes the instrument_info dictionary and caches it in-place.

Returns:

  • dict[str, dict[str, Any]] –

    A mapping from serial number to instrument info for each currently attached instrument.

Source code in src/pypalmsens/lablink/_session.py
114
115
116
117
118
119
120
121
122
123
124
125
126
async def get_instrument_info(self) -> dict[str, dict[str, Any]]:
    """Get info dictionary for currently attached instruments.

    Refreshes the [instrument_info][] dictionary and caches it in-place.

    Returns
    -------
    dict[str, dict[str, Any]]
        A mapping from serial number to instrument info for each currently
        attached instrument.
    """
    await self._get_instruments()
    return self._instrument_info

get_measurement async

get_measurement(measurement: Measurement | str) -> Dataset | DataTree

Fetch a specific measurement by its reference ID.

Parameters:

  • measurement
    (MeasurementRef | str) –

    The measurement to fetch. Can be a MeasurementRef or its string ID.

Returns:

Source code in src/pypalmsens/lablink/_session.py
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
async def get_measurement(self, measurement: Measurement | str) -> xr.Dataset | xr.DataTree:
    """Fetch a specific measurement by its reference ID.

    Parameters
    ----------
    measurement : MeasurementRef | str
        The measurement to fetch. Can be a MeasurementRef or its string ID.

    Returns
    -------
    xr.Dataset | xr.DataTree
        The parsed measurement data as an xarray object.
    """
    import numpy as np

    if isinstance(measurement, Measurement):
        guid = measurement.guid
    else:
        guid = measurement

    response = await self._http.get(f'/Measurements/{guid}')
    parsed = MeasurementResult.model_validate(response.json())

    # metadata = _to_measurement_metadata(parsed)

    datasets = []

    assert parsed.RawDataSets

    for dataset in parsed.RawDataSets:
        data_vars = {}
        attrs: dict[str, Any] = {}

        dataset, *_ = parsed.RawDataSets
        dataset_id = dataset.DataSetId

        assert dataset.DataArrays

        for array in dataset.DataArrays:
            assert array.DataValueType
            array_type = array.DataValueType.name
            # TODO, what is array ID used for?
            # array_id = array.DataArrayId
            values_id = array.DataValuesId

            response = await self._http.get(f'DataSets/{dataset_id}/{values_id}')
            raw = response.content

            if array_type == 'CurrentRange':
                pairs = np.frombuffer(raw, dtype=np.int32).reshape(-1, 2)
                data = pairs[:, 0]
                # TODO: what is other? factor? exponent? How to store.
                # other = pairs[:, 0]

            elif array_type in (
                'AppliedPotential',
                'Charge',
                'MeasuredCurrent',
                'AuxiliaryPotential',
                'ReverseCurrent',
                'ForwardCurrent',
            ):
                data = np.frombuffer(raw, dtype=np.float64)  # little-endian float64

            elif array_type in (
                'TimingStatus',
                'CurrentReadingStatus',
                'ForwardCurrentReadingStatus',
                'ReverseCurrentReadingStatus',
            ):
                data = np.frombuffer(raw, dtype=np.int8)  # int enum (8-bit signed integer)

            elif array_type in ('Index', 'CycleIndex', 'LevelIndex'):
                data = np.frombuffer(raw, dtype=np.int32)  # int enum (32 bit signed)

            elif array_type == 'Timestamp':
                ticks = np.frombuffer(raw, dtype=np.int64)  # 100-ns ticks
                data = ticks * 1e-7  # seconds

            else:
                print(f'Unknown data type: {array_type=}')
                print('  len:', len(response.content))
                print('  hex:', response.content[:32].hex())
                continue

            data_vars[array_type] = ('point', data, {'unit': '...'})

        coords = {'point': range(len(data))}

        ds = xr.Dataset(data_vars=data_vars, coords=coords, attrs=attrs)
        datasets.append(ds)

    if len(datasets) > 1:
        data = xr.concat(datasets, pd.Index(len(datasets), name='new_dim'))
    else:
        data = datasets[0]

    return data

list_instruments async

list_instruments() -> list[Instrument]

List currently attached instruments.

Refreshes the instruments list.

Returns:

  • list of Instrument –

    A list of currently attached instruments.

Source code in src/pypalmsens/lablink/_session.py
128
129
130
131
132
133
134
135
136
137
138
139
async def list_instruments(self) -> list[Instrument]:
    """List currently attached instruments.

    Refreshes the [instruments][] list.

    Returns
    -------
    list of Instrument
        A list of currently attached instruments.
    """
    await self._get_instruments()
    return self._instruments

list_measurements async

list_measurements() -> list[Measurement]

List all measurements.

Returns:

  • list of MeasurementRef –

    A list of measurement references.

Source code in src/pypalmsens/lablink/_session.py
188
189
190
191
192
193
194
195
196
197
198
199
async def list_measurements(self) -> list[Measurement]:
    """List all measurements.

    Returns
    -------
    list of MeasurementRef
        A list of measurement references.
    """
    data = await self._http.get('/Measurements')
    refs = [MeasurementListResult.model_validate(item) for item in data.json()]
    # TODO: Expose `MeasurementListResult` data via Measurement.info()
    return [Measurement(str(ref.Id), session=self) for ref in refs]

list_users async

list_users() -> list[UserInfo]

Get list of users.

Returns:

  • users ( list[UserInfo] ) –

    List of user info

Source code in src/pypalmsens/lablink/_session.py
419
420
421
422
423
424
425
426
427
428
async def list_users(self) -> list[UserInfo]:
    """Get list of users.

    Returns
    -------
    users : list[UserInfo]
        List of user info
    """
    data = await self._http.get('/Users')
    return [UserInfo.from_wire(item) for item in data.json()]

pause_measurement async

pause_measurement(jobs: Sequence[MeasurementJob]) -> None

Pause running measurements on the given jobs.

Parameters:

Source code in src/pypalmsens/lablink/_session.py
353
354
355
356
357
358
359
360
361
362
363
364
365
366
async def pause_measurement(self, jobs: Sequence[MeasurementJob]) -> None:
    """Pause running measurements on the given jobs.

    Parameters
    ----------
    jobs : Sequence[MeasurementJob]
        The measurement jobs to pause.
    """
    payload = {
        'AllInstrumentsMustSucceed': True,
        'InstrumentProperties': {job.serial_number: {} for job in jobs},
    }

    await self._http.post('/Instrument/PauseMeasurement', json=payload)

release async

Release the given instruments back to Lablink.

Parameters:

Source code in src/pypalmsens/lablink/_session.py
173
174
175
176
177
178
179
180
181
182
183
184
185
186
async def release(self, instruments: Sequence[InstrumentClaim]) -> None:
    """Release the given instruments back to Lablink.

    Parameters
    ----------
    instruments : Sequence[InstrumentClaim]
        Claimed instruments to release.
    """
    props = {instrument.serial_number: EmptyProperty() for instrument in instruments}
    payload = SimpleInstrumentsCommand(
        InstrumentProperties=props, AllInstrumentsMustSucceed=True
    )

    await self._http.post('/Instruments/UnClaim', json=payload.model_dump())

resume_measurement async

resume_measurement(jobs: Sequence[MeasurementJob]) -> None

Resume a measurement that was previously paused.

Parameters:

Source code in src/pypalmsens/lablink/_session.py
368
369
370
371
372
373
374
375
376
377
378
379
380
381
async def resume_measurement(self, jobs: Sequence[MeasurementJob]) -> None:
    """Resume a measurement that was previously paused.

    Parameters
    ----------
    jobs : Sequence[MeasurementJob]
        The measurement jobs to resume.
    """
    payload = {
        'AllInstrumentsMustSucceed': True,
        'InstrumentProperties': {job.serial_number: {} for job in jobs},
    }

    await self._http.post('/Instrument/ResumeMeasurement', json=payload)

skip_pre_measurement_stage async

skip_pre_measurement_stage(jobs: Sequence[MeasurementJob]) -> None

Skip the pre-measurement stage on the given measurement jobs.

Parameters:

Source code in src/pypalmsens/lablink/_session.py
338
339
340
341
342
343
344
345
346
347
348
349
350
351
async def skip_pre_measurement_stage(self, jobs: Sequence[MeasurementJob]) -> None:
    """Skip the pre-measurement stage on the given measurement jobs.

    Parameters
    ----------
    jobs : Sequence[MeasurementJob]
        The running measurements to skip the pre-stage of.
    """
    payload = {
        'AllInstrumentsMustSucceed': True,
        'InstrumentProperties': {job.serial_number: {} for job in jobs},
    }

    await self._http.post('/Instrument/SkipPreMeasurementStage', json=payload)

start_measurement async

Start a measurement on each of the claimed instruments.

Parameters:

Returns:

  • list[MeasurementJob] –

    One job per instrument, each with an associated MeasurementJob.

Source code in src/pypalmsens/lablink/_session.py
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
async def start_measurement(
    self, instruments: Sequence[InstrumentClaim], *, method: MethodTypeCompatible
) -> list[MeasurementJob]:
    """Start a measurement on each of the claimed instruments.

    Parameters
    ----------
    instruments : Sequence[InstrumentClaim]
        Instruments (claimed) to start measuremeents on.
    method : MethodTypeCompatible
        The measurement method to apply.

    Returns
    -------
    list[MeasurementJob]
        One job per instrument, each with an associated MeasurementJob.
    """
    payload = {
        **to_payload(method),
        'AllInstrumentsMustSucceed': True,
        'InstrumentProperties': {
            instrument.serial_number: {} for instrument in instruments
        },
    }

    response = await self._http.post('/Instruments/StartMeasurement', json=payload)

    jobs = []
    claims = {claim.serial_number: claim for claim in instruments}

    for data in response.json():
        guid = data['result']
        serial = data['serial']
        claim = claims[serial]
        jobs.append(MeasurementJob(guid=guid, claim=claim))

    return jobs

start_workflow async

start_workflow(instruments: Sequence[InstrumentClaim], *, workflow: str) -> None

Start a workflow on the given instruments.

Parameters:

  • instruments
    (Sequence[InstrumentClaim]) –

    The claimed instruments that will run the workflow.

  • workflow
    (str) –

    Name of the workflow to start.

Source code in src/pypalmsens/lablink/_session.py
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
async def start_workflow(
    self, instruments: Sequence[InstrumentClaim], *, workflow: str
) -> None:
    """Start a workflow on the given instruments.

    Parameters
    ----------
    instruments : Sequence[InstrumentClaim]
        The claimed instruments that will run the workflow.
    workflow : str
        Name of the workflow to start.
    """
    data = {
        'AllInstrumentsMustSucceed': True,
        'InstrumentProperties': {
            instrument.serial_number: workflow for instrument in instruments
        },
    }
    payload = SendWorkflowCommand.model_validate(data).model_dump()
    await self._http.post('/Instrument/SendScript', json=payload)

discover async

discover(ip_version: IPVersion = All, timeout: float = 10) -> list[dict[str, Any]]

Browse the local network for LabLink devices for a fixed duration.

Uses zeroconf to browse for the _lablink._tcp.local. service type. Each discovered device is resolved into a dictionary of properties (hostname, addresses, TXT record fields) and appended to the results list.

Parameters:

  • ip_version

    (IPVersion, default: All ) –

    IP protocol version for browsing/name resolution. Defaults to zeroconf.IPVersion.All.

  • timeout

    (float, default: 10 ) –

    How many seconds to browse before stopping. Default is 10.

Returns:

  • list[dict] –

    One dictionary per discovered LabLink device. Each dict contains:

    • server: fully qualified host name (e.g. "lablink-01.local.")
    • addresses: parsed scoped IP address strings
    • other TXT record fields as-is, e.g. name, serial, version

    The list is empty if no devices are discovered within the timeout.

Examples:

>>> import asyncio
>>> devices = asyncio.run(discover(timeout=10))
>>> device, _* = devices
>>> devices["name"]
'lablink-01'
>>> devices["addresses"]
['192.168.1.42', ...]
Source code in src/pypalmsens/lablink/_discover.py
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
async def discover(
    ip_version: IPVersion = IPVersion.All,
    timeout: float = 10,
) -> list[dict[str, Any]]:
    """
    Browse the local network for LabLink devices for a fixed duration.

    Uses zeroconf to browse for the `_lablink._tcp.local.` service type.
    Each discovered device is resolved into a dictionary of properties
    (hostname, addresses, TXT record fields) and appended to the results list.

    Parameters
    ----------
    ip_version : IPVersion
        IP protocol version for browsing/name resolution.
        Defaults to `zeroconf.IPVersion.All`.
    timeout : float
        How many seconds to browse before stopping. Default is 10.

    Returns
    -------
    list[dict]
        One dictionary per discovered LabLink device. Each dict contains:

        * server: fully qualified host name (e.g. "lablink-01.local.")
        * addresses: parsed scoped IP address strings
        * other TXT record fields as-is, e.g. name, serial, version

        The list is empty if no devices are discovered within the timeout.

    Examples
    --------
    >>> import asyncio
    >>> devices = asyncio.run(discover(timeout=10))
    >>> device, _* = devices
    >>> devices["name"]
    'lablink-01'
    >>> devices["addresses"]
    ['192.168.1.42', ...]
    """
    discovered: list[dict[str, Any]] = []
    tasks: set[asyncio.Task] = set()

    def on_service_state_change(
        zeroconf: Zeroconf, service_type: str, name: str, state_change: ServiceStateChange
    ) -> None:
        logger.info('%s: %s', state_change.name, name)
        if state_change is ServiceStateChange.Added:
            task = asyncio.create_task(
                _resolve_service_info(zeroconf, service_type, name, discovered)
            )
            tasks.add(task)
            task.add_done_callback(tasks.discard)

    aiozc = AsyncZeroconf(ip_version=ip_version)
    browser = AsyncServiceBrowser(
        aiozc.zeroconf, '_lablink._tcp.local.', handlers=[on_service_state_change]
    )
    logger.info('browsing for _lablink._tcp.local (timeout=%s s).', timeout)

    try:
        await asyncio.sleep(timeout)
        _ = await asyncio.gather(*tasks, return_exceptions=True)
    finally:
        await browser.async_cancel()
        await aiozc.async_close()

    return discovered