pulsepal.wave_pal

Python interface for Wave Pal, a waveform player for Pulse Pal 3.

Wave Pal is alternative firmware for Pulse Pal 3 hardware. It stores four sampled waveforms on the device's microSD card, and each output channel plays one of them when it is triggered: by a TTL pulse on a trigger channel, from software, or from the thumb joystick. Waveforms can be up to a million samples long, and are played at up to 100 kHz.

Everything is accessed through WavePalDevice. Import it, connect to the device's serial port, load waveforms, and trigger, e.g.

import numpy as np
from pulsepal import WavePalDevice

with WavePalDevice("COM3") as W:
    W.sampling_rate = 50000                         # Hz, all channels
    t = np.arange(50000) / 50000                    # 1 second
    W.load_waveform(1, 5 * np.sin(2 * np.pi * 10 * t), [1, 3])  # waveform 1, played by channels 1 and 3
    W.trigger([1, 3])

The device needs Wave Pal firmware, which is in /WavePal in the Pulse Pal firmware repository. Its USB protocol is documented in PROTOCOL.md.

Channel settings

Settings that apply to one output channel, such as WavePalDevice.loop_mode, are lists indexed by channel number: index 0 is unused and holds None, and indices 1 to 4 hold the settings of output channels 1-4, as in pulsepal.PulsePalDevice. Setting an element or a slice programs the device at once. Assigning a whole list sets all four channels, and takes one value per channel: a single value raises an error, because it does not say which channels it is meant for.

W.loop_mode[2] = True          # channel 2 only
W.loop_duration[1:5] = [1, 2, 3, 4]
W.loop_mode = [False] * 4      # all four channels

WavePalDevice.trigger_mode is indexed the same way by trigger channel number, 1 or 2, as in Pulse Pal.

Waveforms

The device stores four waveforms, numbered 1-4. Each output channel plays one of them, its WavePalDevice.current_waveform, or none (0, the default). Several channels can play the same waveform, which is loaded only once.

W.load_waveform(1, sine, [1, 3])   # waveform 1, played by channels 1 and 3
W.load_waveform(2, ramp)           # stored: no channel plays it yet
W.current_waveform[1] = 2          # channel 1 plays waveform 2 from its next start

A channel that is playing finishes its waveform: a new current waveform plays from the channel's next start. Loading a waveform stops the channels playing it, outside param sync mode.

Param sync

"Param Sync", Pulse Pal's param sync trigger mode, lets the waveforms of the next trial be loaded during the current one, and take effect the instant it starts. While a trigger channel is in param sync mode, WavePalDevice.load_waveform loads the waveform into a second memory block that the device keeps for each waveform: channels go on playing the waveform it replaces, and triggers still start it. The next rising edge on that trigger channel makes it current. A new WavePalDevice.current_waveform waits for the edge in the same way.

W.trigger_mode[2] = "Param Sync"      # sent at once
W.load_waveform(1, next_trial_wave)   # stored: waveform 1 plays on, unchanged
# The next rising edge on trigger channel 2 makes it current

Sync outputs

An output channel in "Sync" mode (WavePalDevice.output_mode) plays no waveform: it reports another channel's playback as a TTL logic level, for example to mark a waveform's onset and offset for a recording system. It is at its WavePalDevice.sync_voltage while the channel in WavePalDevice.sync_target plays, and at 0 V otherwise.

W.output_mode[4] = "Sync"   # channel 4 reports channel 1, its default sync_target...
W.sync_voltage[4] = 3.3     # ...at 3.3 V

Units

