pulsepal.pulse_pal

Python interface for the Pulse Pal open source pulse train generator.

Pulse Pal delivers precisely timed voltage pulse trains on four analog output channels, and can be triggered by TTL logic on two trigger channels or in software. This module configures and triggers the device over its USB serial port.

Everything is accessed through PulsePalDevice. Import it, connect to the device's serial port, set parameters, and trigger, e.g.

from pulsepal import PulsePalDevice

with PulsePalDevice("COM3") as P:
    P.phase1_voltage[1] = 5            # volts, output channel 1
    P.phase1_duration[1] = 0.001       # seconds: 1 ms pulses,
    P.inter_pulse_interval[1] = 0.049  # 49 ms apart (end of one to start of the next),
    P.pulse_train_duration[1] = 2      # for 2 seconds
    P.trigger(1)

Parameters

Each parameter is a list on the device object, indexed by channel number: index 0 is unused and holds None, and indices 1 to 4 hold the values for output channels 1-4. PulsePalDevice.trigger_mode is indexed the same way by trigger channel, 1 or 2. Assigning an element, a slice or the whole list programs the device at once, on the channels whose value it changes: the others keep what the device holds, which may have been set with its joystick. The whole list takes one value per channel: a single value raises an error, because it does not say which channels it is meant for.

P.phase1_voltage[2] = 7                  # channel 2 only
P.inter_pulse_interval[1:5] = [0.2] * 4  # all four channels
P.phase1_voltage = [5, 5, 5, 5]          # all four channels
P.trigger_mode[2] = "Toggle"             # trigger channel 2

To change several parameters in one command, assign them in a PulsePalDevice.batch block: they are sent together when it ends.

with P.batch():
    P.is_biphasic[1] = True
    P.phase2_voltage[1] = -5
    P.inter_phase_interval[1] = 0.0005

PulsePalDevice.auto_sync set to False does the same for as long as it stays off, until PulsePalDevice.sync_to_device is called; turning it back on before then raises an error. That is how the next trial's parameters wait for a TTL in param sync mode (see PulsePalDevice.trigger_mode).

Assigning an attribute that is not a setting, such as a misspelled one or the MATLAB class's phase1Voltage, raises AttributeError.

Units and values

Voltages are in volts in the range [-10, 10]. Times are in seconds, from 0 to MAX_TIME (9999.9999 s), and are rounded to the nearest cycle of the device's hardware timer (DeviceInfo.cycle_period_us): 10 us on Pulse Pal 3, and 50 us on Pulse Pal 2 and on Pulse Pal 3 with firmware from before October 2026. The parameter then holds the time the device plays, so 0.000123 reads back as 0.00012 (0.0001 on a 50 us timer). A time exactly halfway between two cycles rounds to the even one, as in the MATLAB and C++ classes, and voltages round to the nearest DAC code the same way. On/off parameters are True or False, and modes are names, such as "Gated"; names are not case sensitive, and the integer codes of older Pulse Pal software are accepted too.

A value the device cannot play raises pulsepal.PulsePalError before anything is sent: a voltage outside [-10, 10], a time that is negative, longer than MAX_TIME or not a number, or an unknown name. So does a pulse phase, inter-pulse interval or pulse train duration shorter than DeviceInfo.min_pulse_width_us (10 us on Pulse Pal 3, 100 us on Pulse Pal 2), so that a Pulse Pal's trigger channels can detect the shortest pulse its output channels play. Custom pulse times are not rounded: each must be a multiple of DeviceInfo.min_pulse_width_us.

Saving parameters

PulsePalDevice.export_params returns every parameter as a dict, to store with your data or in a file, and PulsePalDevice.import_params programs the device with one. The device's microSD card holds programs too, which its joystick menu can load: PulsePalDevice.save_program_to_microsd.

Further reading

License

This file is part of the Sanworks PulsePal repository. Copyright (C) Sanworks LLC, Rochester, New York, USA

This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 3.

This program is distributed WITHOUT ANY WARRANTY and without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/.

   1"""
   2Python interface for the [Pulse Pal](https://sites.google.com/site/pulsepalwiki/)
   3open source pulse train generator.
   4
   5Pulse Pal delivers precisely timed voltage pulse trains on four analog
   6output channels, and can be triggered by TTL logic on two trigger
   7channels or in software. This module configures and triggers the device
   8over its USB serial port.
   9
  10Everything is accessed through `PulsePalDevice`. Import it, connect to
  11the device's serial port, set parameters, and trigger, e.g.
  12
  13```python
  14from pulsepal import PulsePalDevice
  15
  16with PulsePalDevice("COM3") as P:
  17    P.phase1_voltage[1] = 5            # volts, output channel 1
  18    P.phase1_duration[1] = 0.001       # seconds: 1 ms pulses,
  19    P.inter_pulse_interval[1] = 0.049  # 49 ms apart (end of one to start of the next),
  20    P.pulse_train_duration[1] = 2      # for 2 seconds
  21    P.trigger(1)
  22```
  23
  24## Parameters
  25
  26Each parameter is a list on the device object, indexed by channel
  27number: index 0 is unused and holds `None`, and indices 1 to 4 hold the
  28values for output channels 1-4. `PulsePalDevice.trigger_mode` is indexed
  29the same way by trigger channel, 1 or 2. Assigning an element, a slice
  30or the whole list programs the device at once, on the channels whose
  31value it changes: the others keep what the device holds, which may have
  32been set with its joystick. The whole list takes one value per channel:
  33a single value raises an error, because it does not say which channels it
  34is meant for.
  35
  36```python
  37P.phase1_voltage[2] = 7                  # channel 2 only
  38P.inter_pulse_interval[1:5] = [0.2] * 4  # all four channels
  39P.phase1_voltage = [5, 5, 5, 5]          # all four channels
  40P.trigger_mode[2] = "Toggle"             # trigger channel 2
  41```
  42
  43To change several parameters in one command, assign them in a
  44`PulsePalDevice.batch` block: they are sent together when it ends.
  45
  46```python
  47with P.batch():
  48    P.is_biphasic[1] = True
  49    P.phase2_voltage[1] = -5
  50    P.inter_phase_interval[1] = 0.0005
  51```
  52
  53`PulsePalDevice.auto_sync` set to `False` does the same for as long as
  54it stays off, until `PulsePalDevice.sync_to_device` is called; turning
  55it back on before then raises an error. That is how the next trial's
  56parameters wait for a TTL in param sync mode (see
  57`PulsePalDevice.trigger_mode`).
  58
  59Assigning an attribute that is not a setting, such as a misspelled one
  60or the MATLAB class's `phase1Voltage`, raises `AttributeError`.
  61
  62## Units and values
  63
  64Voltages are in volts in the range [-10, 10]. Times are in seconds, from
  650 to `MAX_TIME` (9999.9999 s), and are rounded to the nearest cycle of
  66the device's hardware timer (`DeviceInfo.cycle_period_us`): 10 us on
  67Pulse Pal 3, and 50 us on Pulse Pal 2 and on Pulse Pal 3 with firmware
  68from before October 2026. The parameter then holds the time the device
  69plays, so 0.000123 reads back as 0.00012 (0.0001 on a 50 us timer). A
  70time exactly halfway between two cycles rounds to the
  71even one, as in the MATLAB and C++ classes, and voltages round to the
  72nearest DAC code the same way. On/off parameters are `True` or `False`,
  73and modes are names, such as `"Gated"`; names are not case sensitive,
  74and the integer codes of older Pulse Pal software are accepted too.
  75
  76A value the device cannot play raises `pulsepal.PulsePalError` before
  77anything is sent: a voltage outside [-10, 10], a time that is negative,
  78longer than `MAX_TIME` or not a number, or an unknown name. So does a
  79pulse phase, inter-pulse interval or pulse train duration shorter than
  80`DeviceInfo.min_pulse_width_us` (10 us on Pulse Pal 3, 100 us on Pulse
  81Pal 2), so that a Pulse Pal's trigger channels can detect the shortest
  82pulse its output channels play. Custom pulse times are not rounded: each
  83must be a multiple of `DeviceInfo.min_pulse_width_us`.
  84
  85## Saving parameters
  86
  87`PulsePalDevice.export_params` returns every parameter as a dict, to
  88store with your data or in a file, and `PulsePalDevice.import_params`
  89programs the device with one. The device's microSD card holds programs
  90too, which its joystick menu can load:
  91`PulsePalDevice.save_program_to_microsd`.
  92
  93## Further reading
  94
  95- Parameter guide:
  96  https://sites.google.com/site/pulsepalwiki/parameter-guide
  97- Serial interface and general documentation:
  98  https://sites.google.com/site/pulsepalwiki/
  99- `pulsepal.wave_pal`: alternative firmware that makes a Pulse Pal 3 a
 100  four channel waveform player, and its class, `pulsepal.WavePalDevice`.
 101- `pulsepal.synth_pal`: alternative firmware that makes a Pulse Pal 3 a
 102  four channel waveform synthesizer, and its class,
 103  `pulsepal.SynthPalDevice`.
 104
 105## License
 106
 107This file is part of the Sanworks PulsePal repository.
 108Copyright (C) Sanworks LLC, Rochester, New York, USA
 109
 110This program is free software: you can redistribute it and/or modify
 111it under the terms of the GNU General Public License as published by
 112the Free Software Foundation, version 3.
 113
 114This program is distributed WITHOUT ANY WARRANTY and without even the
 115implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 116See the GNU General Public License for more details.
 117
 118You should have received a copy of the GNU General Public License
 119along with this program. If not, see <http://www.gnu.org/licenses/>.
 120"""
 121
 122import collections.abc
 123from dataclasses import dataclass
 124import math
 125import numbers
 126import struct
 127import time
 128import warnings
 129
 130import numpy as np
 131import serial
 132
 133from . import _common
 134from ._common import ChannelSettings, PulsePalError, to_bool, to_name
 135
 136__all__ = ["PulsePalDevice", "DeviceInfo", "DeviceStatus", "TRIGGER_MODES", "CUSTOM_TRAIN_TARGETS", "MAX_TIME"]
 137__docformat__ = "google"
 138
 139MAX_TIME = 9999.9999
 140"""The longest time parameter or custom pulse time, in seconds: the most
 141the device's joystick menu shows and edits (four digits before the
 142point)."""
 143
 144TRIGGER_MODES = ("Normal", "Toggle", "Gated", "Param Sync")
 145"""Names of the trigger modes, in order of their code on the device (0-3).
 146"Param Sync" is on Pulse Pal 3 only. See `PulsePalDevice.trigger_mode`."""
 147
 148CUSTOM_TRAIN_TARGETS = ("Pulses", "Bursts")
 149"""Names of the custom train targets, in order of their code on the device.
 150See `PulsePalDevice.custom_train_target`."""
 151
 152# Output parameters by parameter code (see "Parameter codes" in PulsePal-Firmware/PROTOCOL.md), with
 153# the kind of value each takes. The codes are fixed: installed clients and the firmware use them.
 154# "pulse_time" is a time of at least DeviceInfo.min_pulse_width_us.
 155_OUTPUT_PARAMETERS = {
 156    1: ("is_biphasic", "bool"),
 157    2: ("phase1_voltage", "volts"),
 158    3: ("phase2_voltage", "volts"),
 159    4: ("phase1_duration", "pulse_time"),
 160    5: ("inter_phase_interval", "time"),
 161    6: ("phase2_duration", "pulse_time"),
 162    7: ("inter_pulse_interval", "pulse_time"),
 163    8: ("burst_duration", "time"),
 164    9: ("inter_burst_interval", "time"),
 165    10: ("pulse_train_duration", "pulse_time"),
 166    11: ("pulse_train_delay", "time"),
 167    12: ("link_trigger_channel1", "bool"),
 168    13: ("link_trigger_channel2", "bool"),
 169    14: ("custom_train_id", "train_id"),
 170    15: ("custom_train_target", "target"),
 171    16: ("custom_train_loop", "bool"),
 172    17: ("resting_voltage", "volts"),
 173    18: ("continuous_loop", "bool"),
 174}
 175_OUTPUT_PARAMETER_CODES = {name: code for code, (name, _) in _OUTPUT_PARAMETERS.items()}
 176_TRIGGER_MODE_CODE = 128  # The one trigger channel parameter
 177_CONTINUOUS_LOOP_CODE = 18  # Not in ops 73 and 93, or settings files
 178_BURST_DURATION_CODE = 8  # These two are checked together: see PulsePalDevice._check_custom_bursts()
 179_CUSTOM_TRAIN_TARGET_CODE = 15
 180_FORMAT_KEY = b"WIPE"  # Follows op 97, so that two stray bytes cannot format the card (FORMAT_SD_CARD_KEY in the firmware)
 181# The ops whose reply _write_raw() does not track: those with no reply, and the handshakes (72 and 103), whose reply
 182# read_handshake_reply() reads until the device is quiet
 183_OPS_WITHOUT_TRACKED_REPLY = frozenset({72, 77, 80, 81, 89, 98, 103})
 184# The ops that can change the parameters: if the reply to one is lost, they are read back (_discard_lost_reply())
 185_PARAMETER_OPS = frozenset({73, 74, 90, 91, 92, 97})
 186# The names a script assigns: the output parameters, in parameter code order, then these
 187_SETTING_NAMES = (*(name for name, _ in _OUTPUT_PARAMETERS.values()), "trigger_mode", "auto_sync")
 188
 189# The parameters that ops 73, 92 and 93 carry in each block, in order
 190_TIME_PARAMETERS = ("phase1_duration", "inter_phase_interval", "phase2_duration", "inter_pulse_interval",
 191                    "burst_duration", "inter_burst_interval", "pulse_train_duration", "pulse_train_delay")
 192_VOLTAGE_PARAMETERS = ("phase1_voltage", "phase2_voltage", "resting_voltage")
 193
 194# The default parameters: the device's own (LoadDefaultParameters() in PulsePal-Firmware/PulsePal/SDSettings.ino), which it
 195# loads at startup, after a comm failure and after formatting its microSD card, so that it plays the same program
 196# whichever way it got its defaults. The MATLAB class has the same; the legacy clients keep their own.
 197_DEFAULT_OUTPUT_VALUES = {
 198    "is_biphasic": False,
 199    "phase1_voltage": 5.0,
 200    "phase2_voltage": -5.0,
 201    "phase1_duration": 0.0001,
 202    "inter_phase_interval": 0.0001,
 203    "phase2_duration": 0.0001,
 204    "inter_pulse_interval": 0.001,
 205    "burst_duration": 0.0,
 206    "inter_burst_interval": 0.0,
 207    "pulse_train_duration": 1.0,
 208    "pulse_train_delay": 0.0,
 209    "link_trigger_channel1": False,  # Until 2026-10 True, so a TTL played these pulses on every output channel
 210    "link_trigger_channel2": False,
 211    "custom_train_id": 0,
 212    "custom_train_target": "Pulses",
 213    "custom_train_loop": False,
 214    "resting_voltage": 0.0,
 215    "continuous_loop": False,
 216}
 217
 218
 219@dataclass
 220class DeviceInfo:
 221    """Properties of the connected Pulse Pal device.
 222
 223    An instance is created for each connection and populated during the
 224    handshake in `PulsePalDevice.__init__`. It is available as
 225    `PulsePalDevice.info`. Devices running firmware v21 report only a
 226    firmware version, so the remaining fields are filled in with the
 227    known values for Pulse Pal hardware v2.
 228
 229    ```python
 230    print(P.info.firmware_version)
 231    ```
 232    """
 233
 234    output_parameter_names: tuple = tuple(name for name, _ in _OUTPUT_PARAMETERS.values())
 235    """Output parameter names, ordered by parameter code.
 236
 237    Each is the name of a parameter list on `PulsePalDevice`, and a key of
 238    the dict `PulsePalDevice.export_params` returns.
 239    """
 240
 241    trigger_modes: tuple = TRIGGER_MODES
 242    """Names of the trigger modes the connected device has, accepted by
 243    `PulsePalDevice.trigger_mode`. Pulse Pal 2 has no "Param Sync"."""
 244
 245    custom_train_targets: tuple = CUSTOM_TRAIN_TARGETS
 246    """Names accepted by `PulsePalDevice.custom_train_target`."""
 247
 248    firmware_version: int = None
 249    """Firmware version running on the connected device."""
 250
 251    hardware_version: int = None
 252    """Hardware version of the connected device, e.g. `2` or `3`.
 253
 254    Reported by the device on firmware v22 and newer; assumed to be `2`
 255    on older firmware.
 256    """
 257
 258    circuit_board_revision: int = None
 259    """Revision of the device's circuit board, 0-31.
 260
 261    A Pulse Pal 3 board encodes its revision on five pins, which the
 262    firmware reads at startup. A board that encodes none reports `0`, as
 263    does Pulse Pal 2; firmware older than v22 cannot report one, so it is
 264    also `0` there. To record exactly which hardware ran an experiment,
 265    copy `hardware_version` and `circuit_board_revision` to your data.
 266    """
 267
 268    serial_number: str = None
 269    """USB serial number of the device, e.g. `"20345420"`: the Teensy's,
 270    unique to each Pulse Pal 3, and the same whichever firmware it runs.
 271
 272    Connect by it, wherever the device is plugged in, with
 273    `PulsePalDevice(serial_number="20345420")`. To record exactly which unit ran an
 274    experiment, copy it to your data. Pulse Pal 2 has none, and
 275    firmware older than v22 cannot report one: `""`.
 276    """
 277
 278    max_custom_pulses: int = None
 279    """Maximum number of pulses in a single custom pulse train."""
 280
 281    n_custom_pulse_trains: int = None
 282    """Number of custom pulse trains the device can store."""
 283
 284    cycle_frequency: float = None
 285    """Update frequency of the device's hardware timer, in Hz.
 286
 287    All time parameters are rounded to a whole number of these cycles,
 288    so this sets the timing resolution of the device.
 289    """
 290
 291    cycle_period_us: float = None
 292    """Update period of the device's hardware timer, in microseconds."""
 293
 294    min_pulse_width_us: float = None
 295    """Shortest pulse phase, inter-pulse interval and pulse train duration,
 296    and shortest time between custom pulses, in microseconds.
 297
 298    One timer cycle (10 us) on Pulse Pal 3, whose trigger channels latch
 299    every edge on their inputs. Two cycles (100 us) on Pulse Pal 2, whose
 300    trigger channels read their inputs once per cycle, so that a one cycle
 301    pulse could fall between two reads. A Pulse Pal 2, or a Pulse Pal 3
 302    with firmware from before October 2026, can miss a pulse shorter than
 303    100 us from a Pulse Pal 3. Custom pulse times are multiples of it.
 304    """
 305
 306    max_time: float = MAX_TIME
 307    """Longest time parameter or custom pulse time, in seconds. See
 308    `MAX_TIME`."""
 309
 310
 311@dataclass
 312class DeviceStatus:
 313    """What the device is doing, and what has happened to it, from
 314    `PulsePalDevice.status`.
 315
 316    The counters count from the previous call to `PulsePalDevice.status`,
 317    by this or any earlier connection, or from the device's startup: each
 318    call clears them, and reports what happened since the one before.
 319    """
 320
 321    playing: list
 322    """Numbers of the output channels playing, e.g. `[1, 3]`: from a
 323    channel's start, its pulse train delay included, until its train
 324    ends."""
 325
 326    trigger_edges: list
 327    """Rising edges on each trigger channel, indexed by trigger channel
 328    number (index 0 is unused), whatever its trigger mode and whether or
 329    not they started an output channel."""
 330
 331    channel_starts: list
 332    """Times each output channel started, indexed by channel number
 333    (index 0 is unused): by a trigger channel, `PulsePalDevice.trigger`
 334    or the joystick menu. A trigger that a channel ignored, because it
 335    was already playing, is not a start."""
 336
 337    comm_failures: int
 338    """Commands that reached the device only in part, after which it
 339    showed COMM. FAILURE! and waited for its joystick to be clicked."""
 340
 341
 342def _params_to_import(params):
 343    """The parameters import_params() programs, as {name: values} by this class's names.
 344
 345    `params` is what export_params() returns, or a whole program file as json.load() reads it, whose "params" are
 346    taken; the MATLAB class's names are accepted too ("phase1Voltage"), so that its exportParams() can be imported.
 347    Names that are not parameters are skipped with a warning, and if none is, PulsePalError is raised: the device
 348    would otherwise be sent its program unchanged, with only a warning to say why.
 349    """
 350    if not isinstance(params, collections.abc.Mapping):
 351        raise PulsePalError(
 352            f"import_params() takes a dict of parameters, as export_params() returns. Received {type(params).__name__}."
 353        )
 354    if isinstance(params.get("params"), collections.abc.Mapping):
 355        # A program file, as the GUIs and the MATLAB class's saveProgramToFile() save it: format_version, params, the
 356        # text of each custom train, device_info (see "Program files" in /USING.md)
 357        program = params
 358        params = dict(program["params"])
 359        if "trigger_mode" not in params and "trigger_mode" in program:
 360            params["trigger_mode"] = program["trigger_mode"]  # Files from before format_version held it here
 361        if any(program.get("custom_train_timestamps") or []) or any(program.get("custom_train_voltages") or []):
 362            _common.warn("import_params() imports a program file's parameters only: open it with gui() to load its "
 363                         "custom trains too.")
 364    keys = {}  # This class's name: the key in params
 365    unknown = []
 366    for key in params:
 367        name = _common.snake_case(key) if isinstance(key, str) else None
 368        if name not in _SETTING_NAMES or name == "auto_sync":
 369            unknown.append(key)
 370        elif name in keys:
 371            raise PulsePalError(f"import_params(): {keys[name]!r} and {key!r} are the same parameter.")
 372        else:
 373            keys[name] = key
 374    if not keys:
 375        listed = ", ".join(map(repr, unknown)) or "nothing"
 376        raise PulsePalError(
 377            f"import_params() found no parameter in {listed}, so it programs nothing. It takes what export_params() "
 378            "returns, e.g. {'phase1_voltage': [5, 5, 5, 5]}, or a whole program file (json.load() of one)."
 379        )
 380    if unknown:
 381        _common.warn(f"import_params(): skipped {', '.join(map(repr, unknown))}, which this version of PulsePalDevice "
 382                     "does not have.")
 383    return {name: params[key] for name, key in keys.items()}
 384
 385
 386def _channel_setting(name, doc):
 387    """A property for one of PulsePalDevice's parameter lists."""
 388
 389    def get(self):
 390        return getattr(self, "_" + name)
 391
 392    def set_(self, values):
 393        getattr(self, "_" + name)._assign(values)
 394
 395    return property(get, set_, doc=doc)
 396
 397
 398class PulsePalDevice:
 399    """A class to control a Pulse Pal device on a USB serial port.
 400
 401    Creating an instance opens the serial port, exchanges a handshake
 402    with the device, verifies that its firmware is supported, reads the
 403    device properties into `PulsePalDevice.info`, and programs the
 404    device with the default parameters (see
 405    `PulsePalDevice.set_default_params`).
 406
 407    ```python
 408    from pulsepal import PulsePalDevice
 409
 410    P = PulsePalDevice("COM3")
 411    P.phase1_voltage[1] = 5
 412    P.trigger(1)
 413    P.close()
 414    ```
 415
 416    Here, replace "COM3" with Pulse Pal's USB serial port name.
 417    To view a list of available ports, use
 418    `PulsePalDevice.serialportlist()`.
 419    Pulse Pal's port may not be visible if it is connected to another
 420    instance of PulsePalDevice or an external application. Use
 421    `PulsePalDevice.serialportlist("all")` to view all ports.
 422    If you see multiple available ports, disconnect Pulse Pal's USB plug
 423    and run serialportlist() again. Notice which port disappears from the
 424    list.
 425
 426    PulsePalDevice is also a context manager, which closes the connection on
 427    exit even if an error is raised:
 428
 429    ```python
 430    with PulsePalDevice("COM3") as P:
 431        P.trigger(1)
 432    ```
 433
 434    The attributes below named after Pulse Pal parameters are lists
 435    indexed by channel number, with index 0 unused (see "Parameters"
 436    above). `print(P)` shows them all, and `PulsePalDevice.export_params`
 437    returns them as a dict.
 438    """
 439
 440    port: "serial.Serial"
 441    """The open `serial.Serial` port connected to the device."""
 442
 443    info: DeviceInfo
 444    """Properties of the connected device. See `DeviceInfo`."""
 445
 446    is_biphasic = _channel_setting("is_biphasic", """Pulse shape per channel: `False` for monophasic, `True` for biphasic.
 447
 448    Monophasic pulses use only the phase 1 parameters. Biphasic pulses
 449    follow phase 1 with `PulsePalDevice.inter_phase_interval` and then
 450    phase 2.
 451    """)
 452
 453    phase1_voltage = _channel_setting("phase1_voltage", """Voltage of the first phase of each pulse, in volts [-10, 10].""")
 454
 455    phase2_voltage = _channel_setting("phase2_voltage", """Voltage of the second phase of each pulse, in volts [-10, 10].
 456
 457    Used only when `PulsePalDevice.is_biphasic` is `True` for the channel.
 458    """)
 459
 460    resting_voltage = _channel_setting("resting_voltage", """Voltage held between pulses, in volts [-10, 10].
 461
 462    A new resting voltage reaches an idle channel's output at once. A
 463    channel playing a pulse train keeps playing it, and moves to the new
 464    resting voltage at its next transition to rest.
 465    """)
 466
 467    phase1_duration = _channel_setting("phase1_duration", """Duration of the first phase of each pulse, in seconds.
 468
 469    At least `DeviceInfo.min_pulse_width_us`.
 470    """)
 471
 472    inter_phase_interval = _channel_setting("inter_phase_interval", """Interval between the two phases of a biphasic pulse, in seconds.
 473
 474    The channel rests at `PulsePalDevice.resting_voltage` during the
 475    interval. Used only when `PulsePalDevice.is_biphasic` is `True`.
 476    """)
 477
 478    phase2_duration = _channel_setting("phase2_duration", """Duration of the second phase of each pulse, in seconds.
 479
 480    Used only when `PulsePalDevice.is_biphasic` is `True` for the channel.
 481    At least `DeviceInfo.min_pulse_width_us`.
 482    """)
 483
 484    inter_pulse_interval = _channel_setting("inter_pulse_interval", """Interval from the end of one pulse to the start of the next, in
 485    seconds. At least `DeviceInfo.min_pulse_width_us`.
 486
 487    It is not the pulse period: 1 ms pulses 49 ms apart play 20 pulses per
 488    second.
 489    """)
 490
 491    burst_duration = _channel_setting("burst_duration", """Duration of each burst of pulses, in seconds.
 492
 493    Set to `0` to disable bursts, so that pulses continue for the whole
 494    pulse train. A pulse starts only if it ends before the burst does:
 495    its first phase, or for a biphasic pulse the whole pulse, so that
 496    the end of a burst never cuts off a second phase.
 497    """)
 498
 499    inter_burst_interval = _channel_setting("inter_burst_interval", """Interval between bursts of pulses, in seconds.
 500
 501    The channel rests at `PulsePalDevice.resting_voltage` between
 502    bursts. Ignored when `PulsePalDevice.burst_duration` is `0`.
 503    """)
 504
 505    pulse_train_duration = _channel_setting("pulse_train_duration", """Total duration of the pulse train, in seconds.
 506
 507    At least `DeviceInfo.min_pulse_width_us`. The end of the train cuts
 508    short a monophasic pulse still playing. A biphasic pulse starts only
 509    if it can end by the end of the train, so that it keeps its second
 510    phase. A train's end is set when it starts: a new duration applies
 511    from the next train.
 512    """)
 513
 514    pulse_train_delay = _channel_setting("pulse_train_delay", """Delay from the trigger to the onset of the pulse train, in
 515    seconds.""")
 516
 517    link_trigger_channel1 = _channel_setting("link_trigger_channel1", """Whether each output channel is triggered by trigger channel 1.
 518
 519    `True` links the output channel to trigger channel 1, `False` unlinks
 520    it. By default no output channel is linked to either trigger channel,
 521    so a TTL starts nothing until a script links it.
 522    """)
 523
 524    link_trigger_channel2 = _channel_setting("link_trigger_channel2", """Whether each output channel is triggered by trigger channel 2.
 525
 526    `True` links the output channel to trigger channel 2, `False` unlinks
 527    it.
 528    """)
 529
 530    custom_train_id = _channel_setting("custom_train_id", """Custom pulse train played by each output channel.
 531
 532    `0` plays the parametrically defined train. `1` or higher plays the
 533    matching custom train, previously loaded with
 534    `PulsePalDevice.send_custom_pulse_train` or
 535    `PulsePalDevice.send_custom_waveform`: 1-4 on Pulse Pal 3, 1-2 on
 536    Pulse Pal 2 (`DeviceInfo.n_custom_pulse_trains`).
 537    """)
 538
 539    custom_train_target = _channel_setting("custom_train_target", """What the times of a custom train mark.
 540
 541    `"Pulses"` if each time is the onset of a pulse, `"Bursts"` if each
 542    time is the onset of a burst of pulses, which lasts
 543    `PulsePalDevice.burst_duration`. A burst whose time comes while the
 544    burst before plays is dropped, so that every burst played is on
 545    time. `"Bursts"` needs a burst duration above 0: with
 546    `PulsePalDevice.auto_sync` on, set the burst duration first, or set
 547    both in a `PulsePalDevice.batch` block.
 548    """)
 549
 550    custom_train_loop = _channel_setting("custom_train_loop", """Whether a custom train repeats.
 551
 552    `True` loops the custom train until
 553    `PulsePalDevice.pulse_train_duration` has elapsed, `False` plays it
 554    once. Each pass starts as the last pulse (or burst, for a train
 555    targeting bursts) of the pass before ends.
 556    `PulsePalDevice.continuous_loop` does not apply to custom trains.
 557    """)
 558
 559    continuous_loop = _channel_setting("continuous_loop", """Whether each output channel plays its pulse train until stopped.
 560
 561    `False` plays the pulse train once per trigger, for
 562    `PulsePalDevice.pulse_train_duration`. `True` plays it until the
 563    channel is stopped, ignoring `PulsePalDevice.pulse_train_duration`.
 564    For parametric trains only: a custom train ignores it, and plays as
 565    `PulsePalDevice.custom_train_loop` says. Requires firmware v22 or
 566    newer. The device does not report it, so
 567    `PulsePalDevice.sync_from_device` leaves it as it is.
 568    """)
 569
 570    trigger_mode = _channel_setting("trigger_mode", """Response of each trigger channel to an incoming TTL pulse.
 571
 572    Indexed by trigger channel number, 1 or 2 (index 0 is unused). The
 573    modes, also listed in `DeviceInfo.trigger_modes`, are:
 574
 575    - `"Normal"`: a rising edge starts the pulse trains of the linked
 576      output channels, and edges during a train are ignored.
 577    - `"Toggle"`: as `"Normal"`, but a rising edge during a train stops
 578      it.
 579    - `"Gated"`: the trains play only while the trigger TTL is high.
 580    - `"Param Sync"` (Pulse Pal 3 only): a TTL rising edge starts and
 581      stops nothing. It loads the parameters most recently sent by
 582      `PulsePalDevice.sync_to_device` (or at the end of a
 583      `PulsePalDevice.batch` block), and the custom trains loaded since
 584      the previous edge. This is how the next trial's parameters and
 585      custom trains are sent during the current trial and applied the
 586      instant it starts.
 587
 588    The integer codes 0-3 are accepted too.
 589
 590    An output channel that is idle at a param sync edge takes its new
 591    parameters in the timer cycle the edge is detected. One that is
 592    playing a pulse train finishes that train on the parameters it
 593    started with, and takes the new ones the moment it ends, so a train
 594    that runs past the end of a trial keeps one shape throughout and the
 595    next trigger plays a whole train with the new parameters. A channel
 596    in continuous loop mode has no train end, so it keeps its parameters
 597    until something stops it.
 598
 599    While either trigger channel is in param sync mode, **only
 600    `PulsePalDevice.sync_to_device` (and the end of a
 601    `PulsePalDevice.batch` block) and the custom train loads are held
 602    back**: with `PulsePalDevice.auto_sync` on, every assignment still
 603    programs the device immediately. So leaving param sync mode means
 604    assigning `trigger_mode` with `auto_sync` on; a trigger mode sent by
 605    `PulsePalDevice.sync_to_device` does not take effect until a sync
 606    edge arrives. A custom train loaded in param sync mode
 607    (`PulsePalDevice.send_custom_pulse_train`) replaces the old one at
 608    the edge: channels playing the old one at the edge finish their
 609    trains on it. Leaving param sync mode discards parameters still
 610    waiting for an edge, but makes a custom train still waiting current
 611    at once.
 612
 613    A param sync channel's links to output channels are ignored. To
 614    start a pulse train on the same edge, wire the TTL to the other
 615    trigger channel as well: both edges arrive in the same timer cycle,
 616    and the parameters are loaded first.
 617
 618    Connecting a new `PulsePalDevice`, and
 619    `PulsePalDevice.set_default_params`, take both trigger channels out
 620    of param sync mode, so that the default parameters reach the device
 621    instead of waiting for a TTL.
 622
 623    ```python
 624    P.trigger_mode[2] = "Param Sync"   # sent at once
 625    with P.batch():
 626        P.phase1_voltage[1] = 2.5
 627        P.phase1_duration[1] = 0.002
 628    # Stored by the device: the next rising edge on trigger channel 2 applies it
 629    ```
 630    """)
 631
 632    _CURRENT_FIRMWARE_VERSION = 22
 633    _OLDEST_FIRMWARE_SUPPORTED = 21
 634    _BAUD_RATE = _common.BAUD_RATE  # USB serial ignores it (see _common.BAUD_RATE)
 635
 636    _OP_MENU_BYTE = _common.OP_MENU_BYTE
 637    _HANDSHAKE_OPCODE = _common.OP_HANDSHAKE
 638    _HANDSHAKE_DEVICE_CYCLES_OPCODE = _common.OP_HANDSHAKE_DEVICE_CYCLES
 639    _HANDSHAKE_DEVICE_CYCLES_TIMEOUT = 0.3  # Seconds to wait for a reply to op 103 before trying op 72
 640    _HANDSHAKE_RESPONSE = 75  # 'K'
 641    _DAC_BITMAX = 65535
 642    _PARAM_MESSAGE_BYTES = 178  # Length of the parameter set sent by op 93
 643    _STATUS_MESSAGE_BYTES = 29  # Length of the reply to op 101: playing channels, then 7 uint32 counters
 644    # Phase 1 and 2 durations, inter-pulse interval and train duration last at least this many
 645    # timer cycles, by hardware version, as in the MATLAB and C++ classes and the joystick menu.
 646    # Pulse Pal 2's trigger channels read their inputs once per cycle, so a one cycle pulse from
 647    # another Pulse Pal could fall between two reads. Pulse Pal 3's also latch every edge.
 648    _MIN_PULSE_CYCLES = {2: 2, 3: 1}
 649
 650    _ENDIANNESS = "<"
 651    _STRUCT_FORMATS = {
 652        "uint8": "B",
 653        "int8": "b",
 654        "uint16": "H",
 655        "int16": "h",
 656        "uint32": "I",
 657        "int32": "i",
 658    }
 659    _TYPE_RANGES = {
 660        "uint8": (0, 2**8 - 1),
 661        "int8": (-(2**7), 2**7 - 1),
 662        "uint16": (0, 2**16 - 1),
 663        "int16": (-(2**15), 2**15 - 1),
 664        "uint32": (0, 2**32 - 1),
 665        "int32": (-(2**31), 2**31 - 1),
 666    }
 667
 668    _reply_pending = None  # The op code of a command whose reply has not been read in full yet (see _write_raw())
 669    _unsent = frozenset()  # The settings assigned with auto_sync off since the parameters were last sent or read
 670
 671    def __init__(self, port_name=None, *, serial_number=None, timeout=10):
 672        """Open a connection to a Pulse Pal device.
 673
 674        Opens the serial port, exchanges the handshake, verifies the
 675        firmware version, reads the device properties into
 676        `PulsePalDevice.info`, and programs the device with the default
 677        parameters.
 678
 679        ```python
 680        P = PulsePalDevice("COM3")
 681        P = PulsePalDevice(serial_number="20345420")  # Wherever it is plugged in
 682        ```
 683
 684        Args:
 685            port_name: USB serial port for the Pulse Pal device, such as
 686                `COM3` on Windows or `/dev/ttyACM0` on Linux.
 687            serial_number: Instead of `port_name`, the device's USB serial
 688                number (`DeviceInfo.serial_number`), which finds its port.
 689                Pulse Pal 3 only: Pulse Pal 2 has none.
 690            timeout: Serial read timeout, in seconds.
 691
 692        Firmware newer than this module knows (`v22`) is used with a
 693        warning: new firmware only adds commands, so everything here still
 694        works with it. Update the package to use what is new.
 695
 696        Raises:
 697            PulsePalError: If the device does not return the expected
 698                handshake (for example, it runs Wave Pal or Synth Pal
 699                firmware), or its firmware is older than v21, or no port
 700                has the serial number given. The port is closed again
 701                before any error is raised.
 702            serial.SerialException: If the serial port cannot be opened,
 703                e.g. because another program has it open (on Linux and
 704                macOS, another session of these classes, which lock it).
 705        """
 706        self._closed = True
 707        self._gui = None
 708        self._auto_sync = True
 709        self.info = DeviceInfo()
 710        self._create_settings()
 711        port_name = _common.port_name_from(port_name, serial_number, "PulsePalDevice")
 712        self.port = serial.Serial(
 713            port_name,
 714            self._BAUD_RATE,
 715            timeout=timeout,
 716            rtscts=True,
 717            # Windows opens a port for one program only. Linux and macOS let a second program open it too, and two
 718            # sessions' bytes would then interleave; exclusive locks it (flock), so a second session that also locks
 719            # it, such as another of these classes, gets an error instead
 720            exclusive=True,
 721        )
 722        self._closed = False
 723        try:
 724            self._start_session(port_name)
 725        except BaseException:
 726            # Otherwise the port stays open until the object is garbage
 727            # collected, and a second attempt, or WavePalDevice, cannot open
 728            # it. The device is in an unknown state, so it is not sent the
 729            # disconnect op.
 730            self._close(send_disconnect=False)
 731            raise
 732
 733    def _create_settings(self):
 734        """Create the parameter lists, holding the default values (nothing is sent)."""
 735        for code, (name, _) in _OUTPUT_PARAMETERS.items():
 736            setattr(self, "_" + name, ChannelSettings(
 737                name, [_DEFAULT_OUTPUT_VALUES[name]] * 4, self, f"_apply_{name}"))
 738        self._trigger_mode = ChannelSettings(
 739            "trigger_mode", ["Normal"] * 2, self, "_apply_trigger_mode")
 740
 741    def _start_session(self, port_name):
 742        """Handshake, check the firmware, and program the defaults."""
 743        # Discard anything left unread by an earlier session (one stopped mid-reply, for example):
 744        # it would be read as the handshake's reply. A reply the device sends after this, to a
 745        # command it had not reached yet, is skipped by read_handshake_reply().
 746        self.port.reset_input_buffer()
 747        # Op 103: the session's times are in the device's own timer cycles (10 us on Pulse Pal 3). Firmware from before
 748        # October 2026, Wave Pal and Synth Pal ignore it, and answer op 72, whose times are in 50 us cycles. Either way
 749        # op 94 reports the session's unit, which the class then uses.
 750        self._write_serial((self._OP_MENU_BYTE, self._HANDSHAKE_DEVICE_CYCLES_OPCODE), "uint8")
 751        reply = _common.read_handshake_reply(self.port, timeout=self._HANDSHAKE_DEVICE_CYCLES_TIMEOUT)
 752        if reply is None:
 753            self._write_serial((self._OP_MENU_BYTE, self._HANDSHAKE_OPCODE), "uint8")
 754            received = _common.read_handshake_bytes(self.port)
 755            reply = None if received is None else _common.handshake_reply_from(received)
 756            if reply is not None and reply[0] == self._HANDSHAKE_RESPONSE and reply[1] > 21 and len(received) > 5:
 757                # More than one reply arrived: the device was busy when op 103 came, and answered it with op 72. A Pulse
 758                # Pal 3 answers nothing for about 5 s after it starts, while it shows its splash screen and opens its
 759                # microSD card (measured on Pulse Pal 3: op 103 and op 72 sent 0.2 to 3.5 s after the port opened were
 760                # answered together 5.0 s after it opened). Op 72, answered last, would leave the session in 50 us
 761                # cycles, so op 103 is sent again, now that the device is listening. If the extra bytes were a late
 762                # reply to an earlier session, and the firmware ignores op 103, this waits 0.3 s more.
 763                self._write_serial((self._OP_MENU_BYTE, self._HANDSHAKE_DEVICE_CYCLES_OPCODE), "uint8")
 764                reply = _common.read_handshake_reply(self.port, timeout=self._HANDSHAKE_DEVICE_CYCLES_TIMEOUT) or reply
 765        if reply is None:
 766            raise PulsePalError(
 767                f"No reply to the handshake from the device on {port_name}. Is it a Pulse Pal? "
 768                f"{_common.NO_REPLY_HINT}"
 769            )
 770        handshake, firmware_version = reply
 771        if handshake != self._HANDSHAKE_RESPONSE:
 772            if handshake in _common.FIRMWARE_BY_HANDSHAKE_REPLY:
 773                raise _common.other_firmware_error(handshake, firmware_version, port_name, "Pulse Pal")
 774            raise PulsePalError(
 775                "Incorrect handshake returned. Expected "
 776                f"{self._HANDSHAKE_RESPONSE}, received {handshake}."
 777            )
 778
 779        if firmware_version < self._OLDEST_FIRMWARE_SUPPORTED:
 780            raise PulsePalError(
 781                "Old firmware detected, v"
 782                f"{firmware_version}. v{self._OLDEST_FIRMWARE_SUPPORTED} or "
 783                "newer is required."
 784            )
 785        if firmware_version > self._CURRENT_FIRMWARE_VERSION:
 786            # New firmware only adds commands (see PulsePal-Firmware/PROTOCOL.md), so this class still works with it
 787            warnings.warn(
 788                f"Pulse Pal firmware v{firmware_version} is newer than this pulsepal package knows "
 789                f"(v{self._CURRENT_FIRMWARE_VERSION}). It works with it, but update the package to use what "
 790                "is new.", stacklevel=3)
 791        if firmware_version < self._CURRENT_FIRMWARE_VERSION:
 792            warnings.warn(
 793                f"Pulse Pal firmware v{firmware_version} is supported, but v"
 794                f"{self._CURRENT_FIRMWARE_VERSION} is available: see /MATLAB/FirmwareLoader.", stacklevel=3)
 795        self.info.firmware_version = firmware_version
 796
 797        if self.info.firmware_version > 21:
 798            self._write_serial((self._OP_MENU_BYTE, 94), "uint8")
 799            self.info.hardware_version = self._read_serial(1, "uint8")
 800            self.info.cycle_period_us = self._read_serial(1, "uint32")  # The session's time unit (see op 103 above)
 801            # Not 1 / (period / 1e6): at 10 us that is 99999.99999999999, and times read back from the device would
 802            # convert to 0.00010000000000000002 s instead of 0.0001 s
 803            self.info.cycle_frequency = 1000000 / self.info.cycle_period_us
 804            self.info.n_custom_pulse_trains = self._read_serial(1, "uint8")
 805            self.info.max_custom_pulses = self._read_serial(1, "uint32")
 806            self._write_serial((self._OP_MENU_BYTE, 100), "uint8")  # Circuit board revision
 807            revision = self.port.read(1)
 808            if len(revision) < 1:
 809                raise PulsePalError(
 810                    f"The Pulse Pal on {port_name} did not report its circuit board revision."
 811                )
 812            self._reply_pending = None  # Read without _read_raw() (see _write_raw())
 813            self.info.circuit_board_revision = revision[0]
 814            self._write_serial((self._OP_MENU_BYTE, _common.OP_SERIAL_NUMBER), "uint8")
 815            self.info.serial_number = _common.read_serial_number(self._read_raw)
 816        else:
 817            self.info.hardware_version = 2
 818            self.info.circuit_board_revision = 0
 819            self.info.serial_number = ""  # v21 runs on Pulse Pal 2, which has none
 820            self.info.cycle_period_us = 50
 821            self.info.cycle_frequency = 20000
 822            self.info.n_custom_pulse_trains = 2
 823            self.info.max_custom_pulses = 5000
 824        self.info.min_pulse_width_us = (
 825            self._MIN_PULSE_CYCLES[self.info.hardware_version] * self.info.cycle_period_us
 826        )
 827        if not self._has_param_sync():
 828            self.info.trigger_modes = TRIGGER_MODES[:3]
 829
 830        # Client name op + "PYTHON" in ASCII.
 831        self._write_serial(
 832            (self._OP_MENU_BYTE, 89, 80, 89, 84, 72, 79, 78),
 833            "uint8",
 834        )
 835
 836        self.set_default_params()
 837
 838    @staticmethod
 839    def serialportlist(ports_to_list="available"):
 840        """Return the names of the USB serial ports on this computer.
 841
 842        Called on the class, without connecting to a device, to find the
 843        port name to pass to `PulsePalDevice`:
 844
 845        ```python
 846        from pulsepal import PulsePalDevice
 847
 848        ports = PulsePalDevice.serialportlist()
 849        P = PulsePalDevice(ports[0])
 850        ```
 851
 852        Args:
 853            ports_to_list: `available` to list only the ports that are
 854                not already in use, or `all` to list every USB serial
 855                port. Not case sensitive.
 856
 857        Returns:
 858            Sorted list of port names, such as `["COM3", "COM7"]` on
 859            Windows or `["/dev/ttyACM0"]` on Linux.
 860
 861        Raises:
 862            PulsePalError: If `ports_to_list` is not `available` or
 863                `all`.
 864        """
 865        return _common.serialportlist(ports_to_list)
 866
 867    # ------------------------------------------------------------------
 868    # Programming the device
 869    # ------------------------------------------------------------------
 870
 871    @property
 872    def auto_sync(self):
 873        """Whether assigning a parameter programs the device at once.
 874
 875        `True` (the default): each assignment, such as
 876        `P.phase1_voltage[1] = 5`, programs the device at once, also while
 877        a trigger channel is in param sync mode. It sends the channels
 878        whose value it changes, and nothing for a channel that already
 879        holds the value assigned: the other channels keep what the device
 880        holds, e.g. values set with its joystick (read them with
 881        `PulsePalDevice.sync_from_device`).
 882
 883        `False`: assignments change only this object's copy of the
 884        parameters, checking each value, and
 885        `PulsePalDevice.sync_to_device` sends all of them in one command.
 886        Turning it back on does not send changes made meanwhile, so it
 887        raises `pulsepal.PulsePalError` while there are any: call
 888        `PulsePalDevice.sync_to_device` first to send them, or
 889        `PulsePalDevice.sync_from_device` to discard them. A
 890        `PulsePalDevice.batch` block does it all for you. `close()` warns of
 891        changes never sent.
 892        """
 893        return self._auto_sync
 894
 895    @auto_sync.setter
 896    def auto_sync(self, value):
 897        value = to_bool(value, "auto_sync")
 898        if value and self._unsent:
 899            # Turned on, auto_sync would leave them unsent, and the device playing its old parameters
 900            discard = "sync_from_device() to discard them"
 901            if "continuous_loop" in self._unsent:
 902                discard += " (all but continuous_loop, which the device does not report)"
 903            raise PulsePalError(
 904                f"Changes made with auto_sync off have not been sent to the device: {self._unsent_names()}. Call "
 905                f"sync_to_device() to send them, or {discard}, before turning auto_sync on."
 906            )
 907        self._auto_sync = value
 908
 909    def batch(self):
 910        """Change several parameters, and send them in one command.
 911
 912        Returns a context manager. In its block, assignments change only
 913        this object's copy of the parameters (as with
 914        `PulsePalDevice.auto_sync` off), and when the block ends,
 915        `PulsePalDevice.sync_to_device` sends all of them at once. If the
 916        block raises an error, nothing is sent, and the parameters go
 917        back to what they were.
 918
 919        ```python
 920        with P.batch():
 921            P.phase1_voltage = [5, 5, 2.5, 2.5]
 922            P.phase1_duration[3] = 0.002
 923        ```
 924
 925        In param sync mode, the device stores the parameters for the next
 926        rising edge on the param sync channel (see
 927        `PulsePalDevice.trigger_mode`).
 928        """
 929        return _common.batch(self)
 930
 931    def sync_to_device(self):
 932        """Program the device with this object's copy of all parameters.
 933
 934        Sends every output and trigger parameter to the device in a single
 935        command. Use it after assignments made with
 936        `PulsePalDevice.auto_sync` off; with it on, they have already
 937        reached the device.
 938
 939        ```python
 940        P.auto_sync = False
 941        P.phase1_voltage[1:5] = [5] * 4
 942        P.sync_to_device()
 943        ```
 944
 945        On Pulse Pal 3, if either trigger channel is in param sync mode
 946        (`PulsePalDevice.trigger_mode` `"Param Sync"`), the device stores
 947        the parameters instead of programming them, and loads them on the
 948        next rising edge of that channel. The device still checks every
 949        value. This is the only method whose effect is deferred that way.
 950
 951        Raises:
 952            PulsePalError: If a value is out of range for its parameter
 953                (nothing is sent), or the device does not acknowledge the
 954                command.
 955        """
 956        self._check_sync()
 957        self._send_sync()
 958
 959    def sync_from_device(self):
 960        """Read all parameters from the device into this object's copy.
 961
 962        Overwrites the parameter lists with the program currently on the
 963        device, e.g. after it has been reprogrammed from its thumb
 964        joystick. `PulsePalDevice.continuous_loop` is left as it is: the
 965        device does not report it. Changes made with
 966        `PulsePalDevice.auto_sync` off and not yet sent are discarded, but
 967        for `PulsePalDevice.continuous_loop`.
 968
 969        Requires firmware v22 or newer.
 970
 971        Raises:
 972            PulsePalError: If the connected firmware is older than v22,
 973                or the device does not return the full parameter set.
 974        """
 975        self._require_firmware(22, "sync_from_device()")
 976        for name, values in self._read_device_params().items():
 977            getattr(self, name)._store(values)
 978        self._unsent = self._unsent & {"continuous_loop"}  # Not read: a change to it is still unsent
 979
 980    def set_default_params(self):
 981        """Program the device with the default parameters.
 982
 983        The defaults are monophasic +5 V pulses of 0.1 ms, 1 ms apart
 984        (about 909 a second), for 1 second, resting at 0 V, on all four
 985        output channels; for biphasic pulses, a phase 2 of -5 V and 0.1 ms
 986        after 0.1 ms at rest. No output channel is linked to a trigger
 987        channel, so a TTL starts nothing until a script links it, and both
 988        trigger channels are in normal mode. They are the device's own
 989        defaults, which it also loads at startup, after a comm failure
 990        and after formatting its microSD card. They are sent at once,
 991        also while `PulsePalDevice.auto_sync` is off. The constructor
 992        calls it.
 993        """
 994        for name, value in _DEFAULT_OUTPUT_VALUES.items():
 995            getattr(self, name)._store([value] * 4)
 996        self._trigger_mode._store(["Normal"] * 2)
 997        if self._has_param_sync():
 998            # A device left in param sync mode would store the sync below instead of running it,
 999            # leaving the device on its old program until a TTL arrived. A trigger mode sent on
1000            # its own is not deferred that way, so both trigger channels leave param sync mode
1001            # first. See PulsePalDevice.trigger_mode.
1002            self._send_trigger_modes(["Normal"] * 2, "set_default_params()")
1003        self._send_sync()
1004
1005    def export_params(self):
1006        """Return every parameter, as a dict of plain lists.
1007
1008        Keyed by parameter name (`DeviceInfo.output_parameter_names`, then
1009        `"trigger_mode"`), with one value per channel and no unused index
1010        0. It holds only numbers, booleans and names, so it can be saved
1011        with `json` and logged with your data, to record exactly what the
1012        device played. `PulsePalDevice.import_params` programs it again.
1013
1014        ```python
1015        import json
1016        with open("trial_params.json", "w") as f:
1017            json.dump(P.export_params(), f)
1018        ```
1019        """
1020        names = [*self.info.output_parameter_names, "trigger_mode"]
1021        return {name: list(getattr(self, name))[1:] for name in names}
1022
1023    def import_params(self, params):
1024        """Program the device with parameters exported by `PulsePalDevice.export_params`.
1025
1026        All of them are checked first, and then sent in one command, as
1027        at the end of a `PulsePalDevice.batch` block: in param sync mode,
1028        the device stores them for the next sync edge. Parameters missing
1029        from `params` keep their values. A name that is not a parameter
1030        is skipped with a warning, so that parameters exported by a newer
1031        version of this package, which may have more, can still be
1032        imported; if none is, an error is raised.
1033
1034        A whole program file, as the GUIs save it, is imported too: its
1035        parameters, not its custom trains (a warning says so, if it has
1036        any).
1037
1038        ```python
1039        with open("MyProgram.json") as f:
1040            P.import_params(json.load(f))
1041        ```
1042
1043        Args:
1044            params: A dict of parameter name to one value per channel (a
1045                list, tuple or NumPy array), as `export_params` returns,
1046                or a program file's contents. The MATLAB class's names
1047                (`phase1Voltage`) are accepted too, so that the parameters
1048                its `exportParams()` returns, saved with `jsonencode`, can
1049                be imported.
1050
1051        Raises:
1052            PulsePalError: If a value is invalid, or no name in `params` is
1053                a parameter. Nothing is sent, and the parameters keep the
1054                values they had.
1055        """
1056        params = _params_to_import(params)
1057        with self.batch():
1058            for name, values in params.items():
1059                setattr(self, name, values)
1060
1061    def set_fixed_voltage(self, channels, voltage):
1062        """Set output channels to a fixed voltage.
1063
1064        Each channel holds the voltage until it is set again or until a
1065        pulse train is triggered on it.
1066
1067        ```python
1068        P.set_fixed_voltage(4, 2.5)
1069        P.set_fixed_voltage([1, 3], -1)
1070        ```
1071
1072        Args:
1073            channels: Output channel number, 1-4, or several as a list,
1074                tuple or NumPy array.
1075            voltage: Voltage to set on each of them, in volts [-10, 10].
1076
1077        Raises:
1078            PulsePalError: If a channel number is not 1-4, the voltage is
1079                outside [-10, 10] (nothing is sent), or the device does not
1080                acknowledge the command.
1081        """
1082        channels = _common.channel_numbers(channels)
1083        voltage_bits = self._volts_to_bits(voltage, "voltage")
1084        for channel in channels:
1085            self._write_serial(
1086                (self._OP_MENU_BYTE, 79, channel),
1087                "uint8",
1088                voltage_bits,
1089                "uint16",
1090            )
1091            self._read_ack("set_fixed_voltage()")
1092
1093    def set_calibration(self, channel, voltage_offset):
1094        """Calibrate the zero code of an output channel.
1095
1096        The offset is added to every voltage the channel produces, to
1097        correct for DAC offset error. It is stored in the device's
1098        EEPROM and reloaded on boot, so it only needs to be set once.
1099
1100        Requires Pulse Pal hardware v3 or newer.
1101
1102        Args:
1103            channel: Output channel number, 1-4.
1104            voltage_offset: Offset to apply, in volts [-0.1, 0.1].
1105
1106        Raises:
1107            PulsePalError: If the connected hardware is older than v3,
1108                `channel` is not 1-4, `voltage_offset` is outside
1109                [-0.1, 0.1], or the device does not acknowledge the
1110                command.
1111        """
1112        if self.info.hardware_version < 3:
1113            raise PulsePalError(
1114                "set_calibration() requires hardware v3 or newer."
1115            )
1116        if not (isinstance(channel, numbers.Integral) and channel in (1, 2, 3, 4)):
1117            raise PulsePalError("channel must be 1, 2, 3 or 4")
1118        if not (isinstance(voltage_offset, numbers.Real) and -0.1 <= voltage_offset <= 0.1):  # Also refuses NaN
1119            raise PulsePalError(
1120                "voltage_offset for zero code calibration must be in range "
1121                "[-0.1, 0.1]"
1122            )
1123        # To the nearest DAC code, halfway values to the even one, as the MATLAB class rounds it
1124        voltage_bits = int(round(voltage_offset * (1 / (20 / 65536))))
1125        self._write_serial(
1126            (self._OP_MENU_BYTE, 96, channel - 1),
1127            "uint8",
1128            voltage_bits,
1129            "int16",
1130        )
1131        self._read_ack("set_calibration()")
1132
1133    def set_screen_saver(self, enabled, timeout=1800):
1134        """Switch the device's screen saver on or off, and set its timeout.
1135
1136        With the screen saver on, the device dims its screen once it has
1137        been left alone for `timeout` seconds: no command from the
1138        computer, no rising edge on a trigger channel, and no joystick
1139        click or push. The next of these brings the screen back. Both
1140        settings are stored in the device's EEPROM and kept through power
1141        cycles; the screen saver can also be switched on and off from the
1142        device's joystick menu. A new device has it on, with 1800 s.
1143
1144        The device saves the settings once no channel is playing. Saving
1145        pauses its timer, usually for about 20 us but, once in about 2000
1146        changes, for tens of milliseconds, which would delay a trigger.
1147        Change the settings before an experiment rather than during one.
1148
1149        Requires firmware v22 or newer. Only Pulse Pal 3 has a screen
1150        saver: Pulse Pal 2 accepts `enabled=False` only.
1151
1152        ```python
1153        P.set_screen_saver(True, 300)  # dim after 5 minutes
1154        P.set_screen_saver(False)
1155        ```
1156
1157        Args:
1158            enabled: True (or 1) to switch the screen saver on, False (or
1159                0) to switch it off.
1160            timeout: Seconds without activity before the screen dims, a
1161                whole number from 1 to 65535. It is sent with every call,
1162                so leaving it out sets 1800 s.
1163
1164        Raises:
1165            PulsePalError: If the firmware is older than v22, the
1166                screen saver is switched on with hardware older than v3,
1167                a value is out of range, or the device does not
1168                acknowledge the command.
1169        """
1170        self._require_firmware(22, "set_screen_saver()")
1171        enabled = to_bool(enabled, "enabled")
1172        if not (
1173            isinstance(timeout, numbers.Real)
1174            and not isinstance(timeout, bool)
1175            and math.isfinite(timeout)
1176            and timeout == int(timeout)
1177            and 1 <= timeout <= 65535
1178        ):
1179            raise PulsePalError(
1180                "timeout must be a whole number of seconds from 1 to 65535"
1181            )
1182        if enabled and (self.info.hardware_version or 2) < 3:
1183            raise PulsePalError(
1184                "The screen saver requires hardware v3 or newer: Pulse Pal 2 "
1185                "accepts set_screen_saver(False) only."
1186            )
1187        self._write_serial(
1188            (self._OP_MENU_BYTE, 99, int(enabled)),
1189            "uint8",
1190            int(timeout),
1191            "uint16",
1192        )
1193        self._read_ack("set_screen_saver()")
1194
1195    # ------------------------------------------------------------------
1196    # Custom trains, playback and settings files
1197    # ------------------------------------------------------------------
1198
1199    def send_custom_pulse_train(
1200        self,
1201        custom_train_id,
1202        pulse_times,
1203        voltages,
1204    ):
1205        """Load a custom pulse train onto the device.
1206
1207        A custom pulse train is an arbitrary list of pulse onset times
1208        and voltages, replacing the parametric pulse voltage and onset
1209        timing. Set `PulsePalDevice.custom_train_id` on an output channel
1210        to play the train there. Each pulse takes the channel's own phase
1211        durations; a biphasic pulse's second phase is its voltage with the
1212        sign reversed. A biphasic pulse always plays whole, and a pulse
1213        whose time comes while it plays is dropped, so that every pulse
1214        played is on time.
1215
1216        ```python
1217        P.send_custom_pulse_train(
1218            2, [0, 0.2, 0.5, 1], [8, 4, -3.5, -10]
1219        )
1220        P.custom_train_id[1] = 2
1221        ```
1222
1223        Loading a train stops the output channels playing it, and their
1224        next trigger plays the new train. On Pulse Pal 3, while a trigger
1225        channel is in param sync mode (see `PulsePalDevice.trigger_mode`),
1226        the device stores the train instead, as it stores the parameters
1227        `PulsePalDevice.sync_to_device` sends: channels go on playing the
1228        old train, and the next rising edge on the param sync channel
1229        makes the new one current. A channel playing the old train at that
1230        edge finishes it, and plays the new one from its next trigger. So
1231        the next trial's custom trains can be loaded during the current
1232        trial. Leaving param sync mode makes a stored train current at
1233        once.
1234
1235        Args:
1236            custom_train_id: Custom train to load, from 1 to
1237                `DeviceInfo.n_custom_pulse_trains` (2 on Pulse Pal 2,
1238                4 on Pulse Pal 3).
1239            pulse_times: Pulse onset times, in seconds, relative to the
1240                start of the train, increasing. Each is a multiple of
1241                `DeviceInfo.min_pulse_width_us` (10 us on Pulse Pal 3,
1242                100 us on Pulse Pal 2), from 0 to
1243                `MAX_TIME`. Accepts a list, tuple or 1-D NumPy array.
1244            voltages: Voltage of each pulse, in volts [-10, 10]. Must be
1245                the same length as `pulse_times`.
1246
1247        Raises:
1248            PulsePalError: If `custom_train_id` is out of range,
1249                `pulse_times` or `voltages` is not one-dimensional (a 2-D
1250                array is refused, not flattened), they differ in length,
1251                there are no pulses, or more than
1252                `DeviceInfo.max_custom_pulses`, a pulse time is not a
1253                multiple of `DeviceInfo.min_pulse_width_us`, is out of
1254                range or is not later than the one before it, or the
1255                device does not acknowledge the command.
1256        """
1257        pulse_times_cycles = self._custom_times_to_cycles(pulse_times, "pulse_times")
1258        pulse_voltage_bits = self._volts_array_to_bits(voltages, "voltages")
1259        if len(pulse_times_cycles) != len(pulse_voltage_bits):
1260            raise PulsePalError(
1261                "pulse_times and voltages must be the same length."
1262            )
1263        self._send_custom_train(
1264            custom_train_id,
1265            pulse_times_cycles,
1266            pulse_voltage_bits,
1267            "send_custom_pulse_train()",
1268        )
1269
1270    def send_custom_waveform(
1271        self,
1272        custom_train_id,
1273        sampling_period,
1274        voltages,
1275    ):
1276        """Load an arbitrary waveform onto the device.
1277
1278        A convenience shorthand for
1279        `PulsePalDevice.send_custom_pulse_train` with evenly spaced,
1280        adjoining pulses, so that `voltages` is played as a waveform
1281        sampled every `sampling_period` seconds. It is loaded as a custom
1282        train is: see `PulsePalDevice.send_custom_pulse_train` for what
1283        happens to channels playing it, and in param sync mode.
1284
1285        Set the channel's `PulsePalDevice.phase1_duration` to
1286        `sampling_period` as well, so that each sample is held for the
1287        sampling period.
1288
1289        ```python
1290        import math
1291
1292        samples = [math.sin(i / 10.0) * 10 for i in range(1000)]
1293        P.send_custom_waveform(1, 0.001, samples)   # 1 kHz
1294        P.custom_train_id[2] = 1
1295        P.phase1_duration[2] = 0.001
1296        ```
1297
1298        Args:
1299            custom_train_id: Custom train to load, from 1 to
1300                `DeviceInfo.n_custom_pulse_trains` (2 on Pulse Pal 2,
1301                4 on Pulse Pal 3).
1302            sampling_period: In seconds: a multiple of
1303                `DeviceInfo.min_pulse_width_us` (10 us on Pulse Pal 3,
1304                100 us on Pulse Pal 2). Each voltage is
1305                held for this long.
1306            voltages: Waveform samples, in volts [-10, 10].
1307                Accepts a list, tuple or 1-D NumPy array.
1308
1309        Raises:
1310            PulsePalError: If `custom_train_id` is out of range, there
1311                are no samples, or more than
1312                `DeviceInfo.max_custom_pulses`, `sampling_period` is not a
1313                positive multiple of `DeviceInfo.min_pulse_width_us`, the
1314                last sample would start after `MAX_TIME`, or the device
1315                does not acknowledge the command.
1316        """
1317        pulse_voltage_bits = self._volts_array_to_bits(voltages, "voltages")
1318        period_cycles = self._custom_time_cycles(sampling_period, "sampling_period")
1319        if period_cycles == 0:
1320            raise PulsePalError(
1321                f"sampling_period must be a positive multiple of {self.info.min_pulse_width_us:g} us. "
1322                f"Received {sampling_period!r}."
1323            )
1324        pulse_times = period_cycles * np.arange(len(pulse_voltage_bits), dtype=np.int64)
1325        self._send_custom_train(
1326            custom_train_id,
1327            pulse_times,
1328            pulse_voltage_bits,
1329            "send_custom_waveform()",
1330        )
1331
1332    def trigger(self, channels):
1333        """Trigger output channels in software.
1334
1335        The channels start their pulse trains together, in the same timer
1336        cycle. A channel that is already playing a pulse train ignores
1337        the trigger, and `PulsePalDevice.stop` cancels a trigger that has
1338        not started its channel yet.
1339
1340        ```python
1341        P.trigger(3)          # one channel
1342        P.trigger([1, 4])     # several: a list, tuple or NumPy array
1343        ```
1344
1345        Args:
1346            channels: Output channel number, 1-4, or several as a list,
1347                tuple or NumPy array.
1348
1349        Raises:
1350            PulsePalError: If a channel number is not 1-4, or no channel
1351                is given. Nothing is triggered.
1352        """
1353        self._write_serial((self._OP_MENU_BYTE, 77, _common.channel_bits(channels)), "uint8")
1354
1355    def stop(self, channels=None):
1356        """Stop pulse trains currently playing on the device.
1357
1358        The stopped channels return to their
1359        `PulsePalDevice.resting_voltage`. A soft trigger that has not
1360        started its channel yet is cancelled too.
1361
1362        ```python
1363        P.stop()           # all output channels
1364        P.stop([1, 3, 4])  # channels 1, 3 and 4
1365        ```
1366
1367        Args:
1368            channels: Output channel number, 1-4, or several as a list,
1369                tuple or NumPy array. `None`, the default, stops all
1370                channels. Stopping some channels requires firmware v22
1371                or newer.
1372
1373        Raises:
1374            PulsePalError: If a channel number is not 1-4, or channels are
1375                given and the firmware is older than v22.
1376        """
1377        if self.info.firmware_version < 22:
1378            if channels is not None:
1379                raise PulsePalError("stop() cannot address individual channels before firmware v22")
1380            self._write_serial((self._OP_MENU_BYTE, 80), "uint8")  # Stops all channels
1381            return
1382        bits = 0x0F if channels is None else _common.channel_bits(channels)
1383        self._write_serial((self._OP_MENU_BYTE, 98, bits), "uint8")
1384
1385    def status(self):
1386        """Read which channels are playing, and the counters since the last call.
1387
1388        The counters (see `DeviceStatus`) count from the previous call, or
1389        from the device's startup, and each call clears them. Calling it
1390        before and after a trial checks that the TTLs the trial sent
1391        arrived, and started the trains they should:
1392
1393        ```python
1394        P.status()                     # Clears the counters
1395        run_trial()                    # Your code: one TTL on trigger channel 1, linked to channels 1 and 2
1396        s = P.status()
1397        if s.trigger_edges[1] != 1 or s.channel_starts[1:3] != [1, 1]:
1398            print("The trial's trains did not all start")
1399        ```
1400
1401        Requires firmware v22 or newer.
1402
1403        Returns:
1404            A `DeviceStatus`.
1405
1406        Raises:
1407            PulsePalError: If the firmware is older than v22, or the device
1408                does not reply.
1409        """
1410        self._require_firmware(22, "status()")
1411        self._write_serial((self._OP_MENU_BYTE, 101), "uint8")
1412        values = struct.unpack(f"{self._ENDIANNESS}B7I", self._read_raw(self._STATUS_MESSAGE_BYTES))
1413        return DeviceStatus(
1414            playing=[ch for ch in range(1, 5) if values[0] & (1 << (ch - 1))],
1415            trigger_edges=[None, *values[1:3]],
1416            channel_starts=[None, *values[3:7]],
1417            comm_failures=values[7],
1418        )
1419
1420    def save_program_to_microsd(self, file_name):
1421        """Save the parameters to the device's microSD card, as a program.
1422
1423        The program can be loaded later with
1424        `PulsePalDevice.load_program_from_microsd` or with the joystick
1425        menu's Load Program item. A file of the same name is replaced. To
1426        keep the parameters on this computer instead, see
1427        `PulsePalDevice.export_params`.
1428
1429        ```python
1430        P.save_program_to_microsd("MyProtocol.pps")
1431        ```
1432
1433        Args:
1434            file_name: At most 15 ASCII characters, ending in `.pps`.
1435
1436        Raises:
1437            PulsePalError: If the file name is invalid, or the device could
1438                not write the file to its microSD card. Pulse Pal 2 also
1439                refuses while a channel is playing: its card shares a bus with
1440                the outputs, so stop playback first.
1441        """
1442        self._settings_file_op(file_name, 1, "save_program_to_microsd()")
1443
1444    def load_program_from_microsd(self, file_name):
1445        """Load a program from the device's microSD card.
1446
1447        The device plays the program, and the parameters are read back
1448        into this object (see `PulsePalDevice.sync_from_device`). The
1449        program's trigger modes take effect too, and it is loaded at once,
1450        also in param sync mode.
1451
1452        Args:
1453            file_name: The program's file name, ending in `.pps`, as saved
1454                by `PulsePalDevice.save_program_to_microsd` or the joystick
1455                menu.
1456
1457        Raises:
1458            PulsePalError: If the file name is invalid, or the device could
1459                not load the program: there is no such file on its microSD
1460                card, or it is not a valid Pulse Pal program; or, on Pulse
1461                Pal 2, a channel is playing (see `save_program_to_microsd`).
1462                The device then keeps its parameters, and so does this object.
1463        """
1464        self._settings_file_op(file_name, 2, "load_program_from_microsd()")
1465
1466    def delete_program_from_microsd(self, file_name):
1467        """Delete a program from the device's microSD card.
1468
1469        Args:
1470            file_name: The program's file name, ending in `.pps`.
1471
1472        Raises:
1473            PulsePalError: If the file name is invalid, or the device could
1474                not delete the file, e.g. because there is no such file, or,
1475                on Pulse Pal 2, because a channel is playing.
1476        """
1477        self._settings_file_op(file_name, 3, "delete_program_from_microsd()")
1478
1479    def _settings_file_op(self, file_name, op_byte, context):
1480        """Save (op_byte 1), load (2) or delete (3) a settings file, with op 90."""
1481        valid = (
1482            isinstance(file_name, str)
1483            and all(32 <= ord(character) <= 126 for character in file_name)  # Printable ASCII
1484            and file_name.lower().endswith(".pps")
1485            and 4 < len(file_name) <= 15
1486        )
1487        if not valid:
1488            raise PulsePalError(
1489                f"{context}: the file name must be 1 to 11 ASCII characters followed by .pps, "
1490                f"e.g. 'Protocol1.pps'. Received {file_name!r}."
1491            )
1492        filename_bytes = file_name.encode("ascii")
1493        self._write_serial(
1494            (self._OP_MENU_BYTE, 90, op_byte, len(filename_bytes)),
1495            "uint8",
1496            list(filename_bytes),
1497            "uint8",
1498        )
1499        if self.info.firmware_version > 21:
1500            # Sent after the file operation has finished. A refused load changes nothing on the device.
1501            refusal = {
1502                1: f"Pulse Pal could not save {file_name!r} to its microSD card. Is the card in place?",
1503                2: f"Pulse Pal could not load {file_name!r}: there is no such file on its microSD card, or it is not "
1504                   "a valid Pulse Pal program. The device keeps its parameters.",
1505                3: f"Pulse Pal could not delete {file_name!r}: there is no such file on its microSD card.",
1506            }[op_byte]
1507            # Pulse Pal 2 replies 2 while a channel plays: its microSD card shares the SPI bus with the DAC
1508            busy = (f"Pulse Pal 2 does not use its microSD card while a channel is playing, because the card shares a "
1509                    f"bus with the outputs, so {file_name!r} was not {('saved', 'loaded', 'deleted')[op_byte - 1]}. "
1510                    "Stop playback first, with stop().")
1511            if op_byte == 2:
1512                busy += " The device keeps its parameters."
1513            self._read_ack(context, refusal_message=refusal, refusal_messages={2: busy})
1514        else:
1515            self._reply_pending = None  # Firmware v21 does not acknowledge op 90 (see _write_raw())
1516            if op_byte == 2:
1517                time.sleep(0.1)  # So allow time for the load
1518        if op_byte == 2:
1519            self.sync_from_device()
1520
1521    def format_microsd(self, *, confirm=True, timeout=30):
1522        """Format the device's microSD card.
1523
1524        Erases every program saved on the device and resets its
1525        parameters to the defaults. By default, asks at the console for
1526        confirmation first; a script that runs on its own, or an AI agent,
1527        passes `confirm=False`.
1528
1529        Requires Pulse Pal hardware v3 or newer.
1530
1531        Args:
1532            confirm: If `True`, ask at the console before anything is
1533                erased. If `False`, format at once.
1534            timeout: Seconds to wait for the device to report that
1535                formatting has finished.
1536
1537        Returns:
1538            `True` once the card has been formatted, or `False` if the
1539            user declines the confirmation prompt.
1540
1541        Raises:
1542            PulsePalError: If the connected hardware is older than v3, if
1543                the device reports that formatting failed, or if it does
1544                not report a result within `timeout` seconds.
1545        """
1546        if self.info.hardware_version < 3:
1547            raise PulsePalError(
1548                "format_microsd() requires hardware v3 or newer."
1549            )
1550
1551        if to_bool(confirm, "confirm"):
1552            print("*** Pulse Pal microSD Formatter ***")
1553            print("This will format Pulse Pal's microSD card,")
1554            print("erase all programs saved on the device")
1555            print("and reset all parameters to defaults.")
1556            reply = input("Do you want to continue (y/n)")
1557            if reply.strip().lower() != "y":
1558                print("Choice confirmed - microSD Card NOT formatted.")
1559                return False
1560
1561        self._write_serial((self._OP_MENU_BYTE, 97), "uint8", list(_FORMAT_KEY), "uint8")
1562
1563        # The device replies with lines of status text, the last of which
1564        # contains "!", and then a confirm byte (1 if the card was formatted,
1565        # 0 if not). The confirm byte is sent after the device has reloaded
1566        # its default parameters, so it can arrive well after the text. It
1567        # must be read here: left in the buffer, it would be taken as the
1568        # reply to the next command, and every reply after that would be
1569        # read one byte late.
1570        start = time.time()
1571        message = bytearray()
1572        flag_index = -1
1573        line_end = -1
1574
1575        while time.time() - start < timeout:
1576            n_waiting = self.port.in_waiting
1577            if n_waiting:
1578                message.extend(self.port.read(n_waiting))
1579                flag_index = message.find(b"!")
1580                if flag_index >= 0:
1581                    line_end = message.find(b"\n", flag_index)
1582                if line_end >= 0 and len(message) > line_end + 1:
1583                    break
1584            time.sleep(0.01)
1585        if line_end < 0 or len(message) <= line_end + 1:
1586            raise PulsePalError(
1587                "Pulse Pal did not report the result of formatting "
1588                f"its microSD card within {timeout} s. {_common.NO_REPLY_HINT}"
1589            )
1590        self._reply_pending = None  # The whole reply is read (see _write_raw())
1591        confirm_byte = message[line_end + 1]
1592
1593        text = bytes(message[:flag_index]).decode(
1594            "ascii", errors="replace"
1595        ).rstrip()
1596        if text:
1597            print(text)
1598
1599        # The device has loaded its own defaults. They are this class's, but the device keeps no record of
1600        # this object's other changes (continuous loop mode, for one), so the defaults are programmed, as the
1601        # MATLAB class does, and this object describes the device again.
1602        self.set_default_params()
1603        if confirm_byte != 1:
1604            raise PulsePalError(
1605                "Pulse Pal could not format its microSD card."
1606            )
1607        return True
1608
1609    def gui(self, block=None, theme=None):
1610        """Open the Pulse Pal parameter GUI, or focus an open one.
1611
1612        The GUI edits its own copy of the parameters, and loads them to
1613        the device when its 'Load to Device' button is clicked. The
1614        window closes automatically when the device is closed or
1615        deleted.
1616
1617        Calling this while the GUI is already open focuses the existing
1618        window rather than opening a second one.
1619
1620        Args:
1621            block: If `True`, the call returns when the GUI is closed. If
1622                `False`, the call returns immediately, and the host
1623                application must run the Tk event loop. If `None`, the
1624                GUI blocks only when the host does not already provide a
1625                Tk event loop, e.g. when launched from a script.
1626            theme: `"light"` or `"dark"` to select the color theme, or
1627                `None` to match the desktop theme. Passing a theme to an
1628                already-open GUI recolors it in place.
1629
1630        Returns:
1631            The `pulsepal.gui.PulsePalGUI` instance driving the window.
1632
1633        Raises:
1634            ValueError: If the theme name is not recognized.
1635        """
1636        gui = getattr(self, "_gui", None)
1637        if gui is not None and not gui.is_closed:
1638            if theme is not None:
1639                gui.set_theme(theme)
1640            gui.focus()
1641            return gui
1642
1643        from .gui import PulsePalGUI
1644
1645        gui = PulsePalGUI(self, theme=theme)
1646        self._gui = gui
1647        gui.start(block=block)
1648        return gui
1649
1650    # ------------------------------------------------------------------
1651    # Connection
1652    # ------------------------------------------------------------------
1653
1654    def close(self):
1655        """Close the connection to the device, and the GUI if open.
1656
1657        The device stops all output channels when the client disconnects,
1658        and shows its own name on its screen again. Safe to call more
1659        than once; later calls do nothing. Called automatically when
1660        leaving a `with` block and when the object is garbage collected,
1661        so pulse trains also stop when the last reference to the object
1662        goes, e.g. when a function that created it returns.
1663        """
1664        self._close(send_disconnect=True)
1665
1666    def _close(self, send_disconnect):
1667        """Close the connection. send_disconnect: tell the device first (op 81). False when the device is in
1668        an unknown state, such as after a failed handshake."""
1669        gui = getattr(self, "_gui", None)
1670        self._gui = None
1671        if gui is not None:
1672            try:
1673                gui.close()
1674            except Exception:
1675                # Cleanup must not raise; Tk may already be torn down
1676                pass
1677
1678        if getattr(self, "_closed", True):
1679            return
1680        self._closed = True
1681        if send_disconnect and self._unsent:
1682            _common.warn(f"PulsePalDevice closed with changes made with auto_sync off that were never sent to the "
1683                         f"device: {self._unsent_names()}.")
1684        self._reply_pending = None  # Nothing more is read, so a reply still to come needs no discarding
1685        try:
1686            if send_disconnect and self.port and self.port.is_open:
1687                self._write_serial((self._OP_MENU_BYTE, 81), "uint8")
1688        except Exception:
1689            pass  # The port may already be gone, e.g. the cable was unplugged
1690        finally:
1691            if self.port and self.port.is_open:
1692                self.port.close()
1693
1694    def __enter__(self):
1695        """Enter a `with` block, returning the connected device."""
1696        return self
1697
1698    def __exit__(self, exc_type, exc_value, traceback):
1699        """Disconnect and close the port when leaving a `with` block.
1700
1701        Returns:
1702            `False`, so any exception raised in the block propagates.
1703        """
1704        self.close()
1705        return False
1706
1707    def __del__(self):
1708        """Disconnect and close the port when the object is collected."""
1709        try:
1710            self.close()
1711        except Exception:
1712            # Destructors should not raise; the serial object may already be
1713            # gone during interpreter shutdown.
1714            pass
1715
1716    def __setattr__(self, name, value):
1717        """Refuse a public attribute that is not a setting, such as a misspelled one: it would program nothing (see
1718        _common.refuse_unknown_attribute())."""
1719        if name[0] != "_":
1720            _common.refuse_unknown_attribute(self, name, _SETTING_NAMES)
1721        super().__setattr__(name, value)
1722
1723    def __repr__(self):
1724        """Describe the device and its parameters, e.g. with `print(P)`."""
1725        port = getattr(getattr(self, "port", None), "port", None)
1726        lines = [
1727            f"PulsePalDevice on {port} (Pulse Pal {self.info.hardware_version}, "
1728            f"firmware v{self.info.firmware_version})",
1729            f"auto_sync: {self._auto_sync}",
1730        ]
1731        for name in self.info.output_parameter_names:
1732            lines.append(f"{name}: {list(getattr(self, name))}")
1733        lines.append(f"trigger_mode: {list(self._trigger_mode)}")
1734        return "\n".join(lines)
1735
1736    # ------------------------------------------------------------------
1737    # Internals: parameters
1738    # ------------------------------------------------------------------
1739
1740    def _has_param_sync(self):
1741        """Param sync mode is on Pulse Pal 3, with firmware v22 or newer."""
1742        return (self.info.hardware_version or 2) > 2 and (self.info.firmware_version or 0) > 21
1743
1744    def _normalize_output_value(self, code, value, channel):
1745        """Check a value for an output parameter, and return it as the parameter's list holds it:
1746        a time as the device plays it, rounded to its timer cycle.
1747
1748        Raises PulsePalError, before anything is sent, for a value the device cannot play. The
1749        device refuses most of them too, but it also resets them (see validateOutputParams() in
1750        PulsePal-Firmware/PulsePal/USBOps.ino), so the local copy would describe a different program.
1751        """
1752        name, kind = _OUTPUT_PARAMETERS[code]
1753        label = f"{name} on channel {channel}"
1754        if kind == "bool":
1755            value = to_bool(value, label)
1756            if code == _CONTINUOUS_LOOP_CODE and value and self.info.firmware_version < 22:
1757                raise PulsePalError("continuous_loop requires firmware v22 or newer.")
1758            return value
1759        if kind == "volts":
1760            self._volts_to_bits(value, label)
1761            return float(value)
1762        if kind in ("time", "pulse_time"):
1763            cycles = self._seconds_to_cycles(value, label)
1764            # Checked in whole cycles, as the device receives it: 100 * 1e-6 is just under 0.0001,
1765            # but is exactly 10 cycles of 10 us
1766            if kind == "pulse_time" and cycles < self._min_pulse_cycles():
1767                raise PulsePalError(
1768                    f"{label} must be at least {self._min_pulse_seconds()} s "
1769                    f"({self._min_pulse_cycles_text()} of the device's {self.info.cycle_period_us} us "
1770                    f"timer), so that trigger channels can detect the pulses. Received {value!r}."
1771                )
1772            return self._cycles_to_seconds(cycles)  # The time the device plays
1773        if kind == "train_id":
1774            self._check_whole_number(value, label, 0, self.info.n_custom_pulse_trains)
1775            return int(value)
1776        # "target"
1777        return to_name(value, CUSTOM_TRAIN_TARGETS, label, codes={"Pulses": 0, "Bursts": 1})
1778
1779    def _normalize_trigger_mode(self, value):
1780        modes = self.info.trigger_modes
1781        return to_name(value, modes, "trigger_mode", codes={mode: TRIGGER_MODES.index(mode) for mode in modes})
1782
1783    def _encode_output_param(self, code, values):
1784        """Convert output parameter values to device units.
1785
1786        Returns the converted values and the datatype the device reads for this
1787        parameter code: DAC codes for voltages, hardware timer cycles for times,
1788        and bytes for everything else.
1789        """
1790        name, kind = _OUTPUT_PARAMETERS[code]
1791        if kind == "volts":
1792            return [self._volts_to_bits(v, name) for v in values], "uint16"
1793        if kind in ("time", "pulse_time"):
1794            return [self._seconds_to_cycles(v, name) for v in values], "uint32"
1795        if kind == "target":
1796            return [CUSTOM_TRAIN_TARGETS.index(v) for v in values], "uint8"
1797        return [int(v) for v in values], "uint8"
1798
1799    def _apply_output_param(self, code, values):
1800        """Check new values for all four channels of an output parameter, and with auto_sync on,
1801        program the channels whose value changes. Returns them as the parameter's list holds them."""
1802        values = [self._normalize_output_value(code, v, ch) for ch, v in enumerate(values, start=1)]
1803        name = _OUTPUT_PARAMETERS[code][0]
1804        if not self._auto_sync:
1805            self._unsent = self._unsent | {name}  # Until sync_to_device() sends it (see auto_sync)
1806        else:
1807            if code in (_BURST_DURATION_CODE, _CUSTOM_TRAIN_TARGET_CODE):
1808                # Sent alone, so it must suit the other parameter as the device holds it. In a batch() block, or
1809                # with auto_sync off, both are checked together by sync_to_device().
1810                new = {name: values}
1811                self._check_custom_bursts(new.get("custom_train_target", list(self._custom_train_target)[1:]),
1812                                          new.get("burst_duration", list(self._burst_duration)[1:]))
1813            # Compared as the device receives them: 5 and 5.00001 V are the same DAC code
1814            old_data, _ = self._encode_output_param(code, list(getattr(self, name))[1:])
1815            new_data, _ = self._encode_output_param(code, values)
1816            channels = [ch for ch in range(1, 5) if old_data[ch - 1] != new_data[ch - 1]]
1817            self._send_output_param(code, values, channels, f"setting {name}")
1818        return values
1819
1820    def _send_output_param(self, code, values, channels, context):
1821        """Program one output parameter on some output channels: op 91 if all four change, op 74 for each otherwise.
1822
1823        The other channels are left as the device holds them. Sending all four (op 91) for a change to one put this
1824        object's copy of the others back on the device, undoing what the joystick menu, or a program loaded with it,
1825        had set there.
1826        """
1827        if self.info.firmware_version > 21 and len(channels) == 4:
1828            data, datatype = self._encode_output_param(code, values)
1829            self._write_serial((self._OP_MENU_BYTE, 91, code), "uint8", data, datatype)
1830            self._read_ack(context, on_refusal=lambda: self._refresh_output_param(code, channels))
1831            return
1832        for channel in channels:
1833            # A refusal reads back every channel this assignment changes, so that the copy describes the device for
1834            # those already sent too
1835            self._send_output_param_to_channel(code, channel, values[channel - 1], context, refresh_channels=channels)
1836
1837    def _send_output_param_to_channel(self, code, channel, value, context, refresh_channels=None):
1838        """Program one output parameter on one channel (op 74)."""
1839        if code == _CONTINUOUS_LOOP_CODE and self.info.firmware_version < 22:
1840            return  # Firmware v21 has no parameter 18, and _normalize_output_value() lets only False through
1841        data, datatype = self._encode_output_param(code, [value])
1842        self._write_serial((self._OP_MENU_BYTE, 74, code, channel), "uint8", data, datatype)
1843        self._read_ack(context, on_refusal=lambda: self._refresh_output_param(code, refresh_channels or (channel,)))
1844
1845    def _apply_trigger_mode(self, values):
1846        """Check new trigger modes, and with auto_sync on, program the trigger channels whose mode changes."""
1847        modes = [self._normalize_trigger_mode(v) for v in values]
1848        if not self._auto_sync:
1849            self._unsent = self._unsent | {"trigger_mode"}
1850        else:
1851            channels = [ch for ch in (1, 2) if modes[ch - 1] != self._trigger_mode[ch]]
1852            if len(channels) == 2:
1853                self._send_trigger_modes(modes, "setting trigger_mode")
1854            elif channels:  # One: op 74, which leaves the other trigger channel as the device holds it
1855                channel = channels[0]
1856                self._write_serial((self._OP_MENU_BYTE, 74, _TRIGGER_MODE_CODE, channel,
1857                                    TRIGGER_MODES.index(modes[channel - 1])), "uint8")
1858                self._read_ack("setting trigger_mode", on_refusal=self._refresh_trigger_mode)
1859        return modes
1860
1861    def _send_trigger_modes(self, modes, context):
1862        """Program both trigger channels' modes: op 91, or op 74 per channel on firmware v21."""
1863        codes = [TRIGGER_MODES.index(mode) for mode in modes]
1864        if self.info.firmware_version > 21:
1865            self._write_serial((self._OP_MENU_BYTE, 91, _TRIGGER_MODE_CODE, *codes), "uint8")
1866            self._read_ack(context, on_refusal=self._refresh_trigger_mode)
1867        else:
1868            for channel, mode_code in enumerate(codes, start=1):
1869                self._write_serial((self._OP_MENU_BYTE, 74, _TRIGGER_MODE_CODE, channel, mode_code), "uint8")
1870                self._read_ack(context)
1871
1872    def _snapshot(self):
1873        """All parameters, and which are unsent, for batch() to restore if its block fails."""
1874        names = [*self.info.output_parameter_names, "trigger_mode"]
1875        return {name: list(getattr(self, name))[1:] for name in names}, self._unsent
1876
1877    def _restore(self, snapshot):
1878        params, self._unsent = snapshot
1879        for name, values in params.items():
1880            getattr(self, name)._store(values)
1881
1882    def _unsent_names(self):
1883        """The settings assigned with auto_sync off and not yet sent, for messages, in parameter code order."""
1884        return ", ".join(name for name in _SETTING_NAMES if name in self._unsent)
1885
1886    def _check_sync(self):
1887        """Check the whole local copy before sync_to_device() sends it."""
1888        for code, (name, _) in _OUTPUT_PARAMETERS.items():
1889            values = getattr(self, name)
1890            for ch in range(1, 5):
1891                self._normalize_output_value(code, values[ch], ch)
1892        for ch in (1, 2):
1893            self._normalize_trigger_mode(self._trigger_mode[ch])
1894        self._check_custom_bursts(list(self._custom_train_target)[1:], list(self._burst_duration)[1:])
1895
1896    @staticmethod
1897    def _check_custom_bursts(targets, burst_durations):
1898        """Refuse a custom train targeting bursts on a channel with no burst duration.
1899
1900        Its times are burst onsets, and a burst of no duration plays one timer cycle of a pulse at each: a
1901        program that cannot be what was meant. (The device once played one pulse and then left the channel
1902        "playing", ignoring triggers until it was stopped.)
1903        """
1904        for channel, (target, burst) in enumerate(zip(targets, burst_durations), start=1):
1905            if target == "Bursts" and burst == 0:
1906                raise PulsePalError(
1907                    f"Output channel {channel}: custom_train_target 'Bursts' makes the custom train's times burst "
1908                    "onsets, so burst_duration must be above 0. Set burst_duration first, or set both in a batch() "
1909                    "block."
1910                )
1911
1912    def _send_sync(self):
1913        """Send every parameter in one command: op 92 on firmware v22 or newer, op 73 on v21."""
1914        self._unsent = frozenset()  # All are sent below
1915        if self.info.firmware_version > 21:
1916            self._sync_all_params()
1917        else:
1918            self._sync_all_params_legacy()
1919        self._read_ack("sync_to_device()", on_refusal=self._refresh_after_refused_sync)
1920
1921    def _device_bytes(self, name):
1922        """The byte values of a byte parameter for channels 1-4, as the device reads them."""
1923        values = list(getattr(self, name))[1:]
1924        if name == "custom_train_target":
1925            return [CUSTOM_TRAIN_TARGETS.index(v) for v in values]
1926        return [int(v) for v in values]
1927
1928    def _sync_all_params(self):
1929        """Send all parameters using the packed sync op (firmware v22+).
1930
1931        Values are grouped by width so that the whole program travels as
1932        one uint32 block, one uint16 block and one uint8 block. See op 92
1933        in PulsePal-Firmware/PROTOCOL.md.
1934        """
1935        time_values = []
1936        for name in _TIME_PARAMETERS:
1937            time_values.extend(self._seconds_to_cycles(v) for v in list(getattr(self, name))[1:])
1938        voltage_values = []
1939        for name in _VOLTAGE_PARAMETERS:
1940            voltage_values.extend(self._volts_to_bits(v) for v in list(getattr(self, name))[1:])
1941        single_byte_values = []
1942        for name in ("is_biphasic", "custom_train_id", "custom_train_target", "custom_train_loop",
1943                     "continuous_loop", "link_trigger_channel1", "link_trigger_channel2"):
1944            single_byte_values.extend(self._device_bytes(name))
1945        single_byte_values.extend(TRIGGER_MODES.index(mode) for mode in list(self._trigger_mode)[1:])
1946
1947        self._write_serial(
1948            (self._OP_MENU_BYTE, 92),
1949            "uint8",
1950            time_values,
1951            "uint32",
1952            voltage_values,
1953            "uint16",
1954            single_byte_values,
1955            "uint8",
1956        )
1957
1958    def _sync_all_params_legacy(self):
1959        """Send all parameters using the legacy sync op (firmware v21).
1960
1961        Equivalent to `_sync_all_params`, but lays the program out
1962        channel by channel as the older firmware expects. Continuous
1963        loop mode is not part of it.
1964        """
1965        program_values_32 = []
1966        program_values_16 = []
1967        program_values_8 = []
1968        for ch in range(1, 5):
1969            program_values_32.extend(self._seconds_to_cycles(getattr(self, name)[ch]) for name in _TIME_PARAMETERS)
1970        for ch in range(1, 5):
1971            program_values_16.extend(self._volts_to_bits(getattr(self, name)[ch]) for name in _VOLTAGE_PARAMETERS)
1972        byte_values = {name: self._device_bytes(name) for name in
1973                       ("is_biphasic", "custom_train_id", "custom_train_target", "custom_train_loop")}
1974        for ch in range(4):
1975            program_values_8.extend(byte_values[name][ch] for name in byte_values)
1976        links = self._device_bytes("link_trigger_channel1") + self._device_bytes("link_trigger_channel2")
1977        modes = [TRIGGER_MODES.index(mode) for mode in list(self._trigger_mode)[1:]]
1978
1979        self._write_serial(
1980            (self._OP_MENU_BYTE, 73),
1981            "uint8",
1982            program_values_32,
1983            "uint32",
1984            program_values_16,
1985            "uint16",
1986            program_values_8 + links + modes,
1987            "uint8",
1988        )
1989
1990    def _read_device_params(self):
1991        """Read the device's parameters (op 93).
1992
1993        Returns a dict of parameter values for channels 1-4 (trigger
1994        channels 1-2 for trigger_mode), as the parameter lists hold them.
1995        Continuous loop mode is not part of op 93, so `continuous_loop` is
1996        not included.
1997        """
1998        self._write_serial((self._OP_MENU_BYTE, 93), "uint8")
1999        # The device sends the whole parameter set as one message, so read it in one go and
2000        # unpack it here. See "Op codes", op 93, in PulsePal-Firmware/PROTOCOL.md.
2001        message = self._read_raw(self._PARAM_MESSAGE_BYTES)
2002        values = struct.unpack(f"{self._ENDIANNESS}32I12H26B", message)
2003        params = {}
2004        for index, name in enumerate(_TIME_PARAMETERS):
2005            params[name] = [self._cycles_to_seconds(x) for x in values[index * 4:index * 4 + 4]]
2006        for index, name in enumerate(_VOLTAGE_PARAMETERS):
2007            params[name] = [self._bits_to_volts(x) for x in values[32 + index * 4:32 + index * 4 + 4]]
2008        for index, name in enumerate(("is_biphasic", "custom_train_id", "custom_train_target",
2009                                      "custom_train_loop", "link_trigger_channel1", "link_trigger_channel2")):
2010            codes = values[44 + index * 4:44 + index * 4 + 4]
2011            if name == "custom_train_id":
2012                params[name] = list(codes)
2013            elif name == "custom_train_target":
2014                params[name] = [CUSTOM_TRAIN_TARGETS[min(code, 1)] for code in codes]
2015            else:
2016                params[name] = [bool(code) for code in codes]
2017        params["trigger_mode"] = [TRIGGER_MODES[min(code, 3)] for code in values[68:70]]
2018        return params
2019
2020    def _refresh_output_param(self, code, channels):
2021        """Read an output parameter back from the device into the local copy, for these channels.
2022
2023        Called after the device refused a value for them, which it resets. The parameter's other
2024        channels, and other parameters, keep their local values, which may hold edits not yet synced.
2025        """
2026        name = _OUTPUT_PARAMETERS[code][0]
2027        if self.info.firmware_version < 22 or code == _CONTINUOUS_LOOP_CODE:
2028            return  # No op 93 to read it with, or not in op 93
2029        device_values = self._read_device_params()[name]
2030        settings = getattr(self, name)
2031        local_values = list(settings)[1:]
2032        for ch in channels:
2033            local_values[ch - 1] = device_values[ch - 1]
2034        settings._store(local_values)
2035
2036    def _refresh_trigger_mode(self):
2037        """Read the trigger modes back from the device, after the device refused a new one."""
2038        if self.info.firmware_version > 21:
2039            self._trigger_mode._store(self._read_device_params()["trigger_mode"])
2040
2041    def _refresh_after_refused_sync(self):
2042        """Read the parameters back after the device refused a sync_to_device() set.
2043
2044        The device programs the set with the refused values reset, so the local copy is read back.
2045        In param sync mode the device stores the set instead, and op 93 would return the parameters
2046        playing now, so the local copy is left as it is.
2047        """
2048        if self.info.firmware_version > 21 and "Param Sync" not in list(self._trigger_mode)[1:]:
2049            self.sync_from_device()
2050
2051    def _check_whole_number(self, value, name, low, high):
2052        """Raise PulsePalError unless value is a whole number from low to high."""
2053        valid = (
2054            isinstance(value, numbers.Real)
2055            and not isinstance(value, (bool, np.bool_))
2056            and math.isfinite(value)
2057            and value == int(value)
2058            and low <= value <= high
2059        )
2060        if not valid:
2061            raise PulsePalError(
2062                f"{name} must be a whole number from {low} to {high}. Received {value!r}."
2063            )
2064
2065    def _min_pulse_cycles(self):
2066        """The shortest pulse phase, interval or train, in timer cycles: DeviceInfo.min_pulse_width_us. See
2067        _MIN_PULSE_CYCLES."""
2068        return int(round(self.info.min_pulse_width_us / self.info.cycle_period_us))
2069
2070    def _min_pulse_cycles_text(self):
2071        """_min_pulse_cycles() for messages: "1 cycle", "2 cycles"."""
2072        cycles = self._min_pulse_cycles()
2073        return f"{cycles} cycle" if cycles == 1 else f"{cycles} cycles"
2074
2075    def _min_pulse_seconds(self):
2076        """The shortest pulse phase, interval or train, in seconds: DeviceInfo.min_pulse_width_us."""
2077        return self._cycles_to_seconds(self._min_pulse_cycles())
2078
2079    def _require_firmware(self, minimum_version, context):
2080        """Raise unless the device firmware is new enough for an op."""
2081        if (
2082            self.info.firmware_version is None
2083            or self.info.firmware_version < minimum_version
2084        ):
2085            raise PulsePalError(
2086                f"{context} requires firmware v{minimum_version} or newer. "
2087                f"Detected firmware is v{self.info.firmware_version}."
2088            )
2089
2090    # ------------------------------------------------------------------
2091    # Internals: custom trains
2092    # ------------------------------------------------------------------
2093
2094    def _send_custom_train(self, custom_train_id, pulse_times_cycles,
2095                           pulse_voltage_bits, context):
2096        """Send a custom pulse train, already converted to device units (NumPy integer arrays).
2097
2098        Uses op 95 on firmware v22 or newer, and the legacy ops 75 and 76
2099        (trains 1 and 2 only) on firmware v21.
2100        """
2101        n_trains = self.info.n_custom_pulse_trains
2102        valid_id = (
2103            isinstance(custom_train_id, numbers.Integral)
2104            and not isinstance(custom_train_id, (bool, np.bool_))
2105            and 1 <= custom_train_id <= n_trains
2106        )
2107        if not valid_id:
2108            raise PulsePalError(
2109                f"{context}: custom_train_id must be an integer from 1 to "
2110                f"{n_trains}. Received {custom_train_id!r}."
2111            )
2112        train_id = int(custom_train_id)
2113        n_pulses = len(pulse_times_cycles)
2114        if n_pulses == 0:
2115            # The device refuses an empty train too: it would hold no pulse times to play
2116            raise PulsePalError(
2117                f"{context}: a custom train needs at least one pulse. To play nothing on a channel, set its "
2118                "custom_train_id to a train that holds what it should play, or do not trigger it."
2119            )
2120        if n_pulses > self.info.max_custom_pulses:
2121            raise PulsePalError(
2122                f"{context}: {n_pulses} pulses were given. Pulse Pal can "
2123                f"store up to {self.info.max_custom_pulses} pulses per "
2124                "custom train."
2125            )
2126        # Times are multiples of _min_pulse_cycles() (see _custom_times_to_cycles()), so increasing times are far
2127        # enough apart for a trigger channel to detect each pulse.
2128        too_close = np.flatnonzero(np.diff(pulse_times_cycles) < self._min_pulse_cycles())
2129        if too_close.size:
2130            i = int(too_close[0]) + 1
2131            raise PulsePalError(
2132                f"{context}: pulse times must increase, by at least "
2133                f"{self._min_pulse_seconds()} s ({self._min_pulse_cycles_text()} "
2134                f"of the device's {self.info.cycle_period_us} us "
2135                f"timer). Pulse {i + 1} is at "
2136                f"{self._cycles_to_seconds(pulse_times_cycles[i])} s, "
2137                f"and pulse {i} is at "
2138                f"{self._cycles_to_seconds(pulse_times_cycles[i - 1])} s."
2139            )
2140        if pulse_times_cycles[-1] > self._max_time_cycles():
2141            raise PulsePalError(
2142                f"{context}: the last pulse starts at {self._cycles_to_seconds(pulse_times_cycles[-1])} s. "
2143                f"Pulse times must be at most {self.info.max_time} s."
2144            )
2145
2146        if self.info.firmware_version > 21:
2147            header = bytes([self._OP_MENU_BYTE, 95, train_id - 1])
2148        else:
2149            header = bytes([self._OP_MENU_BYTE, 74 + train_id])
2150        self._write_raw(
2151            header + struct.pack("<I", n_pulses)
2152            + np.asarray(pulse_times_cycles).astype("<u4").tobytes()
2153            + np.asarray(pulse_voltage_bits).astype("<u2").tobytes()
2154        )
2155        self._read_ack(context)
2156
2157    def _number_array(self, values, name, description):
2158        """Return values (a scalar, a list, a tuple or a 1-D NumPy array) as a float64 array, refusing booleans,
2159        strings and anything else that is not a number, as the scalar conversions do.
2160
2161        An array of two or more dimensions, or a list of lists, is refused rather than flattened: one value per
2162        pulse is a list, and a 2-D one is a mistake, such as both rows of a stereo waveform. (The MATLAB class, which
2163        took a matrix's longest side as its pulse count and sent all of it, sent the rest to the device as commands.)
2164        """
2165        if isinstance(values, np.ndarray):
2166            self._check_one_dimensional(values, name)
2167            if values.dtype.kind in "iuf":
2168                return values.ravel().astype(float)
2169        items = self._as_list(values)
2170        refused_types = tuple(kind for kind in {type(item) for item in items}  # Each type once: fast for long lists
2171                              if issubclass(kind, (bool, np.bool_, str, bytes)))
2172        if refused_types:
2173            item = next(item for item in items if isinstance(item, refused_types))
2174            raise PulsePalError(f"{name} must be {description}. Received {item!r}.")
2175        try:
2176            array = np.asarray(items, dtype=float)
2177        except (TypeError, ValueError):
2178            for item in items:
2179                try:
2180                    float(item)
2181                except (TypeError, ValueError):
2182                    raise PulsePalError(f"{name} must be {description}. Received {item!r}.") from None
2183            raise
2184        self._check_one_dimensional(array, name)  # A list of lists
2185        return array
2186
2187    @staticmethod
2188    def _check_one_dimensional(array, name):
2189        if array.ndim > 1:
2190            raise PulsePalError(
2191                f"{name} must be one-dimensional, one value per pulse: a list, a tuple or a 1-D NumPy array. "
2192                f"Received an array of shape {array.shape}."
2193            )
2194
2195    @staticmethod
2196    def _first(values, refused):
2197        """The first value at a True position of the boolean array `refused`, for an error message."""
2198        i = int(np.flatnonzero(refused)[0])
2199        item = values.ravel()[i] if isinstance(values, np.ndarray) else PulsePalDevice._as_list(values)[i]
2200        return item.item() if isinstance(item, np.generic) else item
2201
2202    def _custom_times_to_cycles(self, values, name):
2203        """Convert custom pulse times to timer cycles, all at once: _custom_time_cycles() for each of them.
2204
2205        Each must be a time the device can play, and a whole number of DeviceInfo.min_pulse_width_us to the nearest
2206        microsecond, as in the MATLAB class. Returns an int64 array.
2207        """
2208        seconds = self._number_array(values, name, "a time of 0 s or more")
2209        refused = ~(np.isfinite(seconds) & (seconds >= 0))
2210        if refused.any():
2211            raise PulsePalError(f"{name} must be a time of 0 s or more. Received {self._first(values, refused)!r}.")
2212        # The same arithmetic as _seconds_to_cycles() and _custom_time_cycles(): NumPy's round() also takes a
2213        # halfway value to the even integer
2214        refused = np.round(seconds * float(self.info.cycle_frequency)) > self._max_time_cycles()
2215        if refused.any():
2216            raise PulsePalError(
2217                f"{name} must be at most {self.info.max_time} s, the longest time the device's screen "
2218                f"shows. Received {self._first(values, refused)!r}."
2219            )
2220        microseconds = np.round(seconds * 1e6)
2221        step_us = int(self.info.min_pulse_width_us)
2222        refused = np.mod(microseconds, step_us) != 0
2223        if refused.any():
2224            raise PulsePalError(
2225                f"{name} must be multiples of {step_us} us ({step_us / 1e6:g} s). "
2226                f"Received {self._first(values, refused)!r}."
2227            )
2228        return (microseconds // int(self.info.cycle_period_us)).astype(np.int64)
2229
2230    def _volts_array_to_bits(self, values, name):
2231        """Convert voltages to DAC codes, all at once: _volts_to_bits() for each of them. Returns an int64 array."""
2232        volts = self._number_array(values, name, "in [-10, 10] V")
2233        refused = ~((volts >= -10) & (volts <= 10))  # Also refuses NaN
2234        if refused.any():
2235            raise PulsePalError(f"{name} must be in [-10, 10] V. Received {self._first(values, refused)!r}.")
2236        return np.round((volts + 10) / 20 * self._DAC_BITMAX).astype(np.int64)
2237
2238    # ------------------------------------------------------------------
2239    # Internals: serial port and units
2240    # ------------------------------------------------------------------
2241
2242    def _write_serial(self, *args):
2243        """Write one or more data/type pairs to the serial port, in one write."""
2244        if len(args) % 2 != 0:
2245            raise PulsePalError(
2246                "Serial writes require data/type argument pairs."
2247            )
2248
2249        payload = bytearray()
2250        for i in range(0, len(args), 2):
2251            payload.extend(self._pack_values(args[i], args[i + 1]))
2252        self._write_raw(bytes(payload))
2253
2254    def _write_raw(self, payload):
2255        """Write a command to the serial port, in one write.
2256
2257        A command whose reply was not read in full, because the read timed out or was interrupted (Ctrl-C), leaves
2258        that reply, or the rest of it, to arrive later. Read as the reply to the next command, it put every reply
2259        after it out of step: status() reported channels playing that were not, and assignments the device took
2260        raised refusals. So it is discarded first (_discard_lost_reply()). Then this command's reply, if it has one,
2261        is pending until it has been read: _read_raw() marks it read, and a method that reads a reply otherwise
2262        (format_microsd()) sets _reply_pending back to None itself.
2263        """
2264        if self._reply_pending is not None:
2265            self._discard_lost_reply()
2266        if payload[1] not in _OPS_WITHOUT_TRACKED_REPLY:
2267            self._reply_pending = payload[1]  # Before the write: a Ctrl-C can come as soon as it returns
2268        bytes_written = self.port.write(payload)
2269        if bytes_written != len(payload):
2270            raise PulsePalError(
2271                f"Wrote {bytes_written} byte(s), expected to write "
2272                f"{len(payload)} byte(s)."
2273            )
2274
2275    def _discard_lost_reply(self):
2276        """Discard what arrives of a reply that was not read in full (see _write_raw()), and bring this object back
2277        in step with the device.
2278
2279        The command may have changed the parameters, unknown to this object: an assignment interrupted after its
2280        write, for one, which the device took and this object did not. So after one of _PARAMETER_OPS, they are read
2281        back (op 93), on firmware v22 or newer and outside param sync mode, where op 93 returns the parameters playing
2282        rather than a set stored for the next sync edge.
2283        """
2284        op = self._reply_pending
2285        self._reply_pending = None
2286        n_late = len(_common.read_until_quiet(self.port))
2287        read_back = (op in _PARAMETER_OPS and self.info.firmware_version > 21
2288                     and "Param Sync" not in list(self._trigger_mode)[1:])
2289        _common.warn_lost_reply(f"op {op}", n_late,
2290                                ", and the parameters were read back from the device" if read_back else "")
2291        if read_back:
2292            try:
2293                self.sync_from_device()
2294            except PulsePalError as exc:
2295                raise PulsePalError(
2296                    f"Pulse Pal did not send its parameters, read back after the reply to an earlier command was "
2297                    f"lost. {_common.NO_REPLY_HINT}"
2298                ) from exc
2299
2300    def _read_raw(self, n_bytes):
2301        """Read exactly n_bytes from the serial port: the whole reply to the command last sent, which is then no
2302        longer pending (see _write_raw()). Only connecting reads a reply in more than one call."""
2303        message_bytes = self.port.read(n_bytes)
2304        if len(message_bytes) < n_bytes:
2305            raise PulsePalError(
2306                f"Pulse Pal sent {len(message_bytes)} of the {n_bytes} byte(s) of its reply within "
2307                f"{self.port.timeout} s. {_common.NO_REPLY_HINT}"
2308            )
2309        self._reply_pending = None
2310        return message_bytes
2311
2312    def _read_serial(self, n_values, datatype):
2313        """Read values from the serial port and unpack them with struct."""
2314        fmt = self._STRUCT_FORMATS[datatype]
2315        n_values = int(n_values)
2316        n_bytes = n_values * struct.calcsize(fmt)
2317        message_bytes = self._read_raw(n_bytes)
2318
2319        values = struct.unpack(
2320            f"{self._ENDIANNESS}{n_values}{fmt}",
2321            message_bytes,
2322        )
2323        if n_values == 1:
2324            return values[0]
2325        return list(values)
2326
2327    def _read_ack(self, context, on_refusal=None, refusal_message=None, refusal_messages=None):
2328        """Read a one-byte acknowledgement from the device.
2329
2330        The device replies 1 if it executed the command, or 0 if it rejected
2331        the command because a value was out of range. On a 0, on_refusal()
2332        is called before the error is raised: the device resets a value it
2333        refuses, so callers use it to read the value back into the local copy.
2334        refusal_message replaces the error's usual message, for a command
2335        refused for another reason. refusal_messages maps other replies to
2336        their own message, e.g. op 90's 2.
2337        """
2338        try:
2339            acknowledgement = self._read_serial(1, "uint8")
2340        except PulsePalError as exc:
2341            raise PulsePalError(
2342                f"Pulse Pal did not confirm {context}: no reply arrived within {self.port.timeout} s. "
2343                f"{_common.NO_REPLY_HINT}"
2344            ) from exc
2345        if acknowledgement != 1:
2346            refusal = PulsePalError(
2347                (refusal_messages or {}).get(acknowledgement) or
2348                refusal_message or
2349                f"Pulse Pal rejected the command sent by {context}. "
2350                "This usually means that a channel number, parameter code or "
2351                "value was out of range for the connected device."
2352            )
2353            if on_refusal is not None:
2354                try:
2355                    on_refusal()
2356                except PulsePalError as exc:
2357                    raise refusal from exc
2358            raise refusal
2359
2360    def _pack_values(self, values, datatype):
2361        """Pack scalar, list/tuple, or NumPy array values into bytes."""
2362        fmt = self._STRUCT_FORMATS[datatype]
2363        values_list = self._as_list(values)
2364        min_value, max_value = self._TYPE_RANGES[datatype]
2365        normalized = []
2366        for value in values_list:
2367            value = int(value)
2368            if not min_value <= value <= max_value:
2369                raise PulsePalError(
2370                    f"Value {value} is out of range for {datatype} "
2371                    f"({min_value} to {max_value})."
2372                )
2373            normalized.append(value)
2374        return struct.pack(f"{self._ENDIANNESS}{len(normalized)}{fmt}", *normalized)
2375
2376    @staticmethod
2377    def _as_list(values):
2378        """Return values as a flat list, wrapping scalars in one."""
2379        if isinstance(values, np.ndarray):
2380            return values.ravel().tolist()
2381        if isinstance(values, (bytes, bytearray, str)):
2382            return [values]
2383        if isinstance(values, numbers.Number):
2384            return [values]
2385        try:
2386            return list(values)
2387        except TypeError:
2388            return [values]
2389
2390    def _volts_to_bits(self, value, name="voltage"):
2391        """Convert -10 V to +10 V to the corresponding DAC code.
2392
2393        Rounds to the nearest code, halves to even (round()), as the MATLAB and C++ classes do.
2394        Raises PulsePalError for a voltage outside [-10, 10] or not a number: clamping it would
2395        play a different voltage.
2396        """
2397        try:
2398            volts = float(value)
2399        except (TypeError, ValueError):
2400            volts = float("nan")
2401        if isinstance(value, (bool, np.bool_, str)) or not -10 <= volts <= 10:  # Also refuses NaN
2402            raise PulsePalError(f"{name} must be in [-10, 10] V. Received {value!r}.")
2403        return int(round((volts + 10) / 20 * self._DAC_BITMAX))
2404
2405    def _bits_to_volts(self, value):
2406        """Convert a DAC code to volts, snapping to a clean value within 1 LSB."""
2407        raw_volts = (float(value) / self._DAC_BITMAX * 20) - 10
2408        lsb_volts = 20.0 / self._DAC_BITMAX
2409        # The nearest 3 decimal number (e.g. 5.000, 4.255), if the code is within 1 LSB of it
2410        clean_volts = round(raw_volts, 3)
2411        if abs(raw_volts - clean_volts) <= lsb_volts:
2412            return clean_volts
2413        return round(raw_volts, 4)
2414
2415    def _seconds_to_cycles(self, value, name="time"):
2416        """Convert seconds to the corresponding refresh-cycle count.
2417
2418        Rounds to the nearest cycle, halves to even (round()), as the MATLAB and C++ classes do:
2419        125 us, 2.5 cycles, is 2 cycles in all three. Raises PulsePalError for a time that is
2420        negative, not a number, or longer than DeviceInfo.max_time.
2421        """
2422        try:
2423            seconds = float(value)
2424        except (TypeError, ValueError):
2425            seconds = float("nan")
2426        if isinstance(value, (bool, np.bool_, str)) or not (math.isfinite(seconds) and seconds >= 0):
2427            raise PulsePalError(f"{name} must be a time of 0 s or more. Received {value!r}.")
2428        cycles = int(round(seconds * float(self.info.cycle_frequency)))
2429        if cycles > self._max_time_cycles():
2430            raise PulsePalError(
2431                f"{name} must be at most {self.info.max_time} s, the longest time the device's screen "
2432                f"shows. Received {value!r}."
2433            )
2434        return cycles
2435
2436    def _max_time_cycles(self):
2437        """DeviceInfo.max_time in timer cycles: 999999990 on a 10 us timer, 199999998 on a 50 us timer."""
2438        return int(round(self.info.max_time * float(self.info.cycle_frequency)))
2439
2440    def _custom_time_cycles(self, value, name):
2441        """Convert a custom pulse time or sampling period to timer cycles.
2442
2443        It must be a whole number of DeviceInfo.min_pulse_width_us, to the nearest microsecond,
2444        as in the MATLAB class. A time between two steps is refused, not rounded
2445        as the time parameters are, so that a train plays as it was written.
2446        """
2447        self._seconds_to_cycles(value, name)  # Checks that it is a time the device can play
2448        microseconds = int(round(float(value) * 1e6))
2449        step_us = int(self.info.min_pulse_width_us)
2450        if microseconds % step_us:
2451            raise PulsePalError(
2452                f"{name} must be multiples of {step_us} us ({step_us / 1e6:g} s). Received {value!r}."
2453            )
2454        return microseconds // int(self.info.cycle_period_us)
2455
2456    def _cycles_to_seconds(self, value):
2457        """Convert hardware timer cycle counts to seconds."""
2458        return float(value) / float(self.info.cycle_frequency)
2459
2460
2461def _apply_method(code):
2462    def apply(self, values):
2463        return self._apply_output_param(code, values)
2464    return apply
2465
2466
2467# One _apply_<name> method per output parameter, which its ChannelSettings list calls
2468for _code, (_name, _kind) in _OUTPUT_PARAMETERS.items():
2469    setattr(PulsePalDevice, f"_apply_{_name}", _apply_method(_code))
2470del _code, _name, _kind
class PulsePalDevice:
 399class PulsePalDevice:
 400    """A class to control a Pulse Pal device on a USB serial port.
 401
 402    Creating an instance opens the serial port, exchanges a handshake
 403    with the device, verifies that its firmware is supported, reads the
 404    device properties into `PulsePalDevice.info`, and programs the
 405    device with the default parameters (see
 406    `PulsePalDevice.set_default_params`).
 407
 408    ```python
 409    from pulsepal import PulsePalDevice
 410
 411    P = PulsePalDevice("COM3")
 412    P.phase1_voltage[1] = 5
 413    P.trigger(1)
 414    P.close()
 415    ```
 416
 417    Here, replace "COM3" with Pulse Pal's USB serial port name.
 418    To view a list of available ports, use
 419    `PulsePalDevice.serialportlist()`.
 420    Pulse Pal's port may not be visible if it is connected to another
 421    instance of PulsePalDevice or an external application. Use
 422    `PulsePalDevice.serialportlist("all")` to view all ports.
 423    If you see multiple available ports, disconnect Pulse Pal's USB plug
 424    and run serialportlist() again. Notice which port disappears from the
 425    list.
 426
 427    PulsePalDevice is also a context manager, which closes the connection on
 428    exit even if an error is raised:
 429
 430    ```python
 431    with PulsePalDevice("COM3") as P:
 432        P.trigger(1)
 433    ```
 434
 435    The attributes below named after Pulse Pal parameters are lists
 436    indexed by channel number, with index 0 unused (see "Parameters"
 437    above). `print(P)` shows them all, and `PulsePalDevice.export_params`
 438    returns them as a dict.
 439    """
 440
 441    port: "serial.Serial"
 442    """The open `serial.Serial` port connected to the device."""
 443
 444    info: DeviceInfo
 445    """Properties of the connected device. See `DeviceInfo`."""
 446
 447    is_biphasic = _channel_setting("is_biphasic", """Pulse shape per channel: `False` for monophasic, `True` for biphasic.
 448
 449    Monophasic pulses use only the phase 1 parameters. Biphasic pulses
 450    follow phase 1 with `PulsePalDevice.inter_phase_interval` and then
 451    phase 2.
 452    """)
 453
 454    phase1_voltage = _channel_setting("phase1_voltage", """Voltage of the first phase of each pulse, in volts [-10, 10].""")
 455
 456    phase2_voltage = _channel_setting("phase2_voltage", """Voltage of the second phase of each pulse, in volts [-10, 10].
 457
 458    Used only when `PulsePalDevice.is_biphasic` is `True` for the channel.
 459    """)
 460
 461    resting_voltage = _channel_setting("resting_voltage", """Voltage held between pulses, in volts [-10, 10].
 462
 463    A new resting voltage reaches an idle channel's output at once. A
 464    channel playing a pulse train keeps playing it, and moves to the new
 465    resting voltage at its next transition to rest.
 466    """)
 467
 468    phase1_duration = _channel_setting("phase1_duration", """Duration of the first phase of each pulse, in seconds.
 469
 470    At least `DeviceInfo.min_pulse_width_us`.
 471    """)
 472
 473    inter_phase_interval = _channel_setting("inter_phase_interval", """Interval between the two phases of a biphasic pulse, in seconds.
 474
 475    The channel rests at `PulsePalDevice.resting_voltage` during the
 476    interval. Used only when `PulsePalDevice.is_biphasic` is `True`.
 477    """)
 478
 479    phase2_duration = _channel_setting("phase2_duration", """Duration of the second phase of each pulse, in seconds.
 480
 481    Used only when `PulsePalDevice.is_biphasic` is `True` for the channel.
 482    At least `DeviceInfo.min_pulse_width_us`.
 483    """)
 484
 485    inter_pulse_interval = _channel_setting("inter_pulse_interval", """Interval from the end of one pulse to the start of the next, in
 486    seconds. At least `DeviceInfo.min_pulse_width_us`.
 487
 488    It is not the pulse period: 1 ms pulses 49 ms apart play 20 pulses per
 489    second.
 490    """)
 491
 492    burst_duration = _channel_setting("burst_duration", """Duration of each burst of pulses, in seconds.
 493
 494    Set to `0` to disable bursts, so that pulses continue for the whole
 495    pulse train. A pulse starts only if it ends before the burst does:
 496    its first phase, or for a biphasic pulse the whole pulse, so that
 497    the end of a burst never cuts off a second phase.
 498    """)
 499
 500    inter_burst_interval = _channel_setting("inter_burst_interval", """Interval between bursts of pulses, in seconds.
 501
 502    The channel rests at `PulsePalDevice.resting_voltage` between
 503    bursts. Ignored when `PulsePalDevice.burst_duration` is `0`.
 504    """)
 505
 506    pulse_train_duration = _channel_setting("pulse_train_duration", """Total duration of the pulse train, in seconds.
 507
 508    At least `DeviceInfo.min_pulse_width_us`. The end of the train cuts
 509    short a monophasic pulse still playing. A biphasic pulse starts only
 510    if it can end by the end of the train, so that it keeps its second
 511    phase. A train's end is set when it starts: a new duration applies
 512    from the next train.
 513    """)
 514
 515    pulse_train_delay = _channel_setting("pulse_train_delay", """Delay from the trigger to the onset of the pulse train, in
 516    seconds.""")
 517
 518    link_trigger_channel1 = _channel_setting("link_trigger_channel1", """Whether each output channel is triggered by trigger channel 1.
 519
 520    `True` links the output channel to trigger channel 1, `False` unlinks
 521    it. By default no output channel is linked to either trigger channel,
 522    so a TTL starts nothing until a script links it.
 523    """)
 524
 525    link_trigger_channel2 = _channel_setting("link_trigger_channel2", """Whether each output channel is triggered by trigger channel 2.
 526
 527    `True` links the output channel to trigger channel 2, `False` unlinks
 528    it.
 529    """)
 530
 531    custom_train_id = _channel_setting("custom_train_id", """Custom pulse train played by each output channel.
 532
 533    `0` plays the parametrically defined train. `1` or higher plays the
 534    matching custom train, previously loaded with
 535    `PulsePalDevice.send_custom_pulse_train` or
 536    `PulsePalDevice.send_custom_waveform`: 1-4 on Pulse Pal 3, 1-2 on
 537    Pulse Pal 2 (`DeviceInfo.n_custom_pulse_trains`).
 538    """)
 539
 540    custom_train_target = _channel_setting("custom_train_target", """What the times of a custom train mark.
 541
 542    `"Pulses"` if each time is the onset of a pulse, `"Bursts"` if each
 543    time is the onset of a burst of pulses, which lasts
 544    `PulsePalDevice.burst_duration`. A burst whose time comes while the
 545    burst before plays is dropped, so that every burst played is on
 546    time. `"Bursts"` needs a burst duration above 0: with
 547    `PulsePalDevice.auto_sync` on, set the burst duration first, or set
 548    both in a `PulsePalDevice.batch` block.
 549    """)
 550
 551    custom_train_loop = _channel_setting("custom_train_loop", """Whether a custom train repeats.
 552
 553    `True` loops the custom train until
 554    `PulsePalDevice.pulse_train_duration` has elapsed, `False` plays it
 555    once. Each pass starts as the last pulse (or burst, for a train
 556    targeting bursts) of the pass before ends.
 557    `PulsePalDevice.continuous_loop` does not apply to custom trains.
 558    """)
 559
 560    continuous_loop = _channel_setting("continuous_loop", """Whether each output channel plays its pulse train until stopped.
 561
 562    `False` plays the pulse train once per trigger, for
 563    `PulsePalDevice.pulse_train_duration`. `True` plays it until the
 564    channel is stopped, ignoring `PulsePalDevice.pulse_train_duration`.
 565    For parametric trains only: a custom train ignores it, and plays as
 566    `PulsePalDevice.custom_train_loop` says. Requires firmware v22 or
 567    newer. The device does not report it, so
 568    `PulsePalDevice.sync_from_device` leaves it as it is.
 569    """)
 570
 571    trigger_mode = _channel_setting("trigger_mode", """Response of each trigger channel to an incoming TTL pulse.
 572
 573    Indexed by trigger channel number, 1 or 2 (index 0 is unused). The
 574    modes, also listed in `DeviceInfo.trigger_modes`, are:
 575
 576    - `"Normal"`: a rising edge starts the pulse trains of the linked
 577      output channels, and edges during a train are ignored.
 578    - `"Toggle"`: as `"Normal"`, but a rising edge during a train stops
 579      it.
 580    - `"Gated"`: the trains play only while the trigger TTL is high.
 581    - `"Param Sync"` (Pulse Pal 3 only): a TTL rising edge starts and
 582      stops nothing. It loads the parameters most recently sent by
 583      `PulsePalDevice.sync_to_device` (or at the end of a
 584      `PulsePalDevice.batch` block), and the custom trains loaded since
 585      the previous edge. This is how the next trial's parameters and
 586      custom trains are sent during the current trial and applied the
 587      instant it starts.
 588
 589    The integer codes 0-3 are accepted too.
 590
 591    An output channel that is idle at a param sync edge takes its new
 592    parameters in the timer cycle the edge is detected. One that is
 593    playing a pulse train finishes that train on the parameters it
 594    started with, and takes the new ones the moment it ends, so a train
 595    that runs past the end of a trial keeps one shape throughout and the
 596    next trigger plays a whole train with the new parameters. A channel
 597    in continuous loop mode has no train end, so it keeps its parameters
 598    until something stops it.
 599
 600    While either trigger channel is in param sync mode, **only
 601    `PulsePalDevice.sync_to_device` (and the end of a
 602    `PulsePalDevice.batch` block) and the custom train loads are held
 603    back**: with `PulsePalDevice.auto_sync` on, every assignment still
 604    programs the device immediately. So leaving param sync mode means
 605    assigning `trigger_mode` with `auto_sync` on; a trigger mode sent by
 606    `PulsePalDevice.sync_to_device` does not take effect until a sync
 607    edge arrives. A custom train loaded in param sync mode
 608    (`PulsePalDevice.send_custom_pulse_train`) replaces the old one at
 609    the edge: channels playing the old one at the edge finish their
 610    trains on it. Leaving param sync mode discards parameters still
 611    waiting for an edge, but makes a custom train still waiting current
 612    at once.
 613
 614    A param sync channel's links to output channels are ignored. To
 615    start a pulse train on the same edge, wire the TTL to the other
 616    trigger channel as well: both edges arrive in the same timer cycle,
 617    and the parameters are loaded first.
 618
 619    Connecting a new `PulsePalDevice`, and
 620    `PulsePalDevice.set_default_params`, take both trigger channels out
 621    of param sync mode, so that the default parameters reach the device
 622    instead of waiting for a TTL.
 623
 624    ```python
 625    P.trigger_mode[2] = "Param Sync"   # sent at once
 626    with P.batch():
 627        P.phase1_voltage[1] = 2.5
 628        P.phase1_duration[1] = 0.002
 629    # Stored by the device: the next rising edge on trigger channel 2 applies it
 630    ```
 631    """)
 632
 633    _CURRENT_FIRMWARE_VERSION = 22
 634    _OLDEST_FIRMWARE_SUPPORTED = 21
 635    _BAUD_RATE = _common.BAUD_RATE  # USB serial ignores it (see _common.BAUD_RATE)
 636
 637    _OP_MENU_BYTE = _common.OP_MENU_BYTE
 638    _HANDSHAKE_OPCODE = _common.OP_HANDSHAKE
 639    _HANDSHAKE_DEVICE_CYCLES_OPCODE = _common.OP_HANDSHAKE_DEVICE_CYCLES
 640    _HANDSHAKE_DEVICE_CYCLES_TIMEOUT = 0.3  # Seconds to wait for a reply to op 103 before trying op 72
 641    _HANDSHAKE_RESPONSE = 75  # 'K'
 642    _DAC_BITMAX = 65535
 643    _PARAM_MESSAGE_BYTES = 178  # Length of the parameter set sent by op 93
 644    _STATUS_MESSAGE_BYTES = 29  # Length of the reply to op 101: playing channels, then 7 uint32 counters
 645    # Phase 1 and 2 durations, inter-pulse interval and train duration last at least this many
 646    # timer cycles, by hardware version, as in the MATLAB and C++ classes and the joystick menu.
 647    # Pulse Pal 2's trigger channels read their inputs once per cycle, so a one cycle pulse from
 648    # another Pulse Pal could fall between two reads. Pulse Pal 3's also latch every edge.
 649    _MIN_PULSE_CYCLES = {2: 2, 3: 1}
 650
 651    _ENDIANNESS = "<"
 652    _STRUCT_FORMATS = {
 653        "uint8": "B",
 654        "int8": "b",
 655        "uint16": "H",
 656        "int16": "h",
 657        "uint32": "I",
 658        "int32": "i",
 659    }
 660    _TYPE_RANGES = {
 661        "uint8": (0, 2**8 - 1),
 662        "int8": (-(2**7), 2**7 - 1),
 663        "uint16": (0, 2**16 - 1),
 664        "int16": (-(2**15), 2**15 - 1),
 665        "uint32": (0, 2**32 - 1),
 666        "int32": (-(2**31), 2**31 - 1),
 667    }
 668
 669    _reply_pending = None  # The op code of a command whose reply has not been read in full yet (see _write_raw())
 670    _unsent = frozenset()  # The settings assigned with auto_sync off since the parameters were last sent or read
 671
 672    def __init__(self, port_name=None, *, serial_number=None, timeout=10):
 673        """Open a connection to a Pulse Pal device.
 674
 675        Opens the serial port, exchanges the handshake, verifies the
 676        firmware version, reads the device properties into
 677        `PulsePalDevice.info`, and programs the device with the default
 678        parameters.
 679
 680        ```python
 681        P = PulsePalDevice("COM3")
 682        P = PulsePalDevice(serial_number="20345420")  # Wherever it is plugged in
 683        ```
 684
 685        Args:
 686            port_name: USB serial port for the Pulse Pal device, such as
 687                `COM3` on Windows or `/dev/ttyACM0` on Linux.
 688            serial_number: Instead of `port_name`, the device's USB serial
 689                number (`DeviceInfo.serial_number`), which finds its port.
 690                Pulse Pal 3 only: Pulse Pal 2 has none.
 691            timeout: Serial read timeout, in seconds.
 692
 693        Firmware newer than this module knows (`v22`) is used with a
 694        warning: new firmware only adds commands, so everything here still
 695        works with it. Update the package to use what is new.
 696
 697        Raises:
 698            PulsePalError: If the device does not return the expected
 699                handshake (for example, it runs Wave Pal or Synth Pal
 700                firmware), or its firmware is older than v21, or no port
 701                has the serial number given. The port is closed again
 702                before any error is raised.
 703            serial.SerialException: If the serial port cannot be opened,
 704                e.g. because another program has it open (on Linux and
 705                macOS, another session of these classes, which lock it).
 706        """
 707        self._closed = True
 708        self._gui = None
 709        self._auto_sync = True
 710        self.info = DeviceInfo()
 711        self._create_settings()
 712        port_name = _common.port_name_from(port_name, serial_number, "PulsePalDevice")
 713        self.port = serial.Serial(
 714            port_name,
 715            self._BAUD_RATE,
 716            timeout=timeout,
 717            rtscts=True,
 718            # Windows opens a port for one program only. Linux and macOS let a second program open it too, and two
 719            # sessions' bytes would then interleave; exclusive locks it (flock), so a second session that also locks
 720            # it, such as another of these classes, gets an error instead
 721            exclusive=True,
 722        )
 723        self._closed = False
 724        try:
 725            self._start_session(port_name)
 726        except BaseException:
 727            # Otherwise the port stays open until the object is garbage
 728            # collected, and a second attempt, or WavePalDevice, cannot open
 729            # it. The device is in an unknown state, so it is not sent the
 730            # disconnect op.
 731            self._close(send_disconnect=False)
 732            raise
 733
 734    def _create_settings(self):
 735        """Create the parameter lists, holding the default values (nothing is sent)."""
 736        for code, (name, _) in _OUTPUT_PARAMETERS.items():
 737            setattr(self, "_" + name, ChannelSettings(
 738                name, [_DEFAULT_OUTPUT_VALUES[name]] * 4, self, f"_apply_{name}"))
 739        self._trigger_mode = ChannelSettings(
 740            "trigger_mode", ["Normal"] * 2, self, "_apply_trigger_mode")
 741
 742    def _start_session(self, port_name):
 743        """Handshake, check the firmware, and program the defaults."""
 744        # Discard anything left unread by an earlier session (one stopped mid-reply, for example):
 745        # it would be read as the handshake's reply. A reply the device sends after this, to a
 746        # command it had not reached yet, is skipped by read_handshake_reply().
 747        self.port.reset_input_buffer()
 748        # Op 103: the session's times are in the device's own timer cycles (10 us on Pulse Pal 3). Firmware from before
 749        # October 2026, Wave Pal and Synth Pal ignore it, and answer op 72, whose times are in 50 us cycles. Either way
 750        # op 94 reports the session's unit, which the class then uses.
 751        self._write_serial((self._OP_MENU_BYTE, self._HANDSHAKE_DEVICE_CYCLES_OPCODE), "uint8")
 752        reply = _common.read_handshake_reply(self.port, timeout=self._HANDSHAKE_DEVICE_CYCLES_TIMEOUT)
 753        if reply is None:
 754            self._write_serial((self._OP_MENU_BYTE, self._HANDSHAKE_OPCODE), "uint8")
 755            received = _common.read_handshake_bytes(self.port)
 756            reply = None if received is None else _common.handshake_reply_from(received)
 757            if reply is not None and reply[0] == self._HANDSHAKE_RESPONSE and reply[1] > 21 and len(received) > 5:
 758                # More than one reply arrived: the device was busy when op 103 came, and answered it with op 72. A Pulse
 759                # Pal 3 answers nothing for about 5 s after it starts, while it shows its splash screen and opens its
 760                # microSD card (measured on Pulse Pal 3: op 103 and op 72 sent 0.2 to 3.5 s after the port opened were
 761                # answered together 5.0 s after it opened). Op 72, answered last, would leave the session in 50 us
 762                # cycles, so op 103 is sent again, now that the device is listening. If the extra bytes were a late
 763                # reply to an earlier session, and the firmware ignores op 103, this waits 0.3 s more.
 764                self._write_serial((self._OP_MENU_BYTE, self._HANDSHAKE_DEVICE_CYCLES_OPCODE), "uint8")
 765                reply = _common.read_handshake_reply(self.port, timeout=self._HANDSHAKE_DEVICE_CYCLES_TIMEOUT) or reply
 766        if reply is None:
 767            raise PulsePalError(
 768                f"No reply to the handshake from the device on {port_name}. Is it a Pulse Pal? "
 769                f"{_common.NO_REPLY_HINT}"
 770            )
 771        handshake, firmware_version = reply
 772        if handshake != self._HANDSHAKE_RESPONSE:
 773            if handshake in _common.FIRMWARE_BY_HANDSHAKE_REPLY:
 774                raise _common.other_firmware_error(handshake, firmware_version, port_name, "Pulse Pal")
 775            raise PulsePalError(
 776                "Incorrect handshake returned. Expected "
 777                f"{self._HANDSHAKE_RESPONSE}, received {handshake}."
 778            )
 779
 780        if firmware_version < self._OLDEST_FIRMWARE_SUPPORTED:
 781            raise PulsePalError(
 782                "Old firmware detected, v"
 783                f"{firmware_version}. v{self._OLDEST_FIRMWARE_SUPPORTED} or "
 784                "newer is required."
 785            )
 786        if firmware_version > self._CURRENT_FIRMWARE_VERSION:
 787            # New firmware only adds commands (see PulsePal-Firmware/PROTOCOL.md), so this class still works with it
 788            warnings.warn(
 789                f"Pulse Pal firmware v{firmware_version} is newer than this pulsepal package knows "
 790                f"(v{self._CURRENT_FIRMWARE_VERSION}). It works with it, but update the package to use what "
 791                "is new.", stacklevel=3)
 792        if firmware_version < self._CURRENT_FIRMWARE_VERSION:
 793            warnings.warn(
 794                f"Pulse Pal firmware v{firmware_version} is supported, but v"
 795                f"{self._CURRENT_FIRMWARE_VERSION} is available: see /MATLAB/FirmwareLoader.", stacklevel=3)
 796        self.info.firmware_version = firmware_version
 797
 798        if self.info.firmware_version > 21:
 799            self._write_serial((self._OP_MENU_BYTE, 94), "uint8")
 800            self.info.hardware_version = self._read_serial(1, "uint8")
 801            self.info.cycle_period_us = self._read_serial(1, "uint32")  # The session's time unit (see op 103 above)
 802            # Not 1 / (period / 1e6): at 10 us that is 99999.99999999999, and times read back from the device would
 803            # convert to 0.00010000000000000002 s instead of 0.0001 s
 804            self.info.cycle_frequency = 1000000 / self.info.cycle_period_us
 805            self.info.n_custom_pulse_trains = self._read_serial(1, "uint8")
 806            self.info.max_custom_pulses = self._read_serial(1, "uint32")
 807            self._write_serial((self._OP_MENU_BYTE, 100), "uint8")  # Circuit board revision
 808            revision = self.port.read(1)
 809            if len(revision) < 1:
 810                raise PulsePalError(
 811                    f"The Pulse Pal on {port_name} did not report its circuit board revision."
 812                )
 813            self._reply_pending = None  # Read without _read_raw() (see _write_raw())
 814            self.info.circuit_board_revision = revision[0]
 815            self._write_serial((self._OP_MENU_BYTE, _common.OP_SERIAL_NUMBER), "uint8")
 816            self.info.serial_number = _common.read_serial_number(self._read_raw)
 817        else:
 818            self.info.hardware_version = 2
 819            self.info.circuit_board_revision = 0
 820            self.info.serial_number = ""  # v21 runs on Pulse Pal 2, which has none
 821            self.info.cycle_period_us = 50
 822            self.info.cycle_frequency = 20000
 823            self.info.n_custom_pulse_trains = 2
 824            self.info.max_custom_pulses = 5000
 825        self.info.min_pulse_width_us = (
 826            self._MIN_PULSE_CYCLES[self.info.hardware_version] * self.info.cycle_period_us
 827        )
 828        if not self._has_param_sync():
 829            self.info.trigger_modes = TRIGGER_MODES[:3]
 830
 831        # Client name op + "PYTHON" in ASCII.
 832        self._write_serial(
 833            (self._OP_MENU_BYTE, 89, 80, 89, 84, 72, 79, 78),
 834            "uint8",
 835        )
 836
 837        self.set_default_params()
 838
 839    @staticmethod
 840    def serialportlist(ports_to_list="available"):
 841        """Return the names of the USB serial ports on this computer.
 842
 843        Called on the class, without connecting to a device, to find the
 844        port name to pass to `PulsePalDevice`:
 845
 846        ```python
 847        from pulsepal import PulsePalDevice
 848
 849        ports = PulsePalDevice.serialportlist()
 850        P = PulsePalDevice(ports[0])
 851        ```
 852
 853        Args:
 854            ports_to_list: `available` to list only the ports that are
 855                not already in use, or `all` to list every USB serial
 856                port. Not case sensitive.
 857
 858        Returns:
 859            Sorted list of port names, such as `["COM3", "COM7"]` on
 860            Windows or `["/dev/ttyACM0"]` on Linux.
 861
 862        Raises:
 863            PulsePalError: If `ports_to_list` is not `available` or
 864                `all`.
 865        """
 866        return _common.serialportlist(ports_to_list)
 867
 868    # ------------------------------------------------------------------
 869    # Programming the device
 870    # ------------------------------------------------------------------
 871
 872    @property
 873    def auto_sync(self):
 874        """Whether assigning a parameter programs the device at once.
 875
 876        `True` (the default): each assignment, such as
 877        `P.phase1_voltage[1] = 5`, programs the device at once, also while
 878        a trigger channel is in param sync mode. It sends the channels
 879        whose value it changes, and nothing for a channel that already
 880        holds the value assigned: the other channels keep what the device
 881        holds, e.g. values set with its joystick (read them with
 882        `PulsePalDevice.sync_from_device`).
 883
 884        `False`: assignments change only this object's copy of the
 885        parameters, checking each value, and
 886        `PulsePalDevice.sync_to_device` sends all of them in one command.
 887        Turning it back on does not send changes made meanwhile, so it
 888        raises `pulsepal.PulsePalError` while there are any: call
 889        `PulsePalDevice.sync_to_device` first to send them, or
 890        `PulsePalDevice.sync_from_device` to discard them. A
 891        `PulsePalDevice.batch` block does it all for you. `close()` warns of
 892        changes never sent.
 893        """
 894        return self._auto_sync
 895
 896    @auto_sync.setter
 897    def auto_sync(self, value):
 898        value = to_bool(value, "auto_sync")
 899        if value and self._unsent:
 900            # Turned on, auto_sync would leave them unsent, and the device playing its old parameters
 901            discard = "sync_from_device() to discard them"
 902            if "continuous_loop" in self._unsent:
 903                discard += " (all but continuous_loop, which the device does not report)"
 904            raise PulsePalError(
 905                f"Changes made with auto_sync off have not been sent to the device: {self._unsent_names()}. Call "
 906                f"sync_to_device() to send them, or {discard}, before turning auto_sync on."
 907            )
 908        self._auto_sync = value
 909
 910    def batch(self):
 911        """Change several parameters, and send them in one command.
 912
 913        Returns a context manager. In its block, assignments change only
 914        this object's copy of the parameters (as with
 915        `PulsePalDevice.auto_sync` off), and when the block ends,
 916        `PulsePalDevice.sync_to_device` sends all of them at once. If the
 917        block raises an error, nothing is sent, and the parameters go
 918        back to what they were.
 919
 920        ```python
 921        with P.batch():
 922            P.phase1_voltage = [5, 5, 2.5, 2.5]
 923            P.phase1_duration[3] = 0.002
 924        ```
 925
 926        In param sync mode, the device stores the parameters for the next
 927        rising edge on the param sync channel (see
 928        `PulsePalDevice.trigger_mode`).
 929        """
 930        return _common.batch(self)
 931
 932    def sync_to_device(self):
 933        """Program the device with this object's copy of all parameters.
 934
 935        Sends every output and trigger parameter to the device in a single
 936        command. Use it after assignments made with
 937        `PulsePalDevice.auto_sync` off; with it on, they have already
 938        reached the device.
 939
 940        ```python
 941        P.auto_sync = False
 942        P.phase1_voltage[1:5] = [5] * 4
 943        P.sync_to_device()
 944        ```
 945
 946        On Pulse Pal 3, if either trigger channel is in param sync mode
 947        (`PulsePalDevice.trigger_mode` `"Param Sync"`), the device stores
 948        the parameters instead of programming them, and loads them on the
 949        next rising edge of that channel. The device still checks every
 950        value. This is the only method whose effect is deferred that way.
 951
 952        Raises:
 953            PulsePalError: If a value is out of range for its parameter
 954                (nothing is sent), or the device does not acknowledge the
 955                command.
 956        """
 957        self._check_sync()
 958        self._send_sync()
 959
 960    def sync_from_device(self):
 961        """Read all parameters from the device into this object's copy.
 962
 963        Overwrites the parameter lists with the program currently on the
 964        device, e.g. after it has been reprogrammed from its thumb
 965        joystick. `PulsePalDevice.continuous_loop` is left as it is: the
 966        device does not report it. Changes made with
 967        `PulsePalDevice.auto_sync` off and not yet sent are discarded, but
 968        for `PulsePalDevice.continuous_loop`.
 969
 970        Requires firmware v22 or newer.
 971
 972        Raises:
 973            PulsePalError: If the connected firmware is older than v22,
 974                or the device does not return the full parameter set.
 975        """
 976        self._require_firmware(22, "sync_from_device()")
 977        for name, values in self._read_device_params().items():
 978            getattr(self, name)._store(values)
 979        self._unsent = self._unsent & {"continuous_loop"}  # Not read: a change to it is still unsent
 980
 981    def set_default_params(self):
 982        """Program the device with the default parameters.
 983
 984        The defaults are monophasic +5 V pulses of 0.1 ms, 1 ms apart
 985        (about 909 a second), for 1 second, resting at 0 V, on all four
 986        output channels; for biphasic pulses, a phase 2 of -5 V and 0.1 ms
 987        after 0.1 ms at rest. No output channel is linked to a trigger
 988        channel, so a TTL starts nothing until a script links it, and both
 989        trigger channels are in normal mode. They are the device's own
 990        defaults, which it also loads at startup, after a comm failure
 991        and after formatting its microSD card. They are sent at once,
 992        also while `PulsePalDevice.auto_sync` is off. The constructor
 993        calls it.
 994        """
 995        for name, value in _DEFAULT_OUTPUT_VALUES.items():
 996            getattr(self, name)._store([value] * 4)
 997        self._trigger_mode._store(["Normal"] * 2)
 998        if self._has_param_sync():
 999            # A device left in param sync mode would store the sync below instead of running it,
1000            # leaving the device on its old program until a TTL arrived. A trigger mode sent on
1001            # its own is not deferred that way, so both trigger channels leave param sync mode
1002            # first. See PulsePalDevice.trigger_mode.
1003            self._send_trigger_modes(["Normal"] * 2, "set_default_params()")
1004        self._send_sync()
1005
1006    def export_params(self):
1007        """Return every parameter, as a dict of plain lists.
1008
1009        Keyed by parameter name (`DeviceInfo.output_parameter_names`, then
1010        `"trigger_mode"`), with one value per channel and no unused index
1011        0. It holds only numbers, booleans and names, so it can be saved
1012        with `json` and logged with your data, to record exactly what the
1013        device played. `PulsePalDevice.import_params` programs it again.
1014
1015        ```python
1016        import json
1017        with open("trial_params.json", "w") as f:
1018            json.dump(P.export_params(), f)
1019        ```
1020        """
1021        names = [*self.info.output_parameter_names, "trigger_mode"]
1022        return {name: list(getattr(self, name))[1:] for name in names}
1023
1024    def import_params(self, params):
1025        """Program the device with parameters exported by `PulsePalDevice.export_params`.
1026
1027        All of them are checked first, and then sent in one command, as
1028        at the end of a `PulsePalDevice.batch` block: in param sync mode,
1029        the device stores them for the next sync edge. Parameters missing
1030        from `params` keep their values. A name that is not a parameter
1031        is skipped with a warning, so that parameters exported by a newer
1032        version of this package, which may have more, can still be
1033        imported; if none is, an error is raised.
1034
1035        A whole program file, as the GUIs save it, is imported too: its
1036        parameters, not its custom trains (a warning says so, if it has
1037        any).
1038
1039        ```python
1040        with open("MyProgram.json") as f:
1041            P.import_params(json.load(f))
1042        ```
1043
1044        Args:
1045            params: A dict of parameter name to one value per channel (a
1046                list, tuple or NumPy array), as `export_params` returns,
1047                or a program file's contents. The MATLAB class's names
1048                (`phase1Voltage`) are accepted too, so that the parameters
1049                its `exportParams()` returns, saved with `jsonencode`, can
1050                be imported.
1051
1052        Raises:
1053            PulsePalError: If a value is invalid, or no name in `params` is
1054                a parameter. Nothing is sent, and the parameters keep the
1055                values they had.
1056        """
1057        params = _params_to_import(params)
1058        with self.batch():
1059            for name, values in params.items():
1060                setattr(self, name, values)
1061
1062    def set_fixed_voltage(self, channels, voltage):
1063        """Set output channels to a fixed voltage.
1064
1065        Each channel holds the voltage until it is set again or until a
1066        pulse train is triggered on it.
1067
1068        ```python
1069        P.set_fixed_voltage(4, 2.5)
1070        P.set_fixed_voltage([1, 3], -1)
1071        ```
1072
1073        Args:
1074            channels: Output channel number, 1-4, or several as a list,
1075                tuple or NumPy array.
1076            voltage: Voltage to set on each of them, in volts [-10, 10].
1077
1078        Raises:
1079            PulsePalError: If a channel number is not 1-4, the voltage is
1080                outside [-10, 10] (nothing is sent), or the device does not
1081                acknowledge the command.
1082        """
1083        channels = _common.channel_numbers(channels)
1084        voltage_bits = self._volts_to_bits(voltage, "voltage")
1085        for channel in channels:
1086            self._write_serial(
1087                (self._OP_MENU_BYTE, 79, channel),
1088                "uint8",
1089                voltage_bits,
1090                "uint16",
1091            )
1092            self._read_ack("set_fixed_voltage()")
1093
1094    def set_calibration(self, channel, voltage_offset):
1095        """Calibrate the zero code of an output channel.
1096
1097        The offset is added to every voltage the channel produces, to
1098        correct for DAC offset error. It is stored in the device's
1099        EEPROM and reloaded on boot, so it only needs to be set once.
1100
1101        Requires Pulse Pal hardware v3 or newer.
1102
1103        Args:
1104            channel: Output channel number, 1-4.
1105            voltage_offset: Offset to apply, in volts [-0.1, 0.1].
1106
1107        Raises:
1108            PulsePalError: If the connected hardware is older than v3,
1109                `channel` is not 1-4, `voltage_offset` is outside
1110                [-0.1, 0.1], or the device does not acknowledge the
1111                command.
1112        """
1113        if self.info.hardware_version < 3:
1114            raise PulsePalError(
1115                "set_calibration() requires hardware v3 or newer."
1116            )
1117        if not (isinstance(channel, numbers.Integral) and channel in (1, 2, 3, 4)):
1118            raise PulsePalError("channel must be 1, 2, 3 or 4")
1119        if not (isinstance(voltage_offset, numbers.Real) and -0.1 <= voltage_offset <= 0.1):  # Also refuses NaN
1120            raise PulsePalError(
1121                "voltage_offset for zero code calibration must be in range "
1122                "[-0.1, 0.1]"
1123            )
1124        # To the nearest DAC code, halfway values to the even one, as the MATLAB class rounds it
1125        voltage_bits = int(round(voltage_offset * (1 / (20 / 65536))))
1126        self._write_serial(
1127            (self._OP_MENU_BYTE, 96, channel - 1),
1128            "uint8",
1129            voltage_bits,
1130            "int16",
1131        )
1132        self._read_ack("set_calibration()")
1133
1134    def set_screen_saver(self, enabled, timeout=1800):
1135        """Switch the device's screen saver on or off, and set its timeout.
1136
1137        With the screen saver on, the device dims its screen once it has
1138        been left alone for `timeout` seconds: no command from the
1139        computer, no rising edge on a trigger channel, and no joystick
1140        click or push. The next of these brings the screen back. Both
1141        settings are stored in the device's EEPROM and kept through power
1142        cycles; the screen saver can also be switched on and off from the
1143        device's joystick menu. A new device has it on, with 1800 s.
1144
1145        The device saves the settings once no channel is playing. Saving
1146        pauses its timer, usually for about 20 us but, once in about 2000
1147        changes, for tens of milliseconds, which would delay a trigger.
1148        Change the settings before an experiment rather than during one.
1149
1150        Requires firmware v22 or newer. Only Pulse Pal 3 has a screen
1151        saver: Pulse Pal 2 accepts `enabled=False` only.
1152
1153        ```python
1154        P.set_screen_saver(True, 300)  # dim after 5 minutes
1155        P.set_screen_saver(False)
1156        ```
1157
1158        Args:
1159            enabled: True (or 1) to switch the screen saver on, False (or
1160                0) to switch it off.
1161            timeout: Seconds without activity before the screen dims, a
1162                whole number from 1 to 65535. It is sent with every call,
1163                so leaving it out sets 1800 s.
1164
1165        Raises:
1166            PulsePalError: If the firmware is older than v22, the
1167                screen saver is switched on with hardware older than v3,
1168                a value is out of range, or the device does not
1169                acknowledge the command.
1170        """
1171        self._require_firmware(22, "set_screen_saver()")
1172        enabled = to_bool(enabled, "enabled")
1173        if not (
1174            isinstance(timeout, numbers.Real)
1175            and not isinstance(timeout, bool)
1176            and math.isfinite(timeout)
1177            and timeout == int(timeout)
1178            and 1 <= timeout <= 65535
1179        ):
1180            raise PulsePalError(
1181                "timeout must be a whole number of seconds from 1 to 65535"
1182            )
1183        if enabled and (self.info.hardware_version or 2) < 3:
1184            raise PulsePalError(
1185                "The screen saver requires hardware v3 or newer: Pulse Pal 2 "
1186                "accepts set_screen_saver(False) only."
1187            )
1188        self._write_serial(
1189            (self._OP_MENU_BYTE, 99, int(enabled)),
1190            "uint8",
1191            int(timeout),
1192            "uint16",
1193        )
1194        self._read_ack("set_screen_saver()")
1195
1196    # ------------------------------------------------------------------
1197    # Custom trains, playback and settings files
1198    # ------------------------------------------------------------------
1199
1200    def send_custom_pulse_train(
1201        self,
1202        custom_train_id,
1203        pulse_times,
1204        voltages,
1205    ):
1206        """Load a custom pulse train onto the device.
1207
1208        A custom pulse train is an arbitrary list of pulse onset times
1209        and voltages, replacing the parametric pulse voltage and onset
1210        timing. Set `PulsePalDevice.custom_train_id` on an output channel
1211        to play the train there. Each pulse takes the channel's own phase
1212        durations; a biphasic pulse's second phase is its voltage with the
1213        sign reversed. A biphasic pulse always plays whole, and a pulse
1214        whose time comes while it plays is dropped, so that every pulse
1215        played is on time.
1216
1217        ```python
1218        P.send_custom_pulse_train(
1219            2, [0, 0.2, 0.5, 1], [8, 4, -3.5, -10]
1220        )
1221        P.custom_train_id[1] = 2
1222        ```
1223
1224        Loading a train stops the output channels playing it, and their
1225        next trigger plays the new train. On Pulse Pal 3, while a trigger
1226        channel is in param sync mode (see `PulsePalDevice.trigger_mode`),
1227        the device stores the train instead, as it stores the parameters
1228        `PulsePalDevice.sync_to_device` sends: channels go on playing the
1229        old train, and the next rising edge on the param sync channel
1230        makes the new one current. A channel playing the old train at that
1231        edge finishes it, and plays the new one from its next trigger. So
1232        the next trial's custom trains can be loaded during the current
1233        trial. Leaving param sync mode makes a stored train current at
1234        once.
1235
1236        Args:
1237            custom_train_id: Custom train to load, from 1 to
1238                `DeviceInfo.n_custom_pulse_trains` (2 on Pulse Pal 2,
1239                4 on Pulse Pal 3).
1240            pulse_times: Pulse onset times, in seconds, relative to the
1241                start of the train, increasing. Each is a multiple of
1242                `DeviceInfo.min_pulse_width_us` (10 us on Pulse Pal 3,
1243                100 us on Pulse Pal 2), from 0 to
1244                `MAX_TIME`. Accepts a list, tuple or 1-D NumPy array.
1245            voltages: Voltage of each pulse, in volts [-10, 10]. Must be
1246                the same length as `pulse_times`.
1247
1248        Raises:
1249            PulsePalError: If `custom_train_id` is out of range,
1250                `pulse_times` or `voltages` is not one-dimensional (a 2-D
1251                array is refused, not flattened), they differ in length,
1252                there are no pulses, or more than
1253                `DeviceInfo.max_custom_pulses`, a pulse time is not a
1254                multiple of `DeviceInfo.min_pulse_width_us`, is out of
1255                range or is not later than the one before it, or the
1256                device does not acknowledge the command.
1257        """
1258        pulse_times_cycles = self._custom_times_to_cycles(pulse_times, "pulse_times")
1259        pulse_voltage_bits = self._volts_array_to_bits(voltages, "voltages")
1260        if len(pulse_times_cycles) != len(pulse_voltage_bits):
1261            raise PulsePalError(
1262                "pulse_times and voltages must be the same length."
1263            )
1264        self._send_custom_train(
1265            custom_train_id,
1266            pulse_times_cycles,
1267            pulse_voltage_bits,
1268            "send_custom_pulse_train()",
1269        )
1270
1271    def send_custom_waveform(
1272        self,
1273        custom_train_id,
1274        sampling_period,
1275        voltages,
1276    ):
1277        """Load an arbitrary waveform onto the device.
1278
1279        A convenience shorthand for
1280        `PulsePalDevice.send_custom_pulse_train` with evenly spaced,
1281        adjoining pulses, so that `voltages` is played as a waveform
1282        sampled every `sampling_period` seconds. It is loaded as a custom
1283        train is: see `PulsePalDevice.send_custom_pulse_train` for what
1284        happens to channels playing it, and in param sync mode.
1285
1286        Set the channel's `PulsePalDevice.phase1_duration` to
1287        `sampling_period` as well, so that each sample is held for the
1288        sampling period.
1289
1290        ```python
1291        import math
1292
1293        samples = [math.sin(i / 10.0) * 10 for i in range(1000)]
1294        P.send_custom_waveform(1, 0.001, samples)   # 1 kHz
1295        P.custom_train_id[2] = 1
1296        P.phase1_duration[2] = 0.001
1297        ```
1298
1299        Args:
1300            custom_train_id: Custom train to load, from 1 to
1301                `DeviceInfo.n_custom_pulse_trains` (2 on Pulse Pal 2,
1302                4 on Pulse Pal 3).
1303            sampling_period: In seconds: a multiple of
1304                `DeviceInfo.min_pulse_width_us` (10 us on Pulse Pal 3,
1305                100 us on Pulse Pal 2). Each voltage is
1306                held for this long.
1307            voltages: Waveform samples, in volts [-10, 10].
1308                Accepts a list, tuple or 1-D NumPy array.
1309
1310        Raises:
1311            PulsePalError: If `custom_train_id` is out of range, there
1312                are no samples, or more than
1313                `DeviceInfo.max_custom_pulses`, `sampling_period` is not a
1314                positive multiple of `DeviceInfo.min_pulse_width_us`, the
1315                last sample would start after `MAX_TIME`, or the device
1316                does not acknowledge the command.
1317        """
1318        pulse_voltage_bits = self._volts_array_to_bits(voltages, "voltages")
1319        period_cycles = self._custom_time_cycles(sampling_period, "sampling_period")
1320        if period_cycles == 0:
1321            raise PulsePalError(
1322                f"sampling_period must be a positive multiple of {self.info.min_pulse_width_us:g} us. "
1323                f"Received {sampling_period!r}."
1324            )
1325        pulse_times = period_cycles * np.arange(len(pulse_voltage_bits), dtype=np.int64)
1326        self._send_custom_train(
1327            custom_train_id,
1328            pulse_times,
1329            pulse_voltage_bits,
1330            "send_custom_waveform()",
1331        )
1332
1333    def trigger(self, channels):
1334        """Trigger output channels in software.
1335
1336        The channels start their pulse trains together, in the same timer
1337        cycle. A channel that is already playing a pulse train ignores
1338        the trigger, and `PulsePalDevice.stop` cancels a trigger that has
1339        not started its channel yet.
1340
1341        ```python
1342        P.trigger(3)          # one channel
1343        P.trigger([1, 4])     # several: a list, tuple or NumPy array
1344        ```
1345
1346        Args:
1347            channels: Output channel number, 1-4, or several as a list,
1348                tuple or NumPy array.
1349
1350        Raises:
1351            PulsePalError: If a channel number is not 1-4, or no channel
1352                is given. Nothing is triggered.
1353        """
1354        self._write_serial((self._OP_MENU_BYTE, 77, _common.channel_bits(channels)), "uint8")
1355
1356    def stop(self, channels=None):
1357        """Stop pulse trains currently playing on the device.
1358
1359        The stopped channels return to their
1360        `PulsePalDevice.resting_voltage`. A soft trigger that has not
1361        started its channel yet is cancelled too.
1362
1363        ```python
1364        P.stop()           # all output channels
1365        P.stop([1, 3, 4])  # channels 1, 3 and 4
1366        ```
1367
1368        Args:
1369            channels: Output channel number, 1-4, or several as a list,
1370                tuple or NumPy array. `None`, the default, stops all
1371                channels. Stopping some channels requires firmware v22
1372                or newer.
1373
1374        Raises:
1375            PulsePalError: If a channel number is not 1-4, or channels are
1376                given and the firmware is older than v22.
1377        """
1378        if self.info.firmware_version < 22:
1379            if channels is not None:
1380                raise PulsePalError("stop() cannot address individual channels before firmware v22")
1381            self._write_serial((self._OP_MENU_BYTE, 80), "uint8")  # Stops all channels
1382            return
1383        bits = 0x0F if channels is None else _common.channel_bits(channels)
1384        self._write_serial((self._OP_MENU_BYTE, 98, bits), "uint8")
1385
1386    def status(self):
1387        """Read which channels are playing, and the counters since the last call.
1388
1389        The counters (see `DeviceStatus`) count from the previous call, or
1390        from the device's startup, and each call clears them. Calling it
1391        before and after a trial checks that the TTLs the trial sent
1392        arrived, and started the trains they should:
1393
1394        ```python
1395        P.status()                     # Clears the counters
1396        run_trial()                    # Your code: one TTL on trigger channel 1, linked to channels 1 and 2
1397        s = P.status()
1398        if s.trigger_edges[1] != 1 or s.channel_starts[1:3] != [1, 1]:
1399            print("The trial's trains did not all start")
1400        ```
1401
1402        Requires firmware v22 or newer.
1403
1404        Returns:
1405            A `DeviceStatus`.
1406
1407        Raises:
1408            PulsePalError: If the firmware is older than v22, or the device
1409                does not reply.
1410        """
1411        self._require_firmware(22, "status()")
1412        self._write_serial((self._OP_MENU_BYTE, 101), "uint8")
1413        values = struct.unpack(f"{self._ENDIANNESS}B7I", self._read_raw(self._STATUS_MESSAGE_BYTES))
1414        return DeviceStatus(
1415            playing=[ch for ch in range(1, 5) if values[0] & (1 << (ch - 1))],
1416            trigger_edges=[None, *values[1:3]],
1417            channel_starts=[None, *values[3:7]],
1418            comm_failures=values[7],
1419        )
1420
1421    def save_program_to_microsd(self, file_name):
1422        """Save the parameters to the device's microSD card, as a program.
1423
1424        The program can be loaded later with
1425        `PulsePalDevice.load_program_from_microsd` or with the joystick
1426        menu's Load Program item. A file of the same name is replaced. To
1427        keep the parameters on this computer instead, see
1428        `PulsePalDevice.export_params`.
1429
1430        ```python
1431        P.save_program_to_microsd("MyProtocol.pps")
1432        ```
1433
1434        Args:
1435            file_name: At most 15 ASCII characters, ending in `.pps`.
1436
1437        Raises:
1438            PulsePalError: If the file name is invalid, or the device could
1439                not write the file to its microSD card. Pulse Pal 2 also
1440                refuses while a channel is playing: its card shares a bus with
1441                the outputs, so stop playback first.
1442        """
1443        self._settings_file_op(file_name, 1, "save_program_to_microsd()")
1444
1445    def load_program_from_microsd(self, file_name):
1446        """Load a program from the device's microSD card.
1447
1448        The device plays the program, and the parameters are read back
1449        into this object (see `PulsePalDevice.sync_from_device`). The
1450        program's trigger modes take effect too, and it is loaded at once,
1451        also in param sync mode.
1452
1453        Args:
1454            file_name: The program's file name, ending in `.pps`, as saved
1455                by `PulsePalDevice.save_program_to_microsd` or the joystick
1456                menu.
1457
1458        Raises:
1459            PulsePalError: If the file name is invalid, or the device could
1460                not load the program: there is no such file on its microSD
1461                card, or it is not a valid Pulse Pal program; or, on Pulse
1462                Pal 2, a channel is playing (see `save_program_to_microsd`).
1463                The device then keeps its parameters, and so does this object.
1464        """
1465        self._settings_file_op(file_name, 2, "load_program_from_microsd()")
1466
1467    def delete_program_from_microsd(self, file_name):
1468        """Delete a program from the device's microSD card.
1469
1470        Args:
1471            file_name: The program's file name, ending in `.pps`.
1472
1473        Raises:
1474            PulsePalError: If the file name is invalid, or the device could
1475                not delete the file, e.g. because there is no such file, or,
1476                on Pulse Pal 2, because a channel is playing.
1477        """
1478        self._settings_file_op(file_name, 3, "delete_program_from_microsd()")
1479
1480    def _settings_file_op(self, file_name, op_byte, context):
1481        """Save (op_byte 1), load (2) or delete (3) a settings file, with op 90."""
1482        valid = (
1483            isinstance(file_name, str)
1484            and all(32 <= ord(character) <= 126 for character in file_name)  # Printable ASCII
1485            and file_name.lower().endswith(".pps")
1486            and 4 < len(file_name) <= 15
1487        )
1488        if not valid:
1489            raise PulsePalError(
1490                f"{context}: the file name must be 1 to 11 ASCII characters followed by .pps, "
1491                f"e.g. 'Protocol1.pps'. Received {file_name!r}."
1492            )
1493        filename_bytes = file_name.encode("ascii")
1494        self._write_serial(
1495            (self._OP_MENU_BYTE, 90, op_byte, len(filename_bytes)),
1496            "uint8",
1497            list(filename_bytes),
1498            "uint8",
1499        )
1500        if self.info.firmware_version > 21:
1501            # Sent after the file operation has finished. A refused load changes nothing on the device.
1502            refusal = {
1503                1: f"Pulse Pal could not save {file_name!r} to its microSD card. Is the card in place?",
1504                2: f"Pulse Pal could not load {file_name!r}: there is no such file on its microSD card, or it is not "
1505                   "a valid Pulse Pal program. The device keeps its parameters.",
1506                3: f"Pulse Pal could not delete {file_name!r}: there is no such file on its microSD card.",
1507            }[op_byte]
1508            # Pulse Pal 2 replies 2 while a channel plays: its microSD card shares the SPI bus with the DAC
1509            busy = (f"Pulse Pal 2 does not use its microSD card while a channel is playing, because the card shares a "
1510                    f"bus with the outputs, so {file_name!r} was not {('saved', 'loaded', 'deleted')[op_byte - 1]}. "
1511                    "Stop playback first, with stop().")
1512            if op_byte == 2:
1513                busy += " The device keeps its parameters."
1514            self._read_ack(context, refusal_message=refusal, refusal_messages={2: busy})
1515        else:
1516            self._reply_pending = None  # Firmware v21 does not acknowledge op 90 (see _write_raw())
1517            if op_byte == 2:
1518                time.sleep(0.1)  # So allow time for the load
1519        if op_byte == 2:
1520            self.sync_from_device()
1521
1522    def format_microsd(self, *, confirm=True, timeout=30):
1523        """Format the device's microSD card.
1524
1525        Erases every program saved on the device and resets its
1526        parameters to the defaults. By default, asks at the console for
1527        confirmation first; a script that runs on its own, or an AI agent,
1528        passes `confirm=False`.
1529
1530        Requires Pulse Pal hardware v3 or newer.
1531
1532        Args:
1533            confirm: If `True`, ask at the console before anything is
1534                erased. If `False`, format at once.
1535            timeout: Seconds to wait for the device to report that
1536                formatting has finished.
1537
1538        Returns:
1539            `True` once the card has been formatted, or `False` if the
1540            user declines the confirmation prompt.
1541
1542        Raises:
1543            PulsePalError: If the connected hardware is older than v3, if
1544                the device reports that formatting failed, or if it does
1545                not report a result within `timeout` seconds.
1546        """
1547        if self.info.hardware_version < 3:
1548            raise PulsePalError(
1549                "format_microsd() requires hardware v3 or newer."
1550            )
1551
1552        if to_bool(confirm, "confirm"):
1553            print("*** Pulse Pal microSD Formatter ***")
1554            print("This will format Pulse Pal's microSD card,")
1555            print("erase all programs saved on the device")
1556            print("and reset all parameters to defaults.")
1557            reply = input("Do you want to continue (y/n)")
1558            if reply.strip().lower() != "y":
1559                print("Choice confirmed - microSD Card NOT formatted.")
1560                return False
1561
1562        self._write_serial((self._OP_MENU_BYTE, 97), "uint8", list(_FORMAT_KEY), "uint8")
1563
1564        # The device replies with lines of status text, the last of which
1565        # contains "!", and then a confirm byte (1 if the card was formatted,
1566        # 0 if not). The confirm byte is sent after the device has reloaded
1567        # its default parameters, so it can arrive well after the text. It
1568        # must be read here: left in the buffer, it would be taken as the
1569        # reply to the next command, and every reply after that would be
1570        # read one byte late.
1571        start = time.time()
1572        message = bytearray()
1573        flag_index = -1
1574        line_end = -1
1575
1576        while time.time() - start < timeout:
1577            n_waiting = self.port.in_waiting
1578            if n_waiting:
1579                message.extend(self.port.read(n_waiting))
1580                flag_index = message.find(b"!")
1581                if flag_index >= 0:
1582                    line_end = message.find(b"\n", flag_index)
1583                if line_end >= 0 and len(message) > line_end + 1:
1584                    break
1585            time.sleep(0.01)
1586        if line_end < 0 or len(message) <= line_end + 1:
1587            raise PulsePalError(
1588                "Pulse Pal did not report the result of formatting "
1589                f"its microSD card within {timeout} s. {_common.NO_REPLY_HINT}"
1590            )
1591        self._reply_pending = None  # The whole reply is read (see _write_raw())
1592        confirm_byte = message[line_end + 1]
1593
1594        text = bytes(message[:flag_index]).decode(
1595            "ascii", errors="replace"
1596        ).rstrip()
1597        if text:
1598            print(text)
1599
1600        # The device has loaded its own defaults. They are this class's, but the device keeps no record of
1601        # this object's other changes (continuous loop mode, for one), so the defaults are programmed, as the
1602        # MATLAB class does, and this object describes the device again.
1603        self.set_default_params()
1604        if confirm_byte != 1:
1605            raise PulsePalError(
1606                "Pulse Pal could not format its microSD card."
1607            )
1608        return True
1609
1610    def gui(self, block=None, theme=None):
1611        """Open the Pulse Pal parameter GUI, or focus an open one.
1612
1613        The GUI edits its own copy of the parameters, and loads them to
1614        the device when its 'Load to Device' button is clicked. The
1615        window closes automatically when the device is closed or
1616        deleted.
1617
1618        Calling this while the GUI is already open focuses the existing
1619        window rather than opening a second one.
1620
1621        Args:
1622            block: If `True`, the call returns when the GUI is closed. If
1623                `False`, the call returns immediately, and the host
1624                application must run the Tk event loop. If `None`, the
1625                GUI blocks only when the host does not already provide a
1626                Tk event loop, e.g. when launched from a script.
1627            theme: `"light"` or `"dark"` to select the color theme, or
1628                `None` to match the desktop theme. Passing a theme to an
1629                already-open GUI recolors it in place.
1630
1631        Returns:
1632            The `pulsepal.gui.PulsePalGUI` instance driving the window.
1633
1634        Raises:
1635            ValueError: If the theme name is not recognized.
1636        """
1637        gui = getattr(self, "_gui", None)
1638        if gui is not None and not gui.is_closed:
1639            if theme is not None:
1640                gui.set_theme(theme)
1641            gui.focus()
1642            return gui
1643
1644        from .gui import PulsePalGUI
1645
1646        gui = PulsePalGUI(self, theme=theme)
1647        self._gui = gui
1648        gui.start(block=block)
1649        return gui
1650
1651    # ------------------------------------------------------------------
1652    # Connection
1653    # ------------------------------------------------------------------
1654
1655    def close(self):
1656        """Close the connection to the device, and the GUI if open.
1657
1658        The device stops all output channels when the client disconnects,
1659        and shows its own name on its screen again. Safe to call more
1660        than once; later calls do nothing. Called automatically when
1661        leaving a `with` block and when the object is garbage collected,
1662        so pulse trains also stop when the last reference to the object
1663        goes, e.g. when a function that created it returns.
1664        """
1665        self._close(send_disconnect=True)
1666
1667    def _close(self, send_disconnect):
1668        """Close the connection. send_disconnect: tell the device first (op 81). False when the device is in
1669        an unknown state, such as after a failed handshake."""
1670        gui = getattr(self, "_gui", None)
1671        self._gui = None
1672        if gui is not None:
1673            try:
1674                gui.close()
1675            except Exception:
1676                # Cleanup must not raise; Tk may already be torn down
1677                pass
1678
1679        if getattr(self, "_closed", True):
1680            return
1681        self._closed = True
1682        if send_disconnect and self._unsent:
1683            _common.warn(f"PulsePalDevice closed with changes made with auto_sync off that were never sent to the "
1684                         f"device: {self._unsent_names()}.")
1685        self._reply_pending = None  # Nothing more is read, so a reply still to come needs no discarding
1686        try:
1687            if send_disconnect and self.port and self.port.is_open:
1688                self._write_serial((self._OP_MENU_BYTE, 81), "uint8")
1689        except Exception:
1690            pass  # The port may already be gone, e.g. the cable was unplugged
1691        finally:
1692            if self.port and self.port.is_open:
1693                self.port.close()
1694
1695    def __enter__(self):
1696        """Enter a `with` block, returning the connected device."""
1697        return self
1698
1699    def __exit__(self, exc_type, exc_value, traceback):
1700        """Disconnect and close the port when leaving a `with` block.
1701
1702        Returns:
1703            `False`, so any exception raised in the block propagates.
1704        """
1705        self.close()
1706        return False
1707
1708    def __del__(self):
1709        """Disconnect and close the port when the object is collected."""
1710        try:
1711            self.close()
1712        except Exception:
1713            # Destructors should not raise; the serial object may already be
1714            # gone during interpreter shutdown.
1715            pass
1716
1717    def __setattr__(self, name, value):
1718        """Refuse a public attribute that is not a setting, such as a misspelled one: it would program nothing (see
1719        _common.refuse_unknown_attribute())."""
1720        if name[0] != "_":
1721            _common.refuse_unknown_attribute(self, name, _SETTING_NAMES)
1722        super().__setattr__(name, value)
1723
1724    def __repr__(self):
1725        """Describe the device and its parameters, e.g. with `print(P)`."""
1726        port = getattr(getattr(self, "port", None), "port", None)
1727        lines = [
1728            f"PulsePalDevice on {port} (Pulse Pal {self.info.hardware_version}, "
1729            f"firmware v{self.info.firmware_version})",
1730            f"auto_sync: {self._auto_sync}",
1731        ]
1732        for name in self.info.output_parameter_names:
1733            lines.append(f"{name}: {list(getattr(self, name))}")
1734        lines.append(f"trigger_mode: {list(self._trigger_mode)}")
1735        return "\n".join(lines)
1736
1737    # ------------------------------------------------------------------
1738    # Internals: parameters
1739    # ------------------------------------------------------------------
1740
1741    def _has_param_sync(self):
1742        """Param sync mode is on Pulse Pal 3, with firmware v22 or newer."""
1743        return (self.info.hardware_version or 2) > 2 and (self.info.firmware_version or 0) > 21
1744
1745    def _normalize_output_value(self, code, value, channel):
1746        """Check a value for an output parameter, and return it as the parameter's list holds it:
1747        a time as the device plays it, rounded to its timer cycle.
1748
1749        Raises PulsePalError, before anything is sent, for a value the device cannot play. The
1750        device refuses most of them too, but it also resets them (see validateOutputParams() in
1751        PulsePal-Firmware/PulsePal/USBOps.ino), so the local copy would describe a different program.
1752        """
1753        name, kind = _OUTPUT_PARAMETERS[code]
1754        label = f"{name} on channel {channel}"
1755        if kind == "bool":
1756            value = to_bool(value, label)
1757            if code == _CONTINUOUS_LOOP_CODE and value and self.info.firmware_version < 22:
1758                raise PulsePalError("continuous_loop requires firmware v22 or newer.")
1759            return value
1760        if kind == "volts":
1761            self._volts_to_bits(value, label)
1762            return float(value)
1763        if kind in ("time", "pulse_time"):
1764            cycles = self._seconds_to_cycles(value, label)
1765            # Checked in whole cycles, as the device receives it: 100 * 1e-6 is just under 0.0001,
1766            # but is exactly 10 cycles of 10 us
1767            if kind == "pulse_time" and cycles < self._min_pulse_cycles():
1768                raise PulsePalError(
1769                    f"{label} must be at least {self._min_pulse_seconds()} s "
1770                    f"({self._min_pulse_cycles_text()} of the device's {self.info.cycle_period_us} us "
1771                    f"timer), so that trigger channels can detect the pulses. Received {value!r}."
1772                )
1773            return self._cycles_to_seconds(cycles)  # The time the device plays
1774        if kind == "train_id":
1775            self._check_whole_number(value, label, 0, self.info.n_custom_pulse_trains)
1776            return int(value)
1777        # "target"
1778        return to_name(value, CUSTOM_TRAIN_TARGETS, label, codes={"Pulses": 0, "Bursts": 1})
1779
1780    def _normalize_trigger_mode(self, value):
1781        modes = self.info.trigger_modes
1782        return to_name(value, modes, "trigger_mode", codes={mode: TRIGGER_MODES.index(mode) for mode in modes})
1783
1784    def _encode_output_param(self, code, values):
1785        """Convert output parameter values to device units.
1786
1787        Returns the converted values and the datatype the device reads for this
1788        parameter code: DAC codes for voltages, hardware timer cycles for times,
1789        and bytes for everything else.
1790        """
1791        name, kind = _OUTPUT_PARAMETERS[code]
1792        if kind == "volts":
1793            return [self._volts_to_bits(v, name) for v in values], "uint16"
1794        if kind in ("time", "pulse_time"):
1795            return [self._seconds_to_cycles(v, name) for v in values], "uint32"
1796        if kind == "target":
1797            return [CUSTOM_TRAIN_TARGETS.index(v) for v in values], "uint8"
1798        return [int(v) for v in values], "uint8"
1799
1800    def _apply_output_param(self, code, values):
1801        """Check new values for all four channels of an output parameter, and with auto_sync on,
1802        program the channels whose value changes. Returns them as the parameter's list holds them."""
1803        values = [self._normalize_output_value(code, v, ch) for ch, v in enumerate(values, start=1)]
1804        name = _OUTPUT_PARAMETERS[code][0]
1805        if not self._auto_sync:
1806            self._unsent = self._unsent | {name}  # Until sync_to_device() sends it (see auto_sync)
1807        else:
1808            if code in (_BURST_DURATION_CODE, _CUSTOM_TRAIN_TARGET_CODE):
1809                # Sent alone, so it must suit the other parameter as the device holds it. In a batch() block, or
1810                # with auto_sync off, both are checked together by sync_to_device().
1811                new = {name: values}
1812                self._check_custom_bursts(new.get("custom_train_target", list(self._custom_train_target)[1:]),
1813                                          new.get("burst_duration", list(self._burst_duration)[1:]))
1814            # Compared as the device receives them: 5 and 5.00001 V are the same DAC code
1815            old_data, _ = self._encode_output_param(code, list(getattr(self, name))[1:])
1816            new_data, _ = self._encode_output_param(code, values)
1817            channels = [ch for ch in range(1, 5) if old_data[ch - 1] != new_data[ch - 1]]
1818            self._send_output_param(code, values, channels, f"setting {name}")
1819        return values
1820
1821    def _send_output_param(self, code, values, channels, context):
1822        """Program one output parameter on some output channels: op 91 if all four change, op 74 for each otherwise.
1823
1824        The other channels are left as the device holds them. Sending all four (op 91) for a change to one put this
1825        object's copy of the others back on the device, undoing what the joystick menu, or a program loaded with it,
1826        had set there.
1827        """
1828        if self.info.firmware_version > 21 and len(channels) == 4:
1829            data, datatype = self._encode_output_param(code, values)
1830            self._write_serial((self._OP_MENU_BYTE, 91, code), "uint8", data, datatype)
1831            self._read_ack(context, on_refusal=lambda: self._refresh_output_param(code, channels))
1832            return
1833        for channel in channels:
1834            # A refusal reads back every channel this assignment changes, so that the copy describes the device for
1835            # those already sent too
1836            self._send_output_param_to_channel(code, channel, values[channel - 1], context, refresh_channels=channels)
1837
1838    def _send_output_param_to_channel(self, code, channel, value, context, refresh_channels=None):
1839        """Program one output parameter on one channel (op 74)."""
1840        if code == _CONTINUOUS_LOOP_CODE and self.info.firmware_version < 22:
1841            return  # Firmware v21 has no parameter 18, and _normalize_output_value() lets only False through
1842        data, datatype = self._encode_output_param(code, [value])
1843        self._write_serial((self._OP_MENU_BYTE, 74, code, channel), "uint8", data, datatype)
1844        self._read_ack(context, on_refusal=lambda: self._refresh_output_param(code, refresh_channels or (channel,)))
1845
1846    def _apply_trigger_mode(self, values):
1847        """Check new trigger modes, and with auto_sync on, program the trigger channels whose mode changes."""
1848        modes = [self._normalize_trigger_mode(v) for v in values]
1849        if not self._auto_sync:
1850            self._unsent = self._unsent | {"trigger_mode"}
1851        else:
1852            channels = [ch for ch in (1, 2) if modes[ch - 1] != self._trigger_mode[ch]]
1853            if len(channels) == 2:
1854                self._send_trigger_modes(modes, "setting trigger_mode")
1855            elif channels:  # One: op 74, which leaves the other trigger channel as the device holds it
1856                channel = channels[0]
1857                self._write_serial((self._OP_MENU_BYTE, 74, _TRIGGER_MODE_CODE, channel,
1858                                    TRIGGER_MODES.index(modes[channel - 1])), "uint8")
1859                self._read_ack("setting trigger_mode", on_refusal=self._refresh_trigger_mode)
1860        return modes
1861
1862    def _send_trigger_modes(self, modes, context):
1863        """Program both trigger channels' modes: op 91, or op 74 per channel on firmware v21."""
1864        codes = [TRIGGER_MODES.index(mode) for mode in modes]
1865        if self.info.firmware_version > 21:
1866            self._write_serial((self._OP_MENU_BYTE, 91, _TRIGGER_MODE_CODE, *codes), "uint8")
1867            self._read_ack(context, on_refusal=self._refresh_trigger_mode)
1868        else:
1869            for channel, mode_code in enumerate(codes, start=1):
1870                self._write_serial((self._OP_MENU_BYTE, 74, _TRIGGER_MODE_CODE, channel, mode_code), "uint8")
1871                self._read_ack(context)
1872
1873    def _snapshot(self):
1874        """All parameters, and which are unsent, for batch() to restore if its block fails."""
1875        names = [*self.info.output_parameter_names, "trigger_mode"]
1876        return {name: list(getattr(self, name))[1:] for name in names}, self._unsent
1877
1878    def _restore(self, snapshot):
1879        params, self._unsent = snapshot
1880        for name, values in params.items():
1881            getattr(self, name)._store(values)
1882
1883    def _unsent_names(self):
1884        """The settings assigned with auto_sync off and not yet sent, for messages, in parameter code order."""
1885        return ", ".join(name for name in _SETTING_NAMES if name in self._unsent)
1886
1887    def _check_sync(self):
1888        """Check the whole local copy before sync_to_device() sends it."""
1889        for code, (name, _) in _OUTPUT_PARAMETERS.items():
1890            values = getattr(self, name)
1891            for ch in range(1, 5):
1892                self._normalize_output_value(code, values[ch], ch)
1893        for ch in (1, 2):
1894            self._normalize_trigger_mode(self._trigger_mode[ch])
1895        self._check_custom_bursts(list(self._custom_train_target)[1:], list(self._burst_duration)[1:])
1896
1897    @staticmethod
1898    def _check_custom_bursts(targets, burst_durations):
1899        """Refuse a custom train targeting bursts on a channel with no burst duration.
1900
1901        Its times are burst onsets, and a burst of no duration plays one timer cycle of a pulse at each: a
1902        program that cannot be what was meant. (The device once played one pulse and then left the channel
1903        "playing", ignoring triggers until it was stopped.)
1904        """
1905        for channel, (target, burst) in enumerate(zip(targets, burst_durations), start=1):
1906            if target == "Bursts" and burst == 0:
1907                raise PulsePalError(
1908                    f"Output channel {channel}: custom_train_target 'Bursts' makes the custom train's times burst "
1909                    "onsets, so burst_duration must be above 0. Set burst_duration first, or set both in a batch() "
1910                    "block."
1911                )
1912
1913    def _send_sync(self):
1914        """Send every parameter in one command: op 92 on firmware v22 or newer, op 73 on v21."""
1915        self._unsent = frozenset()  # All are sent below
1916        if self.info.firmware_version > 21:
1917            self._sync_all_params()
1918        else:
1919            self._sync_all_params_legacy()
1920        self._read_ack("sync_to_device()", on_refusal=self._refresh_after_refused_sync)
1921
1922    def _device_bytes(self, name):
1923        """The byte values of a byte parameter for channels 1-4, as the device reads them."""
1924        values = list(getattr(self, name))[1:]
1925        if name == "custom_train_target":
1926            return [CUSTOM_TRAIN_TARGETS.index(v) for v in values]
1927        return [int(v) for v in values]
1928
1929    def _sync_all_params(self):
1930        """Send all parameters using the packed sync op (firmware v22+).
1931
1932        Values are grouped by width so that the whole program travels as
1933        one uint32 block, one uint16 block and one uint8 block. See op 92
1934        in PulsePal-Firmware/PROTOCOL.md.
1935        """
1936        time_values = []
1937        for name in _TIME_PARAMETERS:
1938            time_values.extend(self._seconds_to_cycles(v) for v in list(getattr(self, name))[1:])
1939        voltage_values = []
1940        for name in _VOLTAGE_PARAMETERS:
1941            voltage_values.extend(self._volts_to_bits(v) for v in list(getattr(self, name))[1:])
1942        single_byte_values = []
1943        for name in ("is_biphasic", "custom_train_id", "custom_train_target", "custom_train_loop",
1944                     "continuous_loop", "link_trigger_channel1", "link_trigger_channel2"):
1945            single_byte_values.extend(self._device_bytes(name))
1946        single_byte_values.extend(TRIGGER_MODES.index(mode) for mode in list(self._trigger_mode)[1:])
1947
1948        self._write_serial(
1949            (self._OP_MENU_BYTE, 92),
1950            "uint8",
1951            time_values,
1952            "uint32",
1953            voltage_values,
1954            "uint16",
1955            single_byte_values,
1956            "uint8",
1957        )
1958
1959    def _sync_all_params_legacy(self):
1960        """Send all parameters using the legacy sync op (firmware v21).
1961
1962        Equivalent to `_sync_all_params`, but lays the program out
1963        channel by channel as the older firmware expects. Continuous
1964        loop mode is not part of it.
1965        """
1966        program_values_32 = []
1967        program_values_16 = []
1968        program_values_8 = []
1969        for ch in range(1, 5):
1970            program_values_32.extend(self._seconds_to_cycles(getattr(self, name)[ch]) for name in _TIME_PARAMETERS)
1971        for ch in range(1, 5):
1972            program_values_16.extend(self._volts_to_bits(getattr(self, name)[ch]) for name in _VOLTAGE_PARAMETERS)
1973        byte_values = {name: self._device_bytes(name) for name in
1974                       ("is_biphasic", "custom_train_id", "custom_train_target", "custom_train_loop")}
1975        for ch in range(4):
1976            program_values_8.extend(byte_values[name][ch] for name in byte_values)
1977        links = self._device_bytes("link_trigger_channel1") + self._device_bytes("link_trigger_channel2")
1978        modes = [TRIGGER_MODES.index(mode) for mode in list(self._trigger_mode)[1:]]
1979
1980        self._write_serial(
1981            (self._OP_MENU_BYTE, 73),
1982            "uint8",
1983            program_values_32,
1984            "uint32",
1985            program_values_16,
1986            "uint16",
1987            program_values_8 + links + modes,
1988            "uint8",
1989        )
1990
1991    def _read_device_params(self):
1992        """Read the device's parameters (op 93).
1993
1994        Returns a dict of parameter values for channels 1-4 (trigger
1995        channels 1-2 for trigger_mode), as the parameter lists hold them.
1996        Continuous loop mode is not part of op 93, so `continuous_loop` is
1997        not included.
1998        """
1999        self._write_serial((self._OP_MENU_BYTE, 93), "uint8")
2000        # The device sends the whole parameter set as one message, so read it in one go and
2001        # unpack it here. See "Op codes", op 93, in PulsePal-Firmware/PROTOCOL.md.
2002        message = self._read_raw(self._PARAM_MESSAGE_BYTES)
2003        values = struct.unpack(f"{self._ENDIANNESS}32I12H26B", message)
2004        params = {}
2005        for index, name in enumerate(_TIME_PARAMETERS):
2006            params[name] = [self._cycles_to_seconds(x) for x in values[index * 4:index * 4 + 4]]
2007        for index, name in enumerate(_VOLTAGE_PARAMETERS):
2008            params[name] = [self._bits_to_volts(x) for x in values[32 + index * 4:32 + index * 4 + 4]]
2009        for index, name in enumerate(("is_biphasic", "custom_train_id", "custom_train_target",
2010                                      "custom_train_loop", "link_trigger_channel1", "link_trigger_channel2")):
2011            codes = values[44 + index * 4:44 + index * 4 + 4]
2012            if name == "custom_train_id":
2013                params[name] = list(codes)
2014            elif name == "custom_train_target":
2015                params[name] = [CUSTOM_TRAIN_TARGETS[min(code, 1)] for code in codes]
2016            else:
2017                params[name] = [bool(code) for code in codes]
2018        params["trigger_mode"] = [TRIGGER_MODES[min(code, 3)] for code in values[68:70]]
2019        return params
2020
2021    def _refresh_output_param(self, code, channels):
2022        """Read an output parameter back from the device into the local copy, for these channels.
2023
2024        Called after the device refused a value for them, which it resets. The parameter's other
2025        channels, and other parameters, keep their local values, which may hold edits not yet synced.
2026        """
2027        name = _OUTPUT_PARAMETERS[code][0]
2028        if self.info.firmware_version < 22 or code == _CONTINUOUS_LOOP_CODE:
2029            return  # No op 93 to read it with, or not in op 93
2030        device_values = self._read_device_params()[name]
2031        settings = getattr(self, name)
2032        local_values = list(settings)[1:]
2033        for ch in channels:
2034            local_values[ch - 1] = device_values[ch - 1]
2035        settings._store(local_values)
2036
2037    def _refresh_trigger_mode(self):
2038        """Read the trigger modes back from the device, after the device refused a new one."""
2039        if self.info.firmware_version > 21:
2040            self._trigger_mode._store(self._read_device_params()["trigger_mode"])
2041
2042    def _refresh_after_refused_sync(self):
2043        """Read the parameters back after the device refused a sync_to_device() set.
2044
2045        The device programs the set with the refused values reset, so the local copy is read back.
2046        In param sync mode the device stores the set instead, and op 93 would return the parameters
2047        playing now, so the local copy is left as it is.
2048        """
2049        if self.info.firmware_version > 21 and "Param Sync" not in list(self._trigger_mode)[1:]:
2050            self.sync_from_device()
2051
2052    def _check_whole_number(self, value, name, low, high):
2053        """Raise PulsePalError unless value is a whole number from low to high."""
2054        valid = (
2055            isinstance(value, numbers.Real)
2056            and not isinstance(value, (bool, np.bool_))
2057            and math.isfinite(value)
2058            and value == int(value)
2059            and low <= value <= high
2060        )
2061        if not valid:
2062            raise PulsePalError(
2063                f"{name} must be a whole number from {low} to {high}. Received {value!r}."
2064            )
2065
2066    def _min_pulse_cycles(self):
2067        """The shortest pulse phase, interval or train, in timer cycles: DeviceInfo.min_pulse_width_us. See
2068        _MIN_PULSE_CYCLES."""
2069        return int(round(self.info.min_pulse_width_us / self.info.cycle_period_us))
2070
2071    def _min_pulse_cycles_text(self):
2072        """_min_pulse_cycles() for messages: "1 cycle", "2 cycles"."""
2073        cycles = self._min_pulse_cycles()
2074        return f"{cycles} cycle" if cycles == 1 else f"{cycles} cycles"
2075
2076    def _min_pulse_seconds(self):
2077        """The shortest pulse phase, interval or train, in seconds: DeviceInfo.min_pulse_width_us."""
2078        return self._cycles_to_seconds(self._min_pulse_cycles())
2079
2080    def _require_firmware(self, minimum_version, context):
2081        """Raise unless the device firmware is new enough for an op."""
2082        if (
2083            self.info.firmware_version is None
2084            or self.info.firmware_version < minimum_version
2085        ):
2086            raise PulsePalError(
2087                f"{context} requires firmware v{minimum_version} or newer. "
2088                f"Detected firmware is v{self.info.firmware_version}."
2089            )
2090
2091    # ------------------------------------------------------------------
2092    # Internals: custom trains
2093    # ------------------------------------------------------------------
2094
2095    def _send_custom_train(self, custom_train_id, pulse_times_cycles,
2096                           pulse_voltage_bits, context):
2097        """Send a custom pulse train, already converted to device units (NumPy integer arrays).
2098
2099        Uses op 95 on firmware v22 or newer, and the legacy ops 75 and 76
2100        (trains 1 and 2 only) on firmware v21.
2101        """
2102        n_trains = self.info.n_custom_pulse_trains
2103        valid_id = (
2104            isinstance(custom_train_id, numbers.Integral)
2105            and not isinstance(custom_train_id, (bool, np.bool_))
2106            and 1 <= custom_train_id <= n_trains
2107        )
2108        if not valid_id:
2109            raise PulsePalError(
2110                f"{context}: custom_train_id must be an integer from 1 to "
2111                f"{n_trains}. Received {custom_train_id!r}."
2112            )
2113        train_id = int(custom_train_id)
2114        n_pulses = len(pulse_times_cycles)
2115        if n_pulses == 0:
2116            # The device refuses an empty train too: it would hold no pulse times to play
2117            raise PulsePalError(
2118                f"{context}: a custom train needs at least one pulse. To play nothing on a channel, set its "
2119                "custom_train_id to a train that holds what it should play, or do not trigger it."
2120            )
2121        if n_pulses > self.info.max_custom_pulses:
2122            raise PulsePalError(
2123                f"{context}: {n_pulses} pulses were given. Pulse Pal can "
2124                f"store up to {self.info.max_custom_pulses} pulses per "
2125                "custom train."
2126            )
2127        # Times are multiples of _min_pulse_cycles() (see _custom_times_to_cycles()), so increasing times are far
2128        # enough apart for a trigger channel to detect each pulse.
2129        too_close = np.flatnonzero(np.diff(pulse_times_cycles) < self._min_pulse_cycles())
2130        if too_close.size:
2131            i = int(too_close[0]) + 1
2132            raise PulsePalError(
2133                f"{context}: pulse times must increase, by at least "
2134                f"{self._min_pulse_seconds()} s ({self._min_pulse_cycles_text()} "
2135                f"of the device's {self.info.cycle_period_us} us "
2136                f"timer). Pulse {i + 1} is at "
2137                f"{self._cycles_to_seconds(pulse_times_cycles[i])} s, "
2138                f"and pulse {i} is at "
2139                f"{self._cycles_to_seconds(pulse_times_cycles[i - 1])} s."
2140            )
2141        if pulse_times_cycles[-1] > self._max_time_cycles():
2142            raise PulsePalError(
2143                f"{context}: the last pulse starts at {self._cycles_to_seconds(pulse_times_cycles[-1])} s. "
2144                f"Pulse times must be at most {self.info.max_time} s."
2145            )
2146
2147        if self.info.firmware_version > 21:
2148            header = bytes([self._OP_MENU_BYTE, 95, train_id - 1])
2149        else:
2150            header = bytes([self._OP_MENU_BYTE, 74 + train_id])
2151        self._write_raw(
2152            header + struct.pack("<I", n_pulses)
2153            + np.asarray(pulse_times_cycles).astype("<u4").tobytes()
2154            + np.asarray(pulse_voltage_bits).astype("<u2").tobytes()
2155        )
2156        self._read_ack(context)
2157
2158    def _number_array(self, values, name, description):
2159        """Return values (a scalar, a list, a tuple or a 1-D NumPy array) as a float64 array, refusing booleans,
2160        strings and anything else that is not a number, as the scalar conversions do.
2161
2162        An array of two or more dimensions, or a list of lists, is refused rather than flattened: one value per
2163        pulse is a list, and a 2-D one is a mistake, such as both rows of a stereo waveform. (The MATLAB class, which
2164        took a matrix's longest side as its pulse count and sent all of it, sent the rest to the device as commands.)
2165        """
2166        if isinstance(values, np.ndarray):
2167            self._check_one_dimensional(values, name)
2168            if values.dtype.kind in "iuf":
2169                return values.ravel().astype(float)
2170        items = self._as_list(values)
2171        refused_types = tuple(kind for kind in {type(item) for item in items}  # Each type once: fast for long lists
2172                              if issubclass(kind, (bool, np.bool_, str, bytes)))
2173        if refused_types:
2174            item = next(item for item in items if isinstance(item, refused_types))
2175            raise PulsePalError(f"{name} must be {description}. Received {item!r}.")
2176        try:
2177            array = np.asarray(items, dtype=float)
2178        except (TypeError, ValueError):
2179            for item in items:
2180                try:
2181                    float(item)
2182                except (TypeError, ValueError):
2183                    raise PulsePalError(f"{name} must be {description}. Received {item!r}.") from None
2184            raise
2185        self._check_one_dimensional(array, name)  # A list of lists
2186        return array
2187
2188    @staticmethod
2189    def _check_one_dimensional(array, name):
2190        if array.ndim > 1:
2191            raise PulsePalError(
2192                f"{name} must be one-dimensional, one value per pulse: a list, a tuple or a 1-D NumPy array. "
2193                f"Received an array of shape {array.shape}."
2194            )
2195
2196    @staticmethod
2197    def _first(values, refused):
2198        """The first value at a True position of the boolean array `refused`, for an error message."""
2199        i = int(np.flatnonzero(refused)[0])
2200        item = values.ravel()[i] if isinstance(values, np.ndarray) else PulsePalDevice._as_list(values)[i]
2201        return item.item() if isinstance(item, np.generic) else item
2202
2203    def _custom_times_to_cycles(self, values, name):
2204        """Convert custom pulse times to timer cycles, all at once: _custom_time_cycles() for each of them.
2205
2206        Each must be a time the device can play, and a whole number of DeviceInfo.min_pulse_width_us to the nearest
2207        microsecond, as in the MATLAB class. Returns an int64 array.
2208        """
2209        seconds = self._number_array(values, name, "a time of 0 s or more")
2210        refused = ~(np.isfinite(seconds) & (seconds >= 0))
2211        if refused.any():
2212            raise PulsePalError(f"{name} must be a time of 0 s or more. Received {self._first(values, refused)!r}.")
2213        # The same arithmetic as _seconds_to_cycles() and _custom_time_cycles(): NumPy's round() also takes a
2214        # halfway value to the even integer
2215        refused = np.round(seconds * float(self.info.cycle_frequency)) > self._max_time_cycles()
2216        if refused.any():
2217            raise PulsePalError(
2218                f"{name} must be at most {self.info.max_time} s, the longest time the device's screen "
2219                f"shows. Received {self._first(values, refused)!r}."
2220            )
2221        microseconds = np.round(seconds * 1e6)
2222        step_us = int(self.info.min_pulse_width_us)
2223        refused = np.mod(microseconds, step_us) != 0
2224        if refused.any():
2225            raise PulsePalError(
2226                f"{name} must be multiples of {step_us} us ({step_us / 1e6:g} s). "
2227                f"Received {self._first(values, refused)!r}."
2228            )
2229        return (microseconds // int(self.info.cycle_period_us)).astype(np.int64)
2230
2231    def _volts_array_to_bits(self, values, name):
2232        """Convert voltages to DAC codes, all at once: _volts_to_bits() for each of them. Returns an int64 array."""
2233        volts = self._number_array(values, name, "in [-10, 10] V")
2234        refused = ~((volts >= -10) & (volts <= 10))  # Also refuses NaN
2235        if refused.any():
2236            raise PulsePalError(f"{name} must be in [-10, 10] V. Received {self._first(values, refused)!r}.")
2237        return np.round((volts + 10) / 20 * self._DAC_BITMAX).astype(np.int64)
2238
2239    # ------------------------------------------------------------------
2240    # Internals: serial port and units
2241    # ------------------------------------------------------------------
2242
2243    def _write_serial(self, *args):
2244        """Write one or more data/type pairs to the serial port, in one write."""
2245        if len(args) % 2 != 0:
2246            raise PulsePalError(
2247                "Serial writes require data/type argument pairs."
2248            )
2249
2250        payload = bytearray()
2251        for i in range(0, len(args), 2):
2252            payload.extend(self._pack_values(args[i], args[i + 1]))
2253        self._write_raw(bytes(payload))
2254
2255    def _write_raw(self, payload):
2256        """Write a command to the serial port, in one write.
2257
2258        A command whose reply was not read in full, because the read timed out or was interrupted (Ctrl-C), leaves
2259        that reply, or the rest of it, to arrive later. Read as the reply to the next command, it put every reply
2260        after it out of step: status() reported channels playing that were not, and assignments the device took
2261        raised refusals. So it is discarded first (_discard_lost_reply()). Then this command's reply, if it has one,
2262        is pending until it has been read: _read_raw() marks it read, and a method that reads a reply otherwise
2263        (format_microsd()) sets _reply_pending back to None itself.
2264        """
2265        if self._reply_pending is not None:
2266            self._discard_lost_reply()
2267        if payload[1] not in _OPS_WITHOUT_TRACKED_REPLY:
2268            self._reply_pending = payload[1]  # Before the write: a Ctrl-C can come as soon as it returns
2269        bytes_written = self.port.write(payload)
2270        if bytes_written != len(payload):
2271            raise PulsePalError(
2272                f"Wrote {bytes_written} byte(s), expected to write "
2273                f"{len(payload)} byte(s)."
2274            )
2275
2276    def _discard_lost_reply(self):
2277        """Discard what arrives of a reply that was not read in full (see _write_raw()), and bring this object back
2278        in step with the device.
2279
2280        The command may have changed the parameters, unknown to this object: an assignment interrupted after its
2281        write, for one, which the device took and this object did not. So after one of _PARAMETER_OPS, they are read
2282        back (op 93), on firmware v22 or newer and outside param sync mode, where op 93 returns the parameters playing
2283        rather than a set stored for the next sync edge.
2284        """
2285        op = self._reply_pending
2286        self._reply_pending = None
2287        n_late = len(_common.read_until_quiet(self.port))
2288        read_back = (op in _PARAMETER_OPS and self.info.firmware_version > 21
2289                     and "Param Sync" not in list(self._trigger_mode)[1:])
2290        _common.warn_lost_reply(f"op {op}", n_late,
2291                                ", and the parameters were read back from the device" if read_back else "")
2292        if read_back:
2293            try:
2294                self.sync_from_device()
2295            except PulsePalError as exc:
2296                raise PulsePalError(
2297                    f"Pulse Pal did not send its parameters, read back after the reply to an earlier command was "
2298                    f"lost. {_common.NO_REPLY_HINT}"
2299                ) from exc
2300
2301    def _read_raw(self, n_bytes):
2302        """Read exactly n_bytes from the serial port: the whole reply to the command last sent, which is then no
2303        longer pending (see _write_raw()). Only connecting reads a reply in more than one call."""
2304        message_bytes = self.port.read(n_bytes)
2305        if len(message_bytes) < n_bytes:
2306            raise PulsePalError(
2307                f"Pulse Pal sent {len(message_bytes)} of the {n_bytes} byte(s) of its reply within "
2308                f"{self.port.timeout} s. {_common.NO_REPLY_HINT}"
2309            )
2310        self._reply_pending = None
2311        return message_bytes
2312
2313    def _read_serial(self, n_values, datatype):
2314        """Read values from the serial port and unpack them with struct."""
2315        fmt = self._STRUCT_FORMATS[datatype]
2316        n_values = int(n_values)
2317        n_bytes = n_values * struct.calcsize(fmt)
2318        message_bytes = self._read_raw(n_bytes)
2319
2320        values = struct.unpack(
2321            f"{self._ENDIANNESS}{n_values}{fmt}",
2322            message_bytes,
2323        )
2324        if n_values == 1:
2325            return values[0]
2326        return list(values)
2327
2328    def _read_ack(self, context, on_refusal=None, refusal_message=None, refusal_messages=None):
2329        """Read a one-byte acknowledgement from the device.
2330
2331        The device replies 1 if it executed the command, or 0 if it rejected
2332        the command because a value was out of range. On a 0, on_refusal()
2333        is called before the error is raised: the device resets a value it
2334        refuses, so callers use it to read the value back into the local copy.
2335        refusal_message replaces the error's usual message, for a command
2336        refused for another reason. refusal_messages maps other replies to
2337        their own message, e.g. op 90's 2.
2338        """
2339        try:
2340            acknowledgement = self._read_serial(1, "uint8")
2341        except PulsePalError as exc:
2342            raise PulsePalError(
2343                f"Pulse Pal did not confirm {context}: no reply arrived within {self.port.timeout} s. "
2344                f"{_common.NO_REPLY_HINT}"
2345            ) from exc
2346        if acknowledgement != 1:
2347            refusal = PulsePalError(
2348                (refusal_messages or {}).get(acknowledgement) or
2349                refusal_message or
2350                f"Pulse Pal rejected the command sent by {context}. "
2351                "This usually means that a channel number, parameter code or "
2352                "value was out of range for the connected device."
2353            )
2354            if on_refusal is not None:
2355                try:
2356                    on_refusal()
2357                except PulsePalError as exc:
2358                    raise refusal from exc
2359            raise refusal
2360
2361    def _pack_values(self, values, datatype):
2362        """Pack scalar, list/tuple, or NumPy array values into bytes."""
2363        fmt = self._STRUCT_FORMATS[datatype]
2364        values_list = self._as_list(values)
2365        min_value, max_value = self._TYPE_RANGES[datatype]
2366        normalized = []
2367        for value in values_list:
2368            value = int(value)
2369            if not min_value <= value <= max_value:
2370                raise PulsePalError(
2371                    f"Value {value} is out of range for {datatype} "
2372                    f"({min_value} to {max_value})."
2373                )
2374            normalized.append(value)
2375        return struct.pack(f"{self._ENDIANNESS}{len(normalized)}{fmt}", *normalized)
2376
2377    @staticmethod
2378    def _as_list(values):
2379        """Return values as a flat list, wrapping scalars in one."""
2380        if isinstance(values, np.ndarray):
2381            return values.ravel().tolist()
2382        if isinstance(values, (bytes, bytearray, str)):
2383            return [values]
2384        if isinstance(values, numbers.Number):
2385            return [values]
2386        try:
2387            return list(values)
2388        except TypeError:
2389            return [values]
2390
2391    def _volts_to_bits(self, value, name="voltage"):
2392        """Convert -10 V to +10 V to the corresponding DAC code.
2393
2394        Rounds to the nearest code, halves to even (round()), as the MATLAB and C++ classes do.
2395        Raises PulsePalError for a voltage outside [-10, 10] or not a number: clamping it would
2396        play a different voltage.
2397        """
2398        try:
2399            volts = float(value)
2400        except (TypeError, ValueError):
2401            volts = float("nan")
2402        if isinstance(value, (bool, np.bool_, str)) or not -10 <= volts <= 10:  # Also refuses NaN
2403            raise PulsePalError(f"{name} must be in [-10, 10] V. Received {value!r}.")
2404        return int(round((volts + 10) / 20 * self._DAC_BITMAX))
2405
2406    def _bits_to_volts(self, value):
2407        """Convert a DAC code to volts, snapping to a clean value within 1 LSB."""
2408        raw_volts = (float(value) / self._DAC_BITMAX * 20) - 10
2409        lsb_volts = 20.0 / self._DAC_BITMAX
2410        # The nearest 3 decimal number (e.g. 5.000, 4.255), if the code is within 1 LSB of it
2411        clean_volts = round(raw_volts, 3)
2412        if abs(raw_volts - clean_volts) <= lsb_volts:
2413            return clean_volts
2414        return round(raw_volts, 4)
2415
2416    def _seconds_to_cycles(self, value, name="time"):
2417        """Convert seconds to the corresponding refresh-cycle count.
2418
2419        Rounds to the nearest cycle, halves to even (round()), as the MATLAB and C++ classes do:
2420        125 us, 2.5 cycles, is 2 cycles in all three. Raises PulsePalError for a time that is
2421        negative, not a number, or longer than DeviceInfo.max_time.
2422        """
2423        try:
2424            seconds = float(value)
2425        except (TypeError, ValueError):
2426            seconds = float("nan")
2427        if isinstance(value, (bool, np.bool_, str)) or not (math.isfinite(seconds) and seconds >= 0):
2428            raise PulsePalError(f"{name} must be a time of 0 s or more. Received {value!r}.")
2429        cycles = int(round(seconds * float(self.info.cycle_frequency)))
2430        if cycles > self._max_time_cycles():
2431            raise PulsePalError(
2432                f"{name} must be at most {self.info.max_time} s, the longest time the device's screen "
2433                f"shows. Received {value!r}."
2434            )
2435        return cycles
2436
2437    def _max_time_cycles(self):
2438        """DeviceInfo.max_time in timer cycles: 999999990 on a 10 us timer, 199999998 on a 50 us timer."""
2439        return int(round(self.info.max_time * float(self.info.cycle_frequency)))
2440
2441    def _custom_time_cycles(self, value, name):
2442        """Convert a custom pulse time or sampling period to timer cycles.
2443
2444        It must be a whole number of DeviceInfo.min_pulse_width_us, to the nearest microsecond,
2445        as in the MATLAB class. A time between two steps is refused, not rounded
2446        as the time parameters are, so that a train plays as it was written.
2447        """
2448        self._seconds_to_cycles(value, name)  # Checks that it is a time the device can play
2449        microseconds = int(round(float(value) * 1e6))
2450        step_us = int(self.info.min_pulse_width_us)
2451        if microseconds % step_us:
2452            raise PulsePalError(
2453                f"{name} must be multiples of {step_us} us ({step_us / 1e6:g} s). Received {value!r}."
2454            )
2455        return microseconds // int(self.info.cycle_period_us)
2456
2457    def _cycles_to_seconds(self, value):
2458        """Convert hardware timer cycle counts to seconds."""
2459        return float(value) / float(self.info.cycle_frequency)

A class to control a Pulse Pal device on a USB serial port.

Creating an instance opens the serial port, exchanges a handshake with the device, verifies that its firmware is supported, reads the device properties into PulsePalDevice.info, and programs the device with the default parameters (see PulsePalDevice.set_default_params).

from pulsepal import PulsePalDevice

P = PulsePalDevice("COM3")
P.phase1_voltage[1] = 5
P.trigger(1)
P.close()

Here, replace "COM3" with Pulse Pal's USB serial port name. To view a list of available ports, use PulsePalDevice.serialportlist(). Pulse Pal's port may not be visible if it is connected to another instance of PulsePalDevice or an external application. Use PulsePalDevice.serialportlist("all") to view all ports. If you see multiple available ports, disconnect Pulse Pal's USB plug and run serialportlist() again. Notice which port disappears from the list.

PulsePalDevice is also a context manager, which closes the connection on exit even if an error is raised:

with PulsePalDevice("COM3") as P:
    P.trigger(1)

The attributes below named after Pulse Pal parameters are lists indexed by channel number, with index 0 unused (see "Parameters" above). print(P) shows them all, and PulsePalDevice.export_params returns them as a dict.

PulsePalDevice(port_name=None, *, serial_number=None, timeout=10)
672    def __init__(self, port_name=None, *, serial_number=None, timeout=10):
673        """Open a connection to a Pulse Pal device.
674
675        Opens the serial port, exchanges the handshake, verifies the
676        firmware version, reads the device properties into
677        `PulsePalDevice.info`, and programs the device with the default
678        parameters.
679
680        ```python
681        P = PulsePalDevice("COM3")
682        P = PulsePalDevice(serial_number="20345420")  # Wherever it is plugged in
683        ```
684
685        Args:
686            port_name: USB serial port for the Pulse Pal device, such as
687                `COM3` on Windows or `/dev/ttyACM0` on Linux.
688            serial_number: Instead of `port_name`, the device's USB serial
689                number (`DeviceInfo.serial_number`), which finds its port.
690                Pulse Pal 3 only: Pulse Pal 2 has none.
691            timeout: Serial read timeout, in seconds.
692
693        Firmware newer than this module knows (`v22`) is used with a
694        warning: new firmware only adds commands, so everything here still
695        works with it. Update the package to use what is new.
696
697        Raises:
698            PulsePalError: If the device does not return the expected
699                handshake (for example, it runs Wave Pal or Synth Pal
700                firmware), or its firmware is older than v21, or no port
701                has the serial number given. The port is closed again
702                before any error is raised.
703            serial.SerialException: If the serial port cannot be opened,
704                e.g. because another program has it open (on Linux and
705                macOS, another session of these classes, which lock it).
706        """
707        self._closed = True
708        self._gui = None
709        self._auto_sync = True
710        self.info = DeviceInfo()
711        self._create_settings()
712        port_name = _common.port_name_from(port_name, serial_number, "PulsePalDevice")
713        self.port = serial.Serial(
714            port_name,
715            self._BAUD_RATE,
716            timeout=timeout,
717            rtscts=True,
718            # Windows opens a port for one program only. Linux and macOS let a second program open it too, and two
719            # sessions' bytes would then interleave; exclusive locks it (flock), so a second session that also locks
720            # it, such as another of these classes, gets an error instead
721            exclusive=True,
722        )
723        self._closed = False
724        try:
725            self._start_session(port_name)
726        except BaseException:
727            # Otherwise the port stays open until the object is garbage
728            # collected, and a second attempt, or WavePalDevice, cannot open
729            # it. The device is in an unknown state, so it is not sent the
730            # disconnect op.
731            self._close(send_disconnect=False)
732            raise

Open a connection to a Pulse Pal device.

Opens the serial port, exchanges the handshake, verifies the firmware version, reads the device properties into PulsePalDevice.info, and programs the device with the default parameters.

P = PulsePalDevice("COM3")
P = PulsePalDevice(serial_number="20345420")  # Wherever it is plugged in
Arguments:
  • port_name: USB serial port for the Pulse Pal device, such as COM3 on Windows or /dev/ttyACM0 on Linux.
  • serial_number: Instead of port_name, the device's USB serial number (DeviceInfo.serial_number), which finds its port. Pulse Pal 3 only: Pulse Pal 2 has none.
  • timeout: Serial read timeout, in seconds.

Firmware newer than this module knows (v22) is used with a warning: new firmware only adds commands, so everything here still works with it. Update the package to use what is new.

Raises:
  • PulsePalError: If the device does not return the expected handshake (for example, it runs Wave Pal or Synth Pal firmware), or its firmware is older than v21, or no port has the serial number given. The port is closed again before any error is raised.
  • serial.SerialException: If the serial port cannot be opened, e.g. because another program has it open (on Linux and macOS, another session of these classes, which lock it).
port: serial.serialposix.Serial

The open serial.Serial port connected to the device.

info: DeviceInfo

Properties of the connected device. See DeviceInfo.

is_biphasic
390    def get(self):
391        return getattr(self, "_" + name)
phase1_voltage
390    def get(self):
391        return getattr(self, "_" + name)
phase2_voltage
390    def get(self):
391        return getattr(self, "_" + name)
resting_voltage
390    def get(self):
391        return getattr(self, "_" + name)
phase1_duration
390    def get(self):
391        return getattr(self, "_" + name)
inter_phase_interval
390    def get(self):
391        return getattr(self, "_" + name)
phase2_duration
390    def get(self):
391        return getattr(self, "_" + name)
inter_pulse_interval
390    def get(self):
391        return getattr(self, "_" + name)
burst_duration
390    def get(self):
391        return getattr(self, "_" + name)
inter_burst_interval
390    def get(self):
391        return getattr(self, "_" + name)
pulse_train_duration
390    def get(self):
391        return getattr(self, "_" + name)
pulse_train_delay
390    def get(self):
391        return getattr(self, "_" + name)
custom_train_id
390    def get(self):
391        return getattr(self, "_" + name)
custom_train_target
390    def get(self):
391        return getattr(self, "_" + name)
custom_train_loop
390    def get(self):
391        return getattr(self, "_" + name)
continuous_loop
390    def get(self):
391        return getattr(self, "_" + name)
trigger_mode
390    def get(self):
391        return getattr(self, "_" + name)
@staticmethod
def serialportlist(ports_to_list='available'):
839    @staticmethod
840    def serialportlist(ports_to_list="available"):
841        """Return the names of the USB serial ports on this computer.
842
843        Called on the class, without connecting to a device, to find the
844        port name to pass to `PulsePalDevice`:
845
846        ```python
847        from pulsepal import PulsePalDevice
848
849        ports = PulsePalDevice.serialportlist()
850        P = PulsePalDevice(ports[0])
851        ```
852
853        Args:
854            ports_to_list: `available` to list only the ports that are
855                not already in use, or `all` to list every USB serial
856                port. Not case sensitive.
857
858        Returns:
859            Sorted list of port names, such as `["COM3", "COM7"]` on
860            Windows or `["/dev/ttyACM0"]` on Linux.
861
862        Raises:
863            PulsePalError: If `ports_to_list` is not `available` or
864                `all`.
865        """
866        return _common.serialportlist(ports_to_list)

Return the names of the USB serial ports on this computer.

Called on the class, without connecting to a device, to find the port name to pass to PulsePalDevice:

from pulsepal import PulsePalDevice

ports = PulsePalDevice.serialportlist()
P = PulsePalDevice(ports[0])
Arguments:
  • ports_to_list: available to list only the ports that are not already in use, or all to list every USB serial port. Not case sensitive.
Returns:

Sorted list of port names, such as ["COM3", "COM7"] on Windows or ["/dev/ttyACM0"] on Linux.

Raises:
  • PulsePalError: If ports_to_list is not available or all.
auto_sync
872    @property
873    def auto_sync(self):
874        """Whether assigning a parameter programs the device at once.
875
876        `True` (the default): each assignment, such as
877        `P.phase1_voltage[1] = 5`, programs the device at once, also while
878        a trigger channel is in param sync mode. It sends the channels
879        whose value it changes, and nothing for a channel that already
880        holds the value assigned: the other channels keep what the device
881        holds, e.g. values set with its joystick (read them with
882        `PulsePalDevice.sync_from_device`).
883
884        `False`: assignments change only this object's copy of the
885        parameters, checking each value, and
886        `PulsePalDevice.sync_to_device` sends all of them in one command.
887        Turning it back on does not send changes made meanwhile, so it
888        raises `pulsepal.PulsePalError` while there are any: call
889        `PulsePalDevice.sync_to_device` first to send them, or
890        `PulsePalDevice.sync_from_device` to discard them. A
891        `PulsePalDevice.batch` block does it all for you. `close()` warns of
892        changes never sent.
893        """
894        return self._auto_sync

Whether assigning a parameter programs the device at once.

True (the default): each assignment, such as P.phase1_voltage[1] = 5, programs the device at once, also while a trigger channel is in param sync mode. It sends the channels whose value it changes, and nothing for a channel that already holds the value assigned: the other channels keep what the device holds, e.g. values set with its joystick (read them with PulsePalDevice.sync_from_device).

False: assignments change only this object's copy of the parameters, checking each value, and PulsePalDevice.sync_to_device sends all of them in one command. Turning it back on does not send changes made meanwhile, so it raises pulsepal.PulsePalError while there are any: call PulsePalDevice.sync_to_device first to send them, or PulsePalDevice.sync_from_device to discard them. A PulsePalDevice.batch block does it all for you. close() warns of changes never sent.

def batch(self):
910    def batch(self):
911        """Change several parameters, and send them in one command.
912
913        Returns a context manager. In its block, assignments change only
914        this object's copy of the parameters (as with
915        `PulsePalDevice.auto_sync` off), and when the block ends,
916        `PulsePalDevice.sync_to_device` sends all of them at once. If the
917        block raises an error, nothing is sent, and the parameters go
918        back to what they were.
919
920        ```python
921        with P.batch():
922            P.phase1_voltage = [5, 5, 2.5, 2.5]
923            P.phase1_duration[3] = 0.002
924        ```
925
926        In param sync mode, the device stores the parameters for the next
927        rising edge on the param sync channel (see
928        `PulsePalDevice.trigger_mode`).
929        """
930        return _common.batch(self)

Change several parameters, and send them in one command.

Returns a context manager. In its block, assignments change only this object's copy of the parameters (as with PulsePalDevice.auto_sync off), and when the block ends, PulsePalDevice.sync_to_device sends all of them at once. If the block raises an error, nothing is sent, and the parameters go back to what they were.

with P.batch():
    P.phase1_voltage = [5, 5, 2.5, 2.5]
    P.phase1_duration[3] = 0.002

In param sync mode, the device stores the parameters for the next rising edge on the param sync channel (see PulsePalDevice.trigger_mode).

def sync_to_device(self):
932    def sync_to_device(self):
933        """Program the device with this object's copy of all parameters.
934
935        Sends every output and trigger parameter to the device in a single
936        command. Use it after assignments made with
937        `PulsePalDevice.auto_sync` off; with it on, they have already
938        reached the device.
939
940        ```python
941        P.auto_sync = False
942        P.phase1_voltage[1:5] = [5] * 4
943        P.sync_to_device()
944        ```
945
946        On Pulse Pal 3, if either trigger channel is in param sync mode
947        (`PulsePalDevice.trigger_mode` `"Param Sync"`), the device stores
948        the parameters instead of programming them, and loads them on the
949        next rising edge of that channel. The device still checks every
950        value. This is the only method whose effect is deferred that way.
951
952        Raises:
953            PulsePalError: If a value is out of range for its parameter
954                (nothing is sent), or the device does not acknowledge the
955                command.
956        """
957        self._check_sync()
958        self._send_sync()

Program the device with this object's copy of all parameters.

Sends every output and trigger parameter to the device in a single command. Use it after assignments made with PulsePalDevice.auto_sync off; with it on, they have already reached the device.

P.auto_sync = False
P.phase1_voltage[1:5] = [5] * 4
P.sync_to_device()

On Pulse Pal 3, if either trigger channel is in param sync mode (PulsePalDevice.trigger_mode "Param Sync"), the device stores the parameters instead of programming them, and loads them on the next rising edge of that channel. The device still checks every value. This is the only method whose effect is deferred that way.

Raises:
  • PulsePalError: If a value is out of range for its parameter (nothing is sent), or the device does not acknowledge the command.
def sync_from_device(self):
960    def sync_from_device(self):
961        """Read all parameters from the device into this object's copy.
962
963        Overwrites the parameter lists with the program currently on the
964        device, e.g. after it has been reprogrammed from its thumb
965        joystick. `PulsePalDevice.continuous_loop` is left as it is: the
966        device does not report it. Changes made with
967        `PulsePalDevice.auto_sync` off and not yet sent are discarded, but
968        for `PulsePalDevice.continuous_loop`.
969
970        Requires firmware v22 or newer.
971
972        Raises:
973            PulsePalError: If the connected firmware is older than v22,
974                or the device does not return the full parameter set.
975        """
976        self._require_firmware(22, "sync_from_device()")
977        for name, values in self._read_device_params().items():
978            getattr(self, name)._store(values)
979        self._unsent = self._unsent & {"continuous_loop"}  # Not read: a change to it is still unsent

Read all parameters from the device into this object's copy.

Overwrites the parameter lists with the program currently on the device, e.g. after it has been reprogrammed from its thumb joystick. PulsePalDevice.continuous_loop is left as it is: the device does not report it. Changes made with PulsePalDevice.auto_sync off and not yet sent are discarded, but for PulsePalDevice.continuous_loop.

Requires firmware v22 or newer.

Raises:
  • PulsePalError: If the connected firmware is older than v22, or the device does not return the full parameter set.
def set_default_params(self):
 981    def set_default_params(self):
 982        """Program the device with the default parameters.
 983
 984        The defaults are monophasic +5 V pulses of 0.1 ms, 1 ms apart
 985        (about 909 a second), for 1 second, resting at 0 V, on all four
 986        output channels; for biphasic pulses, a phase 2 of -5 V and 0.1 ms
 987        after 0.1 ms at rest. No output channel is linked to a trigger
 988        channel, so a TTL starts nothing until a script links it, and both
 989        trigger channels are in normal mode. They are the device's own
 990        defaults, which it also loads at startup, after a comm failure
 991        and after formatting its microSD card. They are sent at once,
 992        also while `PulsePalDevice.auto_sync` is off. The constructor
 993        calls it.
 994        """
 995        for name, value in _DEFAULT_OUTPUT_VALUES.items():
 996            getattr(self, name)._store([value] * 4)
 997        self._trigger_mode._store(["Normal"] * 2)
 998        if self._has_param_sync():
 999            # A device left in param sync mode would store the sync below instead of running it,
1000            # leaving the device on its old program until a TTL arrived. A trigger mode sent on
1001            # its own is not deferred that way, so both trigger channels leave param sync mode
1002            # first. See PulsePalDevice.trigger_mode.
1003            self._send_trigger_modes(["Normal"] * 2, "set_default_params()")
1004        self._send_sync()

Program the device with the default parameters.

The defaults are monophasic +5 V pulses of 0.1 ms, 1 ms apart (about 909 a second), for 1 second, resting at 0 V, on all four output channels; for biphasic pulses, a phase 2 of -5 V and 0.1 ms after 0.1 ms at rest. No output channel is linked to a trigger channel, so a TTL starts nothing until a script links it, and both trigger channels are in normal mode. They are the device's own defaults, which it also loads at startup, after a comm failure and after formatting its microSD card. They are sent at once, also while PulsePalDevice.auto_sync is off. The constructor calls it.

def export_params(self):
1006    def export_params(self):
1007        """Return every parameter, as a dict of plain lists.
1008
1009        Keyed by parameter name (`DeviceInfo.output_parameter_names`, then
1010        `"trigger_mode"`), with one value per channel and no unused index
1011        0. It holds only numbers, booleans and names, so it can be saved
1012        with `json` and logged with your data, to record exactly what the
1013        device played. `PulsePalDevice.import_params` programs it again.
1014
1015        ```python
1016        import json
1017        with open("trial_params.json", "w") as f:
1018            json.dump(P.export_params(), f)
1019        ```
1020        """
1021        names = [*self.info.output_parameter_names, "trigger_mode"]
1022        return {name: list(getattr(self, name))[1:] for name in names}

Return every parameter, as a dict of plain lists.

Keyed by parameter name (DeviceInfo.output_parameter_names, then "trigger_mode"), with one value per channel and no unused index

  1. It holds only numbers, booleans and names, so it can be saved with json and logged with your data, to record exactly what the device played. PulsePalDevice.import_params programs it again.
import json
with open("trial_params.json", "w") as f:
    json.dump(P.export_params(), f)
def import_params(self, params):
1024    def import_params(self, params):
1025        """Program the device with parameters exported by `PulsePalDevice.export_params`.
1026
1027        All of them are checked first, and then sent in one command, as
1028        at the end of a `PulsePalDevice.batch` block: in param sync mode,
1029        the device stores them for the next sync edge. Parameters missing
1030        from `params` keep their values. A name that is not a parameter
1031        is skipped with a warning, so that parameters exported by a newer
1032        version of this package, which may have more, can still be
1033        imported; if none is, an error is raised.
1034
1035        A whole program file, as the GUIs save it, is imported too: its
1036        parameters, not its custom trains (a warning says so, if it has
1037        any).
1038
1039        ```python
1040        with open("MyProgram.json") as f:
1041            P.import_params(json.load(f))
1042        ```
1043
1044        Args:
1045            params: A dict of parameter name to one value per channel (a
1046                list, tuple or NumPy array), as `export_params` returns,
1047                or a program file's contents. The MATLAB class's names
1048                (`phase1Voltage`) are accepted too, so that the parameters
1049                its `exportParams()` returns, saved with `jsonencode`, can
1050                be imported.
1051
1052        Raises:
1053            PulsePalError: If a value is invalid, or no name in `params` is
1054                a parameter. Nothing is sent, and the parameters keep the
1055                values they had.
1056        """
1057        params = _params_to_import(params)
1058        with self.batch():
1059            for name, values in params.items():
1060                setattr(self, name, values)

Program the device with parameters exported by PulsePalDevice.export_params.

All of them are checked first, and then sent in one command, as at the end of a PulsePalDevice.batch block: in param sync mode, the device stores them for the next sync edge. Parameters missing from params keep their values. A name that is not a parameter is skipped with a warning, so that parameters exported by a newer version of this package, which may have more, can still be imported; if none is, an error is raised.

A whole program file, as the GUIs save it, is imported too: its parameters, not its custom trains (a warning says so, if it has any).

with open("MyProgram.json") as f:
    P.import_params(json.load(f))
Arguments:
  • params: A dict of parameter name to one value per channel (a list, tuple or NumPy array), as export_params returns, or a program file's contents. The MATLAB class's names (phase1Voltage) are accepted too, so that the parameters its exportParams() returns, saved with jsonencode, can be imported.
Raises:
  • PulsePalError: If a value is invalid, or no name in params is a parameter. Nothing is sent, and the parameters keep the values they had.
def set_fixed_voltage(self, channels, voltage):
1062    def set_fixed_voltage(self, channels, voltage):
1063        """Set output channels to a fixed voltage.
1064
1065        Each channel holds the voltage until it is set again or until a
1066        pulse train is triggered on it.
1067
1068        ```python
1069        P.set_fixed_voltage(4, 2.5)
1070        P.set_fixed_voltage([1, 3], -1)
1071        ```
1072
1073        Args:
1074            channels: Output channel number, 1-4, or several as a list,
1075                tuple or NumPy array.
1076            voltage: Voltage to set on each of them, in volts [-10, 10].
1077
1078        Raises:
1079            PulsePalError: If a channel number is not 1-4, the voltage is
1080                outside [-10, 10] (nothing is sent), or the device does not
1081                acknowledge the command.
1082        """
1083        channels = _common.channel_numbers(channels)
1084        voltage_bits = self._volts_to_bits(voltage, "voltage")
1085        for channel in channels:
1086            self._write_serial(
1087                (self._OP_MENU_BYTE, 79, channel),
1088                "uint8",
1089                voltage_bits,
1090                "uint16",
1091            )
1092            self._read_ack("set_fixed_voltage()")

Set output channels to a fixed voltage.

Each channel holds the voltage until it is set again or until a pulse train is triggered on it.

P.set_fixed_voltage(4, 2.5)
P.set_fixed_voltage([1, 3], -1)
Arguments:
  • channels: Output channel number, 1-4, or several as a list, tuple or NumPy array.
  • voltage: Voltage to set on each of them, in volts [-10, 10].
Raises:
  • PulsePalError: If a channel number is not 1-4, the voltage is outside [-10, 10] (nothing is sent), or the device does not acknowledge the command.
def set_calibration(self, channel, voltage_offset):
1094    def set_calibration(self, channel, voltage_offset):
1095        """Calibrate the zero code of an output channel.
1096
1097        The offset is added to every voltage the channel produces, to
1098        correct for DAC offset error. It is stored in the device's
1099        EEPROM and reloaded on boot, so it only needs to be set once.
1100
1101        Requires Pulse Pal hardware v3 or newer.
1102
1103        Args:
1104            channel: Output channel number, 1-4.
1105            voltage_offset: Offset to apply, in volts [-0.1, 0.1].
1106
1107        Raises:
1108            PulsePalError: If the connected hardware is older than v3,
1109                `channel` is not 1-4, `voltage_offset` is outside
1110                [-0.1, 0.1], or the device does not acknowledge the
1111                command.
1112        """
1113        if self.info.hardware_version < 3:
1114            raise PulsePalError(
1115                "set_calibration() requires hardware v3 or newer."
1116            )
1117        if not (isinstance(channel, numbers.Integral) and channel in (1, 2, 3, 4)):
1118            raise PulsePalError("channel must be 1, 2, 3 or 4")
1119        if not (isinstance(voltage_offset, numbers.Real) and -0.1 <= voltage_offset <= 0.1):  # Also refuses NaN
1120            raise PulsePalError(
1121                "voltage_offset for zero code calibration must be in range "
1122                "[-0.1, 0.1]"
1123            )
1124        # To the nearest DAC code, halfway values to the even one, as the MATLAB class rounds it
1125        voltage_bits = int(round(voltage_offset * (1 / (20 / 65536))))
1126        self._write_serial(
1127            (self._OP_MENU_BYTE, 96, channel - 1),
1128            "uint8",
1129            voltage_bits,
1130            "int16",
1131        )
1132        self._read_ack("set_calibration()")

Calibrate the zero code of an output channel.

The offset is added to every voltage the channel produces, to correct for DAC offset error. It is stored in the device's EEPROM and reloaded on boot, so it only needs to be set once.

Requires Pulse Pal hardware v3 or newer.

Arguments:
  • channel: Output channel number, 1-4.
  • voltage_offset: Offset to apply, in volts [-0.1, 0.1].
Raises:
  • PulsePalError: If the connected hardware is older than v3, channel is not 1-4, voltage_offset is outside [-0.1, 0.1], or the device does not acknowledge the command.
def set_screen_saver(self, enabled, timeout=1800):
1134    def set_screen_saver(self, enabled, timeout=1800):
1135        """Switch the device's screen saver on or off, and set its timeout.
1136
1137        With the screen saver on, the device dims its screen once it has
1138        been left alone for `timeout` seconds: no command from the
1139        computer, no rising edge on a trigger channel, and no joystick
1140        click or push. The next of these brings the screen back. Both
1141        settings are stored in the device's EEPROM and kept through power
1142        cycles; the screen saver can also be switched on and off from the
1143        device's joystick menu. A new device has it on, with 1800 s.
1144
1145        The device saves the settings once no channel is playing. Saving
1146        pauses its timer, usually for about 20 us but, once in about 2000
1147        changes, for tens of milliseconds, which would delay a trigger.
1148        Change the settings before an experiment rather than during one.
1149
1150        Requires firmware v22 or newer. Only Pulse Pal 3 has a screen
1151        saver: Pulse Pal 2 accepts `enabled=False` only.
1152
1153        ```python
1154        P.set_screen_saver(True, 300)  # dim after 5 minutes
1155        P.set_screen_saver(False)
1156        ```
1157
1158        Args:
1159            enabled: True (or 1) to switch the screen saver on, False (or
1160                0) to switch it off.
1161            timeout: Seconds without activity before the screen dims, a
1162                whole number from 1 to 65535. It is sent with every call,
1163                so leaving it out sets 1800 s.
1164
1165        Raises:
1166            PulsePalError: If the firmware is older than v22, the
1167                screen saver is switched on with hardware older than v3,
1168                a value is out of range, or the device does not
1169                acknowledge the command.
1170        """
1171        self._require_firmware(22, "set_screen_saver()")
1172        enabled = to_bool(enabled, "enabled")
1173        if not (
1174            isinstance(timeout, numbers.Real)
1175            and not isinstance(timeout, bool)
1176            and math.isfinite(timeout)
1177            and timeout == int(timeout)
1178            and 1 <= timeout <= 65535
1179        ):
1180            raise PulsePalError(
1181                "timeout must be a whole number of seconds from 1 to 65535"
1182            )
1183        if enabled and (self.info.hardware_version or 2) < 3:
1184            raise PulsePalError(
1185                "The screen saver requires hardware v3 or newer: Pulse Pal 2 "
1186                "accepts set_screen_saver(False) only."
1187            )
1188        self._write_serial(
1189            (self._OP_MENU_BYTE, 99, int(enabled)),
1190            "uint8",
1191            int(timeout),
1192            "uint16",
1193        )
1194        self._read_ack("set_screen_saver()")

Switch the device's screen saver on or off, and set its timeout.

With the screen saver on, the device dims its screen once it has been left alone for timeout seconds: no command from the computer, no rising edge on a trigger channel, and no joystick click or push. The next of these brings the screen back. Both settings are stored in the device's EEPROM and kept through power cycles; the screen saver can also be switched on and off from the device's joystick menu. A new device has it on, with 1800 s.

The device saves the settings once no channel is playing. Saving pauses its timer, usually for about 20 us but, once in about 2000 changes, for tens of milliseconds, which would delay a trigger. Change the settings before an experiment rather than during one.

Requires firmware v22 or newer. Only Pulse Pal 3 has a screen saver: Pulse Pal 2 accepts enabled=False only.

P.set_screen_saver(True, 300)  # dim after 5 minutes
P.set_screen_saver(False)
Arguments:
  • enabled: True (or 1) to switch the screen saver on, False (or 0) to switch it off.
  • timeout: Seconds without activity before the screen dims, a whole number from 1 to 65535. It is sent with every call, so leaving it out sets 1800 s.
Raises:
  • PulsePalError: If the firmware is older than v22, the screen saver is switched on with hardware older than v3, a value is out of range, or the device does not acknowledge the command.
def send_custom_pulse_train(self, custom_train_id, pulse_times, voltages):
1200    def send_custom_pulse_train(
1201        self,
1202        custom_train_id,
1203        pulse_times,
1204        voltages,
1205    ):
1206        """Load a custom pulse train onto the device.
1207
1208        A custom pulse train is an arbitrary list of pulse onset times
1209        and voltages, replacing the parametric pulse voltage and onset
1210        timing. Set `PulsePalDevice.custom_train_id` on an output channel
1211        to play the train there. Each pulse takes the channel's own phase
1212        durations; a biphasic pulse's second phase is its voltage with the
1213        sign reversed. A biphasic pulse always plays whole, and a pulse
1214        whose time comes while it plays is dropped, so that every pulse
1215        played is on time.
1216
1217        ```python
1218        P.send_custom_pulse_train(
1219            2, [0, 0.2, 0.5, 1], [8, 4, -3.5, -10]
1220        )
1221        P.custom_train_id[1] = 2
1222        ```
1223
1224        Loading a train stops the output channels playing it, and their
1225        next trigger plays the new train. On Pulse Pal 3, while a trigger
1226        channel is in param sync mode (see `PulsePalDevice.trigger_mode`),
1227        the device stores the train instead, as it stores the parameters
1228        `PulsePalDevice.sync_to_device` sends: channels go on playing the
1229        old train, and the next rising edge on the param sync channel
1230        makes the new one current. A channel playing the old train at that
1231        edge finishes it, and plays the new one from its next trigger. So
1232        the next trial's custom trains can be loaded during the current
1233        trial. Leaving param sync mode makes a stored train current at
1234        once.
1235
1236        Args:
1237            custom_train_id: Custom train to load, from 1 to
1238                `DeviceInfo.n_custom_pulse_trains` (2 on Pulse Pal 2,
1239                4 on Pulse Pal 3).
1240            pulse_times: Pulse onset times, in seconds, relative to the
1241                start of the train, increasing. Each is a multiple of
1242                `DeviceInfo.min_pulse_width_us` (10 us on Pulse Pal 3,
1243                100 us on Pulse Pal 2), from 0 to
1244                `MAX_TIME`. Accepts a list, tuple or 1-D NumPy array.
1245            voltages: Voltage of each pulse, in volts [-10, 10]. Must be
1246                the same length as `pulse_times`.
1247
1248        Raises:
1249            PulsePalError: If `custom_train_id` is out of range,
1250                `pulse_times` or `voltages` is not one-dimensional (a 2-D
1251                array is refused, not flattened), they differ in length,
1252                there are no pulses, or more than
1253                `DeviceInfo.max_custom_pulses`, a pulse time is not a
1254                multiple of `DeviceInfo.min_pulse_width_us`, is out of
1255                range or is not later than the one before it, or the
1256                device does not acknowledge the command.
1257        """
1258        pulse_times_cycles = self._custom_times_to_cycles(pulse_times, "pulse_times")
1259        pulse_voltage_bits = self._volts_array_to_bits(voltages, "voltages")
1260        if len(pulse_times_cycles) != len(pulse_voltage_bits):
1261            raise PulsePalError(
1262                "pulse_times and voltages must be the same length."
1263            )
1264        self._send_custom_train(
1265            custom_train_id,
1266            pulse_times_cycles,
1267            pulse_voltage_bits,
1268            "send_custom_pulse_train()",
1269        )

Load a custom pulse train onto the device.

A custom pulse train is an arbitrary list of pulse onset times and voltages, replacing the parametric pulse voltage and onset timing. Set PulsePalDevice.custom_train_id on an output channel to play the train there. Each pulse takes the channel's own phase durations; a biphasic pulse's second phase is its voltage with the sign reversed. A biphasic pulse always plays whole, and a pulse whose time comes while it plays is dropped, so that every pulse played is on time.

P.send_custom_pulse_train(
    2, [0, 0.2, 0.5, 1], [8, 4, -3.5, -10]
)
P.custom_train_id[1] = 2

Loading a train stops the output channels playing it, and their next trigger plays the new train. On Pulse Pal 3, while a trigger channel is in param sync mode (see PulsePalDevice.trigger_mode), the device stores the train instead, as it stores the parameters PulsePalDevice.sync_to_device sends: channels go on playing the old train, and the next rising edge on the param sync channel makes the new one current. A channel playing the old train at that edge finishes it, and plays the new one from its next trigger. So the next trial's custom trains can be loaded during the current trial. Leaving param sync mode makes a stored train current at once.

Arguments:
  • custom_train_id: Custom train to load, from 1 to DeviceInfo.n_custom_pulse_trains (2 on Pulse Pal 2, 4 on Pulse Pal 3).
  • pulse_times: Pulse onset times, in seconds, relative to the start of the train, increasing. Each is a multiple of DeviceInfo.min_pulse_width_us (10 us on Pulse Pal 3, 100 us on Pulse Pal 2), from 0 to MAX_TIME. Accepts a list, tuple or 1-D NumPy array.
  • voltages: Voltage of each pulse, in volts [-10, 10]. Must be the same length as pulse_times.
Raises:
  • PulsePalError: If custom_train_id is out of range, pulse_times or voltages is not one-dimensional (a 2-D array is refused, not flattened), they differ in length, there are no pulses, or more than DeviceInfo.max_custom_pulses, a pulse time is not a multiple of DeviceInfo.min_pulse_width_us, is out of range or is not later than the one before it, or the device does not acknowledge the command.
def send_custom_waveform(self, custom_train_id, sampling_period, voltages):
1271    def send_custom_waveform(
1272        self,
1273        custom_train_id,
1274        sampling_period,
1275        voltages,
1276    ):
1277        """Load an arbitrary waveform onto the device.
1278
1279        A convenience shorthand for
1280        `PulsePalDevice.send_custom_pulse_train` with evenly spaced,
1281        adjoining pulses, so that `voltages` is played as a waveform
1282        sampled every `sampling_period` seconds. It is loaded as a custom
1283        train is: see `PulsePalDevice.send_custom_pulse_train` for what
1284        happens to channels playing it, and in param sync mode.
1285
1286        Set the channel's `PulsePalDevice.phase1_duration` to
1287        `sampling_period` as well, so that each sample is held for the
1288        sampling period.
1289
1290        ```python
1291        import math
1292
1293        samples = [math.sin(i / 10.0) * 10 for i in range(1000)]
1294        P.send_custom_waveform(1, 0.001, samples)   # 1 kHz
1295        P.custom_train_id[2] = 1
1296        P.phase1_duration[2] = 0.001
1297        ```
1298
1299        Args:
1300            custom_train_id: Custom train to load, from 1 to
1301                `DeviceInfo.n_custom_pulse_trains` (2 on Pulse Pal 2,
1302                4 on Pulse Pal 3).
1303            sampling_period: In seconds: a multiple of
1304                `DeviceInfo.min_pulse_width_us` (10 us on Pulse Pal 3,
1305                100 us on Pulse Pal 2). Each voltage is
1306                held for this long.
1307            voltages: Waveform samples, in volts [-10, 10].
1308                Accepts a list, tuple or 1-D NumPy array.
1309
1310        Raises:
1311            PulsePalError: If `custom_train_id` is out of range, there
1312                are no samples, or more than
1313                `DeviceInfo.max_custom_pulses`, `sampling_period` is not a
1314                positive multiple of `DeviceInfo.min_pulse_width_us`, the
1315                last sample would start after `MAX_TIME`, or the device
1316                does not acknowledge the command.
1317        """
1318        pulse_voltage_bits = self._volts_array_to_bits(voltages, "voltages")
1319        period_cycles = self._custom_time_cycles(sampling_period, "sampling_period")
1320        if period_cycles == 0:
1321            raise PulsePalError(
1322                f"sampling_period must be a positive multiple of {self.info.min_pulse_width_us:g} us. "
1323                f"Received {sampling_period!r}."
1324            )
1325        pulse_times = period_cycles * np.arange(len(pulse_voltage_bits), dtype=np.int64)
1326        self._send_custom_train(
1327            custom_train_id,
1328            pulse_times,
1329            pulse_voltage_bits,
1330            "send_custom_waveform()",
1331        )

Load an arbitrary waveform onto the device.

A convenience shorthand for PulsePalDevice.send_custom_pulse_train with evenly spaced, adjoining pulses, so that voltages is played as a waveform sampled every sampling_period seconds. It is loaded as a custom train is: see PulsePalDevice.send_custom_pulse_train for what happens to channels playing it, and in param sync mode.

Set the channel's PulsePalDevice.phase1_duration to sampling_period as well, so that each sample is held for the sampling period.

import math

samples = [math.sin(i / 10.0) * 10 for i in range(1000)]
P.send_custom_waveform(1, 0.001, samples)   # 1 kHz
P.custom_train_id[2] = 1
P.phase1_duration[2] = 0.001
Arguments:
  • custom_train_id: Custom train to load, from 1 to DeviceInfo.n_custom_pulse_trains (2 on Pulse Pal 2, 4 on Pulse Pal 3).
  • sampling_period: In seconds: a multiple of DeviceInfo.min_pulse_width_us (10 us on Pulse Pal 3, 100 us on Pulse Pal 2). Each voltage is held for this long.
  • voltages: Waveform samples, in volts [-10, 10]. Accepts a list, tuple or 1-D NumPy array.
Raises:
def trigger(self, channels):
1333    def trigger(self, channels):
1334        """Trigger output channels in software.
1335
1336        The channels start their pulse trains together, in the same timer
1337        cycle. A channel that is already playing a pulse train ignores
1338        the trigger, and `PulsePalDevice.stop` cancels a trigger that has
1339        not started its channel yet.
1340
1341        ```python
1342        P.trigger(3)          # one channel
1343        P.trigger([1, 4])     # several: a list, tuple or NumPy array
1344        ```
1345
1346        Args:
1347            channels: Output channel number, 1-4, or several as a list,
1348                tuple or NumPy array.
1349
1350        Raises:
1351            PulsePalError: If a channel number is not 1-4, or no channel
1352                is given. Nothing is triggered.
1353        """
1354        self._write_serial((self._OP_MENU_BYTE, 77, _common.channel_bits(channels)), "uint8")

Trigger output channels in software.

The channels start their pulse trains together, in the same timer cycle. A channel that is already playing a pulse train ignores the trigger, and PulsePalDevice.stop cancels a trigger that has not started its channel yet.

P.trigger(3)          # one channel
P.trigger([1, 4])     # several: a list, tuple or NumPy array
Arguments:
  • channels: Output channel number, 1-4, or several as a list, tuple or NumPy array.
Raises:
  • PulsePalError: If a channel number is not 1-4, or no channel is given. Nothing is triggered.
def stop(self, channels=None):
1356    def stop(self, channels=None):
1357        """Stop pulse trains currently playing on the device.
1358
1359        The stopped channels return to their
1360        `PulsePalDevice.resting_voltage`. A soft trigger that has not
1361        started its channel yet is cancelled too.
1362
1363        ```python
1364        P.stop()           # all output channels
1365        P.stop([1, 3, 4])  # channels 1, 3 and 4
1366        ```
1367
1368        Args:
1369            channels: Output channel number, 1-4, or several as a list,
1370                tuple or NumPy array. `None`, the default, stops all
1371                channels. Stopping some channels requires firmware v22
1372                or newer.
1373
1374        Raises:
1375            PulsePalError: If a channel number is not 1-4, or channels are
1376                given and the firmware is older than v22.
1377        """
1378        if self.info.firmware_version < 22:
1379            if channels is not None:
1380                raise PulsePalError("stop() cannot address individual channels before firmware v22")
1381            self._write_serial((self._OP_MENU_BYTE, 80), "uint8")  # Stops all channels
1382            return
1383        bits = 0x0F if channels is None else _common.channel_bits(channels)
1384        self._write_serial((self._OP_MENU_BYTE, 98, bits), "uint8")

Stop pulse trains currently playing on the device.

The stopped channels return to their PulsePalDevice.resting_voltage. A soft trigger that has not started its channel yet is cancelled too.

P.stop()           # all output channels
P.stop([1, 3, 4])  # channels 1, 3 and 4
Arguments:
  • channels: Output channel number, 1-4, or several as a list, tuple or NumPy array. None, the default, stops all channels. Stopping some channels requires firmware v22 or newer.
Raises:
  • PulsePalError: If a channel number is not 1-4, or channels are given and the firmware is older than v22.
def status(self):
1386    def status(self):
1387        """Read which channels are playing, and the counters since the last call.
1388
1389        The counters (see `DeviceStatus`) count from the previous call, or
1390        from the device's startup, and each call clears them. Calling it
1391        before and after a trial checks that the TTLs the trial sent
1392        arrived, and started the trains they should:
1393
1394        ```python
1395        P.status()                     # Clears the counters
1396        run_trial()                    # Your code: one TTL on trigger channel 1, linked to channels 1 and 2
1397        s = P.status()
1398        if s.trigger_edges[1] != 1 or s.channel_starts[1:3] != [1, 1]:
1399            print("The trial's trains did not all start")
1400        ```
1401
1402        Requires firmware v22 or newer.
1403
1404        Returns:
1405            A `DeviceStatus`.
1406
1407        Raises:
1408            PulsePalError: If the firmware is older than v22, or the device
1409                does not reply.
1410        """
1411        self._require_firmware(22, "status()")
1412        self._write_serial((self._OP_MENU_BYTE, 101), "uint8")
1413        values = struct.unpack(f"{self._ENDIANNESS}B7I", self._read_raw(self._STATUS_MESSAGE_BYTES))
1414        return DeviceStatus(
1415            playing=[ch for ch in range(1, 5) if values[0] & (1 << (ch - 1))],
1416            trigger_edges=[None, *values[1:3]],
1417            channel_starts=[None, *values[3:7]],
1418            comm_failures=values[7],
1419        )

Read which channels are playing, and the counters since the last call.

The counters (see DeviceStatus) count from the previous call, or from the device's startup, and each call clears them. Calling it before and after a trial checks that the TTLs the trial sent arrived, and started the trains they should:

P.status()                     # Clears the counters
run_trial()                    # Your code: one TTL on trigger channel 1, linked to channels 1 and 2
s = P.status()
if s.trigger_edges[1] != 1 or s.channel_starts[1:3] != [1, 1]:
    print("The trial's trains did not all start")

Requires firmware v22 or newer.

Returns:

A DeviceStatus.

Raises:
  • PulsePalError: If the firmware is older than v22, or the device does not reply.
def save_program_to_microsd(self, file_name):
1421    def save_program_to_microsd(self, file_name):
1422        """Save the parameters to the device's microSD card, as a program.
1423
1424        The program can be loaded later with
1425        `PulsePalDevice.load_program_from_microsd` or with the joystick
1426        menu's Load Program item. A file of the same name is replaced. To
1427        keep the parameters on this computer instead, see
1428        `PulsePalDevice.export_params`.
1429
1430        ```python
1431        P.save_program_to_microsd("MyProtocol.pps")
1432        ```
1433
1434        Args:
1435            file_name: At most 15 ASCII characters, ending in `.pps`.
1436
1437        Raises:
1438            PulsePalError: If the file name is invalid, or the device could
1439                not write the file to its microSD card. Pulse Pal 2 also
1440                refuses while a channel is playing: its card shares a bus with
1441                the outputs, so stop playback first.
1442        """
1443        self._settings_file_op(file_name, 1, "save_program_to_microsd()")

Save the parameters to the device's microSD card, as a program.

The program can be loaded later with PulsePalDevice.load_program_from_microsd or with the joystick menu's Load Program item. A file of the same name is replaced. To keep the parameters on this computer instead, see PulsePalDevice.export_params.

P.save_program_to_microsd("MyProtocol.pps")
Arguments:
  • file_name: At most 15 ASCII characters, ending in .pps.
Raises:
  • PulsePalError: If the file name is invalid, or the device could not write the file to its microSD card. Pulse Pal 2 also refuses while a channel is playing: its card shares a bus with the outputs, so stop playback first.
def load_program_from_microsd(self, file_name):
1445    def load_program_from_microsd(self, file_name):
1446        """Load a program from the device's microSD card.
1447
1448        The device plays the program, and the parameters are read back
1449        into this object (see `PulsePalDevice.sync_from_device`). The
1450        program's trigger modes take effect too, and it is loaded at once,
1451        also in param sync mode.
1452
1453        Args:
1454            file_name: The program's file name, ending in `.pps`, as saved
1455                by `PulsePalDevice.save_program_to_microsd` or the joystick
1456                menu.
1457
1458        Raises:
1459            PulsePalError: If the file name is invalid, or the device could
1460                not load the program: there is no such file on its microSD
1461                card, or it is not a valid Pulse Pal program; or, on Pulse
1462                Pal 2, a channel is playing (see `save_program_to_microsd`).
1463                The device then keeps its parameters, and so does this object.
1464        """
1465        self._settings_file_op(file_name, 2, "load_program_from_microsd()")

Load a program from the device's microSD card.

The device plays the program, and the parameters are read back into this object (see PulsePalDevice.sync_from_device). The program's trigger modes take effect too, and it is loaded at once, also in param sync mode.

Arguments:
Raises:
  • PulsePalError: If the file name is invalid, or the device could not load the program: there is no such file on its microSD card, or it is not a valid Pulse Pal program; or, on Pulse Pal 2, a channel is playing (see save_program_to_microsd). The device then keeps its parameters, and so does this object.
def delete_program_from_microsd(self, file_name):
1467    def delete_program_from_microsd(self, file_name):
1468        """Delete a program from the device's microSD card.
1469
1470        Args:
1471            file_name: The program's file name, ending in `.pps`.
1472
1473        Raises:
1474            PulsePalError: If the file name is invalid, or the device could
1475                not delete the file, e.g. because there is no such file, or,
1476                on Pulse Pal 2, because a channel is playing.
1477        """
1478        self._settings_file_op(file_name, 3, "delete_program_from_microsd()")

Delete a program from the device's microSD card.

Arguments:
  • file_name: The program's file name, ending in .pps.
Raises:
  • PulsePalError: If the file name is invalid, or the device could not delete the file, e.g. because there is no such file, or, on Pulse Pal 2, because a channel is playing.
def format_microsd(self, *, confirm=True, timeout=30):
1522    def format_microsd(self, *, confirm=True, timeout=30):
1523        """Format the device's microSD card.
1524
1525        Erases every program saved on the device and resets its
1526        parameters to the defaults. By default, asks at the console for
1527        confirmation first; a script that runs on its own, or an AI agent,
1528        passes `confirm=False`.
1529
1530        Requires Pulse Pal hardware v3 or newer.
1531
1532        Args:
1533            confirm: If `True`, ask at the console before anything is
1534                erased. If `False`, format at once.
1535            timeout: Seconds to wait for the device to report that
1536                formatting has finished.
1537
1538        Returns:
1539            `True` once the card has been formatted, or `False` if the
1540            user declines the confirmation prompt.
1541
1542        Raises:
1543            PulsePalError: If the connected hardware is older than v3, if
1544                the device reports that formatting failed, or if it does
1545                not report a result within `timeout` seconds.
1546        """
1547        if self.info.hardware_version < 3:
1548            raise PulsePalError(
1549                "format_microsd() requires hardware v3 or newer."
1550            )
1551
1552        if to_bool(confirm, "confirm"):
1553            print("*** Pulse Pal microSD Formatter ***")
1554            print("This will format Pulse Pal's microSD card,")
1555            print("erase all programs saved on the device")
1556            print("and reset all parameters to defaults.")
1557            reply = input("Do you want to continue (y/n)")
1558            if reply.strip().lower() != "y":
1559                print("Choice confirmed - microSD Card NOT formatted.")
1560                return False
1561
1562        self._write_serial((self._OP_MENU_BYTE, 97), "uint8", list(_FORMAT_KEY), "uint8")
1563
1564        # The device replies with lines of status text, the last of which
1565        # contains "!", and then a confirm byte (1 if the card was formatted,
1566        # 0 if not). The confirm byte is sent after the device has reloaded
1567        # its default parameters, so it can arrive well after the text. It
1568        # must be read here: left in the buffer, it would be taken as the
1569        # reply to the next command, and every reply after that would be
1570        # read one byte late.
1571        start = time.time()
1572        message = bytearray()
1573        flag_index = -1
1574        line_end = -1
1575
1576        while time.time() - start < timeout:
1577            n_waiting = self.port.in_waiting
1578            if n_waiting:
1579                message.extend(self.port.read(n_waiting))
1580                flag_index = message.find(b"!")
1581                if flag_index >= 0:
1582                    line_end = message.find(b"\n", flag_index)
1583                if line_end >= 0 and len(message) > line_end + 1:
1584                    break
1585            time.sleep(0.01)
1586        if line_end < 0 or len(message) <= line_end + 1:
1587            raise PulsePalError(
1588                "Pulse Pal did not report the result of formatting "
1589                f"its microSD card within {timeout} s. {_common.NO_REPLY_HINT}"
1590            )
1591        self._reply_pending = None  # The whole reply is read (see _write_raw())
1592        confirm_byte = message[line_end + 1]
1593
1594        text = bytes(message[:flag_index]).decode(
1595            "ascii", errors="replace"
1596        ).rstrip()
1597        if text:
1598            print(text)
1599
1600        # The device has loaded its own defaults. They are this class's, but the device keeps no record of
1601        # this object's other changes (continuous loop mode, for one), so the defaults are programmed, as the
1602        # MATLAB class does, and this object describes the device again.
1603        self.set_default_params()
1604        if confirm_byte != 1:
1605            raise PulsePalError(
1606                "Pulse Pal could not format its microSD card."
1607            )
1608        return True

Format the device's microSD card.

Erases every program saved on the device and resets its parameters to the defaults. By default, asks at the console for confirmation first; a script that runs on its own, or an AI agent, passes confirm=False.

Requires Pulse Pal hardware v3 or newer.

Arguments:
  • confirm: If True, ask at the console before anything is erased. If False, format at once.
  • timeout: Seconds to wait for the device to report that formatting has finished.
Returns:

True once the card has been formatted, or False if the user declines the confirmation prompt.

Raises:
  • PulsePalError: If the connected hardware is older than v3, if the device reports that formatting failed, or if it does not report a result within timeout seconds.
def gui(self, block=None, theme=None):
1610    def gui(self, block=None, theme=None):
1611        """Open the Pulse Pal parameter GUI, or focus an open one.
1612
1613        The GUI edits its own copy of the parameters, and loads them to
1614        the device when its 'Load to Device' button is clicked. The
1615        window closes automatically when the device is closed or
1616        deleted.
1617
1618        Calling this while the GUI is already open focuses the existing
1619        window rather than opening a second one.
1620
1621        Args:
1622            block: If `True`, the call returns when the GUI is closed. If
1623                `False`, the call returns immediately, and the host
1624                application must run the Tk event loop. If `None`, the
1625                GUI blocks only when the host does not already provide a
1626                Tk event loop, e.g. when launched from a script.
1627            theme: `"light"` or `"dark"` to select the color theme, or
1628                `None` to match the desktop theme. Passing a theme to an
1629                already-open GUI recolors it in place.
1630
1631        Returns:
1632            The `pulsepal.gui.PulsePalGUI` instance driving the window.
1633
1634        Raises:
1635            ValueError: If the theme name is not recognized.
1636        """
1637        gui = getattr(self, "_gui", None)
1638        if gui is not None and not gui.is_closed:
1639            if theme is not None:
1640                gui.set_theme(theme)
1641            gui.focus()
1642            return gui
1643
1644        from .gui import PulsePalGUI
1645
1646        gui = PulsePalGUI(self, theme=theme)
1647        self._gui = gui
1648        gui.start(block=block)
1649        return gui

Open the Pulse Pal parameter GUI, or focus an open one.

The GUI edits its own copy of the parameters, and loads them to the device when its 'Load to Device' button is clicked. The window closes automatically when the device is closed or deleted.

Calling this while the GUI is already open focuses the existing window rather than opening a second one.

Arguments:
  • block: If True, the call returns when the GUI is closed. If False, the call returns immediately, and the host application must run the Tk event loop. If None, the GUI blocks only when the host does not already provide a Tk event loop, e.g. when launched from a script.
  • theme: "light" or "dark" to select the color theme, or None to match the desktop theme. Passing a theme to an already-open GUI recolors it in place.
Returns:

The pulsepal.gui.PulsePalGUI instance driving the window.

Raises:
  • ValueError: If the theme name is not recognized.
def close(self):
1655    def close(self):
1656        """Close the connection to the device, and the GUI if open.
1657
1658        The device stops all output channels when the client disconnects,
1659        and shows its own name on its screen again. Safe to call more
1660        than once; later calls do nothing. Called automatically when
1661        leaving a `with` block and when the object is garbage collected,
1662        so pulse trains also stop when the last reference to the object
1663        goes, e.g. when a function that created it returns.
1664        """
1665        self._close(send_disconnect=True)

Close the connection to the device, and the GUI if open.

The device stops all output channels when the client disconnects, and shows its own name on its screen again. Safe to call more than once; later calls do nothing. Called automatically when leaving a with block and when the object is garbage collected, so pulse trains also stop when the last reference to the object goes, e.g. when a function that created it returns.

@dataclass
class DeviceInfo:
220@dataclass
221class DeviceInfo:
222    """Properties of the connected Pulse Pal device.
223
224    An instance is created for each connection and populated during the
225    handshake in `PulsePalDevice.__init__`. It is available as
226    `PulsePalDevice.info`. Devices running firmware v21 report only a
227    firmware version, so the remaining fields are filled in with the
228    known values for Pulse Pal hardware v2.
229
230    ```python
231    print(P.info.firmware_version)
232    ```
233    """
234
235    output_parameter_names: tuple = tuple(name for name, _ in _OUTPUT_PARAMETERS.values())
236    """Output parameter names, ordered by parameter code.
237
238    Each is the name of a parameter list on `PulsePalDevice`, and a key of
239    the dict `PulsePalDevice.export_params` returns.
240    """
241
242    trigger_modes: tuple = TRIGGER_MODES
243    """Names of the trigger modes the connected device has, accepted by
244    `PulsePalDevice.trigger_mode`. Pulse Pal 2 has no "Param Sync"."""
245
246    custom_train_targets: tuple = CUSTOM_TRAIN_TARGETS
247    """Names accepted by `PulsePalDevice.custom_train_target`."""
248
249    firmware_version: int = None
250    """Firmware version running on the connected device."""
251
252    hardware_version: int = None
253    """Hardware version of the connected device, e.g. `2` or `3`.
254
255    Reported by the device on firmware v22 and newer; assumed to be `2`
256    on older firmware.
257    """
258
259    circuit_board_revision: int = None
260    """Revision of the device's circuit board, 0-31.
261
262    A Pulse Pal 3 board encodes its revision on five pins, which the
263    firmware reads at startup. A board that encodes none reports `0`, as
264    does Pulse Pal 2; firmware older than v22 cannot report one, so it is
265    also `0` there. To record exactly which hardware ran an experiment,
266    copy `hardware_version` and `circuit_board_revision` to your data.
267    """
268
269    serial_number: str = None
270    """USB serial number of the device, e.g. `"20345420"`: the Teensy's,
271    unique to each Pulse Pal 3, and the same whichever firmware it runs.
272
273    Connect by it, wherever the device is plugged in, with
274    `PulsePalDevice(serial_number="20345420")`. To record exactly which unit ran an
275    experiment, copy it to your data. Pulse Pal 2 has none, and
276    firmware older than v22 cannot report one: `""`.
277    """
278
279    max_custom_pulses: int = None
280    """Maximum number of pulses in a single custom pulse train."""
281
282    n_custom_pulse_trains: int = None
283    """Number of custom pulse trains the device can store."""
284
285    cycle_frequency: float = None
286    """Update frequency of the device's hardware timer, in Hz.
287
288    All time parameters are rounded to a whole number of these cycles,
289    so this sets the timing resolution of the device.
290    """
291
292    cycle_period_us: float = None
293    """Update period of the device's hardware timer, in microseconds."""
294
295    min_pulse_width_us: float = None
296    """Shortest pulse phase, inter-pulse interval and pulse train duration,
297    and shortest time between custom pulses, in microseconds.
298
299    One timer cycle (10 us) on Pulse Pal 3, whose trigger channels latch
300    every edge on their inputs. Two cycles (100 us) on Pulse Pal 2, whose
301    trigger channels read their inputs once per cycle, so that a one cycle
302    pulse could fall between two reads. A Pulse Pal 2, or a Pulse Pal 3
303    with firmware from before October 2026, can miss a pulse shorter than
304    100 us from a Pulse Pal 3. Custom pulse times are multiples of it.
305    """
306
307    max_time: float = MAX_TIME
308    """Longest time parameter or custom pulse time, in seconds. See
309    `MAX_TIME`."""

Properties of the connected Pulse Pal device.

An instance is created for each connection and populated during the handshake in PulsePalDevice.__init__. It is available as PulsePalDevice.info. Devices running firmware v21 report only a firmware version, so the remaining fields are filled in with the known values for Pulse Pal hardware v2.

print(P.info.firmware_version)
DeviceInfo( output_parameter_names: tuple = ('is_biphasic', 'phase1_voltage', 'phase2_voltage', 'phase1_duration', 'inter_phase_interval', 'phase2_duration', 'inter_pulse_interval', 'burst_duration', 'inter_burst_interval', 'pulse_train_duration', 'pulse_train_delay', 'link_trigger_channel1', 'link_trigger_channel2', 'custom_train_id', 'custom_train_target', 'custom_train_loop', 'resting_voltage', 'continuous_loop'), trigger_modes: tuple = ('Normal', 'Toggle', 'Gated', 'Param Sync'), custom_train_targets: tuple = ('Pulses', 'Bursts'), firmware_version: int = None, hardware_version: int = None, circuit_board_revision: int = None, serial_number: str = None, max_custom_pulses: int = None, n_custom_pulse_trains: int = None, cycle_frequency: float = None, cycle_period_us: float = None, min_pulse_width_us: float = None, max_time: float = 9999.9999)
output_parameter_names: tuple = ('is_biphasic', 'phase1_voltage', 'phase2_voltage', 'phase1_duration', 'inter_phase_interval', 'phase2_duration', 'inter_pulse_interval', 'burst_duration', 'inter_burst_interval', 'pulse_train_duration', 'pulse_train_delay', 'link_trigger_channel1', 'link_trigger_channel2', 'custom_train_id', 'custom_train_target', 'custom_train_loop', 'resting_voltage', 'continuous_loop')

Output parameter names, ordered by parameter code.

Each is the name of a parameter list on PulsePalDevice, and a key of the dict PulsePalDevice.export_params returns.

trigger_modes: tuple = ('Normal', 'Toggle', 'Gated', 'Param Sync')

Names of the trigger modes the connected device has, accepted by PulsePalDevice.trigger_mode. Pulse Pal 2 has no "Param Sync".

custom_train_targets: tuple = ('Pulses', 'Bursts')
firmware_version: int = None

Firmware version running on the connected device.

hardware_version: int = None

Hardware version of the connected device, e.g. 2 or 3.

Reported by the device on firmware v22 and newer; assumed to be 2 on older firmware.

circuit_board_revision: int = None

Revision of the device's circuit board, 0-31.

A Pulse Pal 3 board encodes its revision on five pins, which the firmware reads at startup. A board that encodes none reports 0, as does Pulse Pal 2; firmware older than v22 cannot report one, so it is also 0 there. To record exactly which hardware ran an experiment, copy hardware_version and circuit_board_revision to your data.

serial_number: str = None

USB serial number of the device, e.g. "20345420": the Teensy's, unique to each Pulse Pal 3, and the same whichever firmware it runs.

Connect by it, wherever the device is plugged in, with PulsePalDevice(serial_number="20345420"). To record exactly which unit ran an experiment, copy it to your data. Pulse Pal 2 has none, and firmware older than v22 cannot report one: "".

max_custom_pulses: int = None

Maximum number of pulses in a single custom pulse train.

n_custom_pulse_trains: int = None

Number of custom pulse trains the device can store.

cycle_frequency: float = None

Update frequency of the device's hardware timer, in Hz.

All time parameters are rounded to a whole number of these cycles, so this sets the timing resolution of the device.

cycle_period_us: float = None

Update period of the device's hardware timer, in microseconds.

min_pulse_width_us: float = None

Shortest pulse phase, inter-pulse interval and pulse train duration, and shortest time between custom pulses, in microseconds.

One timer cycle (10 us) on Pulse Pal 3, whose trigger channels latch every edge on their inputs. Two cycles (100 us) on Pulse Pal 2, whose trigger channels read their inputs once per cycle, so that a one cycle pulse could fall between two reads. A Pulse Pal 2, or a Pulse Pal 3 with firmware from before October 2026, can miss a pulse shorter than 100 us from a Pulse Pal 3. Custom pulse times are multiples of it.

max_time: float = 9999.9999

Longest time parameter or custom pulse time, in seconds. See MAX_TIME.

@dataclass
class DeviceStatus:
312@dataclass
313class DeviceStatus:
314    """What the device is doing, and what has happened to it, from
315    `PulsePalDevice.status`.
316
317    The counters count from the previous call to `PulsePalDevice.status`,
318    by this or any earlier connection, or from the device's startup: each
319    call clears them, and reports what happened since the one before.
320    """
321
322    playing: list
323    """Numbers of the output channels playing, e.g. `[1, 3]`: from a
324    channel's start, its pulse train delay included, until its train
325    ends."""
326
327    trigger_edges: list
328    """Rising edges on each trigger channel, indexed by trigger channel
329    number (index 0 is unused), whatever its trigger mode and whether or
330    not they started an output channel."""
331
332    channel_starts: list
333    """Times each output channel started, indexed by channel number
334    (index 0 is unused): by a trigger channel, `PulsePalDevice.trigger`
335    or the joystick menu. A trigger that a channel ignored, because it
336    was already playing, is not a start."""
337
338    comm_failures: int
339    """Commands that reached the device only in part, after which it
340    showed COMM. FAILURE! and waited for its joystick to be clicked."""

What the device is doing, and what has happened to it, from PulsePalDevice.status.

The counters count from the previous call to PulsePalDevice.status, by this or any earlier connection, or from the device's startup: each call clears them, and reports what happened since the one before.

DeviceStatus( playing: list, trigger_edges: list, channel_starts: list, comm_failures: int)
playing: list

Numbers of the output channels playing, e.g. [1, 3]: from a channel's start, its pulse train delay included, until its train ends.

trigger_edges: list

Rising edges on each trigger channel, indexed by trigger channel number (index 0 is unused), whatever its trigger mode and whether or not they started an output channel.

channel_starts: list

Times each output channel started, indexed by channel number (index 0 is unused): by a trigger channel, PulsePalDevice.trigger or the joystick menu. A trigger that a channel ignored, because it was already playing, is not a start.

comm_failures: int

Commands that reached the device only in part, after which it showed COMM. FAILURE! and waited for its joystick to be clicked.

TRIGGER_MODES = ('Normal', 'Toggle', 'Gated', 'Param Sync')

Names of the trigger modes, in order of their code on the device (0-3). "Param Sync" is on Pulse Pal 3 only. See PulsePalDevice.trigger_mode.

CUSTOM_TRAIN_TARGETS = ('Pulses', 'Bursts')

Names of the custom train targets, in order of their code on the device. See PulsePalDevice.custom_train_target.

MAX_TIME = 9999.9999

The longest time parameter or custom pulse time, in seconds: the most the device's joystick menu shows and edits (four digits before the point).