Voltages are in volts, within WavePalDevice.output_range. Times are in seconds, and the sampling rate is in Hz.

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 Wave Pal, a waveform player for Pulse Pal 3.
   3
   4Wave Pal is alternative firmware for Pulse Pal 3 hardware. It stores four
   5sampled waveforms on the device's microSD card, and each output channel
   6plays one of them when it is triggered: by a TTL pulse on a trigger
   7channel, from software, or from the thumb joystick. Waveforms can be up
   8to a million samples long, and are played at up to 100 kHz.
   9
  10Everything is accessed through `WavePalDevice`. Import it, connect to
  11the device's serial port, load waveforms, and trigger, e.g.
  12
  13```python
  14import numpy as np
  15from pulsepal import WavePalDevice
  16
  17with WavePalDevice("COM3") as W:
  18    W.sampling_rate = 50000                         # Hz, all channels
  19    t = np.arange(50000) / 50000                    # 1 second
  20    W.load_waveform(1, 5 * np.sin(2 * np.pi * 10 * t), [1, 3])  # waveform 1, played by channels 1 and 3
  21    W.trigger([1, 3])
  22```
  23
  24The device needs Wave Pal firmware, which is in
  25[/WavePal](https://github.com/sanworks/PulsePal-Firmware/tree/main/WavePal) in the
  26Pulse Pal firmware repository. Its USB protocol is documented in
  27[PROTOCOL.md](https://github.com/sanworks/PulsePal-Firmware/blob/main/WavePal/PROTOCOL.md).
  28
  29## Channel settings
  30
  31Settings that apply to one output channel, such as
  32`WavePalDevice.loop_mode`, are lists indexed by channel number: index 0
  33is unused and holds `None`, and indices 1 to 4 hold the settings of
  34output channels 1-4, as in `pulsepal.PulsePalDevice`. Setting an element
  35or a slice programs the device at once. Assigning a whole list sets all
  36four channels, and takes one value per channel: a single value raises an
  37error, because it does not say which channels it is meant for.
  38
  39```python
  40W.loop_mode[2] = True          # channel 2 only
  41W.loop_duration[1:5] = [1, 2, 3, 4]
  42W.loop_mode = [False] * 4      # all four channels
  43```
  44
  45`WavePalDevice.trigger_mode` is indexed the same way by trigger channel
  46number, 1 or 2, as in Pulse Pal.
  47
  48## Waveforms
  49
  50The device stores four waveforms, numbered 1-4. Each output channel plays
  51one of them, its `WavePalDevice.current_waveform`, or none (`0`, the
  52default). Several channels can play the same waveform, which is loaded
  53only once.
  54
  55```python
  56W.load_waveform(1, sine, [1, 3])   # waveform 1, played by channels 1 and 3
  57W.load_waveform(2, ramp)           # stored: no channel plays it yet
  58W.current_waveform[1] = 2          # channel 1 plays waveform 2 from its next start
  59```
  60
  61A channel that is playing finishes its waveform: a new current waveform
  62plays from the channel's next start. Loading a waveform stops the
  63channels playing it, outside param sync mode.
  64
  65## Param sync
  66
  67`"Param Sync"`, Pulse Pal's param sync trigger mode, lets the waveforms
  68of the next trial be loaded during the current one, and take effect the
  69instant it starts. While a trigger channel is in param sync mode,
  70`WavePalDevice.load_waveform` loads the waveform into a second memory
  71block that the device keeps for each waveform: channels go on playing
  72the waveform it replaces, and triggers still start it. The next rising
  73edge on that trigger channel makes it current. A new
  74`WavePalDevice.current_waveform` waits for the edge in the same way.
  75
  76```python
  77W.trigger_mode[2] = "Param Sync"      # sent at once
  78W.load_waveform(1, next_trial_wave)   # stored: waveform 1 plays on, unchanged
  79# The next rising edge on trigger channel 2 makes it current
  80```
  81
  82## Sync outputs
  83
  84An output channel in `"Sync"` mode (`WavePalDevice.output_mode`) plays no
  85waveform: it reports another channel's playback as a TTL logic level, for
  86example to mark a waveform's onset and offset for a recording system. It
  87is at its `WavePalDevice.sync_voltage` while the channel in
  88`WavePalDevice.sync_target` plays, and at 0 V otherwise.
  89
  90```python
  91W.output_mode[4] = "Sync"   # channel 4 reports channel 1, its default sync_target...
  92W.sync_voltage[4] = 3.3     # ...at 3.3 V
  93```
  94
  95## Units
  96
  97Voltages are in volts, within `WavePalDevice.output_range`. Times are in
  98seconds, and the sampling rate is in Hz.
  99
 100## License
 101
 102This file is part of the Sanworks PulsePal repository.
 103Copyright (C) Sanworks LLC, Rochester, New York, USA
 104
 105This program is free software: you can redistribute it and/or modify
 106it under the terms of the GNU General Public License as published by
 107the Free Software Foundation, version 3.
 108
 109This program is distributed WITHOUT ANY WARRANTY and without even the
 110implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 111See the GNU General Public License for more details.
 112
 113You should have received a copy of the GNU General Public License
 114along with this program. If not, see <http://www.gnu.org/licenses/>.
 115"""
 116
 117from dataclasses import dataclass
 118import math
 119import numbers
 120import struct
 121import warnings
 122
 123import numpy as np
 124import serial
 125
 126from . import _common
 127from ._common import ChannelSettings, PulsePalError, to_bool, to_name
 128
 129__all__ = ["WavePalDevice", "DeviceInfo", "DeviceStatus", "OUTPUT_RANGES", "TRIGGER_MODES", "OUTPUT_MODES"]
 130__docformat__ = "google"
 131
 132OUTPUT_RANGES = {
 133    "0V:5V": (0.0, 5.0),
 134    "0V:10V": (0.0, 10.0),
 135    "-5V:5V": (-5.0, 5.0),
 136    "-10V:10V": (-10.0, 10.0),
 137}
 138"""Output ranges in order of their range index on the device, with their
 139limits in volts. See "Output ranges" in PulsePal-Firmware/WavePal/PROTOCOL.md."""
 140
 141TRIGGER_MODES = ("Normal", "Toggle", "Gated", "Param Sync", "Master")
 142"""Names of the trigger modes. See `WavePalDevice.trigger_mode`."""
 143
 144# Each trigger mode's code on the device. The first four are Pulse Pal's codes.
 145_TRIGGER_MODE_CODES = {"Normal": 0, "Toggle": 1, "Gated": 2, "Param Sync": 3, "Master": 4}
 146
 147OUTPUT_MODES = ("Signal", "Sync")
 148"""Names of the output modes, in order of their code on the device. See
 149`WavePalDevice.output_mode`."""
 150
 151_DEFAULT_SYNC_TARGETS = [2, 1, 1, 1]  # Channel 1 reports channel 2, and the others report channel 1
 152_SYNC_VOLTAGE_LIMITS = (3.0, 5.0)  # Volts. Within every output range
 153
 154
 155# The channel settings export_params() returns, after the sampling rate and the output range
 156_CHANNEL_SETTINGS = ("current_waveform", "loop_mode", "loop_duration", "trigger_mode", "link_trigger_channel1",
 157                     "link_trigger_channel2", "output_mode", "sync_target", "sync_voltage")
 158_SETTING_NAMES = ("sampling_rate", "output_range", *_CHANNEL_SETTINGS)  # The names a script assigns
 159# The ops whose reply _write_command() does not track: those with no reply ('P', 'X', 81 and 89), and the handshake
 160# (72), whose reply read_handshake_reply() reads until the device is quiet
 161_OPS_WITHOUT_TRACKED_REPLY = frozenset({72, 81, 89, ord("P"), ord("X")})
 162
 163
 164@dataclass
 165class DeviceInfo:
 166    """Properties of the connected Wave Pal.
 167
 168    Populated when `WavePalDevice` connects, and available as
 169    `WavePalDevice.info`.
 170    """
 171
 172    firmware_version: int = None
 173    """Wave Pal firmware version running on the device."""
 174
 175    hardware_version: int = None
 176    """Pulse Pal hardware version, e.g. `3`."""
 177
 178    circuit_board_revision: int = None
 179    """Revision of the device's circuit board, 0-31.
 180
 181    The board encodes its revision on five pins, which the firmware reads
 182    at startup. A board that encodes none reports `0`. To record exactly
 183    which hardware ran an experiment, copy `hardware_version` and
 184    `circuit_board_revision` to your data.
 185    """
 186
 187    serial_number: str = None
 188    """USB serial number of the device, e.g. `"20345420"`: the Teensy's,
 189    unique to each Pulse Pal 3, and the same whichever firmware it runs.
 190
 191    Connect by it, wherever the device is plugged in, with
 192    `WavePalDevice(serial_number="20345420")`. To record exactly which unit ran an
 193    experiment, copy it to your data.
 194    """
 195
 196    n_channels: int = None
 197    """Number of output channels."""
 198
 199    n_waveforms: int = None
 200    """Number of waveforms the device stores, numbered from 1."""
 201
 202    max_samples: int = None
 203    """Maximum number of samples in one waveform."""
 204
 205    max_sampling_rate: int = None
 206    """Highest sampling rate, in Hz."""
 207
 208    buffer_samples: int = None
 209    """Samples per playback buffer.
 210
 211    The first `buffer_samples` samples of each waveform are kept in the
 212    device's RAM, so that playback starts at once. A waveform no longer
 213    than this plays without reading the microSD card.
 214    """
 215
 216    sample_clock_hz: int = None
 217    """Clock that the sample rate is divided from, in Hz.
 218
 219    See `WavePalDevice.actual_sampling_rate`.
 220    """
 221
 222    output_ranges: tuple = tuple(OUTPUT_RANGES)
 223    """Names of the output ranges, accepted by
 224    `WavePalDevice.output_range`."""
 225
 226    trigger_modes: tuple = TRIGGER_MODES
 227    """Names of the trigger modes, accepted by
 228    `WavePalDevice.trigger_mode`."""
 229
 230    output_modes: tuple = OUTPUT_MODES
 231    """Names of the output modes, accepted by
 232    `WavePalDevice.output_mode`."""
 233
 234
 235@dataclass
 236class DeviceStatus:
 237    """A snapshot of the device's playback state, from
 238    `WavePalDevice.status`."""
 239
 240    playing: list
 241    """Numbers of the output channels playing a waveform, e.g. `[1, 3]`."""
 242
 243    samples_loaded: list
 244    """Samples in each waveform, `0` if it has none.
 245
 246    Indexed by waveform number, with index 0 unused. This is what the
 247    device holds, which can include waveforms loaded by an earlier
 248    connection. A load stored for a param sync edge counts from the edge.
 249    """
 250
 251    underruns: list
 252    """Underruns on each channel since the device started, indexed by
 253    channel number.
 254
 255    An underrun is a block of samples that was not read from the microSD
 256    card by the time it was due. The output then holds its last value
 257    until the block arrives. See "Storage and buffering" in the
 258    [Wave Pal protocol](https://github.com/sanworks/PulsePal-Firmware/blob/main/WavePal/PROTOCOL.md#storage-and-buffering).
 259    """
 260
 261    longest_interrupt_us: float
 262    """Longest run of the device's playback interrupt since the previous
 263    call to `WavePalDevice.status`, in microseconds.
 264
 265    It must stay below the sample period, `1e6 / sampling_rate`.
 266    """
 267
 268    current_waveform: list
 269    """The waveform each output channel plays from its next start, `0` for
 270    none, as the device holds it. Indexed by channel number.
 271
 272    In param sync mode, `WavePalDevice.current_waveform` set since the
 273    last edge is in `DeviceStatus.stored_current_waveform` until the next
 274    one.
 275    """
 276
 277    stored_waveforms: list
 278    """Numbers of the waveforms loaded in param sync mode since the last
 279    edge, which the next edge makes current, e.g. `[2]`."""
 280
 281    stored_current_waveform: list
 282    """The current waveforms set in param sync mode since the last edge,
 283    which the next edge applies, indexed by channel number. `None` if
 284    none were set."""
 285
 286
 287class WavePalDevice:
 288    """A class to control a Wave Pal on a USB serial port.
 289
 290    Creating an instance opens the serial port, checks that the device
 291    runs Wave Pal firmware, reads its properties into
 292    `WavePalDevice.info`, shows "PYTHON Connected" on the device's
 293    screen, stops any playback and programs the default settings (see
 294    `WavePalDevice.set_default_params`).
 295
 296    ```python
 297    from pulsepal import WavePalDevice
 298
 299    W = WavePalDevice("COM3")
 300    W.load_waveform(1, [0, 1, 2, 3, 4, 5, 0], 1)   # waveform 1, played by channel 1
 301    W.trigger(1)
 302    W.close()
 303    ```
 304
 305    Replace "COM3" with the device's USB serial port name, which
 306    `WavePalDevice.serialportlist` lists. `WavePalDevice` is also a
 307    context manager, which closes the port on exit.
 308
 309    Closing the connection stops playback, as it does on Pulse Pal, and
 310    puts the device's own name back on its screen. The device keeps its
 311    settings and waveforms, so TTL triggers still play them.
 312    """
 313
 314    port: "serial.Serial"
 315    """The open `serial.Serial` port connected to the device."""
 316
 317    info: DeviceInfo
 318    """Properties of the connected device. See `DeviceInfo`."""
 319
 320    _CURRENT_FIRMWARE_VERSION = 1
 321    _BAUD_RATE = _common.BAUD_RATE  # USB serial ignores it (see _common.BAUD_RATE)
 322
 323    _OP_MENU_BYTE = _common.OP_MENU_BYTE
 324    _OP_HANDSHAKE = _common.OP_HANDSHAKE
 325    _OP_DISCONNECT = 81
 326    _OP_SET_CLIENT_NAME = 89
 327    _OP_SET_SCREEN_SAVER = 99
 328    _OP_HARDWARE_REVISION = 100
 329    _OP_HARDWARE_INFO = ord("N")
 330    _OP_SET_SAMPLING_RATE = ord("S")
 331    _OP_SET_OUTPUT_RANGE = ord("R")
 332    _OP_LOAD_WAVEFORM = ord("L")
 333    _OP_SET_CURRENT_WAVEFORMS = ord("C")
 334    _OP_TRIGGER = ord("P")
 335    _OP_STOP = ord("X")
 336    _OP_SET_FIXED_VOLTAGE = ord("!")
 337    _OP_SET_LOOP_MODE = ord("O")
 338    _OP_SET_LOOP_DURATION = ord("D")
 339    _OP_SET_TRIGGER_MODE = ord("T")
 340    _OP_SET_TRIGGER_LINKS = ord("I")
 341    _OP_SET_OUTPUT_MODES = ord("M")
 342    _OP_SET_SYNC_VOLTAGES = ord("V")
 343    _OP_GET_STATUS = ord("G")
 344    _OP_GET_PLAYBACK_CHECKSUMS = ord("Z")
 345
 346    _HANDSHAKE_REPLY = 87  # 'W'
 347    _HARDWARE_INFO_FORMAT = "<BBIIIIB"
 348    _STATUS_FORMAT = "<B4I4II4BBB4B"
 349    _DAC_BITMAX = 65535
 350    _UINT32_MAX = 2**32 - 1
 351    _ALL_CHANNELS = 0x0F
 352    # The ops that carry a setting, which _discard_lost_reply() sends again if the reply to one is lost
 353    _SETTING_OPS = frozenset(map(ord, "SRCODTIMV"))
 354
 355    _reply_pending = None  # The op code of a command whose reply has not been read in full yet (see _write_command())
 356
 357    def __init__(self, port_name=None, *, serial_number=None, timeout=10):
 358        """Open a connection to a Wave Pal.
 359
 360        Args:
 361            port_name: USB serial port of the device, such as `COM3` on
 362                Windows or `/dev/ttyACM0` on Linux.
 363            serial_number: Instead of `port_name`, the device's USB serial
 364                number (`DeviceInfo.serial_number`), which finds its port
 365                wherever it is plugged in.
 366            timeout: Serial read timeout, in seconds. Loading a long
 367                waveform onto a slow microSD card can take a few seconds.
 368
 369        Firmware newer than this module knows is used with a warning: new
 370        firmware only adds commands. Update the package to use what is new.
 371
 372        Raises:
 373            PulsePalError: If the device does not reply to the handshake, or
 374                runs other firmware.
 375            serial.SerialException: If the serial port cannot be opened,
 376                e.g. because another program has it open (on Linux and
 377                macOS, another session of these classes, which lock it).
 378        """
 379        self._closed = True
 380        self.info = DeviceInfo()
 381        self._sampling_rate = None
 382        self._output_range = None
 383        self._waveforms = []  # Indexed by waveform number, once the device has said how many it stores
 384        self._current_waveform = ChannelSettings(
 385            "current_waveform", [0] * 4, self, "_apply_current_waveform")
 386        self._loop_mode = ChannelSettings(
 387            "loop_mode", [False] * 4, self, "_apply_loop_mode")
 388        self._loop_duration = ChannelSettings(
 389            "loop_duration", [0.0] * 4, self, "_apply_loop_duration")
 390        self._trigger_mode = ChannelSettings(
 391            "trigger_mode", ["Normal"] * 2, self, "_apply_trigger_mode")
 392        self._link_trigger_channel1 = ChannelSettings(
 393            "link_trigger_channel1", [False] * 4, self,
 394            "_apply_trigger_channel1_links")
 395        self._link_trigger_channel2 = ChannelSettings(
 396            "link_trigger_channel2", [False] * 4, self,
 397            "_apply_trigger_channel2_links")
 398        self._output_mode = ChannelSettings(
 399            "output_mode", ["Signal"] * 4, self, "_apply_output_mode")
 400        self._sync_target = ChannelSettings(
 401            "sync_target", list(_DEFAULT_SYNC_TARGETS), self, "_apply_sync_target")
 402        self._sync_voltage = ChannelSettings(
 403            "sync_voltage", [5.0] * 4, self, "_apply_sync_voltage")
 404
 405        port_name = _common.port_name_from(port_name, serial_number, "WavePalDevice")
 406        self.port = serial.Serial(
 407            port_name,
 408            self._BAUD_RATE,
 409            timeout=timeout,
 410            rtscts=True,
 411            # Windows opens a port for one program only. Linux and macOS let a second program open it too, and two
 412            # sessions' bytes would then interleave; exclusive locks it (flock), so a second session that also locks
 413            # it, such as another of these classes, gets an error instead
 414            exclusive=True,
 415        )
 416        self._closed = False
 417        try:
 418            # Discard anything left in the buffer by an earlier session
 419            self.port.reset_input_buffer()
 420            self._handshake()
 421            self._read_hardware_info()
 422            self._waveforms = [None] * (self.info.n_waveforms + 1)
 423            # Client name op + "PYTHON" in ASCII, shown as "PYTHON Connected"
 424            self._write_command(self._OP_SET_CLIENT_NAME, b"PYTHON")
 425            self.stop()
 426            self.set_default_params()
 427        except BaseException:
 428            # Op 81 means something else to other devices, so it is sent
 429            # only once the device has identified itself as a Wave Pal
 430            self._close(send_disconnect=self.info.firmware_version is not None)
 431            raise
 432
 433    @staticmethod
 434    def serialportlist(ports_to_list="available"):
 435        """Return the names of the USB serial ports on this computer.
 436
 437        Called on the class, without connecting to a device, to find the
 438        port name to pass to `WavePalDevice`.
 439
 440        Args:
 441            ports_to_list: `available` to list only the ports that are
 442                not already in use, or `all` to list every USB serial
 443                port. Not case sensitive.
 444
 445        Returns:
 446            Sorted list of port names, such as `["COM3", "COM7"]`.
 447
 448        Raises:
 449            PulsePalError: If `ports_to_list` is not `available` or `all`.
 450        """
 451        return _common.serialportlist(ports_to_list)
 452
 453    # ------------------------------------------------------------------
 454    # Settings
 455    # ------------------------------------------------------------------
 456
 457    def set_default_params(self):
 458        """Program the default settings on the device.
 459
 460        The defaults are both trigger channels in normal mode, a 10 kHz
 461        sampling rate, the -10 V to 10 V output range, loop mode off with
 462        loop durations of 0, no output channel linked to a trigger channel
 463        (so a TTL starts nothing until a script links it), every channel in
 464        `"Signal"` output mode, with sync targets `[2, 1, 1, 1]` and sync
 465        voltages of 5 V, and no current waveform on any channel. They match
 466        the settings the device starts with. The
 467        trigger modes are sent first: a trigger channel leaving param sync
 468        mode makes what was stored for its next edge current, and the
 469        settings after it then apply at once.
 470
 471        Loaded waveforms are kept, and loaded again if the output range
 472        changes (see `WavePalDevice.output_range`).
 473
 474        Raises:
 475            PulsePalError: If a loaded waveform does not fit the default
 476                output range, -10 V to 10 V.
 477        """
 478        self.trigger_mode = ["Normal"] * 2
 479        self.sampling_rate = 10000
 480        self.output_range = "-10V:10V"
 481        self.loop_mode = [False] * 4
 482        self.loop_duration = [0] * 4
 483        self._set_trigger_links([False] * 4, [False] * 4)
 484        self._set_output_modes(["Signal"] * 4, _DEFAULT_SYNC_TARGETS)
 485        self.sync_voltage = [5.0] * 4
 486        self.current_waveform = [0] * 4
 487
 488    @property
 489    def sampling_rate(self):
 490        """Sampling rate of all output channels, in Hz.
 491
 492        A whole number from 1 to `DeviceInfo.max_sampling_rate`. It can be
 493        changed during playback. The rate played can differ slightly from
 494        the rate set: see `WavePalDevice.actual_sampling_rate`.
 495        """
 496        return self._sampling_rate
 497
 498    @sampling_rate.setter
 499    def sampling_rate(self, rate):
 500        rate_hz = self._normalize_sampling_rate(rate)
 501        # Loop durations are sent in samples, so check that they still fit
 502        # before anything is changed
 503        loop_samples = None
 504        if self._sampling_rate is not None:
 505            loop_samples = self._durations_to_samples(
 506                self._loop_duration[1:], rate_hz)
 507        self._write_command(self._OP_SET_SAMPLING_RATE,
 508                            struct.pack("<I", rate_hz))
 509        self._read_ack("setting sampling_rate")
 510        self._sampling_rate = rate_hz
 511        if loop_samples is not None:
 512            self._send_loop_duration_samples(loop_samples)
 513
 514    @property
 515    def actual_sampling_rate(self):
 516        """The sampling rate the device plays, in Hz.
 517
 518        The device divides `DeviceInfo.sample_clock_hz` (24 MHz) by a
 519        whole number, so the rate played is the nearest one of those to
 520        `WavePalDevice.sampling_rate`. For example, 44100 Hz plays at
 521        44117.6 Hz. Rates that divide 24 MHz exactly, such as 10 kHz,
 522        25 kHz or 100 kHz, play exactly.
 523        """
 524        return self._actual_rate(self._sampling_rate)
 525
 526    @property
 527    def output_range(self):
 528        """Voltage range of all output channels.
 529
 530        One of `DeviceInfo.output_ranges`: `"0V:5V"`, `"0V:10V"`,
 531        `"-5V:5V"` or `"-10V:10V"`. The smallest range that fits the
 532        waveforms gives the finest voltage steps.
 533
 534        Changing the range stops playback, sets all outputs to 0 V, and
 535        loads the waveforms again, encoded for the new range. It raises
 536        an error, and changes nothing, if a loaded waveform does not fit
 537        the new range, or if a trigger channel is in param sync mode,
 538        where the loads would wait for a TTL edge.
 539        """
 540        return self._output_range
 541
 542    @output_range.setter
 543    def output_range(self, range_name):
 544        name = self._check_output_range(range_name, self._trigger_mode[1:])
 545        changed = name != self._output_range
 546        range_index = list(OUTPUT_RANGES).index(name)
 547        self._write_command(self._OP_SET_OUTPUT_RANGE, bytes([range_index]))
 548        self._read_ack("setting output_range")
 549        self._output_range = name
 550        if changed:
 551            # The device unloads the waveforms when the range changes,
 552            # because their samples encode voltages in the old range. The
 553            # channels keep their current waveforms.
 554            waveforms = self._waveforms
 555            self._waveforms = [None] * len(waveforms)
 556            for number, waveform in enumerate(waveforms):
 557                if waveform is not None:
 558                    self.load_waveform(number, waveform)
 559
 560    @property
 561    def current_waveform(self):
 562        """The waveform each output channel plays, by waveform number.
 563
 564        Indexed by channel number (see "Channel settings" above). Each
 565        value is the number of a waveform loaded with
 566        `WavePalDevice.load_waveform`, 1 to `DeviceInfo.n_waveforms`, or
 567        `0` for none, the default: a channel with no waveform ignores
 568        triggers. Several channels can play the same waveform.
 569
 570        A channel that is playing finishes its waveform: the new one plays
 571        from the channel's next start. In param sync mode, a change waits
 572        for the next rising edge on the param sync trigger channel (see
 573        `WavePalDevice.trigger_mode`).
 574
 575        ```python
 576        W.current_waveform[1] = 2            # channel 1 plays waveform 2
 577        W.current_waveform = [1, 1, 1, 1]    # all four play waveform 1
 578        ```
 579        """
 580        return self._current_waveform
 581
 582    @current_waveform.setter
 583    def current_waveform(self, values):
 584        self._current_waveform._assign(values)
 585
 586    @property
 587    def loop_mode(self):
 588        """Whether each output channel loops its waveform.
 589
 590        Indexed by channel number (see "Channel settings" above). `True`
 591        repeats the waveform until `WavePalDevice.loop_duration` has
 592        elapsed, or until stopped if the loop duration is 0. `False` plays
 593        it once. A change applies to playback in progress.
 594        """
 595        return self._loop_mode
 596
 597    @loop_mode.setter
 598    def loop_mode(self, values):
 599        self._loop_mode._assign(values)
 600
 601    @property
 602    def loop_duration(self):
 603        """How long each output channel loops its waveform, in seconds.
 604
 605        Indexed by channel number (see "Channel settings" above). Applies
 606        in loop mode only, and counts from the trigger. The channel stops
 607        when it has elapsed, part way through the waveform if need be. `0`
 608        loops until the channel is stopped. Durations are rounded to a
 609        whole number of samples, and a nonzero duration lasts at least
 610        one sample.
 611        """
 612        return self._loop_duration
 613
 614    @loop_duration.setter
 615    def loop_duration(self, values):
 616        self._loop_duration._assign(values)
 617
 618    @property
 619    def trigger_mode(self):
 620        """How each trigger channel acts on the output channels linked to it.
 621
 622        Indexed by trigger channel number, 1 or 2 (index 0 is unused), as
 623        in Pulse Pal. A TTL edge on a trigger channel acts on the output
 624        channels linked to it (`WavePalDevice.link_trigger_channel1`,
 625        `WavePalDevice.link_trigger_channel2`):
 626
 627        - `"Normal"`: a rising edge starts the linked channels' waveforms.
 628          Channels that are playing ignore it.
 629        - `"Toggle"`: a rising edge starts the linked channels, or stops
 630          those that are playing.
 631        - `"Gated"`: a rising edge starts the linked channels, and a
 632          falling edge stops them, unless the other trigger channel is also
 633          gated, linked to them, and still high. With loop mode on and a
 634          loop duration of 0, a waveform plays for exactly as long as the
 635          TTL is high.
 636        - `"Param Sync"`: a rising edge starts and stops nothing (the
 637          channel's links are ignored). It makes the waveforms loaded,
 638          and the `WavePalDevice.current_waveform` set, since the previous
 639          edge current. This is how the next trial's waveforms are loaded
 640          during the current trial, and played from the instant it starts.
 641        - `"Master"`: a rising edge starts the linked channels, and
 642          restarts those that are playing from their first sample.
 643
 644        The first four are Pulse Pal's trigger modes. Names are not case
 645        sensitive.
 646
 647        While a trigger channel is in param sync mode,
 648        `WavePalDevice.load_waveform` loads into a second memory block
 649        that the device keeps for each waveform. Channels go on playing
 650        the waveform it replaces, and triggers still start it, until the
 651        edge. A channel that is playing at the edge finishes what it plays,
 652        and plays the new waveform from its next start. A later load of the
 653        same waveform before the edge replaces the earlier one, and stops
 654        any channel still playing the waveform from before the previous
 655        edge, since the device reuses that memory block. Changes to
 656        `WavePalDevice.current_waveform` wait for the edge in the same
 657        way. Other settings apply at once.
 658
 659        When neither trigger channel is in param sync mode any more, what
 660        was waiting for an edge becomes current at once, so
 661        `WavePalDevice.waveforms` and `WavePalDevice.current_waveform`
 662        describe the device again. (Pulse Pal and Synth Pal discard their
 663        stored parameters and settings then; Pulse Pal makes its stored
 664        custom trains current, as this class does its waveforms.)
 665        `WavePalDevice.output_range` cannot change
 666        in param sync mode. To make the waveforms current on the same edge
 667        that starts the channels, wire the TTL to the other trigger channel
 668        as well: the param sync edge is handled first.
 669
 670        ```python
 671        W.trigger_mode[2] = "Param Sync"      # sent at once
 672        W.load_waveform(1, next_trial_wave)   # waits for trigger channel 2's next rising edge
 673        ```
 674        """
 675        return self._trigger_mode
 676
 677    @trigger_mode.setter
 678    def trigger_mode(self, values):
 679        self._trigger_mode._assign(values)
 680
 681    @property
 682    def link_trigger_channel1(self):
 683        """Whether each output channel is triggered by trigger channel 1.
 684
 685        Indexed by channel number (see "Channel settings" above). By
 686        default no output channel is linked to either trigger channel, so
 687        a TTL starts nothing until a script links it.
 688        """
 689        return self._link_trigger_channel1
 690
 691    @link_trigger_channel1.setter
 692    def link_trigger_channel1(self, values):
 693        self._link_trigger_channel1._assign(values)
 694
 695    @property
 696    def link_trigger_channel2(self):
 697        """Whether each output channel is triggered by trigger channel 2.
 698
 699        Indexed by channel number (see "Channel settings" above).
 700        """
 701        return self._link_trigger_channel2
 702
 703    @link_trigger_channel2.setter
 704    def link_trigger_channel2(self, values):
 705        self._link_trigger_channel2._assign(values)
 706
 707    @property
 708    def output_mode(self):
 709        """What each output channel outputs: `"Signal"` or `"Sync"`.
 710
 711        Indexed by channel number (see "Channel settings" above).
 712
 713        - `"Signal"`, the default: the channel plays its
 714          `WavePalDevice.current_waveform` when it is triggered.
 715        - `"Sync"`: the channel plays no waveform. It reports the playback
 716          of another output channel, its `WavePalDevice.sync_target`, as a
 717          TTL logic level: `WavePalDevice.sync_voltage` while the target
 718          plays, and 0 V otherwise. It goes high on the same output update
 719          as the target's first sample, and low on the update that returns
 720          the target to 0 V, one sample period after its last sample, or as
 721          soon as the target is stopped. So it is high for exactly the
 722          waveform's duration (or loop duration). A restart in master mode
 723          leaves it high.
 724
 725        A channel in Sync mode ignores triggers, its trigger links and
 726        `WavePalDevice.stop`, and `WavePalDevice.trigger` and
 727        `WavePalDevice.set_fixed_voltage` raise an error for it. A channel
 728        entering Sync mode stops playing, and takes its target's level at
 729        once. A channel cannot report another channel in Sync mode, which
 730        plays nothing. Names are not case sensitive. In param sync mode, a
 731        change applies at once.
 732
 733        ```python
 734        W.output_mode[2] = "Sync"   # channel 2 reports channel 1, its default sync_target
 735        ```
 736        """
 737        return self._output_mode
 738
 739    @output_mode.setter
 740    def output_mode(self, values):
 741        self._output_mode._assign(values)
 742
 743    @property
 744    def sync_target(self):
 745        """The output channel each channel reports in Sync mode.
 746
 747        Indexed by channel number (see "Channel settings" above). Each
 748        value is another output channel's number, 1-4: a channel cannot
 749        report itself, and a channel in Sync mode cannot report one that is
 750        in Sync mode too. Only channels in Sync mode use it (see
 751        `WavePalDevice.output_mode`). The default is `[2, 1, 1, 1]`:
 752        channel 1 reports channel 2, and the others report channel 1.
 753
 754        ```python
 755        W.sync_target[4] = 3
 756        W.output_mode[4] = "Sync"   # channel 4 reports channel 3
 757        ```
 758        """
 759        return self._sync_target
 760
 761    @sync_target.setter
 762    def sync_target(self, values):
 763        self._sync_target._assign(values)
 764
 765    @property
 766    def sync_voltage(self):
 767        """Each channel's voltage in Sync mode while its target plays, in volts.
 768
 769        Indexed by channel number (see "Channel settings" above). 3 V to
 770        5 V, and 5 V by default. Only channels in Sync mode use it (see
 771        `WavePalDevice.output_mode`). It is the same in every
 772        `WavePalDevice.output_range`, so changing the range does not change
 773        it. A sync output that is high goes to a new voltage at once.
 774        """
 775        return self._sync_voltage
 776
 777    @sync_voltage.setter
 778    def sync_voltage(self, values):
 779        self._sync_voltage._assign(values)
 780
 781    def set_screen_saver(self, enabled, timeout=1800):
 782        """Switch the device's screen saver on or off, and set its timeout.
 783
 784        With the screen saver on, the device dims its screen once it has
 785        been left alone for `timeout` seconds: no command from a computer,
 786        no rising edge on a trigger channel, and no joystick click or
 787        push. The next of these brings the screen back. The device keeps
 788        both settings in its EEPROM, shared with Pulse Pal and Synth Pal
 789        firmware, and saves them once no channel is playing. A new device
 790        starts with the screen saver on and 1800 s.
 791
 792        Args:
 793            enabled: `True` to switch the screen saver on, `False` to
 794                switch it off.
 795            timeout: Seconds without activity before the screen dims, 1 to
 796                65535. It is sent with every call, so leaving it out sets
 797                1800 s.
 798
 799        Raises:
 800            PulsePalError: If a value is out of range.
 801        """
 802        state = to_bool(enabled, "enabled")
 803        if isinstance(timeout, (bool, np.bool_)) \
 804                or not isinstance(timeout, numbers.Integral) \
 805                or not 1 <= timeout <= 65535:
 806            raise PulsePalError(
 807                "timeout must be a whole number of seconds from 1 to 65535. "
 808                f"Received {timeout!r}."
 809            )
 810        self._write_command(self._OP_SET_SCREEN_SAVER,
 811                            struct.pack("<BH", int(state), int(timeout)))
 812        self._read_ack("set_screen_saver()")
 813
 814    def export_params(self):
 815        """Return every setting, as a dict of plain values and lists.
 816
 817        Keyed by setting name: `"sampling_rate"` and `"output_range"`, then
 818        the channel settings, each with one value per channel and no
 819        unused index 0. It holds only numbers, booleans and names, so it
 820        can be saved with `json` and logged with your data. The waveforms
 821        are not part of it: `WavePalDevice.waveforms` holds them.
 822
 823        ```python
 824        import json
 825        with open("session_settings.json", "w") as f:
 826            json.dump(W.export_params(), f)
 827        ```
 828        """
 829        params = {"sampling_rate": self._sampling_rate, "output_range": self._output_range}
 830        for name in _CHANNEL_SETTINGS:
 831            params[name] = list(getattr(self, name))[1:]
 832        return params
 833
 834    def import_params(self, params):
 835        """Program the device with settings exported by `WavePalDevice.export_params`.
 836
 837        All of them are checked first, and nothing is sent if one is
 838        invalid. They are then sent in an order that lets each take
 839        effect: a trigger channel leaving param sync mode first, then the
 840        sampling rate, the output range and the channel settings, and a
 841        trigger channel entering param sync mode last. So
 842        `WavePalDevice.current_waveform` applies at once, unless a trigger
 843        channel was in param sync mode and stays in it: then it waits for
 844        the next edge, as an assignment would. Settings missing from
 845        `params` keep their values. A name that is not a setting is
 846        skipped with a warning, so that settings exported by a newer
 847        version of this package, which may have more, can still be
 848        imported.
 849
 850        The waveforms are not settings: load them with
 851        `WavePalDevice.load_waveform` first, since a current waveform must
 852        be a loaded one.
 853
 854        ```python
 855        import json
 856        with open("session_settings.json") as f:
 857            W.import_params(json.load(f))
 858        ```
 859
 860        Args:
 861            params: A dict of setting name to its value: a number for
 862                `"sampling_rate"`, a name for `"output_range"`, and one
 863                value per channel (a list, tuple or NumPy array) for the
 864                others, as `export_params` returns.
 865
 866        Raises:
 867            PulsePalError: If a value is invalid (nothing is sent), or the
 868                device rejects a setting.
 869        """
 870        names = {"sampling_rate", "output_range", *_CHANNEL_SETTINGS}
 871        unknown = [name for name in params if name not in names]
 872        if unknown:
 873            warnings.warn(f"import_params(): skipped {', '.join(map(repr, unknown))}, which this version of "
 874                          "WavePalDevice does not have.", stacklevel=2)
 875        new = {}
 876        for name in _CHANNEL_SETTINGS:
 877            if name in params:
 878                n = 2 if name == "trigger_mode" else self.info.n_channels
 879                new[name] = _common.one_value_per_channel(name, params[name], n)
 880        if "current_waveform" in new:
 881            new["current_waveform"] = self._normalize_current_waveform(new["current_waveform"])
 882        if "loop_mode" in new:
 883            new["loop_mode"] = [to_bool(value, "loop_mode") for value in new["loop_mode"]]
 884        if "loop_duration" in new:
 885            new["loop_duration"] = self._normalize_loop_durations(new["loop_duration"])
 886        for name in ("link_trigger_channel1", "link_trigger_channel2"):
 887            if name in new:
 888                new[name] = [to_bool(value, name) for value in new[name]]
 889        if "output_mode" in new:
 890            new["output_mode"] = [to_name(value, OUTPUT_MODES, "output mode") for value in new["output_mode"]]
 891        if "sync_target" in new:
 892            new["sync_target"] = self._normalize_sync_targets(new["sync_target"])
 893        if "sync_voltage" in new:
 894            new["sync_voltage"] = self._normalize_sync_voltages(new["sync_voltage"])
 895        output_modes = new.get("output_mode", list(self._output_mode)[1:])
 896        sync_targets = new.get("sync_target", list(self._sync_target)[1:])
 897        self._check_output_modes(output_modes, sync_targets)
 898        modes = list(self._trigger_mode)[1:]
 899        if "trigger_mode" in new:
 900            modes = [to_name(value, TRIGGER_MODES, "trigger mode") for value in new["trigger_mode"]]
 901        # The trigger modes the other settings are sent in: those of channels leaving param sync mode are sent
 902        # first, those of channels entering it last
 903        first_modes = [new_mode if (old == "Param Sync" and new_mode != "Param Sync") else old
 904                       for old, new_mode in zip(self._trigger_mode[1:], modes)]
 905        rate = self._sampling_rate
 906        if "sampling_rate" in params:
 907            rate = self._normalize_sampling_rate(params["sampling_rate"])
 908        range_name = self._output_range
 909        if "output_range" in params:
 910            range_name = self._check_output_range(params["output_range"], first_modes)
 911        self._durations_to_samples(new.get("loop_duration", self._loop_duration[1:]), rate)  # They fit at the rate
 912
 913        if first_modes != list(self._trigger_mode)[1:]:
 914            self.trigger_mode = first_modes
 915        if rate != self._sampling_rate:
 916            self.sampling_rate = rate
 917        if range_name != self._output_range:
 918            self.output_range = range_name
 919        for name in ("loop_mode", "loop_duration"):
 920            if name in new:
 921                setattr(self, name, new[name])
 922        if "link_trigger_channel1" in new or "link_trigger_channel2" in new:
 923            self._set_trigger_links(new.get("link_trigger_channel1", self._link_trigger_channel1[1:]),
 924                                    new.get("link_trigger_channel2", self._link_trigger_channel2[1:]))
 925        if "output_mode" in new or "sync_target" in new:
 926            self._set_output_modes(output_modes, sync_targets)
 927        if "sync_voltage" in new:
 928            self.sync_voltage = new["sync_voltage"]
 929        if "current_waveform" in new:
 930            self.current_waveform = new["current_waveform"]
 931        if modes != first_modes:
 932            self.trigger_mode = modes
 933
 934    @property
 935    def waveforms(self):
 936        """The waveforms loaded with `WavePalDevice.load_waveform`.
 937
 938        A list indexed by waveform number, 1 to `DeviceInfo.n_waveforms`,
 939        with index 0 unused. Each element is a read-only NumPy array of
 940        voltages, or `None` if this object has not loaded that waveform. In
 941        param sync mode, it holds the waveforms loaded since the last edge
 942        before the device plays them. `WavePalDevice.status` shows what
 943        the device itself holds.
 944        """
 945        return list(self._waveforms)
 946
 947    # ------------------------------------------------------------------
 948    # Waveforms and playback
 949    # ------------------------------------------------------------------
 950
 951    def load_waveform(self, waveform_number, waveform, channels=None):
 952        """Load one of the device's waveforms, and choose the channels that play it.
 953
 954        The samples are written to the device's microSD card, and the
 955        first `DeviceInfo.buffer_samples` of them are also kept in its RAM.
 956        Outside param sync mode, loading stops the channels playing that
 957        waveform, and the new one plays from their next start. Other
 958        channels keep playing. In param sync mode, the new waveform waits
 959        for the next rising edge on the param sync trigger channel, and
 960        channels go on playing the old one until then (see
 961        `WavePalDevice.trigger_mode`).
 962
 963        ```python
 964        t = np.arange(10000) / W.sampling_rate
 965        W.load_waveform(2, 3 * np.sin(2 * np.pi * 100 * t), [1, 3])
 966        ```
 967
 968        Args:
 969            waveform_number: The waveform to load, 1 to
 970                `DeviceInfo.n_waveforms`.
 971            waveform: Voltages of the samples, played at
 972                `WavePalDevice.sampling_rate`. A list, tuple or NumPy
 973                array of 1 to `DeviceInfo.max_samples` values, all within
 974                `WavePalDevice.output_range`.
 975            channels: Output channels that play this waveform, from their
 976                next start: one channel number 1-4, or several as a list,
 977                tuple or NumPy array. It sets their
 978                `WavePalDevice.current_waveform`, and leaves the other
 979                channels' alone, so channels already playing this waveform
 980                play the new one. `None`, the default, changes no channel.
 981
 982        Raises:
 983            PulsePalError: If an argument is invalid, or the device could
 984                not store the waveform. The waveform is then left out of
 985                `WavePalDevice.waveforms`: outside param sync mode the
 986                device has unloaded it, and in param sync mode it plays the
 987                version made current at the last edge.
 988        """
 989        number = self._waveform_number(waveform_number)
 990        channel_list = None if channels is None else _common.channel_numbers(channels)
 991        samples = np.array(waveform, dtype=float).ravel()
 992        if not 1 <= samples.size <= self.info.max_samples:
 993            raise PulsePalError(
 994                f"A waveform must have 1 to {self.info.max_samples} samples. "
 995                f"Received {samples.size}."
 996            )
 997        codes = self._volts_to_codes(samples)
 998        self._waveforms[number] = None  # Until the device has stored it. Outside param sync mode, it unloads it first.
 999        self._write_command(
1000            self._OP_LOAD_WAVEFORM,
1001            struct.pack("<BI", number, samples.size) + codes.tobytes(),
1002        )
1003        self._read_ack("load_waveform()")
1004        samples.flags.writeable = False
1005        self._waveforms[number] = samples
1006        if channel_list:
1007            values = list(self._current_waveform[1:])
1008            for channel in channel_list:
1009                values[channel - 1] = number
1010            self._current_waveform._assign(values)
1011
1012    def trigger(self, channels):
1013        """Trigger output channels in software.
1014
1015        Idle channels start their current waveforms from the first
1016        sample, together. Channels that are playing ignore it, as Pulse
1017        Pal's channels ignore a soft trigger while they play a pulse train.
1018
1019        ```python
1020        W.trigger(1)
1021        W.trigger([2, 4])     # a list, tuple or NumPy array
1022        ```
1023
1024        Args:
1025            channels: Output channel number 1-4, or several as a list,
1026                tuple or NumPy array.
1027
1028        Raises:
1029            PulsePalError: If a channel has no waveform to play: its
1030                `WavePalDevice.current_waveform` is 0, or a waveform this
1031                object has not loaded, or it is in Sync mode (see
1032                `WavePalDevice.output_mode`). Nothing is sent.
1033        """
1034        channel_list = _common.channel_numbers(channels)
1035        for channel in channel_list:
1036            if self._output_mode[channel] == "Sync":
1037                raise PulsePalError(
1038                    f"Channel {channel} is in Sync mode: it reports channel {self._sync_target[channel]}'s playback, "
1039                    f"and plays no waveform. Set output_mode[{channel}] = 'Signal' to play one."
1040                )
1041            number = self._current_waveform[channel]
1042            if number == 0:
1043                raise PulsePalError(
1044                    f"Channel {channel} has no waveform to play. Set current_waveform[{channel}] to a loaded "
1045                    f"waveform's number, or load one with load_waveform(number, waveform, {channel})."
1046                )
1047            if self._waveforms[number] is None:
1048                raise PulsePalError(
1049                    f"Channel {channel} plays waveform {number}, which is not loaded. Load it with "
1050                    f"load_waveform({number}, waveform)."
1051                )
1052        self._write_command(self._OP_TRIGGER, bytes([_common.channel_bits(channel_list)]))
1053
1054    def stop(self, channels=None):
1055        """Stop playback. The stopped channels output 0 V.
1056
1057        Channels in Sync mode are left alone: they go low once the channels
1058        they report stop. See `WavePalDevice.output_mode`.
1059
1060        Args:
1061            channels: Output channel number 1-4, or several as a list,
1062                tuple or NumPy array. `None` stops all channels.
1063        """
1064        bits = self._ALL_CHANNELS if channels is None else _common.channel_bits(channels)
1065        self._write_command(self._OP_STOP, bytes([bits]))
1066
1067    def set_fixed_voltage(self, channels, voltage):
1068        """Set output channels to a fixed voltage.
1069
1070        Stops playback on those channels. The voltage holds until the
1071        channel is triggered or stopped.
1072
1073        Args:
1074            channels: Output channel number 1-4, or several as a list,
1075                tuple or NumPy array.
1076            voltage: Voltage, within `WavePalDevice.output_range`.
1077
1078        Raises:
1079            PulsePalError: If the voltage is outside the output range, a
1080                channel is in Sync mode, whose voltage follows its target
1081                (see `WavePalDevice.output_mode`), or the device rejects the
1082                command.
1083        """
1084        bits = _common.channel_bits(channels)
1085        for channel in _common.channel_numbers(channels):
1086            if self._output_mode[channel] == "Sync":
1087                raise PulsePalError(
1088                    f"Channel {channel} is in Sync mode: its voltage follows channel {self._sync_target[channel]}'s "
1089                    f"playback. Set output_mode[{channel}] = 'Signal' first."
1090                )
1091        code = int(self._volts_to_codes([voltage])[0])
1092        self._write_command(self._OP_SET_FIXED_VOLTAGE,
1093                            struct.pack("<BH", bits, code))
1094        self._read_ack("set_fixed_voltage()")
1095
1096    def status(self):
1097        """Read the device's playback state.
1098
1099        Returns:
1100            A `DeviceStatus`, with the channels that are playing, the
1101            number of samples in each waveform, underrun counts, the
1102            longest playback interrupt, each channel's current waveform,
1103            and what waits for a param sync edge.
1104        """
1105        self._write_command(self._OP_GET_STATUS)
1106        values = struct.unpack(
1107            self._STATUS_FORMAT,
1108            self._read_raw(struct.calcsize(self._STATUS_FORMAT)),
1109        )
1110        playing_bits = values[0]
1111        stored_load_bits = values[14]
1112        return DeviceStatus(
1113            playing=[ch for ch in range(1, 5)
1114                     if playing_bits & (1 << (ch - 1))],
1115            samples_loaded=[None, *values[1:5]],
1116            underruns=[None, *values[5:9]],
1117            longest_interrupt_us=values[9] / 1000,
1118            current_waveform=[None, *values[10:14]],
1119            stored_waveforms=[n for n in range(1, 5) if stored_load_bits & (1 << (n - 1))],
1120            stored_current_waveform=[None, *values[16:20]] if values[15] else None,
1121        )
1122
1123    def _playback_checksums(self):
1124        """For testing: what each channel played since it last started.
1125
1126        Returns two lists indexed by channel number, with index 0 unused:
1127        the number of samples played, and the sum of their DAC codes
1128        modulo 2**32. `tests/wavepal_hardware_test.py` compares them with
1129        the waveforms it loaded, to check every sample the device played.
1130        """
1131        self._write_command(self._OP_GET_PLAYBACK_CHECKSUMS)
1132        values = struct.unpack("<8I", self._read_raw(32))
1133        return [None, *values[:4]], [None, *values[4:]]
1134
1135    # ------------------------------------------------------------------
1136    # Connection
1137    # ------------------------------------------------------------------
1138
1139    def close(self):
1140        """Close the connection to the device.
1141
1142        The device stops playback on all channels, and shows its own name
1143        on its screen again, in place of "PYTHON Connected". It keeps its
1144        settings and waveforms, so TTL triggers still play them. Safe to
1145        call more than once. Called automatically when leaving a `with`
1146        block and when the object is garbage collected, so playback also
1147        stops when the last reference to the object goes.
1148
1149        """
1150        self._close(send_disconnect=True)
1151
1152    def _close(self, send_disconnect):
1153        """Close the connection. send_disconnect: tell the device first (op 81). False when the device may not
1154        run this firmware: op 81 means something else to other devices."""
1155        if getattr(self, "_closed", True):
1156            return
1157        self._closed = True
1158        self._reply_pending = None  # Nothing more is read, so a reply still to come needs no discarding
1159        try:
1160            if send_disconnect and self.port and self.port.is_open:
1161                self._write_command(self._OP_DISCONNECT)
1162        except Exception:
1163            pass  # The port may already be gone, e.g. the cable was unplugged
1164        finally:
1165            if self.port and self.port.is_open:
1166                self.port.close()
1167
1168    def __enter__(self):
1169        """Enter a `with` block, returning the connected device."""
1170        return self
1171
1172    def __exit__(self, exc_type, exc_value, traceback):
1173        """Close the port when leaving a `with` block.
1174
1175        Returns:
1176            `False`, so any exception raised in the block propagates.
1177        """
1178        self.close()
1179        return False
1180
1181    def __del__(self):
1182        """Close the port when the object is collected."""
1183        try:
1184            self.close()
1185        except Exception:
1186            # Destructors should not raise; the serial object may already be
1187            # gone during interpreter shutdown.
1188            pass
1189
1190    def __setattr__(self, name, value):
1191        """Refuse a public attribute that is not a setting, such as a misspelled one: it would program nothing (see
1192        _common.refuse_unknown_attribute())."""
1193        if name[0] != "_":
1194            _common.refuse_unknown_attribute(self, name, _SETTING_NAMES)
1195        super().__setattr__(name, value)
1196
1197    def __repr__(self):
1198        """Describe the device and its settings, e.g. with `print(W)`."""
1199        port = getattr(getattr(self, "port", None), "port", None)
1200        loaded = ", ".join(
1201            f"{number}: {'none' if w is None else f'{w.size} samples'}"
1202            for number, w in enumerate(self._waveforms) if number > 0
1203        )
1204        return (
1205            f"WavePalDevice on {port} (Wave Pal firmware "
1206            f"v{self.info.firmware_version})\n"
1207            f"sampling_rate: {self._sampling_rate} Hz\n"
1208            f"output_range: {self._output_range}\n"
1209            f"current_waveform: {list(self._current_waveform)}\n"
1210            f"loop_mode: {list(self._loop_mode)}\n"
1211            f"loop_duration: {list(self._loop_duration)}\n"
1212            f"trigger_mode: {list(self._trigger_mode)}\n"
1213            f"link_trigger_channel1: {list(self._link_trigger_channel1)}\n"
1214            f"link_trigger_channel2: {list(self._link_trigger_channel2)}\n"
1215            f"output_mode: {list(self._output_mode)}\n"
1216            f"sync_target: {list(self._sync_target)}\n"
1217            f"sync_voltage: {list(self._sync_voltage)}\n"
1218            f"waveforms: {loaded}"
1219        )
1220
1221    # ------------------------------------------------------------------
1222    # Internals
1223    # ------------------------------------------------------------------
1224
1225    def _handshake(self):
1226        """Check that the device runs a supported Wave Pal firmware."""
1227        self._write_command(self._OP_HANDSHAKE)
1228        handshake = _common.read_handshake_reply(self.port)  # Skips a reply to an earlier session's command
1229        if handshake is None:
1230            raise PulsePalError(
1231                f"No reply from the device on {self.port.port}. Is it a "
1232                "Pulse Pal 3 running Wave Pal firmware?"
1233                f" {_common.NO_REPLY_HINT}"
1234            )
1235        reply, version = handshake
1236        if reply != self._HANDSHAKE_REPLY:
1237            if reply in _common.FIRMWARE_BY_HANDSHAKE_REPLY:
1238                raise _common.other_firmware_error(reply, version, self.port.port, "Wave Pal")
1239            raise PulsePalError(
1240                "Incorrect handshake returned. Expected "
1241                f"{self._HANDSHAKE_REPLY}, received {reply}."
1242            )
1243        if version > self._CURRENT_FIRMWARE_VERSION:
1244            # New firmware only adds commands (see PROTOCOL.md), so this class still works with it
1245            warnings.warn(
1246                f"Wave Pal firmware v{version} is newer than this pulsepal package knows "
1247                f"(v{self._CURRENT_FIRMWARE_VERSION}). It works with it, but update the package to use what is "
1248                "new.", stacklevel=3)
1249        self.info.firmware_version = version
1250
1251    def _read_hardware_info(self):
1252        self._write_command(self._OP_HARDWARE_INFO)
1253        (
1254            self.info.hardware_version,
1255            self.info.n_channels,
1256            self.info.max_samples,
1257            self.info.max_sampling_rate,
1258            self.info.buffer_samples,
1259            self.info.sample_clock_hz,
1260            self.info.n_waveforms,
1261        ) = struct.unpack(
1262            self._HARDWARE_INFO_FORMAT,
1263            self._read_raw(struct.calcsize(self._HARDWARE_INFO_FORMAT)),
1264        )
1265        self._write_command(self._OP_HARDWARE_REVISION)
1266        self.info.circuit_board_revision = self._read_raw(1)[0]
1267        self._write_command(_common.OP_SERIAL_NUMBER)
1268        self.info.serial_number = _common.read_serial_number(self._read_raw)
1269
1270    def _apply_current_waveform(self, values):
1271        waveform_numbers = self._normalize_current_waveform(values)
1272        self._write_command(self._OP_SET_CURRENT_WAVEFORMS, bytes(waveform_numbers))
1273        self._read_ack("setting current_waveform")
1274        return waveform_numbers
1275
1276    def _normalize_current_waveform(self, values):
1277        """Check new current waveforms for all channels, and return them as the list holds them."""
1278        waveform_numbers = []
1279        for channel, value in enumerate(values, start=1):
1280            if (isinstance(value, (bool, np.bool_)) or not isinstance(value, numbers.Integral)
1281                    or not 0 <= value <= self.info.n_waveforms):
1282                raise PulsePalError(
1283                    f"current_waveform values are waveform numbers, 1-{self.info.n_waveforms}, or 0 for none. "
1284                    f"Received {value!r}."
1285                )
1286            value = int(value)
1287            # A channel left on a waveform whose load failed is not refused here: trigger() refuses it
1288            if value != 0 and value != self._current_waveform[channel] and self._waveforms[value] is None:
1289                raise PulsePalError(
1290                    f"Waveform {value} is not loaded. Load it with load_waveform({value}, waveform) first."
1291                )
1292            waveform_numbers.append(value)
1293        return waveform_numbers
1294
1295    def _apply_loop_mode(self, values):
1296        modes = [to_bool(value, "loop_mode") for value in values]
1297        self._write_command(self._OP_SET_LOOP_MODE, bytes(map(int, modes)))
1298        self._read_ack("setting loop_mode")
1299        return modes
1300
1301    def _apply_loop_duration(self, values):
1302        durations = self._normalize_loop_durations(values)
1303        samples = self._durations_to_samples(durations, self._sampling_rate)
1304        self._send_loop_duration_samples(samples)
1305        return durations
1306
1307    def _normalize_loop_durations(self, values):
1308        """Check new loop durations for all channels, and return them as the list holds them, in seconds."""
1309        durations = []
1310        for value in values:
1311            if isinstance(value, (bool, np.bool_)) or not isinstance(value, numbers.Real):
1312                raise PulsePalError(
1313                    f"loop_duration must be in seconds. Received {value!r}."
1314                )
1315            duration = float(value)
1316            if not math.isfinite(duration) or duration < 0:
1317                raise PulsePalError(
1318                    "loop_duration must be 0 (loop until stopped) or a "
1319                    f"positive number of seconds. Received {value!r}."
1320                )
1321            durations.append(duration)
1322        return durations
1323
1324    def _send_loop_duration_samples(self, samples):
1325        self._write_command(self._OP_SET_LOOP_DURATION,
1326                            struct.pack("<4I", *samples))
1327        self._read_ack("setting loop_duration")
1328
1329    def _durations_to_samples(self, durations, rate_hz):
1330        """Convert loop durations in seconds to samples at a sampling rate."""
1331        actual_rate = self._actual_rate(rate_hz)
1332        samples = []
1333        for duration in durations:
1334            n = round(duration * actual_rate)
1335            if duration > 0:
1336                n = max(n, 1)  # 0 samples would mean "loop until stopped"
1337            if n > self._UINT32_MAX:
1338                raise PulsePalError(
1339                    f"A loop_duration of {duration} s is too long at "
1340                    f"{rate_hz} Hz. The longest is "
1341                    f"{self._UINT32_MAX / actual_rate:.0f} s."
1342                )
1343            samples.append(n)
1344        return samples
1345
1346    def _apply_trigger_mode(self, values):
1347        names = [to_name(value, TRIGGER_MODES, "trigger mode") for value in values]
1348        self._write_command(
1349            self._OP_SET_TRIGGER_MODE,
1350            bytes(_TRIGGER_MODE_CODES[name] for name in names),
1351        )
1352        self._read_ack("setting trigger_mode")
1353        return names
1354
1355    # One op programs both trigger channels' links, so each list is sent
1356    # with the other's current values
1357    def _apply_trigger_channel1_links(self, values):
1358        links1 = [to_bool(v, "link_trigger_channel1") for v in values]
1359        self._send_trigger_links(links1, self._link_trigger_channel2[1:])
1360        return links1
1361
1362    def _apply_trigger_channel2_links(self, values):
1363        links2 = [to_bool(v, "link_trigger_channel2") for v in values]
1364        self._send_trigger_links(self._link_trigger_channel1[1:], links2)
1365        return links2
1366
1367    def _set_trigger_links(self, links1, links2):
1368        """Program both trigger channels' links with one command."""
1369        self._send_trigger_links(links1, links2)
1370        self._link_trigger_channel1._store(links1)
1371        self._link_trigger_channel2._store(links2)
1372
1373    def _send_trigger_links(self, links1, links2):
1374        self._write_command(self._OP_SET_TRIGGER_LINKS,
1375                            bytes([*map(int, links1), *map(int, links2)]))
1376        self._read_ack("setting the trigger channel links")
1377
1378    # One op programs the output modes and the sync targets, which the device
1379    # checks together, so each list is sent with the other's current values
1380    def _apply_output_mode(self, values):
1381        modes = [to_name(value, OUTPUT_MODES, "output mode") for value in values]
1382        self._send_output_modes(modes, self._sync_target[1:])
1383        return modes
1384
1385    def _apply_sync_target(self, values):
1386        targets = self._normalize_sync_targets(values)
1387        self._send_output_modes(self._output_mode[1:], targets)
1388        return targets
1389
1390    def _set_output_modes(self, modes, targets):
1391        """Program the output modes and the sync targets with one command."""
1392        self._send_output_modes(modes, targets)
1393        self._output_mode._store(modes)
1394        self._sync_target._store(targets)
1395
1396    def _send_output_modes(self, modes, targets):
1397        self._check_output_modes(modes, targets)
1398        self._write_command(self._OP_SET_OUTPUT_MODES,
1399                            bytes([*(OUTPUT_MODES.index(mode) for mode in modes), *targets]))
1400        self._read_ack("setting output_mode and sync_target")
1401
1402    def _normalize_sync_targets(self, values):
1403        """Check new sync targets for all channels, and return them as the list holds them."""
1404        targets = []
1405        for channel, value in enumerate(values, start=1):
1406            if (isinstance(value, (bool, np.bool_)) or not isinstance(value, numbers.Integral)
1407                    or not 1 <= value <= self.info.n_channels):
1408                raise PulsePalError(
1409                    f"sync_target values are output channel numbers, 1-{self.info.n_channels}. Received {value!r}."
1410                )
1411            if value == channel:
1412                raise PulsePalError(
1413                    f"sync_target[{channel}] cannot be {channel}: a channel cannot report itself. Choose another "
1414                    "output channel."
1415                )
1416            targets.append(int(value))
1417        return targets
1418
1419    @staticmethod
1420    def _check_output_modes(modes, targets):
1421        """Check that no channel in Sync mode reports a channel in Sync mode, which plays nothing."""
1422        for channel, (mode, target) in enumerate(zip(modes, targets), start=1):
1423            if mode == "Sync" and modes[target - 1] == "Sync":
1424                raise PulsePalError(
1425                    f"Channel {channel} would be in Sync mode, reporting channel {target}, which would be in Sync mode "
1426                    f"too, and plays no waveform. Set sync_target[{channel}] to a channel in Signal mode, or "
1427                    f"output_mode[{target}] to 'Signal' first."
1428                )
1429
1430    def _apply_sync_voltage(self, values):
1431        voltages = self._normalize_sync_voltages(values)
1432        self._send_sync_voltages(voltages)
1433        return voltages
1434
1435    @staticmethod
1436    def _normalize_sync_voltages(values):
1437        """Check new sync voltages for all channels, and return them as the list holds them, in volts."""
1438        low, high = _SYNC_VOLTAGE_LIMITS
1439        for value in values:
1440            # Written so that NaN fails it
1441            if isinstance(value, (bool, np.bool_)) or not isinstance(value, numbers.Real) or not low <= value <= high:
1442                raise PulsePalError(
1443                    f"sync_voltage values are in volts, {low:g} to {high:g}. Received {value!r}."
1444                )
1445        return [float(value) for value in values]
1446
1447    def _send_sync_voltages(self, voltages):
1448        # In microvolts: the device converts them to DAC codes for its output range
1449        self._write_command(self._OP_SET_SYNC_VOLTAGES,
1450                            struct.pack("<4I", *(round(volts * 1e6) for volts in voltages)))
1451        self._read_ack("setting sync_voltage")
1452
1453    def _actual_rate(self, rate_hz):
1454        # The sample period is the nearest whole number of clock cycles, computed in integers as the
1455        # firmware's setSamplingRate() does. A rate halfway between two (e.g. 3072 Hz: 7812.5 cycles)
1456        # rounds up there, where round() would round to even.
1457        clock = self.info.sample_clock_hz
1458        return clock / ((clock + rate_hz // 2) // rate_hz)
1459
1460    def _normalize_sampling_rate(self, rate):
1461        """Check a sampling rate, and return it as a whole number of Hz."""
1462        try:
1463            rate_hz = int(rate)
1464            is_whole = rate_hz == rate and not isinstance(rate, (bool, str))
1465        except (TypeError, ValueError, OverflowError):
1466            is_whole = False
1467        if not is_whole or not 1 <= rate_hz <= self.info.max_sampling_rate:
1468            raise PulsePalError(
1469                "sampling_rate must be a whole number of Hz from 1 to "
1470                f"{self.info.max_sampling_rate}. Received {rate!r}."
1471            )
1472        return rate_hz
1473
1474    def _check_output_range(self, range_name, trigger_modes):
1475        """Check that the output range can be set, with these trigger modes, and return its canonical name."""
1476        name = self._range_name(range_name)
1477        low, high = OUTPUT_RANGES[name]
1478        for number, waveform in enumerate(self._waveforms):
1479            if waveform is not None and (
1480                    waveform.min() < low or waveform.max() > high):
1481                raise PulsePalError(
1482                    f"Waveform {number} spans "
1483                    f"{waveform.min():g} V to {waveform.max():g} V, which "
1484                    f"does not fit the {name} range. Load a new waveform "
1485                    "first, or choose a wider range."
1486                )
1487        if name != self._output_range and "Param Sync" in trigger_modes:
1488            raise PulsePalError(
1489                "output_range cannot change while a trigger channel is in param sync mode: the waveforms are "
1490                "loaded again for the new range, and in param sync mode they would wait for a TTL edge. Set "
1491                "trigger_mode to another mode first."
1492            )
1493        return name
1494
1495    def _range_name(self, range_name):
1496        """Return the canonical name of an output range."""
1497        if isinstance(range_name, str):
1498            for name in OUTPUT_RANGES:
1499                if name.lower() == range_name.replace(" ", "").lower():
1500                    return name
1501        raise PulsePalError(
1502            f"Unknown output range: {range_name!r}. Valid ranges are "
1503            f"{', '.join(OUTPUT_RANGES)}."
1504        )
1505
1506    def _volts_to_codes(self, volts):
1507        """Convert voltages to DAC codes in the current output range."""
1508        low, high = OUTPUT_RANGES[self._output_range]
1509        volts = np.asarray(volts, dtype=float)
1510        if not np.all(np.isfinite(volts)):
1511            raise PulsePalError("Voltages must be finite numbers.")
1512        if volts.min() < low or volts.max() > high:
1513            raise PulsePalError(
1514                f"Voltages must be within the output range, {low:g} V to "
1515                f"{high:g} V. Received {volts.min():g} V to "
1516                f"{volts.max():g} V. Change output_range to use a wider "
1517                "range."
1518            )
1519        codes = np.round((volts - low) / (high - low) * self._DAC_BITMAX)
1520        return codes.astype("<u2")
1521
1522    def _waveform_number(self, number):
1523        if (
1524            not isinstance(number, numbers.Integral)
1525            or isinstance(number, (bool, np.bool_))
1526            or not 1 <= number <= self.info.n_waveforms
1527        ):
1528            raise PulsePalError(
1529                f"Waveforms are numbered 1-{self.info.n_waveforms}. Received {number!r}."
1530            )
1531        return int(number)
1532
1533    def _write_command(self, op_code, data=b""):
1534        """Send one command, with its framing byte, in a single write.
1535
1536        A command whose reply was not read in full, because the read timed out or was interrupted (Ctrl-C), leaves
1537        that reply, or the rest of it, to arrive later. Read as the reply to the next command, it would put every
1538        reply after it out of step. So it is discarded first (_discard_lost_reply()), and this command's reply, if it
1539        has one, is pending until _read_raw() has read it, as in PulsePalDevice.
1540        """
1541        if self._reply_pending is not None:
1542            self._discard_lost_reply()
1543        if op_code not in _OPS_WITHOUT_TRACKED_REPLY:
1544            self._reply_pending = op_code  # Before the write: a Ctrl-C can come as soon as it returns
1545        message = bytes([self._OP_MENU_BYTE, op_code]) + data
1546        bytes_written = self.port.write(message)
1547        if bytes_written != len(message):
1548            raise PulsePalError(
1549                f"Wrote {bytes_written} byte(s), expected to write "
1550                f"{len(message)} byte(s)."
1551            )
1552
1553    def _discard_lost_reply(self):
1554        """Discard what arrives of a reply that was not read in full (see _write_command()), and bring the device
1555        back in step with this object.
1556
1557        The command may have changed a setting, unknown to this object: an assignment interrupted after its write,
1558        for one, which the device took and this object did not. Wave Pal cannot report its settings, so the setting
1559        such a command carried is sent again as this object holds it. A change of output range unloads the device's
1560        waveforms, so after one they are loaded again too. A waveform whose load was lost is already left out of
1561        `waveforms`.
1562        """
1563        op = self._reply_pending
1564        self._reply_pending = None
1565        n_late = len(_common.read_until_quiet(self.port))
1566        send_again = op in self._SETTING_OPS
1567        _common.warn_lost_reply(f"op {chr(op)!r}", n_late,
1568                                ", and the setting it carried was sent again as this object holds it" if send_again
1569                                else "")
1570        if send_again:
1571            try:
1572                self._send_setting_again(op)
1573            except PulsePalError as exc:
1574                raise PulsePalError(f"After the reply to an earlier command was lost: {exc}") from exc
1575
1576    def _send_setting_again(self, op):
1577        """Send the setting that op carries, as this object holds it (see _discard_lost_reply())."""
1578        if op == self._OP_SET_SAMPLING_RATE:
1579            self._write_command(op, struct.pack("<I", self._sampling_rate))
1580            self._read_ack("setting sampling_rate")
1581        elif op == self._OP_SET_OUTPUT_RANGE:
1582            self._write_command(op, bytes([list(OUTPUT_RANGES).index(self._output_range)]))
1583            self._read_ack("setting output_range")
1584            waveforms = self._waveforms
1585            self._waveforms = [None] * len(waveforms)
1586            for number, waveform in enumerate(waveforms):
1587                if waveform is not None:
1588                    self.load_waveform(number, waveform)
1589        elif op == self._OP_SET_CURRENT_WAVEFORMS:
1590            self._write_command(op, bytes(self._current_waveform[1:]))
1591            self._read_ack("setting current_waveform")
1592        elif op == self._OP_SET_LOOP_MODE:
1593            self._write_command(op, bytes(map(int, self._loop_mode[1:])))
1594            self._read_ack("setting loop_mode")
1595        elif op == self._OP_SET_LOOP_DURATION:
1596            self._send_loop_duration_samples(self._durations_to_samples(self._loop_duration[1:], self._sampling_rate))
1597        elif op == self._OP_SET_TRIGGER_MODE:
1598            self._write_command(op, bytes(_TRIGGER_MODE_CODES[name] for name in self._trigger_mode[1:]))
1599            self._read_ack("setting trigger_mode")
1600        elif op == self._OP_SET_OUTPUT_MODES:
1601            self._send_output_modes(self._output_mode[1:], self._sync_target[1:])
1602        elif op == self._OP_SET_SYNC_VOLTAGES:
1603            self._send_sync_voltages(self._sync_voltage[1:])
1604        else:  # Trigger links
1605            self._send_trigger_links(self._link_trigger_channel1[1:], self._link_trigger_channel2[1:])
1606
1607    def _read_raw(self, n_bytes):
1608        """Read exactly n_bytes from the serial port: the whole reply to the command last sent, which is then no
1609        longer pending (see _write_command()). Only connecting reads a reply in more than one call."""
1610        message = self.port.read(n_bytes)
1611        if len(message) < n_bytes:
1612            raise PulsePalError(
1613                f"Wave Pal sent {len(message)} of the {n_bytes} byte(s) of its reply within "
1614                f"{self.port.timeout} s. {_common.NO_REPLY_HINT}"
1615            )
1616        self._reply_pending = None
1617        return message
1618
1619    def _read_ack(self, context):
1620        """Read a one-byte confirmation: 1 if the device executed the
1621        command, 0 if it rejected it."""
1622        try:
1623            reply = self._read_raw(1)[0]
1624        except PulsePalError as exc:
1625            raise PulsePalError(
1626                f"Wave Pal did not confirm {context}: no reply arrived within {self.port.timeout} s. "
1627                f"{_common.NO_REPLY_HINT}"
1628            ) from exc
1629        if reply != 1:
1630            raise PulsePalError(
1631                f"Wave Pal rejected {context}. A value was out of range, "
1632                "or a waveform could not be written to the microSD card."
1633            )
class WavePalDevice:
 288class WavePalDevice:
 289    """A class to control a Wave Pal on a USB serial port.
 290
 291    Creating an instance opens the serial port, checks that the device
 292    runs Wave Pal firmware, reads its properties into
 293    `WavePalDevice.info`, shows "PYTHON Connected" on the device's
 294    screen, stops any playback and programs the default settings (see
 295    `WavePalDevice.set_default_params`).
 296
 297    ```python
 298    from pulsepal import WavePalDevice
 299
 300    W = WavePalDevice("COM3")
 301    W.load_waveform(1, [0, 1, 2, 3, 4, 5, 0], 1)   # waveform 1, played by channel 1
 302    W.trigger(1)
 303    W.close()
 304    ```
 305
 306    Replace "COM3" with the device's USB serial port name, which
 307    `WavePalDevice.serialportlist` lists. `WavePalDevice` is also a
 308    context manager, which closes the port on exit.
 309
 310    Closing the connection stops playback, as it does on Pulse Pal, and
 311    puts the device's own name back on its screen. The device keeps its
 312    settings and waveforms, so TTL triggers still play them.
 313    """
 314
 315    port: "serial.Serial"
 316    """The open `serial.Serial` port connected to the device."""
 317
 318    info: DeviceInfo
 319    """Properties of the connected device. See `DeviceInfo`."""
 320
 321    _CURRENT_FIRMWARE_VERSION = 1
 322    _BAUD_RATE = _common.BAUD_RATE  # USB serial ignores it (see _common.BAUD_RATE)
 323
 324    _OP_MENU_BYTE = _common.OP_MENU_BYTE
 325    _OP_HANDSHAKE = _common.OP_HANDSHAKE
 326    _OP_DISCONNECT = 81
 327    _OP_SET_CLIENT_NAME = 89
 328    _OP_SET_SCREEN_SAVER = 99
 329    _OP_HARDWARE_REVISION = 100
 330    _OP_HARDWARE_INFO = ord("N")
 331    _OP_SET_SAMPLING_RATE = ord("S")
 332    _OP_SET_OUTPUT_RANGE = ord("R")
 333    _OP_LOAD_WAVEFORM = ord("L")
 334    _OP_SET_CURRENT_WAVEFORMS = ord("C")
 335    _OP_TRIGGER = ord("P")
 336    _OP_STOP = ord("X")
 337    _OP_SET_FIXED_VOLTAGE = ord("!")
 338    _OP_SET_LOOP_MODE = ord("O")
 339    _OP_SET_LOOP_DURATION = ord("D")
 340    _OP_SET_TRIGGER_MODE = ord("T")
 341    _OP_SET_TRIGGER_LINKS = ord("I")
 342    _OP_SET_OUTPUT_MODES = ord("M")
 343    _OP_SET_SYNC_VOLTAGES = ord("V")
 344    _OP_GET_STATUS = ord("G")
 345    _OP_GET_PLAYBACK_CHECKSUMS = ord("Z")
 346
 347    _HANDSHAKE_REPLY = 87  # 'W'
 348    _HARDWARE_INFO_FORMAT = "<BBIIIIB"
 349    _STATUS_FORMAT = "<B4I4II4BBB4B"
 350    _DAC_BITMAX = 65535
 351    _UINT32_MAX = 2**32 - 1
 352    _ALL_CHANNELS = 0x0F
 353    # The ops that carry a setting, which _discard_lost_reply() sends again if the reply to one is lost
 354    _SETTING_OPS = frozenset(map(ord, "SRCODTIMV"))
 355
 356    _reply_pending = None  # The op code of a command whose reply has not been read in full yet (see _write_command())
 357
 358    def __init__(self, port_name=None, *, serial_number=None, timeout=10):
 359        """Open a connection to a Wave Pal.
 360
 361        Args:
 362            port_name: USB serial port of the device, such as `COM3` on
 363                Windows or `/dev/ttyACM0` on Linux.
 364            serial_number: Instead of `port_name`, the device's USB serial
 365                number (`DeviceInfo.serial_number`), which finds its port
 366                wherever it is plugged in.
 367            timeout: Serial read timeout, in seconds. Loading a long
 368                waveform onto a slow microSD card can take a few seconds.
 369
 370        Firmware newer than this module knows is used with a warning: new
 371        firmware only adds commands. Update the package to use what is new.
 372
 373        Raises:
 374            PulsePalError: If the device does not reply to the handshake, or
 375                runs other firmware.
 376            serial.SerialException: If the serial port cannot be opened,
 377                e.g. because another program has it open (on Linux and
 378                macOS, another session of these classes, which lock it).
 379        """
 380        self._closed = True
 381        self.info = DeviceInfo()
 382        self._sampling_rate = None
 383        self._output_range = None
 384        self._waveforms = []  # Indexed by waveform number, once the device has said how many it stores
 385        self._current_waveform = ChannelSettings(
 386            "current_waveform", [0] * 4, self, "_apply_current_waveform")
 387        self._loop_mode = ChannelSettings(
 388            "loop_mode", [False] * 4, self, "_apply_loop_mode")
 389        self._loop_duration = ChannelSettings(
 390            "loop_duration", [0.0] * 4, self, "_apply_loop_duration")
 391        self._trigger_mode = ChannelSettings(
 392            "trigger_mode", ["Normal"] * 2, self, "_apply_trigger_mode")
 393        self._link_trigger_channel1 = ChannelSettings(
 394            "link_trigger_channel1", [False] * 4, self,
 395            "_apply_trigger_channel1_links")
 396        self._link_trigger_channel2 = ChannelSettings(
 397            "link_trigger_channel2", [False] * 4, self,
 398            "_apply_trigger_channel2_links")
 399        self._output_mode = ChannelSettings(
 400            "output_mode", ["Signal"] * 4, self, "_apply_output_mode")
 401        self._sync_target = ChannelSettings(
 402            "sync_target", list(_DEFAULT_SYNC_TARGETS), self, "_apply_sync_target")
 403        self._sync_voltage = ChannelSettings(
 404            "sync_voltage", [5.0] * 4, self, "_apply_sync_voltage")
 405
 406        port_name = _common.port_name_from(port_name, serial_number, "WavePalDevice")
 407        self.port = serial.Serial(
 408            port_name,
 409            self._BAUD_RATE,
 410            timeout=timeout,
 411            rtscts=True,
 412            # Windows opens a port for one program only. Linux and macOS let a second program open it too, and two
 413            # sessions' bytes would then interleave; exclusive locks it (flock), so a second session that also locks
 414            # it, such as another of these classes, gets an error instead
 415            exclusive=True,
 416        )
 417        self._closed = False
 418        try:
 419            # Discard anything left in the buffer by an earlier session
 420            self.port.reset_input_buffer()
 421            self._handshake()
 422            self._read_hardware_info()
 423            self._waveforms = [None] * (self.info.n_waveforms + 1)
 424            # Client name op + "PYTHON" in ASCII, shown as "PYTHON Connected"
 425            self._write_command(self._OP_SET_CLIENT_NAME, b"PYTHON")
 426            self.stop()
 427            self.set_default_params()
 428        except BaseException:
 429            # Op 81 means something else to other devices, so it is sent
 430            # only once the device has identified itself as a Wave Pal
 431            self._close(send_disconnect=self.info.firmware_version is not None)
 432            raise
 433
 434    @staticmethod
 435    def serialportlist(ports_to_list="available"):
 436        """Return the names of the USB serial ports on this computer.
 437
 438        Called on the class, without connecting to a device, to find the
 439        port name to pass to `WavePalDevice`.
 440
 441        Args:
 442            ports_to_list: `available` to list only the ports that are
 443                not already in use, or `all` to list every USB serial
 444                port. Not case sensitive.
 445
 446        Returns:
 447            Sorted list of port names, such as `["COM3", "COM7"]`.
 448
 449        Raises:
 450            PulsePalError: If `ports_to_list` is not `available` or `all`.
 451        """
 452        return _common.serialportlist(ports_to_list)
 453
 454    # ------------------------------------------------------------------
 455    # Settings
 456    # ------------------------------------------------------------------
 457
 458    def set_default_params(self):
 459        """Program the default settings on the device.
 460
 461        The defaults are both trigger channels in normal mode, a 10 kHz
 462        sampling rate, the -10 V to 10 V output range, loop mode off with
 463        loop durations of 0, no output channel linked to a trigger channel
 464        (so a TTL starts nothing until a script links it), every channel in
 465        `"Signal"` output mode, with sync targets `[2, 1, 1, 1]` and sync
 466        voltages of 5 V, and no current waveform on any channel. They match
 467        the settings the device starts with. The
 468        trigger modes are sent first: a trigger channel leaving param sync
 469        mode makes what was stored for its next edge current, and the
 470        settings after it then apply at once.
 471
 472        Loaded waveforms are kept, and loaded again if the output range
 473        changes (see `WavePalDevice.output_range`).
 474
 475        Raises:
 476            PulsePalError: If a loaded waveform does not fit the default
 477                output range, -10 V to 10 V.
 478        """
 479        self.trigger_mode = ["Normal"] * 2
 480        self.sampling_rate = 10000
 481        self.output_range = "-10V:10V"
 482        self.loop_mode = [False] * 4
 483        self.loop_duration = [0] * 4
 484        self._set_trigger_links([False] * 4, [False] * 4)
 485        self._set_output_modes(["Signal"] * 4, _DEFAULT_SYNC_TARGETS)
 486        self.sync_voltage = [5.0] * 4
 487        self.current_waveform = [0] * 4
 488
 489    @property
 490    def sampling_rate(self):
 491        """Sampling rate of all output channels, in Hz.
 492
 493        A whole number from 1 to `DeviceInfo.max_sampling_rate`. It can be
 494        changed during playback. The rate played can differ slightly from
 495        the rate set: see `WavePalDevice.actual_sampling_rate`.
 496        """
 497        return self._sampling_rate
 498
 499    @sampling_rate.setter
 500    def sampling_rate(self, rate):
 501        rate_hz = self._normalize_sampling_rate(rate)
 502        # Loop durations are sent in samples, so check that they still fit
 503        # before anything is changed
 504        loop_samples = None
 505        if self._sampling_rate is not None:
 506            loop_samples = self._durations_to_samples(
 507                self._loop_duration[1:], rate_hz)
 508        self._write_command(self._OP_SET_SAMPLING_RATE,
 509                            struct.pack("<I", rate_hz))
 510        self._read_ack("setting sampling_rate")
 511        self._sampling_rate = rate_hz
 512        if loop_samples is not None:
 513            self._send_loop_duration_samples(loop_samples)
 514
 515    @property
 516    def actual_sampling_rate(self):
 517        """The sampling rate the device plays, in Hz.
 518
 519        The device divides `DeviceInfo.sample_clock_hz` (24 MHz) by a
 520        whole number, so the rate played is the nearest one of those to
 521        `WavePalDevice.sampling_rate`. For example, 44100 Hz plays at
 522        44117.6 Hz. Rates that divide 24 MHz exactly, such as 10 kHz,
 523        25 kHz or 100 kHz, play exactly.
 524        """
 525        return self._actual_rate(self._sampling_rate)
 526
 527    @property
 528    def output_range(self):
 529        """Voltage range of all output channels.
 530
 531        One of `DeviceInfo.output_ranges`: `"0V:5V"`, `"0V:10V"`,
 532        `"-5V:5V"` or `"-10V:10V"`. The smallest range that fits the
 533        waveforms gives the finest voltage steps.
 534
 535        Changing the range stops playback, sets all outputs to 0 V, and
 536        loads the waveforms again, encoded for the new range. It raises
 537        an error, and changes nothing, if a loaded waveform does not fit
 538        the new range, or if a trigger channel is in param sync mode,
 539        where the loads would wait for a TTL edge.
 540        """
 541        return self._output_range
 542
 543    @output_range.setter
 544    def output_range(self, range_name):
 545        name = self._check_output_range(range_name, self._trigger_mode[1:])
 546        changed = name != self._output_range
 547        range_index = list(OUTPUT_RANGES).index(name)
 548        self._write_command(self._OP_SET_OUTPUT_RANGE, bytes([range_index]))
 549        self._read_ack("setting output_range")
 550        self._output_range = name
 551        if changed:
 552            # The device unloads the waveforms when the range changes,
 553            # because their samples encode voltages in the old range. The
 554            # channels keep their current waveforms.
 555            waveforms = self._waveforms
 556            self._waveforms = [None] * len(waveforms)
 557            for number, waveform in enumerate(waveforms):
 558                if waveform is not None:
 559                    self.load_waveform(number, waveform)
 560
 561    @property
 562    def current_waveform(self):
 563        """The waveform each output channel plays, by waveform number.
 564
 565        Indexed by channel number (see "Channel settings" above). Each
 566        value is the number of a waveform loaded with
 567        `WavePalDevice.load_waveform`, 1 to `DeviceInfo.n_waveforms`, or
 568        `0` for none, the default: a channel with no waveform ignores
 569        triggers. Several channels can play the same waveform.
 570
 571        A channel that is playing finishes its waveform: the new one plays
 572        from the channel's next start. In param sync mode, a change waits
 573        for the next rising edge on the param sync trigger channel (see
 574        `WavePalDevice.trigger_mode`).
 575
 576        ```python
 577        W.current_waveform[1] = 2            # channel 1 plays waveform 2
 578        W.current_waveform = [1, 1, 1, 1]    # all four play waveform 1
 579        ```
 580        """
 581        return self._current_waveform
 582
 583    @current_waveform.setter
 584    def current_waveform(self, values):
 585        self._current_waveform._assign(values)
 586
 587    @property
 588    def loop_mode(self):
 589        """Whether each output channel loops its waveform.
 590
 591        Indexed by channel number (see "Channel settings" above). `True`
 592        repeats the waveform until `WavePalDevice.loop_duration` has
 593        elapsed, or until stopped if the loop duration is 0. `False` plays
 594        it once. A change applies to playback in progress.
 595        """
 596        return self._loop_mode
 597
 598    @loop_mode.setter
 599    def loop_mode(self, values):
 600        self._loop_mode._assign(values)
 601
 602    @property
 603    def loop_duration(self):
 604        """How long each output channel loops its waveform, in seconds.
 605
 606        Indexed by channel number (see "Channel settings" above). Applies
 607        in loop mode only, and counts from the trigger. The channel stops
 608        when it has elapsed, part way through the waveform if need be. `0`
 609        loops until the channel is stopped. Durations are rounded to a
 610        whole number of samples, and a nonzero duration lasts at least
 611        one sample.
 612        """
 613        return self._loop_duration
 614
 615    @loop_duration.setter
 616    def loop_duration(self, values):
 617        self._loop_duration._assign(values)
 618
 619    @property
 620    def trigger_mode(self):
 621        """How each trigger channel acts on the output channels linked to it.
 622
 623        Indexed by trigger channel number, 1 or 2 (index 0 is unused), as
 624        in Pulse Pal. A TTL edge on a trigger channel acts on the output
 625        channels linked to it (`WavePalDevice.link_trigger_channel1`,
 626        `WavePalDevice.link_trigger_channel2`):
 627
 628        - `"Normal"`: a rising edge starts the linked channels' waveforms.
 629          Channels that are playing ignore it.
 630        - `"Toggle"`: a rising edge starts the linked channels, or stops
 631          those that are playing.
 632        - `"Gated"`: a rising edge starts the linked channels, and a
 633          falling edge stops them, unless the other trigger channel is also
 634          gated, linked to them, and still high. With loop mode on and a
 635          loop duration of 0, a waveform plays for exactly as long as the
 636          TTL is high.
 637        - `"Param Sync"`: a rising edge starts and stops nothing (the
 638          channel's links are ignored). It makes the waveforms loaded,
 639          and the `WavePalDevice.current_waveform` set, since the previous
 640          edge current. This is how the next trial's waveforms are loaded
 641          during the current trial, and played from the instant it starts.
 642        - `"Master"`: a rising edge starts the linked channels, and
 643          restarts those that are playing from their first sample.
 644
 645        The first four are Pulse Pal's trigger modes. Names are not case
 646        sensitive.
 647
 648        While a trigger channel is in param sync mode,
 649        `WavePalDevice.load_waveform` loads into a second memory block
 650        that the device keeps for each waveform. Channels go on playing
 651        the waveform it replaces, and triggers still start it, until the
 652        edge. A channel that is playing at the edge finishes what it plays,
 653        and plays the new waveform from its next start. A later load of the
 654        same waveform before the edge replaces the earlier one, and stops
 655        any channel still playing the waveform from before the previous
 656        edge, since the device reuses that memory block. Changes to
 657        `WavePalDevice.current_waveform` wait for the edge in the same
 658        way. Other settings apply at once.
 659
 660        When neither trigger channel is in param sync mode any more, what
 661        was waiting for an edge becomes current at once, so
 662        `WavePalDevice.waveforms` and `WavePalDevice.current_waveform`
 663        describe the device again. (Pulse Pal and Synth Pal discard their
 664        stored parameters and settings then; Pulse Pal makes its stored
 665        custom trains current, as this class does its waveforms.)
 666        `WavePalDevice.output_range` cannot change
 667        in param sync mode. To make the waveforms current on the same edge
 668        that starts the channels, wire the TTL to the other trigger channel
 669        as well: the param sync edge is handled first.
 670
 671        ```python
 672        W.trigger_mode[2] = "Param Sync"      # sent at once
 673        W.load_waveform(1, next_trial_wave)   # waits for trigger channel 2's next rising edge
 674        ```
 675        """
 676        return self._trigger_mode
 677
 678    @trigger_mode.setter
 679    def trigger_mode(self, values):
 680        self._trigger_mode._assign(values)
 681
 682    @property
 683    def link_trigger_channel1(self):
 684        """Whether each output channel is triggered by trigger channel 1.
 685
 686        Indexed by channel number (see "Channel settings" above). By
 687        default no output channel is linked to either trigger channel, so
 688        a TTL starts nothing until a script links it.
 689        """
 690        return self._link_trigger_channel1
 691
 692    @link_trigger_channel1.setter
 693    def link_trigger_channel1(self, values):
 694        self._link_trigger_channel1._assign(values)
 695
 696    @property
 697    def link_trigger_channel2(self):
 698        """Whether each output channel is triggered by trigger channel 2.
 699
 700        Indexed by channel number (see "Channel settings" above).
 701        """
 702        return self._link_trigger_channel2
 703
 704    @link_trigger_channel2.setter
 705    def link_trigger_channel2(self, values):
 706        self._link_trigger_channel2._assign(values)
 707
 708    @property
 709    def output_mode(self):
 710        """What each output channel outputs: `"Signal"` or `"Sync"`.
 711
 712        Indexed by channel number (see "Channel settings" above).
 713
 714        - `"Signal"`, the default: the channel plays its
 715          `WavePalDevice.current_waveform` when it is triggered.
 716        - `"Sync"`: the channel plays no waveform. It reports the playback
 717          of another output channel, its `WavePalDevice.sync_target`, as a
 718          TTL logic level: `WavePalDevice.sync_voltage` while the target
 719          plays, and 0 V otherwise. It goes high on the same output update
 720          as the target's first sample, and low on the update that returns
 721          the target to 0 V, one sample period after its last sample, or as
 722          soon as the target is stopped. So it is high for exactly the
 723          waveform's duration (or loop duration). A restart in master mode
 724          leaves it high.
 725
 726        A channel in Sync mode ignores triggers, its trigger links and
 727        `WavePalDevice.stop`, and `WavePalDevice.trigger` and
 728        `WavePalDevice.set_fixed_voltage` raise an error for it. A channel
 729        entering Sync mode stops playing, and takes its target's level at
 730        once. A channel cannot report another channel in Sync mode, which
 731        plays nothing. Names are not case sensitive. In param sync mode, a
 732        change applies at once.
 733
 734        ```python
 735        W.output_mode[2] = "Sync"   # channel 2 reports channel 1, its default sync_target
 736        ```
 737        """
 738        return self._output_mode
 739
 740    @output_mode.setter
 741    def output_mode(self, values):
 742        self._output_mode._assign(values)
 743
 744    @property
 745    def sync_target(self):
 746        """The output channel each channel reports in Sync mode.
 747
 748        Indexed by channel number (see "Channel settings" above). Each
 749        value is another output channel's number, 1-4: a channel cannot
 750        report itself, and a channel in Sync mode cannot report one that is
 751        in Sync mode too. Only channels in Sync mode use it (see
 752        `WavePalDevice.output_mode`). The default is `[2, 1, 1, 1]`:
 753        channel 1 reports channel 2, and the others report channel 1.
 754
 755        ```python
 756        W.sync_target[4] = 3
 757        W.output_mode[4] = "Sync"   # channel 4 reports channel 3
 758        ```
 759        """
 760        return self._sync_target
 761
 762    @sync_target.setter
 763    def sync_target(self, values):
 764        self._sync_target._assign(values)
 765
 766    @property
 767    def sync_voltage(self):
 768        """Each channel's voltage in Sync mode while its target plays, in volts.
 769
 770        Indexed by channel number (see "Channel settings" above). 3 V to
 771        5 V, and 5 V by default. Only channels in Sync mode use it (see
 772        `WavePalDevice.output_mode`). It is the same in every
 773        `WavePalDevice.output_range`, so changing the range does not change
 774        it. A sync output that is high goes to a new voltage at once.
 775        """
 776        return self._sync_voltage
 777
 778    @sync_voltage.setter
 779    def sync_voltage(self, values):
 780        self._sync_voltage._assign(values)
 781
 782    def set_screen_saver(self, enabled, timeout=1800):
 783        """Switch the device's screen saver on or off, and set its timeout.
 784
 785        With the screen saver on, the device dims its screen once it has
 786        been left alone for `timeout` seconds: no command from a computer,
 787        no rising edge on a trigger channel, and no joystick click or
 788        push. The next of these brings the screen back. The device keeps
 789        both settings in its EEPROM, shared with Pulse Pal and Synth Pal
 790        firmware, and saves them once no channel is playing. A new device
 791        starts with the screen saver on and 1800 s.
 792
 793        Args:
 794            enabled: `True` to switch the screen saver on, `False` to
 795                switch it off.
 796            timeout: Seconds without activity before the screen dims, 1 to
 797                65535. It is sent with every call, so leaving it out sets
 798                1800 s.
 799
 800        Raises:
 801            PulsePalError: If a value is out of range.
 802        """
 803        state = to_bool(enabled, "enabled")
 804        if isinstance(timeout, (bool, np.bool_)) \
 805                or not isinstance(timeout, numbers.Integral) \
 806                or not 1 <= timeout <= 65535:
 807            raise PulsePalError(
 808                "timeout must be a whole number of seconds from 1 to 65535. "
 809                f"Received {timeout!r}."
 810            )
 811        self._write_command(self._OP_SET_SCREEN_SAVER,
 812                            struct.pack("<BH", int(state), int(timeout)))
 813        self._read_ack("set_screen_saver()")
 814
 815    def export_params(self):
 816        """Return every setting, as a dict of plain values and lists.
 817
 818        Keyed by setting name: `"sampling_rate"` and `"output_range"`, then
 819        the channel settings, each with one value per channel and no
 820        unused index 0. It holds only numbers, booleans and names, so it
 821        can be saved with `json` and logged with your data. The waveforms
 822        are not part of it: `WavePalDevice.waveforms` holds them.
 823
 824        ```python
 825        import json
 826        with open("session_settings.json", "w") as f:
 827            json.dump(W.export_params(), f)
 828        ```
 829        """
 830        params = {"sampling_rate": self._sampling_rate, "output_range": self._output_range}
 831        for name in _CHANNEL_SETTINGS:
 832            params[name] = list(getattr(self, name))[1:]
 833        return params
 834
 835    def import_params(self, params):
 836        """Program the device with settings exported by `WavePalDevice.export_params`.
 837
 838        All of them are checked first, and nothing is sent if one is
 839        invalid. They are then sent in an order that lets each take
 840        effect: a trigger channel leaving param sync mode first, then the
 841        sampling rate, the output range and the channel settings, and a
 842        trigger channel entering param sync mode last. So
 843        `WavePalDevice.current_waveform` applies at once, unless a trigger
 844        channel was in param sync mode and stays in it: then it waits for
 845        the next edge, as an assignment would. Settings missing from
 846        `params` keep their values. A name that is not a setting is
 847        skipped with a warning, so that settings exported by a newer
 848        version of this package, which may have more, can still be
 849        imported.
 850
 851        The waveforms are not settings: load them with
 852        `WavePalDevice.load_waveform` first, since a current waveform must
 853        be a loaded one.
 854
 855        ```python
 856        import json
 857        with open("session_settings.json") as f:
 858            W.import_params(json.load(f))
 859        ```
 860
 861        Args:
 862            params: A dict of setting name to its value: a number for
 863                `"sampling_rate"`, a name for `"output_range"`, and one
 864                value per channel (a list, tuple or NumPy array) for the
 865                others, as `export_params` returns.
 866
 867        Raises:
 868            PulsePalError: If a value is invalid (nothing is sent), or the
 869                device rejects a setting.
 870        """
 871        names = {"sampling_rate", "output_range", *_CHANNEL_SETTINGS}
 872        unknown = [name for name in params if name not in names]
 873        if unknown:
 874            warnings.warn(f"import_params(): skipped {', '.join(map(repr, unknown))}, which this version of "
 875                          "WavePalDevice does not have.", stacklevel=2)
 876        new = {}
 877        for name in _CHANNEL_SETTINGS:
 878            if name in params:
 879                n = 2 if name == "trigger_mode" else self.info.n_channels
 880                new[name] = _common.one_value_per_channel(name, params[name], n)
 881        if "current_waveform" in new:
 882            new["current_waveform"] = self._normalize_current_waveform(new["current_waveform"])
 883        if "loop_mode" in new:
 884            new["loop_mode"] = [to_bool(value, "loop_mode") for value in new["loop_mode"]]
 885        if "loop_duration" in new:
 886            new["loop_duration"] = self._normalize_loop_durations(new["loop_duration"])
 887        for name in ("link_trigger_channel1", "link_trigger_channel2"):
 888            if name in new:
 889                new[name] = [to_bool(value, name) for value in new[name]]
 890        if "output_mode" in new:
 891            new["output_mode"] = [to_name(value, OUTPUT_MODES, "output mode") for value in new["output_mode"]]
 892        if "sync_target" in new:
 893            new["sync_target"] = self._normalize_sync_targets(new["sync_target"])
 894        if "sync_voltage" in new:
 895            new["sync_voltage"] = self._normalize_sync_voltages(new["sync_voltage"])
 896        output_modes = new.get("output_mode", list(self._output_mode)[1:])
 897        sync_targets = new.get("sync_target", list(self._sync_target)[1:])
 898        self._check_output_modes(output_modes, sync_targets)
 899        modes = list(self._trigger_mode)[1:]
 900        if "trigger_mode" in new:
 901            modes = [to_name(value, TRIGGER_MODES, "trigger mode") for value in new["trigger_mode"]]
 902        # The trigger modes the other settings are sent in: those of channels leaving param sync mode are sent
 903        # first, those of channels entering it last
 904        first_modes = [new_mode if (old == "Param Sync" and new_mode != "Param Sync") else old
 905                       for old, new_mode in zip(self._trigger_mode[1:], modes)]
 906        rate = self._sampling_rate
 907        if "sampling_rate" in params:
 908            rate = self._normalize_sampling_rate(params["sampling_rate"])
 909        range_name = self._output_range
 910        if "output_range" in params:
 911            range_name = self._check_output_range(params["output_range"], first_modes)
 912        self._durations_to_samples(new.get("loop_duration", self._loop_duration[1:]), rate)  # They fit at the rate
 913
 914        if first_modes != list(self._trigger_mode)[1:]:
 915            self.trigger_mode = first_modes
 916        if rate != self._sampling_rate:
 917            self.sampling_rate = rate
 918        if range_name != self._output_range:
 919            self.output_range = range_name
 920        for name in ("loop_mode", "loop_duration"):
 921            if name in new:
 922                setattr(self, name, new[name])
 923        if "link_trigger_channel1" in new or "link_trigger_channel2" in new:
 924            self._set_trigger_links(new.get("link_trigger_channel1", self._link_trigger_channel1[1:]),
 925                                    new.get("link_trigger_channel2", self._link_trigger_channel2[1:]))
 926        if "output_mode" in new or "sync_target" in new:
 927            self._set_output_modes(output_modes, sync_targets)
 928        if "sync_voltage" in new:
 929            self.sync_voltage = new["sync_voltage"]
 930        if "current_waveform" in new:
 931            self.current_waveform = new["current_waveform"]
 932        if modes != first_modes:
 933            self.trigger_mode = modes
 934
 935    @property
 936    def waveforms(self):
 937        """The waveforms loaded with `WavePalDevice.load_waveform`.
 938
 939        A list indexed by waveform number, 1 to `DeviceInfo.n_waveforms`,
 940        with index 0 unused. Each element is a read-only NumPy array of
 941        voltages, or `None` if this object has not loaded that waveform. In
 942        param sync mode, it holds the waveforms loaded since the last edge
 943        before the device plays them. `WavePalDevice.status` shows what
 944        the device itself holds.
 945        """
 946        return list(self._waveforms)
 947
 948    # ------------------------------------------------------------------
 949    # Waveforms and playback
 950    # ------------------------------------------------------------------
 951
 952    def load_waveform(self, waveform_number, waveform, channels=None):
 953        """Load one of the device's waveforms, and choose the channels that play it.
 954
 955        The samples are written to the device's microSD card, and the
 956        first `DeviceInfo.buffer_samples` of them are also kept in its RAM.
 957        Outside param sync mode, loading stops the channels playing that
 958        waveform, and the new one plays from their next start. Other
 959        channels keep playing. In param sync mode, the new waveform waits
 960        for the next rising edge on the param sync trigger channel, and
 961        channels go on playing the old one until then (see
 962        `WavePalDevice.trigger_mode`).
 963
 964        ```python
 965        t = np.arange(10000) / W.sampling_rate
 966        W.load_waveform(2, 3 * np.sin(2 * np.pi * 100 * t), [1, 3])
 967        ```
 968
 969        Args:
 970            waveform_number: The waveform to load, 1 to
 971                `DeviceInfo.n_waveforms`.
 972            waveform: Voltages of the samples, played at
 973                `WavePalDevice.sampling_rate`. A list, tuple or NumPy
 974                array of 1 to `DeviceInfo.max_samples` values, all within
 975                `WavePalDevice.output_range`.
 976            channels: Output channels that play this waveform, from their
 977                next start: one channel number 1-4, or several as a list,
 978                tuple or NumPy array. It sets their
 979                `WavePalDevice.current_waveform`, and leaves the other
 980                channels' alone, so channels already playing this waveform
 981                play the new one. `None`, the default, changes no channel.
 982
 983        Raises:
 984            PulsePalError: If an argument is invalid, or the device could
 985                not store the waveform. The waveform is then left out of
 986                `WavePalDevice.waveforms`: outside param sync mode the
 987                device has unloaded it, and in param sync mode it plays the
 988                version made current at the last edge.
 989        """
 990        number = self._waveform_number(waveform_number)
 991        channel_list = None if channels is None else _common.channel_numbers(channels)
 992        samples = np.array(waveform, dtype=float).ravel()
 993        if not 1 <= samples.size <= self.info.max_samples:
 994            raise PulsePalError(
 995                f"A waveform must have 1 to {self.info.max_samples} samples. "
 996                f"Received {samples.size}."
 997            )
 998        codes = self._volts_to_codes(samples)
 999        self._waveforms[number] = None  # Until the device has stored it. Outside param sync mode, it unloads it first.
1000        self._write_command(
1001            self._OP_LOAD_WAVEFORM,
1002            struct.pack("<BI", number, samples.size) + codes.tobytes(),
1003        )
1004        self._read_ack("load_waveform()")
1005        samples.flags.writeable = False
1006        self._waveforms[number] = samples
1007        if channel_list:
1008            values = list(self._current_waveform[1:])
1009            for channel in channel_list:
1010                values[channel - 1] = number
1011            self._current_waveform._assign(values)
1012
1013    def trigger(self, channels):
1014        """Trigger output channels in software.
1015
1016        Idle channels start their current waveforms from the first
1017        sample, together. Channels that are playing ignore it, as Pulse
1018        Pal's channels ignore a soft trigger while they play a pulse train.
1019
1020        ```python
1021        W.trigger(1)
1022        W.trigger([2, 4])     # a list, tuple or NumPy array
1023        ```
1024
1025        Args:
1026            channels: Output channel number 1-4, or several as a list,
1027                tuple or NumPy array.
1028
1029        Raises:
1030            PulsePalError: If a channel has no waveform to play: its
1031                `WavePalDevice.current_waveform` is 0, or a waveform this
1032                object has not loaded, or it is in Sync mode (see
1033                `WavePalDevice.output_mode`). Nothing is sent.
1034        """
1035        channel_list = _common.channel_numbers(channels)
1036        for channel in channel_list:
1037            if self._output_mode[channel] == "Sync":
1038                raise PulsePalError(
1039                    f"Channel {channel} is in Sync mode: it reports channel {self._sync_target[channel]}'s playback, "
1040                    f"and plays no waveform. Set output_mode[{channel}] = 'Signal' to play one."
1041                )
1042            number = self._current_waveform[channel]
1043            if number == 0:
1044                raise PulsePalError(
1045                    f"Channel {channel} has no waveform to play. Set current_waveform[{channel}] to a loaded "
1046                    f"waveform's number, or load one with load_waveform(number, waveform, {channel})."
1047                )
1048            if self._waveforms[number] is None:
1049                raise PulsePalError(
1050                    f"Channel {channel} plays waveform {number}, which is not loaded. Load it with "
1051                    f"load_waveform({number}, waveform)."
1052                )
1053        self._write_command(self._OP_TRIGGER, bytes([_common.channel_bits(channel_list)]))
1054
1055    def stop(self, channels=None):
1056        """Stop playback. The stopped channels output 0 V.
1057
1058        Channels in Sync mode are left alone: they go low once the channels
1059        they report stop. See `WavePalDevice.output_mode`.
1060
1061        Args:
1062            channels: Output channel number 1-4, or several as a list,
1063                tuple or NumPy array. `None` stops all channels.
1064        """
1065        bits = self._ALL_CHANNELS if channels is None else _common.channel_bits(channels)
1066        self._write_command(self._OP_STOP, bytes([bits]))
1067
1068    def set_fixed_voltage(self, channels, voltage):
1069        """Set output channels to a fixed voltage.
1070
1071        Stops playback on those channels. The voltage holds until the
1072        channel is triggered or stopped.
1073
1074        Args:
1075            channels: Output channel number 1-4, or several as a list,
1076                tuple or NumPy array.
1077            voltage: Voltage, within `WavePalDevice.output_range`.
1078
1079        Raises:
1080            PulsePalError: If the voltage is outside the output range, a
1081                channel is in Sync mode, whose voltage follows its target
1082                (see `WavePalDevice.output_mode`), or the device rejects the
1083                command.
1084        """
1085        bits = _common.channel_bits(channels)
1086        for channel in _common.channel_numbers(channels):
1087            if self._output_mode[channel] == "Sync":
1088                raise PulsePalError(
1089                    f"Channel {channel} is in Sync mode: its voltage follows channel {self._sync_target[channel]}'s "
1090                    f"playback. Set output_mode[{channel}] = 'Signal' first."
1091                )
1092        code = int(self._volts_to_codes([voltage])[0])
1093        self._write_command(self._OP_SET_FIXED_VOLTAGE,
1094                            struct.pack("<BH", bits, code))
1095        self._read_ack("set_fixed_voltage()")
1096
1097    def status(self):
1098        """Read the device's playback state.
1099
1100        Returns:
1101            A `DeviceStatus`, with the channels that are playing, the
1102            number of samples in each waveform, underrun counts, the
1103            longest playback interrupt, each channel's current waveform,
1104            and what waits for a param sync edge.
1105        """
1106        self._write_command(self._OP_GET_STATUS)
1107        values = struct.unpack(
1108            self._STATUS_FORMAT,
1109            self._read_raw(struct.calcsize(self._STATUS_FORMAT)),
1110        )
1111        playing_bits = values[0]
1112        stored_load_bits = values[14]
1113        return DeviceStatus(
1114            playing=[ch for ch in range(1, 5)
1115                     if playing_bits & (1 << (ch - 1))],
1116            samples_loaded=[None, *values[1:5]],
1117            underruns=[None, *values[5:9]],
1118            longest_interrupt_us=values[9] / 1000,
1119            current_waveform=[None, *values[10:14]],
1120            stored_waveforms=[n for n in range(1, 5) if stored_load_bits & (1 << (n - 1))],
1121            stored_current_waveform=[None, *values[16:20]] if values[15] else None,
1122        )
1123
1124    def _playback_checksums(self):
1125        """For testing: what each channel played since it last started.
1126
1127        Returns two lists indexed by channel number, with index 0 unused:
1128        the number of samples played, and the sum of their DAC codes
1129        modulo 2**32. `tests/wavepal_hardware_test.py` compares them with
1130        the waveforms it loaded, to check every sample the device played.
1131        """
1132        self._write_command(self._OP_GET_PLAYBACK_CHECKSUMS)
1133        values = struct.unpack("<8I", self._read_raw(32))
1134        return [None, *values[:4]], [None, *values[4:]]
1135
1136    # ------------------------------------------------------------------
1137    # Connection
1138    # ------------------------------------------------------------------
1139
1140    def close(self):
1141        """Close the connection to the device.
1142
1143        The device stops playback on all channels, and shows its own name
1144        on its screen again, in place of "PYTHON Connected". It keeps its
1145        settings and waveforms, so TTL triggers still play them. Safe to
1146        call more than once. Called automatically when leaving a `with`
1147        block and when the object is garbage collected, so playback also
1148        stops when the last reference to the object goes.
1149
1150        """
1151        self._close(send_disconnect=True)
1152
1153    def _close(self, send_disconnect):
1154        """Close the connection. send_disconnect: tell the device first (op 81). False when the device may not
1155        run this firmware: op 81 means something else to other devices."""
1156        if getattr(self, "_closed", True):
1157            return
1158        self._closed = True
1159        self._reply_pending = None  # Nothing more is read, so a reply still to come needs no discarding
1160        try:
1161            if send_disconnect and self.port and self.port.is_open:
1162                self._write_command(self._OP_DISCONNECT)
1163        except Exception:
1164            pass  # The port may already be gone, e.g. the cable was unplugged
1165        finally:
1166            if self.port and self.port.is_open:
1167                self.port.close()
1168
1169    def __enter__(self):
1170        """Enter a `with` block, returning the connected device."""
1171        return self
1172
1173    def __exit__(self, exc_type, exc_value, traceback):
1174        """Close the port when leaving a `with` block.
1175
1176        Returns:
1177            `False`, so any exception raised in the block propagates.
1178        """
1179        self.close()
1180        return False
1181
1182    def __del__(self):
1183        """Close the port when the object is collected."""
1184        try:
1185            self.close()
1186        except Exception:
1187            # Destructors should not raise; the serial object may already be
1188            # gone during interpreter shutdown.
1189            pass
1190
1191    def __setattr__(self, name, value):
1192        """Refuse a public attribute that is not a setting, such as a misspelled one: it would program nothing (see
1193        _common.refuse_unknown_attribute())."""
1194        if name[0] != "_":
1195            _common.refuse_unknown_attribute(self, name, _SETTING_NAMES)
1196        super().__setattr__(name, value)
1197
1198    def __repr__(self):
1199        """Describe the device and its settings, e.g. with `print(W)`."""
1200        port = getattr(getattr(self, "port", None), "port", None)
1201        loaded = ", ".join(
1202            f"{number}: {'none' if w is None else f'{w.size} samples'}"
1203            for number, w in enumerate(self._waveforms) if number > 0
1204        )
1205        return (
1206            f"WavePalDevice on {port} (Wave Pal firmware "
1207            f"v{self.info.firmware_version})\n"
1208            f"sampling_rate: {self._sampling_rate} Hz\n"
1209            f"output_range: {self._output_range}\n"
1210            f"current_waveform: {list(self._current_waveform)}\n"
1211            f"loop_mode: {list(self._loop_mode)}\n"
1212            f"loop_duration: {list(self._loop_duration)}\n"
1213            f"trigger_mode: {list(self._trigger_mode)}\n"
1214            f"link_trigger_channel1: {list(self._link_trigger_channel1)}\n"
1215            f"link_trigger_channel2: {list(self._link_trigger_channel2)}\n"
1216            f"output_mode: {list(self._output_mode)}\n"
1217            f"sync_target: {list(self._sync_target)}\n"
1218            f"sync_voltage: {list(self._sync_voltage)}\n"
1219            f"waveforms: {loaded}"
1220        )
1221
1222    # ------------------------------------------------------------------
1223    # Internals
1224    # ------------------------------------------------------------------
1225
1226    def _handshake(self):
1227        """Check that the device runs a supported Wave Pal firmware."""
1228        self._write_command(self._OP_HANDSHAKE)
1229        handshake = _common.read_handshake_reply(self.port)  # Skips a reply to an earlier session's command
1230        if handshake is None:
1231            raise PulsePalError(
1232                f"No reply from the device on {self.port.port}. Is it a "
1233                "Pulse Pal 3 running Wave Pal firmware?"
1234                f" {_common.NO_REPLY_HINT}"
1235            )
1236        reply, version = handshake
1237        if reply != self._HANDSHAKE_REPLY:
1238            if reply in _common.FIRMWARE_BY_HANDSHAKE_REPLY:
1239                raise _common.other_firmware_error(reply, version, self.port.port, "Wave Pal")
1240            raise PulsePalError(
1241                "Incorrect handshake returned. Expected "
1242                f"{self._HANDSHAKE_REPLY}, received {reply}."
1243            )
1244        if version > self._CURRENT_FIRMWARE_VERSION:
1245            # New firmware only adds commands (see PROTOCOL.md), so this class still works with it
1246            warnings.warn(
1247                f"Wave Pal firmware v{version} is newer than this pulsepal package knows "
1248                f"(v{self._CURRENT_FIRMWARE_VERSION}). It works with it, but update the package to use what is "
1249                "new.", stacklevel=3)
1250        self.info.firmware_version = version
1251
1252    def _read_hardware_info(self):
1253        self._write_command(self._OP_HARDWARE_INFO)
1254        (
1255            self.info.hardware_version,
1256            self.info.n_channels,
1257            self.info.max_samples,
1258            self.info.max_sampling_rate,
1259            self.info.buffer_samples,
1260            self.info.sample_clock_hz,
1261            self.info.n_waveforms,
1262        ) = struct.unpack(
1263            self._HARDWARE_INFO_FORMAT,
1264            self._read_raw(struct.calcsize(self._HARDWARE_INFO_FORMAT)),
1265        )
1266        self._write_command(self._OP_HARDWARE_REVISION)
1267        self.info.circuit_board_revision = self._read_raw(1)[0]
1268        self._write_command(_common.OP_SERIAL_NUMBER)
1269        self.info.serial_number = _common.read_serial_number(self._read_raw)
1270
1271    def _apply_current_waveform(self, values):
1272        waveform_numbers = self._normalize_current_waveform(values)
1273        self._write_command(self._OP_SET_CURRENT_WAVEFORMS, bytes(waveform_numbers))
1274        self._read_ack("setting current_waveform")
1275        return waveform_numbers
1276
1277    def _normalize_current_waveform(self, values):
1278        """Check new current waveforms for all channels, and return them as the list holds them."""
1279        waveform_numbers = []
1280        for channel, value in enumerate(values, start=1):
1281            if (isinstance(value, (bool, np.bool_)) or not isinstance(value, numbers.Integral)
1282                    or not 0 <= value <= self.info.n_waveforms):
1283                raise PulsePalError(
1284                    f"current_waveform values are waveform numbers, 1-{self.info.n_waveforms}, or 0 for none. "
1285                    f"Received {value!r}."
1286                )
1287            value = int(value)
1288            # A channel left on a waveform whose load failed is not refused here: trigger() refuses it
1289            if value != 0 and value != self._current_waveform[channel] and self._waveforms[value] is None:
1290                raise PulsePalError(
1291                    f"Waveform {value} is not loaded. Load it with load_waveform({value}, waveform) first."
1292                )
1293            waveform_numbers.append(value)
1294        return waveform_numbers
1295
1296    def _apply_loop_mode(self, values):
1297        modes = [to_bool(value, "loop_mode") for value in values]
1298        self._write_command(self._OP_SET_LOOP_MODE, bytes(map(int, modes)))
1299        self._read_ack("setting loop_mode")
1300        return modes
1301
1302    def _apply_loop_duration(self, values):
1303        durations = self._normalize_loop_durations(values)
1304        samples = self._durations_to_samples(durations, self._sampling_rate)
1305        self._send_loop_duration_samples(samples)
1306        return durations
1307
1308    def _normalize_loop_durations(self, values):
1309        """Check new loop durations for all channels, and return them as the list holds them, in seconds."""
1310        durations = []
1311        for value in values:
1312            if isinstance(value, (bool, np.bool_)) or not isinstance(value, numbers.Real):
1313                raise PulsePalError(
1314                    f"loop_duration must be in seconds. Received {value!r}."
1315                )
1316            duration = float(value)
1317            if not math.isfinite(duration) or duration < 0:
1318                raise PulsePalError(
1319                    "loop_duration must be 0 (loop until stopped) or a "
1320                    f"positive number of seconds. Received {value!r}."
1321                )
1322            durations.append(duration)
1323        return durations
1324
1325    def _send_loop_duration_samples(self, samples):
1326        self._write_command(self._OP_SET_LOOP_DURATION,
1327                            struct.pack("<4I", *samples))
1328        self._read_ack("setting loop_duration")
1329
1330    def _durations_to_samples(self, durations, rate_hz):
1331        """Convert loop durations in seconds to samples at a sampling rate."""
1332        actual_rate = self._actual_rate(rate_hz)
1333        samples = []
1334        for duration in durations:
1335            n = round(duration * actual_rate)
1336            if duration > 0:
1337                n = max(n, 1)  # 0 samples would mean "loop until stopped"
1338            if n > self._UINT32_MAX:
1339                raise PulsePalError(
1340                    f"A loop_duration of {duration} s is too long at "
1341                    f"{rate_hz} Hz. The longest is "
1342                    f"{self._UINT32_MAX / actual_rate:.0f} s."
1343                )
1344            samples.append(n)
1345        return samples
1346
1347    def _apply_trigger_mode(self, values):
1348        names = [to_name(value, TRIGGER_MODES, "trigger mode") for value in values]
1349        self._write_command(
1350            self._OP_SET_TRIGGER_MODE,
1351            bytes(_TRIGGER_MODE_CODES[name] for name in names),
1352        )
1353        self._read_ack("setting trigger_mode")
1354        return names
1355
1356    # One op programs both trigger channels' links, so each list is sent
1357    # with the other's current values
1358    def _apply_trigger_channel1_links(self, values):
1359        links1 = [to_bool(v, "link_trigger_channel1") for v in values]
1360        self._send_trigger_links(links1, self._link_trigger_channel2[1:])
1361        return links1
1362
1363    def _apply_trigger_channel2_links(self, values):
1364        links2 = [to_bool(v, "link_trigger_channel2") for v in values]
1365        self._send_trigger_links(self._link_trigger_channel1[1:], links2)
1366        return links2
1367
1368    def _set_trigger_links(self, links1, links2):
1369        """Program both trigger channels' links with one command."""
1370        self._send_trigger_links(links1, links2)
1371        self._link_trigger_channel1._store(links1)
1372        self._link_trigger_channel2._store(links2)
1373
1374    def _send_trigger_links(self, links1, links2):
1375        self._write_command(self._OP_SET_TRIGGER_LINKS,
1376                            bytes([*map(int, links1), *map(int, links2)]))
1377        self._read_ack("setting the trigger channel links")
1378
1379    # One op programs the output modes and the sync targets, which the device
1380    # checks together, so each list is sent with the other's current values
1381    def _apply_output_mode(self, values):
1382        modes = [to_name(value, OUTPUT_MODES, "output mode") for value in values]
1383        self._send_output_modes(modes, self._sync_target[1:])
1384        return modes
1385
1386    def _apply_sync_target(self, values):
1387        targets = self._normalize_sync_targets(values)
1388        self._send_output_modes(self._output_mode[1:], targets)
1389        return targets
1390
1391    def _set_output_modes(self, modes, targets):
1392        """Program the output modes and the sync targets with one command."""
1393        self._send_output_modes(modes, targets)
1394        self._output_mode._store(modes)
1395        self._sync_target._store(targets)
1396
1397    def _send_output_modes(self, modes, targets):
1398        self._check_output_modes(modes, targets)
1399        self._write_command(self._OP_SET_OUTPUT_MODES,
1400                            bytes([*(OUTPUT_MODES.index(mode) for mode in modes), *targets]))
1401        self._read_ack("setting output_mode and sync_target")
1402
1403    def _normalize_sync_targets(self, values):
1404        """Check new sync targets for all channels, and return them as the list holds them."""
1405        targets = []
1406        for channel, value in enumerate(values, start=1):
1407            if (isinstance(value, (bool, np.bool_)) or not isinstance(value, numbers.Integral)
1408                    or not 1 <= value <= self.info.n_channels):
1409                raise PulsePalError(
1410                    f"sync_target values are output channel numbers, 1-{self.info.n_channels}. Received {value!r}."
1411                )
1412            if value == channel:
1413                raise PulsePalError(
1414                    f"sync_target[{channel}] cannot be {channel}: a channel cannot report itself. Choose another "
1415                    "output channel."
1416                )
1417            targets.append(int(value))
1418        return targets
1419
1420    @staticmethod
1421    def _check_output_modes(modes, targets):
1422        """Check that no channel in Sync mode reports a channel in Sync mode, which plays nothing."""
1423        for channel, (mode, target) in enumerate(zip(modes, targets), start=1):
1424            if mode == "Sync" and modes[target - 1] == "Sync":
1425                raise PulsePalError(
1426                    f"Channel {channel} would be in Sync mode, reporting channel {target}, which would be in Sync mode "
1427                    f"too, and plays no waveform. Set sync_target[{channel}] to a channel in Signal mode, or "
1428                    f"output_mode[{target}] to 'Signal' first."
1429                )
1430
1431    def _apply_sync_voltage(self, values):
1432        voltages = self._normalize_sync_voltages(values)
1433        self._send_sync_voltages(voltages)
1434        return voltages
1435
1436    @staticmethod
1437    def _normalize_sync_voltages(values):
1438        """Check new sync voltages for all channels, and return them as the list holds them, in volts."""
1439        low, high = _SYNC_VOLTAGE_LIMITS
1440        for value in values:
1441            # Written so that NaN fails it
1442            if isinstance(value, (bool, np.bool_)) or not isinstance(value, numbers.Real) or not low <= value <= high:
1443                raise PulsePalError(
1444                    f"sync_voltage values are in volts, {low:g} to {high:g}. Received {value!r}."
1445                )
1446        return [float(value) for value in values]
1447
1448    def _send_sync_voltages(self, voltages):
1449        # In microvolts: the device converts them to DAC codes for its output range
1450        self._write_command(self._OP_SET_SYNC_VOLTAGES,
1451                            struct.pack("<4I", *(round(volts * 1e6) for volts in voltages)))
1452        self._read_ack("setting sync_voltage")
1453
1454    def _actual_rate(self, rate_hz):
1455        # The sample period is the nearest whole number of clock cycles, computed in integers as the
1456        # firmware's setSamplingRate() does. A rate halfway between two (e.g. 3072 Hz: 7812.5 cycles)
1457        # rounds up there, where round() would round to even.
1458        clock = self.info.sample_clock_hz
1459        return clock / ((clock + rate_hz // 2) // rate_hz)
1460
1461    def _normalize_sampling_rate(self, rate):
1462        """Check a sampling rate, and return it as a whole number of Hz."""
1463        try:
1464            rate_hz = int(rate)
1465            is_whole = rate_hz == rate and not isinstance(rate, (bool, str))
1466        except (TypeError, ValueError, OverflowError):
1467            is_whole = False
1468        if not is_whole or not 1 <= rate_hz <= self.info.max_sampling_rate:
1469            raise PulsePalError(
1470                "sampling_rate must be a whole number of Hz from 1 to "
1471                f"{self.info.max_sampling_rate}. Received {rate!r}."
1472            )
1473        return rate_hz
1474
1475    def _check_output_range(self, range_name, trigger_modes):
1476        """Check that the output range can be set, with these trigger modes, and return its canonical name."""
1477        name = self._range_name(range_name)
1478        low, high = OUTPUT_RANGES[name]
1479        for number, waveform in enumerate(self._waveforms):
1480            if waveform is not None and (
1481                    waveform.min() < low or waveform.max() > high):
1482                raise PulsePalError(
1483                    f"Waveform {number} spans "
1484                    f"{waveform.min():g} V to {waveform.max():g} V, which "
1485                    f"does not fit the {name} range. Load a new waveform "
1486                    "first, or choose a wider range."
1487                )
1488        if name != self._output_range and "Param Sync" in trigger_modes:
1489            raise PulsePalError(
1490                "output_range cannot change while a trigger channel is in param sync mode: the waveforms are "
1491                "loaded again for the new range, and in param sync mode they would wait for a TTL edge. Set "
1492                "trigger_mode to another mode first."
1493            )
1494        return name
1495
1496    def _range_name(self, range_name):
1497        """Return the canonical name of an output range."""
1498        if isinstance(range_name, str):
1499            for name in OUTPUT_RANGES:
1500                if name.lower() == range_name.replace(" ", "").lower():
1501                    return name
1502        raise PulsePalError(
1503            f"Unknown output range: {range_name!r}. Valid ranges are "
1504            f"{', '.join(OUTPUT_RANGES)}."
1505        )
1506
1507    def _volts_to_codes(self, volts):
1508        """Convert voltages to DAC codes in the current output range."""
1509        low, high = OUTPUT_RANGES[self._output_range]
1510        volts = np.asarray(volts, dtype=float)
1511        if not np.all(np.isfinite(volts)):
1512            raise PulsePalError("Voltages must be finite numbers.")
1513        if volts.min() < low or volts.max() > high:
1514            raise PulsePalError(
1515                f"Voltages must be within the output range, {low:g} V to "
1516                f"{high:g} V. Received {volts.min():g} V to "
1517                f"{volts.max():g} V. Change output_range to use a wider "
1518                "range."
1519            )
1520        codes = np.round((volts - low) / (high - low) * self._DAC_BITMAX)
1521        return codes.astype("<u2")
1522
1523    def _waveform_number(self, number):
1524        if (
1525            not isinstance(number, numbers.Integral)
1526            or isinstance(number, (bool, np.bool_))
1527            or not 1 <= number <= self.info.n_waveforms
1528        ):
1529            raise PulsePalError(
1530                f"Waveforms are numbered 1-{self.info.n_waveforms}. Received {number!r}."
1531            )
1532        return int(number)
1533
1534    def _write_command(self, op_code, data=b""):
1535        """Send one command, with its framing byte, in a single write.
1536
1537        A command whose reply was not read in full, because the read timed out or was interrupted (Ctrl-C), leaves
1538        that reply, or the rest of it, to arrive later. Read as the reply to the next command, it would put every
1539        reply after it out of step. So it is discarded first (_discard_lost_reply()), and this command's reply, if it
1540        has one, is pending until _read_raw() has read it, as in PulsePalDevice.
1541        """
1542        if self._reply_pending is not None:
1543            self._discard_lost_reply()
1544        if op_code not in _OPS_WITHOUT_TRACKED_REPLY:
1545            self._reply_pending = op_code  # Before the write: a Ctrl-C can come as soon as it returns
1546        message = bytes([self._OP_MENU_BYTE, op_code]) + data
1547        bytes_written = self.port.write(message)
1548        if bytes_written != len(message):
1549            raise PulsePalError(
1550                f"Wrote {bytes_written} byte(s), expected to write "
1551                f"{len(message)} byte(s)."
1552            )
1553
1554    def _discard_lost_reply(self):
1555        """Discard what arrives of a reply that was not read in full (see _write_command()), and bring the device
1556        back in step with this object.
1557
1558        The command may have changed a setting, unknown to this object: an assignment interrupted after its write,
1559        for one, which the device took and this object did not. Wave Pal cannot report its settings, so the setting
1560        such a command carried is sent again as this object holds it. A change of output range unloads the device's
1561        waveforms, so after one they are loaded again too. A waveform whose load was lost is already left out of
1562        `waveforms`.
1563        """
1564        op = self._reply_pending
1565        self._reply_pending = None
1566        n_late = len(_common.read_until_quiet(self.port))
1567        send_again = op in self._SETTING_OPS
1568        _common.warn_lost_reply(f"op {chr(op)!r}", n_late,
1569                                ", and the setting it carried was sent again as this object holds it" if send_again
1570                                else "")
1571        if send_again:
1572            try:
1573                self._send_setting_again(op)
1574            except PulsePalError as exc:
1575                raise PulsePalError(f"After the reply to an earlier command was lost: {exc}") from exc
1576
1577    def _send_setting_again(self, op):
1578        """Send the setting that op carries, as this object holds it (see _discard_lost_reply())."""
1579        if op == self._OP_SET_SAMPLING_RATE:
1580            self._write_command(op, struct.pack("<I", self._sampling_rate))
1581            self._read_ack("setting sampling_rate")
1582        elif op == self._OP_SET_OUTPUT_RANGE:
1583            self._write_command(op, bytes([list(OUTPUT_RANGES).index(self._output_range)]))
1584            self._read_ack("setting output_range")
1585            waveforms = self._waveforms
1586            self._waveforms = [None] * len(waveforms)
1587            for number, waveform in enumerate(waveforms):
1588                if waveform is not None:
1589                    self.load_waveform(number, waveform)
1590        elif op == self._OP_SET_CURRENT_WAVEFORMS:
1591            self._write_command(op, bytes(self._current_waveform[1:]))
1592            self._read_ack("setting current_waveform")
1593        elif op == self._OP_SET_LOOP_MODE:
1594            self._write_command(op, bytes(map(int, self._loop_mode[1:])))
1595            self._read_ack("setting loop_mode")
1596        elif op == self._OP_SET_LOOP_DURATION:
1597            self._send_loop_duration_samples(self._durations_to_samples(self._loop_duration[1:], self._sampling_rate))
1598        elif op == self._OP_SET_TRIGGER_MODE:
1599            self._write_command(op, bytes(_TRIGGER_MODE_CODES[name] for name in self._trigger_mode[1:]))
1600            self._read_ack("setting trigger_mode")
1601        elif op == self._OP_SET_OUTPUT_MODES:
1602            self._send_output_modes(self._output_mode[1:], self._sync_target[1:])
1603        elif op == self._OP_SET_SYNC_VOLTAGES:
1604            self._send_sync_voltages(self._sync_voltage[1:])
1605        else:  # Trigger links
1606            self._send_trigger_links(self._link_trigger_channel1[1:], self._link_trigger_channel2[1:])
1607
1608    def _read_raw(self, n_bytes):
1609        """Read exactly n_bytes from the serial port: the whole reply to the command last sent, which is then no
1610        longer pending (see _write_command()). Only connecting reads a reply in more than one call."""
1611        message = self.port.read(n_bytes)
1612        if len(message) < n_bytes:
1613            raise PulsePalError(
1614                f"Wave Pal sent {len(message)} of the {n_bytes} byte(s) of its reply within "
1615                f"{self.port.timeout} s. {_common.NO_REPLY_HINT}"
1616            )
1617        self._reply_pending = None
1618        return message
1619
1620    def _read_ack(self, context):
1621        """Read a one-byte confirmation: 1 if the device executed the
1622        command, 0 if it rejected it."""
1623        try:
1624            reply = self._read_raw(1)[0]
1625        except PulsePalError as exc:
1626            raise PulsePalError(
1627                f"Wave Pal did not confirm {context}: no reply arrived within {self.port.timeout} s. "
1628                f"{_common.NO_REPLY_HINT}"
1629            ) from exc
1630        if reply != 1:
1631            raise PulsePalError(
1632                f"Wave Pal rejected {context}. A value was out of range, "
1633                "or a waveform could not be written to the microSD card."
1634            )

A class to control a Wave Pal on a USB serial port.

Creating an instance opens the serial port, checks that the device runs Wave Pal firmware, reads its properties into WavePalDevice.info, shows "PYTHON Connected" on the device's screen, stops any playback and programs the default settings (see WavePalDevice.set_default_params).

from pulsepal import WavePalDevice

W = WavePalDevice("COM3")
W.load_waveform(1, [0, 1, 2, 3, 4, 5, 0], 1)   # waveform 1, played by channel 1
W.trigger(1)
W.close()

Replace "COM3" with the device's USB serial port name, which WavePalDevice.serialportlist lists. WavePalDevice is also a context manager, which closes the port on exit.

Closing the connection stops playback, as it does on Pulse Pal, and puts the device's own name back on its screen. The device keeps its settings and waveforms, so TTL triggers still play them.

WavePalDevice(port_name=None, *, serial_number=None, timeout=10)
358    def __init__(self, port_name=None, *, serial_number=None, timeout=10):
359        """Open a connection to a Wave Pal.
360
361        Args:
362            port_name: USB serial port of the device, such as `COM3` on
363                Windows or `/dev/ttyACM0` on Linux.
364            serial_number: Instead of `port_name`, the device's USB serial
365                number (`DeviceInfo.serial_number`), which finds its port
366                wherever it is plugged in.
367            timeout: Serial read timeout, in seconds. Loading a long
368                waveform onto a slow microSD card can take a few seconds.
369
370        Firmware newer than this module knows is used with a warning: new
371        firmware only adds commands. Update the package to use what is new.
372
373        Raises:
374            PulsePalError: If the device does not reply to the handshake, or
375                runs other firmware.
376            serial.SerialException: If the serial port cannot be opened,
377                e.g. because another program has it open (on Linux and
378                macOS, another session of these classes, which lock it).
379        """
380        self._closed = True
381        self.info = DeviceInfo()
382        self._sampling_rate = None
383        self._output_range = None
384        self._waveforms = []  # Indexed by waveform number, once the device has said how many it stores
385        self._current_waveform = ChannelSettings(
386            "current_waveform", [0] * 4, self, "_apply_current_waveform")
387        self._loop_mode = ChannelSettings(
388            "loop_mode", [False] * 4, self, "_apply_loop_mode")
389        self._loop_duration = ChannelSettings(
390            "loop_duration", [0.0] * 4, self, "_apply_loop_duration")
391        self._trigger_mode = ChannelSettings(
392            "trigger_mode", ["Normal"] * 2, self, "_apply_trigger_mode")
393        self._link_trigger_channel1 = ChannelSettings(
394            "link_trigger_channel1", [False] * 4, self,
395            "_apply_trigger_channel1_links")
396        self._link_trigger_channel2 = ChannelSettings(
397            "link_trigger_channel2", [False] * 4, self,
398            "_apply_trigger_channel2_links")
399        self._output_mode = ChannelSettings(
400            "output_mode", ["Signal"] * 4, self, "_apply_output_mode")
401        self._sync_target = ChannelSettings(
402            "sync_target", list(_DEFAULT_SYNC_TARGETS), self, "_apply_sync_target")
403        self._sync_voltage = ChannelSettings(
404            "sync_voltage", [5.0] * 4, self, "_apply_sync_voltage")
405
406        port_name = _common.port_name_from(port_name, serial_number, "WavePalDevice")
407        self.port = serial.Serial(
408            port_name,
409            self._BAUD_RATE,
410            timeout=timeout,
411            rtscts=True,
412            # Windows opens a port for one program only. Linux and macOS let a second program open it too, and two
413            # sessions' bytes would then interleave; exclusive locks it (flock), so a second session that also locks
414            # it, such as another of these classes, gets an error instead
415            exclusive=True,
416        )
417        self._closed = False
418        try:
419            # Discard anything left in the buffer by an earlier session
420            self.port.reset_input_buffer()
421            self._handshake()
422            self._read_hardware_info()
423            self._waveforms = [None] * (self.info.n_waveforms + 1)
424            # Client name op + "PYTHON" in ASCII, shown as "PYTHON Connected"
425            self._write_command(self._OP_SET_CLIENT_NAME, b"PYTHON")
426            self.stop()
427            self.set_default_params()
428        except BaseException:
429            # Op 81 means something else to other devices, so it is sent
430            # only once the device has identified itself as a Wave Pal
431            self._close(send_disconnect=self.info.firmware_version is not None)
432            raise

Open a connection to a Wave Pal.

Arguments:
  • port_name: USB serial port of the 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 wherever it is plugged in.
  • timeout: Serial read timeout, in seconds. Loading a long waveform onto a slow microSD card can take a few seconds.

Firmware newer than this module knows is used with a warning: new firmware only adds commands. Update the package to use what is new.

Raises:
  • PulsePalError: If the device does not reply to the handshake, or runs other firmware.
  • 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.

@staticmethod
def serialportlist(ports_to_list='available'):
434    @staticmethod
435    def serialportlist(ports_to_list="available"):
436        """Return the names of the USB serial ports on this computer.
437
438        Called on the class, without connecting to a device, to find the
439        port name to pass to `WavePalDevice`.
440
441        Args:
442            ports_to_list: `available` to list only the ports that are
443                not already in use, or `all` to list every USB serial
444                port. Not case sensitive.
445
446        Returns:
447            Sorted list of port names, such as `["COM3", "COM7"]`.
448
449        Raises:
450            PulsePalError: If `ports_to_list` is not `available` or `all`.
451        """
452        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 WavePalDevice.

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"].

Raises:
  • PulsePalError: If ports_to_list is not available or all.
def set_default_params(self):
458    def set_default_params(self):
459        """Program the default settings on the device.
460
461        The defaults are both trigger channels in normal mode, a 10 kHz
462        sampling rate, the -10 V to 10 V output range, loop mode off with
463        loop durations of 0, no output channel linked to a trigger channel
464        (so a TTL starts nothing until a script links it), every channel in
465        `"Signal"` output mode, with sync targets `[2, 1, 1, 1]` and sync
466        voltages of 5 V, and no current waveform on any channel. They match
467        the settings the device starts with. The
468        trigger modes are sent first: a trigger channel leaving param sync
469        mode makes what was stored for its next edge current, and the
470        settings after it then apply at once.
471
472        Loaded waveforms are kept, and loaded again if the output range
473        changes (see `WavePalDevice.output_range`).
474
475        Raises:
476            PulsePalError: If a loaded waveform does not fit the default
477                output range, -10 V to 10 V.
478        """
479        self.trigger_mode = ["Normal"] * 2
480        self.sampling_rate = 10000
481        self.output_range = "-10V:10V"
482        self.loop_mode = [False] * 4
483        self.loop_duration = [0] * 4
484        self._set_trigger_links([False] * 4, [False] * 4)
485        self._set_output_modes(["Signal"] * 4, _DEFAULT_SYNC_TARGETS)
486        self.sync_voltage = [5.0] * 4
487        self.current_waveform = [0] * 4

Program the default settings on the device.

The defaults are both trigger channels in normal mode, a 10 kHz sampling rate, the -10 V to 10 V output range, loop mode off with loop durations of 0, no output channel linked to a trigger channel (so a TTL starts nothing until a script links it), every channel in "Signal" output mode, with sync targets [2, 1, 1, 1] and sync voltages of 5 V, and no current waveform on any channel. They match the settings the device starts with. The trigger modes are sent first: a trigger channel leaving param sync mode makes what was stored for its next edge current, and the settings after it then apply at once.

Loaded waveforms are kept, and loaded again if the output range changes (see WavePalDevice.output_range).

Raises:
  • PulsePalError: If a loaded waveform does not fit the default output range, -10 V to 10 V.
sampling_rate
489    @property
490    def sampling_rate(self):
491        """Sampling rate of all output channels, in Hz.
492
493        A whole number from 1 to `DeviceInfo.max_sampling_rate`. It can be
494        changed during playback. The rate played can differ slightly from
495        the rate set: see `WavePalDevice.actual_sampling_rate`.
496        """
497        return self._sampling_rate

Sampling rate of all output channels, in Hz.

A whole number from 1 to DeviceInfo.max_sampling_rate. It can be changed during playback. The rate played can differ slightly from the rate set: see WavePalDevice.actual_sampling_rate.

actual_sampling_rate
515    @property
516    def actual_sampling_rate(self):
517        """The sampling rate the device plays, in Hz.
518
519        The device divides `DeviceInfo.sample_clock_hz` (24 MHz) by a
520        whole number, so the rate played is the nearest one of those to
521        `WavePalDevice.sampling_rate`. For example, 44100 Hz plays at
522        44117.6 Hz. Rates that divide 24 MHz exactly, such as 10 kHz,
523        25 kHz or 100 kHz, play exactly.
524        """
525        return self._actual_rate(self._sampling_rate)

The sampling rate the device plays, in Hz.

The device divides DeviceInfo.sample_clock_hz (24 MHz) by a whole number, so the rate played is the nearest one of those to WavePalDevice.sampling_rate. For example, 44100 Hz plays at 44117.6 Hz. Rates that divide 24 MHz exactly, such as 10 kHz, 25 kHz or 100 kHz, play exactly.

output_range
527    @property
528    def output_range(self):
529        """Voltage range of all output channels.
530
531        One of `DeviceInfo.output_ranges`: `"0V:5V"`, `"0V:10V"`,
532        `"-5V:5V"` or `"-10V:10V"`. The smallest range that fits the
533        waveforms gives the finest voltage steps.
534
535        Changing the range stops playback, sets all outputs to 0 V, and
536        loads the waveforms again, encoded for the new range. It raises
537        an error, and changes nothing, if a loaded waveform does not fit
538        the new range, or if a trigger channel is in param sync mode,
539        where the loads would wait for a TTL edge.
540        """
541        return self._output_range

Voltage range of all output channels.

One of DeviceInfo.output_ranges: "0V:5V", "0V:10V", "-5V:5V" or "-10V:10V". The smallest range that fits the waveforms gives the finest voltage steps.

Changing the range stops playback, sets all outputs to 0 V, and loads the waveforms again, encoded for the new range. It raises an error, and changes nothing, if a loaded waveform does not fit the new range, or if a trigger channel is in param sync mode, where the loads would wait for a TTL edge.

current_waveform
561    @property
562    def current_waveform(self):
563        """The waveform each output channel plays, by waveform number.
564
565        Indexed by channel number (see "Channel settings" above). Each
566        value is the number of a waveform loaded with
567        `WavePalDevice.load_waveform`, 1 to `DeviceInfo.n_waveforms`, or
568        `0` for none, the default: a channel with no waveform ignores
569        triggers. Several channels can play the same waveform.
570
571        A channel that is playing finishes its waveform: the new one plays
572        from the channel's next start. In param sync mode, a change waits
573        for the next rising edge on the param sync trigger channel (see
574        `WavePalDevice.trigger_mode`).
575
576        ```python
577        W.current_waveform[1] = 2            # channel 1 plays waveform 2
578        W.current_waveform = [1, 1, 1, 1]    # all four play waveform 1
579        ```
580        """
581        return self._current_waveform

The waveform each output channel plays, by waveform number.

Indexed by channel number (see "Channel settings" above). Each value is the number of a waveform loaded with WavePalDevice.load_waveform, 1 to DeviceInfo.n_waveforms, or 0 for none, the default: a channel with no waveform ignores triggers. Several channels can play the same waveform.

A channel that is playing finishes its waveform: the new one plays from the channel's next start. In param sync mode, a change waits for the next rising edge on the param sync trigger channel (see WavePalDevice.trigger_mode).

W.current_waveform[1] = 2            # channel 1 plays waveform 2
W.current_waveform = [1, 1, 1, 1]    # all four play waveform 1
loop_mode
587    @property
588    def loop_mode(self):
589        """Whether each output channel loops its waveform.
590
591        Indexed by channel number (see "Channel settings" above). `True`
592        repeats the waveform until `WavePalDevice.loop_duration` has
593        elapsed, or until stopped if the loop duration is 0. `False` plays
594        it once. A change applies to playback in progress.
595        """
596        return self._loop_mode

Whether each output channel loops its waveform.

Indexed by channel number (see "Channel settings" above). True repeats the waveform until WavePalDevice.loop_duration has elapsed, or until stopped if the loop duration is 0. False plays it once. A change applies to playback in progress.

loop_duration
602    @property
603    def loop_duration(self):
604        """How long each output channel loops its waveform, in seconds.
605
606        Indexed by channel number (see "Channel settings" above). Applies
607        in loop mode only, and counts from the trigger. The channel stops
608        when it has elapsed, part way through the waveform if need be. `0`
609        loops until the channel is stopped. Durations are rounded to a
610        whole number of samples, and a nonzero duration lasts at least
611        one sample.
612        """
613        return self._loop_duration

How long each output channel loops its waveform, in seconds.

Indexed by channel number (see "Channel settings" above). Applies in loop mode only, and counts from the trigger. The channel stops when it has elapsed, part way through the waveform if need be. 0 loops until the channel is stopped. Durations are rounded to a whole number of samples, and a nonzero duration lasts at least one sample.

trigger_mode
619    @property
620    def trigger_mode(self):
621        """How each trigger channel acts on the output channels linked to it.
622
623        Indexed by trigger channel number, 1 or 2 (index 0 is unused), as
624        in Pulse Pal. A TTL edge on a trigger channel acts on the output
625        channels linked to it (`WavePalDevice.link_trigger_channel1`,
626        `WavePalDevice.link_trigger_channel2`):
627
628        - `"Normal"`: a rising edge starts the linked channels' waveforms.
629          Channels that are playing ignore it.
630        - `"Toggle"`: a rising edge starts the linked channels, or stops
631          those that are playing.
632        - `"Gated"`: a rising edge starts the linked channels, and a
633          falling edge stops them, unless the other trigger channel is also
634          gated, linked to them, and still high. With loop mode on and a
635          loop duration of 0, a waveform plays for exactly as long as the
636          TTL is high.
637        - `"Param Sync"`: a rising edge starts and stops nothing (the
638          channel's links are ignored). It makes the waveforms loaded,
639          and the `WavePalDevice.current_waveform` set, since the previous
640          edge current. This is how the next trial's waveforms are loaded
641          during the current trial, and played from the instant it starts.
642        - `"Master"`: a rising edge starts the linked channels, and
643          restarts those that are playing from their first sample.
644
645        The first four are Pulse Pal's trigger modes. Names are not case
646        sensitive.
647
648        While a trigger channel is in param sync mode,
649        `WavePalDevice.load_waveform` loads into a second memory block
650        that the device keeps for each waveform. Channels go on playing
651        the waveform it replaces, and triggers still start it, until the
652        edge. A channel that is playing at the edge finishes what it plays,
653        and plays the new waveform from its next start. A later load of the
654        same waveform before the edge replaces the earlier one, and stops
655        any channel still playing the waveform from before the previous
656        edge, since the device reuses that memory block. Changes to
657        `WavePalDevice.current_waveform` wait for the edge in the same
658        way. Other settings apply at once.
659
660        When neither trigger channel is in param sync mode any more, what
661        was waiting for an edge becomes current at once, so
662        `WavePalDevice.waveforms` and `WavePalDevice.current_waveform`
663        describe the device again. (Pulse Pal and Synth Pal discard their
664        stored parameters and settings then; Pulse Pal makes its stored
665        custom trains current, as this class does its waveforms.)
666        `WavePalDevice.output_range` cannot change
667        in param sync mode. To make the waveforms current on the same edge
668        that starts the channels, wire the TTL to the other trigger channel
669        as well: the param sync edge is handled first.
670
671        ```python
672        W.trigger_mode[2] = "Param Sync"      # sent at once
673        W.load_waveform(1, next_trial_wave)   # waits for trigger channel 2's next rising edge
674        ```
675        """
676        return self._trigger_mode

How each trigger channel acts on the output channels linked to it.

Indexed by trigger channel number, 1 or 2 (index 0 is unused), as in Pulse Pal. A TTL edge on a trigger channel acts on the output channels linked to it (WavePalDevice.link_trigger_channel1, WavePalDevice.link_trigger_channel2):

  • "Normal": a rising edge starts the linked channels' waveforms. Channels that are playing ignore it.
  • "Toggle": a rising edge starts the linked channels, or stops those that are playing.
  • "Gated": a rising edge starts the linked channels, and a falling edge stops them, unless the other trigger channel is also gated, linked to them, and still high. With loop mode on and a loop duration of 0, a waveform plays for exactly as long as the TTL is high.
  • "Param Sync": a rising edge starts and stops nothing (the channel's links are ignored). It makes the waveforms loaded, and the WavePalDevice.current_waveform set, since the previous edge current. This is how the next trial's waveforms are loaded during the current trial, and played from the instant it starts.
  • "Master": a rising edge starts the linked channels, and restarts those that are playing from their first sample.

The first four are Pulse Pal's trigger modes. Names are not case sensitive.

While a trigger channel is in param sync mode, WavePalDevice.load_waveform loads into a second memory block that the device keeps for each waveform. Channels go on playing the waveform it replaces, and triggers still start it, until the edge. A channel that is playing at the edge finishes what it plays, and plays the new waveform from its next start. A later load of the same waveform before the edge replaces the earlier one, and stops any channel still playing the waveform from before the previous edge, since the device reuses that memory block. Changes to WavePalDevice.current_waveform wait for the edge in the same way. Other settings apply at once.

When neither trigger channel is in param sync mode any more, what was waiting for an edge becomes current at once, so WavePalDevice.waveforms and WavePalDevice.current_waveform describe the device again. (Pulse Pal and Synth Pal discard their stored parameters and settings then; Pulse Pal makes its stored custom trains current, as this class does its waveforms.) WavePalDevice.output_range cannot change in param sync mode. To make the waveforms current on the same edge that starts the channels, wire the TTL to the other trigger channel as well: the param sync edge is handled first.

W.trigger_mode[2] = "Param Sync"      # sent at once
W.load_waveform(1, next_trial_wave)   # waits for trigger channel 2's next rising edge
output_mode
708    @property
709    def output_mode(self):
710        """What each output channel outputs: `"Signal"` or `"Sync"`.
711
712        Indexed by channel number (see "Channel settings" above).
713
714        - `"Signal"`, the default: the channel plays its
715          `WavePalDevice.current_waveform` when it is triggered.
716        - `"Sync"`: the channel plays no waveform. It reports the playback
717          of another output channel, its `WavePalDevice.sync_target`, as a
718          TTL logic level: `WavePalDevice.sync_voltage` while the target
719          plays, and 0 V otherwise. It goes high on the same output update
720          as the target's first sample, and low on the update that returns
721          the target to 0 V, one sample period after its last sample, or as
722          soon as the target is stopped. So it is high for exactly the
723          waveform's duration (or loop duration). A restart in master mode
724          leaves it high.
725
726        A channel in Sync mode ignores triggers, its trigger links and
727        `WavePalDevice.stop`, and `WavePalDevice.trigger` and
728        `WavePalDevice.set_fixed_voltage` raise an error for it. A channel
729        entering Sync mode stops playing, and takes its target's level at
730        once. A channel cannot report another channel in Sync mode, which
731        plays nothing. Names are not case sensitive. In param sync mode, a
732        change applies at once.
733
734        ```python
735        W.output_mode[2] = "Sync"   # channel 2 reports channel 1, its default sync_target
736        ```
737        """
738        return self._output_mode

What each output channel outputs: "Signal" or "Sync".

Indexed by channel number (see "Channel settings" above).

  • "Signal", the default: the channel plays its WavePalDevice.current_waveform when it is triggered.
  • "Sync": the channel plays no waveform. It reports the playback of another output channel, its WavePalDevice.sync_target, as a TTL logic level: WavePalDevice.sync_voltage while the target plays, and 0 V otherwise. It goes high on the same output update as the target's first sample, and low on the update that returns the target to 0 V, one sample period after its last sample, or as soon as the target is stopped. So it is high for exactly the waveform's duration (or loop duration). A restart in master mode leaves it high.

A channel in Sync mode ignores triggers, its trigger links and WavePalDevice.stop, and WavePalDevice.trigger and WavePalDevice.set_fixed_voltage raise an error for it. A channel entering Sync mode stops playing, and takes its target's level at once. A channel cannot report another channel in Sync mode, which plays nothing. Names are not case sensitive. In param sync mode, a change applies at once.

W.output_mode[2] = "Sync"   # channel 2 reports channel 1, its default sync_target
sync_target
744    @property
745    def sync_target(self):
746        """The output channel each channel reports in Sync mode.
747
748        Indexed by channel number (see "Channel settings" above). Each
749        value is another output channel's number, 1-4: a channel cannot
750        report itself, and a channel in Sync mode cannot report one that is
751        in Sync mode too. Only channels in Sync mode use it (see
752        `WavePalDevice.output_mode`). The default is `[2, 1, 1, 1]`:
753        channel 1 reports channel 2, and the others report channel 1.
754
755        ```python
756        W.sync_target[4] = 3
757        W.output_mode[4] = "Sync"   # channel 4 reports channel 3
758        ```
759        """
760        return self._sync_target

The output channel each channel reports in Sync mode.

Indexed by channel number (see "Channel settings" above). Each value is another output channel's number, 1-4: a channel cannot report itself, and a channel in Sync mode cannot report one that is in Sync mode too. Only channels in Sync mode use it (see WavePalDevice.output_mode). The default is [2, 1, 1, 1]: channel 1 reports channel 2, and the others report channel 1.

W.sync_target[4] = 3
W.output_mode[4] = "Sync"   # channel 4 reports channel 3
sync_voltage
766    @property
767    def sync_voltage(self):
768        """Each channel's voltage in Sync mode while its target plays, in volts.
769
770        Indexed by channel number (see "Channel settings" above). 3 V to
771        5 V, and 5 V by default. Only channels in Sync mode use it (see
772        `WavePalDevice.output_mode`). It is the same in every
773        `WavePalDevice.output_range`, so changing the range does not change
774        it. A sync output that is high goes to a new voltage at once.
775        """
776        return self._sync_voltage

Each channel's voltage in Sync mode while its target plays, in volts.

Indexed by channel number (see "Channel settings" above). 3 V to 5 V, and 5 V by default. Only channels in Sync mode use it (see WavePalDevice.output_mode). It is the same in every WavePalDevice.output_range, so changing the range does not change it. A sync output that is high goes to a new voltage at once.

def set_screen_saver(self, enabled, timeout=1800):
782    def set_screen_saver(self, enabled, timeout=1800):
783        """Switch the device's screen saver on or off, and set its timeout.
784
785        With the screen saver on, the device dims its screen once it has
786        been left alone for `timeout` seconds: no command from a computer,
787        no rising edge on a trigger channel, and no joystick click or
788        push. The next of these brings the screen back. The device keeps
789        both settings in its EEPROM, shared with Pulse Pal and Synth Pal
790        firmware, and saves them once no channel is playing. A new device
791        starts with the screen saver on and 1800 s.
792
793        Args:
794            enabled: `True` to switch the screen saver on, `False` to
795                switch it off.
796            timeout: Seconds without activity before the screen dims, 1 to
797                65535. It is sent with every call, so leaving it out sets
798                1800 s.
799
800        Raises:
801            PulsePalError: If a value is out of range.
802        """
803        state = to_bool(enabled, "enabled")
804        if isinstance(timeout, (bool, np.bool_)) \
805                or not isinstance(timeout, numbers.Integral) \
806                or not 1 <= timeout <= 65535:
807            raise PulsePalError(
808                "timeout must be a whole number of seconds from 1 to 65535. "
809                f"Received {timeout!r}."
810            )
811        self._write_command(self._OP_SET_SCREEN_SAVER,
812                            struct.pack("<BH", int(state), int(timeout)))
813        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 a computer, no rising edge on a trigger channel, and no joystick click or push. The next of these brings the screen back. The device keeps both settings in its EEPROM, shared with Pulse Pal and Synth Pal firmware, and saves them once no channel is playing. A new device starts with the screen saver on and 1800 s.

Arguments:
  • enabled: True to switch the screen saver on, False to switch it off.
  • timeout: Seconds without activity before the screen dims, 1 to
    1. It is sent with every call, so leaving it out sets 1800 s.
Raises:
  • PulsePalError: If a value is out of range.
def export_params(self):
815    def export_params(self):
816        """Return every setting, as a dict of plain values and lists.
817
818        Keyed by setting name: `"sampling_rate"` and `"output_range"`, then
819        the channel settings, each with one value per channel and no
820        unused index 0. It holds only numbers, booleans and names, so it
821        can be saved with `json` and logged with your data. The waveforms
822        are not part of it: `WavePalDevice.waveforms` holds them.
823
824        ```python
825        import json
826        with open("session_settings.json", "w") as f:
827            json.dump(W.export_params(), f)
828        ```
829        """
830        params = {"sampling_rate": self._sampling_rate, "output_range": self._output_range}
831        for name in _CHANNEL_SETTINGS:
832            params[name] = list(getattr(self, name))[1:]
833        return params

Return every setting, as a dict of plain values and lists.

Keyed by setting name: "sampling_rate" and "output_range", then the channel settings, each with one value per channel and no unused index 0. It holds only numbers, booleans and names, so it can be saved with json and logged with your data. The waveforms are not part of it: WavePalDevice.waveforms holds them.

import json
with open("session_settings.json", "w") as f:
    json.dump(W.export_params(), f)
def import_params(self, params):
835    def import_params(self, params):
836        """Program the device with settings exported by `WavePalDevice.export_params`.
837
838        All of them are checked first, and nothing is sent if one is
839        invalid. They are then sent in an order that lets each take
840        effect: a trigger channel leaving param sync mode first, then the
841        sampling rate, the output range and the channel settings, and a
842        trigger channel entering param sync mode last. So
843        `WavePalDevice.current_waveform` applies at once, unless a trigger
844        channel was in param sync mode and stays in it: then it waits for
845        the next edge, as an assignment would. Settings missing from
846        `params` keep their values. A name that is not a setting is
847        skipped with a warning, so that settings exported by a newer
848        version of this package, which may have more, can still be
849        imported.
850
851        The waveforms are not settings: load them with
852        `WavePalDevice.load_waveform` first, since a current waveform must
853        be a loaded one.
854
855        ```python
856        import json
857        with open("session_settings.json") as f:
858            W.import_params(json.load(f))
859        ```
860
861        Args:
862            params: A dict of setting name to its value: a number for
863                `"sampling_rate"`, a name for `"output_range"`, and one
864                value per channel (a list, tuple or NumPy array) for the
865                others, as `export_params` returns.
866
867        Raises:
868            PulsePalError: If a value is invalid (nothing is sent), or the
869                device rejects a setting.
870        """
871        names = {"sampling_rate", "output_range", *_CHANNEL_SETTINGS}
872        unknown = [name for name in params if name not in names]
873        if unknown:
874            warnings.warn(f"import_params(): skipped {', '.join(map(repr, unknown))}, which this version of "
875                          "WavePalDevice does not have.", stacklevel=2)
876        new = {}
877        for name in _CHANNEL_SETTINGS:
878            if name in params:
879                n = 2 if name == "trigger_mode" else self.info.n_channels
880                new[name] = _common.one_value_per_channel(name, params[name], n)
881        if "current_waveform" in new:
882            new["current_waveform"] = self._normalize_current_waveform(new["current_waveform"])
883        if "loop_mode" in new:
884            new["loop_mode"] = [to_bool(value, "loop_mode") for value in new["loop_mode"]]
885        if "loop_duration" in new:
886            new["loop_duration"] = self._normalize_loop_durations(new["loop_duration"])
887        for name in ("link_trigger_channel1", "link_trigger_channel2"):
888            if name in new:
889                new[name] = [to_bool(value, name) for value in new[name]]
890        if "output_mode" in new:
891            new["output_mode"] = [to_name(value, OUTPUT_MODES, "output mode") for value in new["output_mode"]]
892        if "sync_target" in new:
893            new["sync_target"] = self._normalize_sync_targets(new["sync_target"])
894        if "sync_voltage" in new:
895            new["sync_voltage"] = self._normalize_sync_voltages(new["sync_voltage"])
896        output_modes = new.get("output_mode", list(self._output_mode)[1:])
897        sync_targets = new.get("sync_target", list(self._sync_target)[1:])
898        self._check_output_modes(output_modes, sync_targets)
899        modes = list(self._trigger_mode)[1:]
900        if "trigger_mode" in new:
901            modes = [to_name(value, TRIGGER_MODES, "trigger mode") for value in new["trigger_mode"]]
902        # The trigger modes the other settings are sent in: those of channels leaving param sync mode are sent
903        # first, those of channels entering it last
904        first_modes = [new_mode if (old == "Param Sync" and new_mode != "Param Sync") else old
905                       for old, new_mode in zip(self._trigger_mode[1:], modes)]
906        rate = self._sampling_rate
907        if "sampling_rate" in params:
908            rate = self._normalize_sampling_rate(params["sampling_rate"])
909        range_name = self._output_range
910        if "output_range" in params:
911            range_name = self._check_output_range(params["output_range"], first_modes)
912        self._durations_to_samples(new.get("loop_duration", self._loop_duration[1:]), rate)  # They fit at the rate
913
914        if first_modes != list(self._trigger_mode)[1:]:
915            self.trigger_mode = first_modes
916        if rate != self._sampling_rate:
917            self.sampling_rate = rate
918        if range_name != self._output_range:
919            self.output_range = range_name
920        for name in ("loop_mode", "loop_duration"):
921            if name in new:
922                setattr(self, name, new[name])
923        if "link_trigger_channel1" in new or "link_trigger_channel2" in new:
924            self._set_trigger_links(new.get("link_trigger_channel1", self._link_trigger_channel1[1:]),
925                                    new.get("link_trigger_channel2", self._link_trigger_channel2[1:]))
926        if "output_mode" in new or "sync_target" in new:
927            self._set_output_modes(output_modes, sync_targets)
928        if "sync_voltage" in new:
929            self.sync_voltage = new["sync_voltage"]
930        if "current_waveform" in new:
931            self.current_waveform = new["current_waveform"]
932        if modes != first_modes:
933            self.trigger_mode = modes

Program the device with settings exported by WavePalDevice.export_params.

All of them are checked first, and nothing is sent if one is invalid. They are then sent in an order that lets each take effect: a trigger channel leaving param sync mode first, then the sampling rate, the output range and the channel settings, and a trigger channel entering param sync mode last. So WavePalDevice.current_waveform applies at once, unless a trigger channel was in param sync mode and stays in it: then it waits for the next edge, as an assignment would. Settings missing from params keep their values. A name that is not a setting is skipped with a warning, so that settings exported by a newer version of this package, which may have more, can still be imported.

The waveforms are not settings: load them with WavePalDevice.load_waveform first, since a current waveform must be a loaded one.

import json
with open("session_settings.json") as f:
    W.import_params(json.load(f))
Arguments:
  • params: A dict of setting name to its value: a number for "sampling_rate", a name for "output_range", and one value per channel (a list, tuple or NumPy array) for the others, as export_params returns.
Raises:
  • PulsePalError: If a value is invalid (nothing is sent), or the device rejects a setting.
waveforms
935    @property
936    def waveforms(self):
937        """The waveforms loaded with `WavePalDevice.load_waveform`.
938
939        A list indexed by waveform number, 1 to `DeviceInfo.n_waveforms`,
940        with index 0 unused. Each element is a read-only NumPy array of
941        voltages, or `None` if this object has not loaded that waveform. In
942        param sync mode, it holds the waveforms loaded since the last edge
943        before the device plays them. `WavePalDevice.status` shows what
944        the device itself holds.
945        """
946        return list(self._waveforms)

The waveforms loaded with WavePalDevice.load_waveform.

A list indexed by waveform number, 1 to DeviceInfo.n_waveforms, with index 0 unused. Each element is a read-only NumPy array of voltages, or None if this object has not loaded that waveform. In param sync mode, it holds the waveforms loaded since the last edge before the device plays them. WavePalDevice.status shows what the device itself holds.

def load_waveform(self, waveform_number, waveform, channels=None):
 952    def load_waveform(self, waveform_number, waveform, channels=None):
 953        """Load one of the device's waveforms, and choose the channels that play it.
 954
 955        The samples are written to the device's microSD card, and the
 956        first `DeviceInfo.buffer_samples` of them are also kept in its RAM.
 957        Outside param sync mode, loading stops the channels playing that
 958        waveform, and the new one plays from their next start. Other
 959        channels keep playing. In param sync mode, the new waveform waits
 960        for the next rising edge on the param sync trigger channel, and
 961        channels go on playing the old one until then (see
 962        `WavePalDevice.trigger_mode`).
 963
 964        ```python
 965        t = np.arange(10000) / W.sampling_rate
 966        W.load_waveform(2, 3 * np.sin(2 * np.pi * 100 * t), [1, 3])
 967        ```
 968
 969        Args:
 970            waveform_number: The waveform to load, 1 to
 971                `DeviceInfo.n_waveforms`.
 972            waveform: Voltages of the samples, played at
 973                `WavePalDevice.sampling_rate`. A list, tuple or NumPy
 974                array of 1 to `DeviceInfo.max_samples` values, all within
 975                `WavePalDevice.output_range`.
 976            channels: Output channels that play this waveform, from their
 977                next start: one channel number 1-4, or several as a list,
 978                tuple or NumPy array. It sets their
 979                `WavePalDevice.current_waveform`, and leaves the other
 980                channels' alone, so channels already playing this waveform
 981                play the new one. `None`, the default, changes no channel.
 982
 983        Raises:
 984            PulsePalError: If an argument is invalid, or the device could
 985                not store the waveform. The waveform is then left out of
 986                `WavePalDevice.waveforms`: outside param sync mode the
 987                device has unloaded it, and in param sync mode it plays the
 988                version made current at the last edge.
 989        """
 990        number = self._waveform_number(waveform_number)
 991        channel_list = None if channels is None else _common.channel_numbers(channels)
 992        samples = np.array(waveform, dtype=float).ravel()
 993        if not 1 <= samples.size <= self.info.max_samples:
 994            raise PulsePalError(
 995                f"A waveform must have 1 to {self.info.max_samples} samples. "
 996                f"Received {samples.size}."
 997            )
 998        codes = self._volts_to_codes(samples)
 999        self._waveforms[number] = None  # Until the device has stored it. Outside param sync mode, it unloads it first.
1000        self._write_command(
1001            self._OP_LOAD_WAVEFORM,
1002            struct.pack("<BI", number, samples.size) + codes.tobytes(),
1003        )
1004        self._read_ack("load_waveform()")
1005        samples.flags.writeable = False
1006        self._waveforms[number] = samples
1007        if channel_list:
1008            values = list(self._current_waveform[1:])
1009            for channel in channel_list:
1010                values[channel - 1] = number
1011            self._current_waveform._assign(values)

Load one of the device's waveforms, and choose the channels that play it.

The samples are written to the device's microSD card, and the first DeviceInfo.buffer_samples of them are also kept in its RAM. Outside param sync mode, loading stops the channels playing that waveform, and the new one plays from their next start. Other channels keep playing. In param sync mode, the new waveform waits for the next rising edge on the param sync trigger channel, and channels go on playing the old one until then (see WavePalDevice.trigger_mode).

t = np.arange(10000) / W.sampling_rate
W.load_waveform(2, 3 * np.sin(2 * np.pi * 100 * t), [1, 3])
Arguments:
Raises:
  • PulsePalError: If an argument is invalid, or the device could not store the waveform. The waveform is then left out of WavePalDevice.waveforms: outside param sync mode the device has unloaded it, and in param sync mode it plays the version made current at the last edge.
def trigger(self, channels):
1013    def trigger(self, channels):
1014        """Trigger output channels in software.
1015
1016        Idle channels start their current waveforms from the first
1017        sample, together. Channels that are playing ignore it, as Pulse
1018        Pal's channels ignore a soft trigger while they play a pulse train.
1019
1020        ```python
1021        W.trigger(1)
1022        W.trigger([2, 4])     # a list, tuple or NumPy array
1023        ```
1024
1025        Args:
1026            channels: Output channel number 1-4, or several as a list,
1027                tuple or NumPy array.
1028
1029        Raises:
1030            PulsePalError: If a channel has no waveform to play: its
1031                `WavePalDevice.current_waveform` is 0, or a waveform this
1032                object has not loaded, or it is in Sync mode (see
1033                `WavePalDevice.output_mode`). Nothing is sent.
1034        """
1035        channel_list = _common.channel_numbers(channels)
1036        for channel in channel_list:
1037            if self._output_mode[channel] == "Sync":
1038                raise PulsePalError(
1039                    f"Channel {channel} is in Sync mode: it reports channel {self._sync_target[channel]}'s playback, "
1040                    f"and plays no waveform. Set output_mode[{channel}] = 'Signal' to play one."
1041                )
1042            number = self._current_waveform[channel]
1043            if number == 0:
1044                raise PulsePalError(
1045                    f"Channel {channel} has no waveform to play. Set current_waveform[{channel}] to a loaded "
1046                    f"waveform's number, or load one with load_waveform(number, waveform, {channel})."
1047                )
1048            if self._waveforms[number] is None:
1049                raise PulsePalError(
1050                    f"Channel {channel} plays waveform {number}, which is not loaded. Load it with "
1051                    f"load_waveform({number}, waveform)."
1052                )
1053        self._write_command(self._OP_TRIGGER, bytes([_common.channel_bits(channel_list)]))

Trigger output channels in software.

Idle channels start their current waveforms from the first sample, together. Channels that are playing ignore it, as Pulse Pal's channels ignore a soft trigger while they play a pulse train.

W.trigger(1)
W.trigger([2, 4])     # a list, tuple or NumPy array
Arguments:
  • channels: Output channel number 1-4, or several as a list, tuple or NumPy array.
Raises:
def stop(self, channels=None):
1055    def stop(self, channels=None):
1056        """Stop playback. The stopped channels output 0 V.
1057
1058        Channels in Sync mode are left alone: they go low once the channels
1059        they report stop. See `WavePalDevice.output_mode`.
1060
1061        Args:
1062            channels: Output channel number 1-4, or several as a list,
1063                tuple or NumPy array. `None` stops all channels.
1064        """
1065        bits = self._ALL_CHANNELS if channels is None else _common.channel_bits(channels)
1066        self._write_command(self._OP_STOP, bytes([bits]))

Stop playback. The stopped channels output 0 V.

Channels in Sync mode are left alone: they go low once the channels they report stop. See WavePalDevice.output_mode.

Arguments:
  • channels: Output channel number 1-4, or several as a list, tuple or NumPy array. None stops all channels.
def set_fixed_voltage(self, channels, voltage):
1068    def set_fixed_voltage(self, channels, voltage):
1069        """Set output channels to a fixed voltage.
1070
1071        Stops playback on those channels. The voltage holds until the
1072        channel is triggered or stopped.
1073
1074        Args:
1075            channels: Output channel number 1-4, or several as a list,
1076                tuple or NumPy array.
1077            voltage: Voltage, within `WavePalDevice.output_range`.
1078
1079        Raises:
1080            PulsePalError: If the voltage is outside the output range, a
1081                channel is in Sync mode, whose voltage follows its target
1082                (see `WavePalDevice.output_mode`), or the device rejects the
1083                command.
1084        """
1085        bits = _common.channel_bits(channels)
1086        for channel in _common.channel_numbers(channels):
1087            if self._output_mode[channel] == "Sync":
1088                raise PulsePalError(
1089                    f"Channel {channel} is in Sync mode: its voltage follows channel {self._sync_target[channel]}'s "
1090                    f"playback. Set output_mode[{channel}] = 'Signal' first."
1091                )
1092        code = int(self._volts_to_codes([voltage])[0])
1093        self._write_command(self._OP_SET_FIXED_VOLTAGE,
1094                            struct.pack("<BH", bits, code))
1095        self._read_ack("set_fixed_voltage()")

Set output channels to a fixed voltage.

Stops playback on those channels. The voltage holds until the channel is triggered or stopped.

Arguments:
  • channels: Output channel number 1-4, or several as a list, tuple or NumPy array.
  • voltage: Voltage, within WavePalDevice.output_range.
Raises:
  • PulsePalError: If the voltage is outside the output range, a channel is in Sync mode, whose voltage follows its target (see WavePalDevice.output_mode), or the device rejects the command.
def status(self):
1097    def status(self):
1098        """Read the device's playback state.
1099
1100        Returns:
1101            A `DeviceStatus`, with the channels that are playing, the
1102            number of samples in each waveform, underrun counts, the
1103            longest playback interrupt, each channel's current waveform,
1104            and what waits for a param sync edge.
1105        """
1106        self._write_command(self._OP_GET_STATUS)
1107        values = struct.unpack(
1108            self._STATUS_FORMAT,
1109            self._read_raw(struct.calcsize(self._STATUS_FORMAT)),
1110        )
1111        playing_bits = values[0]
1112        stored_load_bits = values[14]
1113        return DeviceStatus(
1114            playing=[ch for ch in range(1, 5)
1115                     if playing_bits & (1 << (ch - 1))],
1116            samples_loaded=[None, *values[1:5]],
1117            underruns=[None, *values[5:9]],
1118            longest_interrupt_us=values[9] / 1000,
1119            current_waveform=[None, *values[10:14]],
1120            stored_waveforms=[n for n in range(1, 5) if stored_load_bits & (1 << (n - 1))],
1121            stored_current_waveform=[None, *values[16:20]] if values[15] else None,
1122        )

Read the device's playback state.

Returns:

A DeviceStatus, with the channels that are playing, the number of samples in each waveform, underrun counts, the longest playback interrupt, each channel's current waveform, and what waits for a param sync edge.

def close(self):
1140    def close(self):
1141        """Close the connection to the device.
1142
1143        The device stops playback on all channels, and shows its own name
1144        on its screen again, in place of "PYTHON Connected". It keeps its
1145        settings and waveforms, so TTL triggers still play them. Safe to
1146        call more than once. Called automatically when leaving a `with`
1147        block and when the object is garbage collected, so playback also
1148        stops when the last reference to the object goes.
1149
1150        """
1151        self._close(send_disconnect=True)

Close the connection to the device.

The device stops playback on all channels, and shows its own name on its screen again, in place of "PYTHON Connected". It keeps its settings and waveforms, so TTL triggers still play them. Safe to call more than once. Called automatically when leaving a with block and when the object is garbage collected, so playback also stops when the last reference to the object goes.

@dataclass
class DeviceInfo:
165@dataclass
166class DeviceInfo:
167    """Properties of the connected Wave Pal.
168
169    Populated when `WavePalDevice` connects, and available as
170    `WavePalDevice.info`.
171    """
172
173    firmware_version: int = None
174    """Wave Pal firmware version running on the device."""
175
176    hardware_version: int = None
177    """Pulse Pal hardware version, e.g. `3`."""
178
179    circuit_board_revision: int = None
180    """Revision of the device's circuit board, 0-31.
181
182    The board encodes its revision on five pins, which the firmware reads
183    at startup. A board that encodes none reports `0`. To record exactly
184    which hardware ran an experiment, copy `hardware_version` and
185    `circuit_board_revision` to your data.
186    """
187
188    serial_number: str = None
189    """USB serial number of the device, e.g. `"20345420"`: the Teensy's,
190    unique to each Pulse Pal 3, and the same whichever firmware it runs.
191
192    Connect by it, wherever the device is plugged in, with
193    `WavePalDevice(serial_number="20345420")`. To record exactly which unit ran an
194    experiment, copy it to your data.
195    """
196
197    n_channels: int = None
198    """Number of output channels."""
199
200    n_waveforms: int = None
201    """Number of waveforms the device stores, numbered from 1."""
202
203    max_samples: int = None
204    """Maximum number of samples in one waveform."""
205
206    max_sampling_rate: int = None
207    """Highest sampling rate, in Hz."""
208
209    buffer_samples: int = None
210    """Samples per playback buffer.
211
212    The first `buffer_samples` samples of each waveform are kept in the
213    device's RAM, so that playback starts at once. A waveform no longer
214    than this plays without reading the microSD card.
215    """
216
217    sample_clock_hz: int = None
218    """Clock that the sample rate is divided from, in Hz.
219
220    See `WavePalDevice.actual_sampling_rate`.
221    """
222
223    output_ranges: tuple = tuple(OUTPUT_RANGES)
224    """Names of the output ranges, accepted by
225    `WavePalDevice.output_range`."""
226
227    trigger_modes: tuple = TRIGGER_MODES
228    """Names of the trigger modes, accepted by
229    `WavePalDevice.trigger_mode`."""
230
231    output_modes: tuple = OUTPUT_MODES
232    """Names of the output modes, accepted by
233    `WavePalDevice.output_mode`."""

Properties of the connected Wave Pal.

Populated when WavePalDevice connects, and available as WavePalDevice.info.

DeviceInfo( firmware_version: int = None, hardware_version: int = None, circuit_board_revision: int = None, serial_number: str = None, n_channels: int = None, n_waveforms: int = None, max_samples: int = None, max_sampling_rate: int = None, buffer_samples: int = None, sample_clock_hz: int = None, output_ranges: tuple = ('0V:5V', '0V:10V', '-5V:5V', '-10V:10V'), trigger_modes: tuple = ('Normal', 'Toggle', 'Gated', 'Param Sync', 'Master'), output_modes: tuple = ('Signal', 'Sync'))
firmware_version: int = None

Wave Pal firmware version running on the device.

hardware_version: int = None

Pulse Pal hardware version, e.g. 3.

circuit_board_revision: int = None

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

The board encodes its revision on five pins, which the firmware reads at startup. A board that encodes none reports 0. 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 WavePalDevice(serial_number="20345420"). To record exactly which unit ran an experiment, copy it to your data.

n_channels: int = None

Number of output channels.

n_waveforms: int = None

Number of waveforms the device stores, numbered from 1.

max_samples: int = None

Maximum number of samples in one waveform.

max_sampling_rate: int = None

Highest sampling rate, in Hz.

buffer_samples: int = None

Samples per playback buffer.

The first buffer_samples samples of each waveform are kept in the device's RAM, so that playback starts at once. A waveform no longer than this plays without reading the microSD card.

sample_clock_hz: int = None

Clock that the sample rate is divided from, in Hz.

See WavePalDevice.actual_sampling_rate.

output_ranges: tuple = ('0V:5V', '0V:10V', '-5V:5V', '-10V:10V')

Names of the output ranges, accepted by WavePalDevice.output_range.

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

Names of the trigger modes, accepted by WavePalDevice.trigger_mode.

output_modes: tuple = ('Signal', 'Sync')

Names of the output modes, accepted by WavePalDevice.output_mode.

@dataclass
class DeviceStatus:
236@dataclass
237class DeviceStatus:
238    """A snapshot of the device's playback state, from
239    `WavePalDevice.status`."""
240
241    playing: list
242    """Numbers of the output channels playing a waveform, e.g. `[1, 3]`."""
243
244    samples_loaded: list
245    """Samples in each waveform, `0` if it has none.
246
247    Indexed by waveform number, with index 0 unused. This is what the
248    device holds, which can include waveforms loaded by an earlier
249    connection. A load stored for a param sync edge counts from the edge.
250    """
251
252    underruns: list
253    """Underruns on each channel since the device started, indexed by
254    channel number.
255
256    An underrun is a block of samples that was not read from the microSD
257    card by the time it was due. The output then holds its last value
258    until the block arrives. See "Storage and buffering" in the
259    [Wave Pal protocol](https://github.com/sanworks/PulsePal-Firmware/blob/main/WavePal/PROTOCOL.md#storage-and-buffering).
260    """
261
262    longest_interrupt_us: float
263    """Longest run of the device's playback interrupt since the previous
264    call to `WavePalDevice.status`, in microseconds.
265
266    It must stay below the sample period, `1e6 / sampling_rate`.
267    """
268
269    current_waveform: list
270    """The waveform each output channel plays from its next start, `0` for
271    none, as the device holds it. Indexed by channel number.
272
273    In param sync mode, `WavePalDevice.current_waveform` set since the
274    last edge is in `DeviceStatus.stored_current_waveform` until the next
275    one.
276    """
277
278    stored_waveforms: list
279    """Numbers of the waveforms loaded in param sync mode since the last
280    edge, which the next edge makes current, e.g. `[2]`."""
281
282    stored_current_waveform: list
283    """The current waveforms set in param sync mode since the last edge,
284    which the next edge applies, indexed by channel number. `None` if
285    none were set."""

A snapshot of the device's playback state, from WavePalDevice.status.

DeviceStatus( playing: list, samples_loaded: list, underruns: list, longest_interrupt_us: float, current_waveform: list, stored_waveforms: list, stored_current_waveform: list)
playing: list

Numbers of the output channels playing a waveform, e.g. [1, 3].

samples_loaded: list

Samples in each waveform, 0 if it has none.

Indexed by waveform number, with index 0 unused. This is what the device holds, which can include waveforms loaded by an earlier connection. A load stored for a param sync edge counts from the edge.

underruns: list

Underruns on each channel since the device started, indexed by channel number.

An underrun is a block of samples that was not read from the microSD card by the time it was due. The output then holds its last value until the block arrives. See "Storage and buffering" in the Wave Pal protocol.

longest_interrupt_us: float

Longest run of the device's playback interrupt since the previous call to WavePalDevice.status, in microseconds.

It must stay below the sample period, 1e6 / sampling_rate.

current_waveform: list

The waveform each output channel plays from its next start, 0 for none, as the device holds it. Indexed by channel number.

In param sync mode, WavePalDevice.current_waveform set since the last edge is in DeviceStatus.stored_current_waveform until the next one.

stored_waveforms: list

Numbers of the waveforms loaded in param sync mode since the last edge, which the next edge makes current, e.g. [2].

stored_current_waveform: list

The current waveforms set in param sync mode since the last edge, which the next edge applies, indexed by channel number. None if none were set.

OUTPUT_RANGES = {'0V:5V': (0.0, 5.0), '0V:10V': (0.0, 10.0), '-5V:5V': (-5.0, 5.0), '-10V:10V': (-10.0, 10.0)}

Output ranges in order of their range index on the device, with their limits in volts. See "Output ranges" in PulsePal-Firmware/WavePal/PROTOCOL.md.

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

Names of the trigger modes. See WavePalDevice.trigger_mode.

OUTPUT_MODES = ('Signal', 'Sync')

Names of the output modes, in order of their code on the device. See WavePalDevice.output_mode.