From ba4c3f17262e684a4676d41f4c77e6bdc35d585d Mon Sep 17 00:00:00 2001 From: Kartik Khandelwal <78846877+Illtrapx@users.noreply.github.com> Date: Tue, 20 Oct 2026 15:28:40 +0200 Subject: [PATCH 1/6] fix(logic_analyzer): count pulses from the measured signal period The firmware does not implement START_COUNTING and FETCH_COUNT, so count_pulses() always returned 0. Measure the period of the signal with a capture instead, and calculate the number of pulses from it. --- pslab/instrument/logic_analyzer.py | 62 ++++++++++++------------------ tests/test_logic_analyzer.py | 48 +++++++++++++++++++++++ 2 files changed, 73 insertions(+), 37 deletions(-) diff --git a/pslab/instrument/logic_analyzer.py b/pslab/instrument/logic_analyzer.py index 8888034..42e81db 100644 --- a/pslab/instrument/logic_analyzer.py +++ b/pslab/instrument/logic_analyzer.py @@ -713,12 +713,15 @@ def get_states(self) -> Dict[str, bool]: } def count_pulses( - self, channel: str = "FRQ", interval: float = 1, block: bool = True - ) -> Union[int, None]: + self, channel: str = "FRQ", interval: float = 1, timeout: float = 1 + ) -> int: """Count pulses on a digital input. - The counter is 16 bits, so it will roll over after 65535 pulses. This - method can be used at the same time as the oscilloscope. + The number of pulses is calculated from the period of the signal, which + is measured by capturing logic events. This method can be used at the + same time as the oscilloscope. The signal must be slow enough for the + capture to resolve the time between two events, and fast enough for two + events to be captured within the timeout. Parameters ---------- @@ -727,46 +730,31 @@ def count_pulses( interval : float, optional Time in seconds during which to count pulses. The default value is 1 second. - block : bool, optional - Whether to block while counting pulses or not. If False, this - method will return None, and the pulses must be manually fetched - using :meth:`fetch_pulse_count`. Additionally, the interval - argument has no meaning if block is False; the counter will keep - counting even after the interval time has expired. The default - value is True. + timeout : float, optional + Timeout in seconds before cancelling the capture. The default value + is 1 second. Returns ------- - Union[int, None] - Number of pulses counted during the interval, or None if block is - False. + int + Number of pulses counted during the interval, or 0 if the signal is + too slow, or too fast, to be measured. """ - self._reset_prescaler() - self._device.send_byte(CP.COMMON) - self._device.send_byte(CP.START_COUNTING) - self._device.send_byte(self._channels[channel].number) - self._device.get_ack() - - if block: - time.sleep(interval) - else: - return + timestamps = self.capture( + channel, 2, modes=["sixteen rising"], timeout=timeout + )[0] - return self.fetch_pulse_count() + try: + # Sixteen rising edges are captured, so the time between two + # captured events covers 16 periods of the signal. + period = (timestamps[1] - timestamps[0]) * 1e-6 / 16 + except IndexError: + return 0 - def fetch_pulse_count(self) -> int: - """Return the number of pulses counted since calling :meth:`count_pulses`. + if period <= 0: + return 0 - Returns - ------- - int - Number of pulses counted since calling :meth:`count_pulses`. - """ - self._device.send_byte(CP.COMMON) - self._device.send_byte(CP.FETCH_COUNT) - count = self._device.get_int() - self._device.get_ack() - return count + return int(round(interval / period)) def _reset_prescaler(self): self._device.send_byte(CP.TIMING) diff --git a/tests/test_logic_analyzer.py b/tests/test_logic_analyzer.py index 550a929..51ea32b 100644 --- a/tests/test_logic_analyzer.py +++ b/tests/test_logic_analyzer.py @@ -280,3 +280,51 @@ def test_count_pulses(la): pulses = la.count_pulses("LA2", interval) expected_pulses = FREQUENCY * interval assert expected_pulses == pytest.approx(pulses, rel=0.1) # Pretty bad accuracy. + + +# The tests below do not need a connected PSLab, since the capture is mocked. + + +class FakeDevice: + """Stand-in for a SerialHandler, recording the commands it receives.""" + + def __init__(self): + self.commands = [] + + def send_byte(self, value): + self.commands.append(value) + + def send_int(self, value): + self.commands.append(value) + + def get_ack(self): + return True + + def get_byte(self): + return 0 + + def get_int(self): + return 0 + + +def test_count_pulses_from_the_measured_period(mocker): + la = LogicAnalyzer(FakeDevice()) + # A 100 kHz signal, sampled every 16th rising edge. + mocker.patch.object(la, "capture", return_value=[np.array([0, 160])]) + assert la.count_pulses("LA2", 0.2) == FREQUENCY * 0.2 + + +@pytest.mark.parametrize("timestamps", [np.array([]), np.array([500, 500])]) +def test_count_pulses_without_a_measurable_period(mocker, timestamps): + la = LogicAnalyzer(FakeDevice()) + mocker.patch.object(la, "capture", return_value=[timestamps]) + assert la.count_pulses("LA2", 0.2) == 0 + + +def test_count_pulses_does_not_use_the_firmware_counter(mocker): + device = FakeDevice() + la = LogicAnalyzer(device) + mocker.patch.object(la, "capture", return_value=[np.array([0, 160])]) + la.count_pulses("LA2", 0.2) + assert CP.START_COUNTING not in device.commands + assert CP.FETCH_COUNT not in device.commands From 62f063de32b34a8e8e5106d0fcc5208d2ee5729d Mon Sep 17 00:00:00 2001 From: Kartik Khandelwal Date: Tue, 20 Oct 2026 17:30:06 +0200 Subject: [PATCH 2/6] fix(logic_analyzer): restore the channel map and reject negative intervals count_pulses() hands a channel name to capture(), which maps that name to channel one and leaves it there, so a later capture(2, ...) selected the same input twice. Save the map and put it back in a finally block, the way measure_frequency() does. A negative interval used to raise ValueError from time.sleep(); it now raised ValueError before the capture instead of returning a negative count. The docstring claimed the method can run alongside the oscilloscope, but the capture it uses stops the logic capture and clears the shared buffer. --- pslab/instrument/logic_analyzer.py | 20 +++++++++++--- tests/test_logic_analyzer.py | 42 ++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 4 deletions(-) diff --git a/pslab/instrument/logic_analyzer.py b/pslab/instrument/logic_analyzer.py index 42e81db..5e59ed4 100644 --- a/pslab/instrument/logic_analyzer.py +++ b/pslab/instrument/logic_analyzer.py @@ -718,7 +718,7 @@ def count_pulses( """Count pulses on a digital input. The number of pulses is calculated from the period of the signal, which - is measured by capturing logic events. This method can be used at the + is measured by capturing logic events. This method cannot be used at the same time as the oscilloscope. The signal must be slow enough for the capture to resolve the time between two events, and fast enough for two events to be captured within the timeout. @@ -739,10 +739,22 @@ def count_pulses( int Number of pulses counted during the interval, or 0 if the signal is too slow, or too fast, to be measured. + + Raises + ------ + ValueError if the interval is negative. """ - timestamps = self.capture( - channel, 2, modes=["sixteen rising"], timeout=timeout - )[0] + if interval < 0: + raise ValueError("Interval cannot be negative.") + + tmp = self._channel_one_map + self._channel_one_map = channel + try: + timestamps = self.capture( + channel, 2, modes=["sixteen rising"], timeout=timeout + )[0] + finally: + self._channel_one_map = tmp try: # Sixteen rising edges are captured, so the time between two diff --git a/tests/test_logic_analyzer.py b/tests/test_logic_analyzer.py index 51ea32b..a6b7895 100644 --- a/tests/test_logic_analyzer.py +++ b/tests/test_logic_analyzer.py @@ -328,3 +328,45 @@ def test_count_pulses_does_not_use_the_firmware_counter(mocker): la.count_pulses("LA2", 0.2) assert CP.START_COUNTING not in device.commands assert CP.FETCH_COUNT not in device.commands + + +def capture_updating_the_channel_map(la, timestamps): + """Stand-in for capture(), which maps a channel name to channel one.""" + + def capture(channels, events, **kwargs): + la._check_arguments(channels, events) + return [timestamps] + + return capture + + +def test_count_pulses_restores_the_channel_map(mocker): + la = LogicAnalyzer(FakeDevice()) + mocker.patch.object( + la, + "capture", + side_effect=capture_updating_the_channel_map(la, np.array([0, 160])), + ) + assert la.count_pulses("LA2", 0.2) == FREQUENCY * 0.2 + assert la._channel_one_map == "LA1" + + +def test_count_pulses_restores_the_channel_map_when_capture_fails(mocker): + la = LogicAnalyzer(FakeDevice()) + + def capture(channels, events, **kwargs): + la._check_arguments(channels, events) + raise ValueError("capture failed") + + mocker.patch.object(la, "capture", side_effect=capture) + with pytest.raises(ValueError): + la.count_pulses("LA2", 0.2) + assert la._channel_one_map == "LA1" + + +def test_count_pulses_rejects_a_negative_interval(mocker): + la = LogicAnalyzer(FakeDevice()) + capture = mocker.patch.object(la, "capture", return_value=[np.array([0, 160])]) + with pytest.raises(ValueError): + la.count_pulses("LA2", -0.2) + assert not capture.called From ce773d49f1fefebe45bde92ac2ea4aa8b47d77fb Mon Sep 17 00:00:00 2001 From: Kartik Khandelwal <78846877+Illtrapx@users.noreply.github.com> Date: Sun, 8 Nov 2026 09:28:10 +0100 Subject: [PATCH 3/6] fix(logic_analyzer): take the pulse period modulo the counter's range The capture counter is 32 bits, so the two events can straddle a wrap when the signal is slow and the timeout long enough. The difference comes back negative and the period check returned 0 for a measurable signal. Add the counter's range to the difference when it is negative. A test with two events on either side of the wrap covers it. --- pslab/instrument/logic_analyzer.py | 7 ++++++- tests/test_logic_analyzer.py | 9 +++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/pslab/instrument/logic_analyzer.py b/pslab/instrument/logic_analyzer.py index 5e59ed4..b48f43c 100644 --- a/pslab/instrument/logic_analyzer.py +++ b/pslab/instrument/logic_analyzer.py @@ -759,7 +759,12 @@ def count_pulses( try: # Sixteen rising edges are captured, so the time between two # captured events covers 16 periods of the signal. - period = (timestamps[1] - timestamps[0]) * 1e-6 / 16 + delta = timestamps[1] - timestamps[0] + if delta < 0: + # The capture counter is 32 bits and wraps after 67 seconds, + # so the difference has to be taken modulo its range. + delta += 2**32 / CP.CLOCK_RATE * 1e6 + period = delta * 1e-6 / 16 except IndexError: return 0 diff --git a/tests/test_logic_analyzer.py b/tests/test_logic_analyzer.py index a6b7895..65b2d1d 100644 --- a/tests/test_logic_analyzer.py +++ b/tests/test_logic_analyzer.py @@ -370,3 +370,12 @@ def test_count_pulses_rejects_a_negative_interval(mocker): with pytest.raises(ValueError): la.count_pulses("LA2", -0.2) assert not capture.called + + +def test_count_pulses_across_a_counter_rollover(mocker): + la = LogicAnalyzer(FakeDevice()) + # Same 100 kHz signal, but the second event is seen after the 32-bit + # capture counter has wrapped. + wrap = 2**32 / CP.CLOCK_RATE * 1e6 + mocker.patch.object(la, "capture", return_value=[np.array([wrap - 80, 80])]) + assert la.count_pulses("LA2", 0.2) == FREQUENCY * 0.2 From 897085032f0c7a1437e8ff7988285b51f927bc23 Mon Sep 17 00:00:00 2001 From: Kartik Khandelwal <78846877+Illtrapx@users.noreply.github.com> Date: Mon, 9 Nov 2026 04:19:42 +0100 Subject: [PATCH 4/6] fix(logic_analyzer): restore nonblocking pulse counting --- pslab/instrument/logic_analyzer.py | 76 +++++++++++++++++++++--- tests/test_logic_analyzer.py | 95 +++++++++++++++++++++++++++++- 2 files changed, 161 insertions(+), 10 deletions(-) diff --git a/pslab/instrument/logic_analyzer.py b/pslab/instrument/logic_analyzer.py index b48f43c..ee58b37 100644 --- a/pslab/instrument/logic_analyzer.py +++ b/pslab/instrument/logic_analyzer.py @@ -58,6 +58,7 @@ def __init__(self, device: ConnectionHandler | None = None): self._channel_one_map = "LA1" self._channel_two_map = "LA2" self._trimmed = 0 + self._pulse_count_capture = None def measure_frequency( self, channel: str, simultaneous_oscilloscope: bool = False, timeout: float = 1 @@ -713,8 +714,13 @@ def get_states(self) -> Dict[str, bool]: } def count_pulses( - self, channel: str = "FRQ", interval: float = 1, timeout: float = 1 - ) -> int: + self, + channel: str = "FRQ", + interval: float = 1, + timeout: float = 1, + *, + block: bool = True, + ) -> Union[int, None]: """Count pulses on a digital input. The number of pulses is calculated from the period of the signal, which @@ -731,31 +737,82 @@ def count_pulses( Time in seconds during which to count pulses. The default value is 1 second. timeout : float, optional - Timeout in seconds before cancelling the capture. The default value - is 1 second. + Timeout in seconds before cancelling a blocking capture. The default + value is 1 second. It does not delay a nonblocking call. A boolean + in this position is treated as the original API's blocking flag. + block : bool, optional + If False, return None without waiting for capture. Use + :meth:`fetch_pulse_count` to estimate pulses since this call; the + interval argument is ignored in that case. The default is True. Returns ------- - int - Number of pulses counted during the interval, or 0 if the signal is - too slow, or too fast, to be measured. + Union[int, None] + Estimated number of pulses, or 0 if the signal cannot be measured. + Return None if block is False. Raises ------ ValueError if the interval is negative. """ + if isinstance(timeout, bool): + # The original API used the third argument as the blocking flag. + block, timeout = timeout, 1 if interval < 0: raise ValueError("Interval cannot be negative.") + self._pulse_count_capture = None + started = time.monotonic() tmp = self._channel_one_map self._channel_one_map = channel try: timestamps = self.capture( - channel, 2, modes=["sixteen rising"], timeout=timeout - )[0] + channel, 2, modes=["sixteen rising"], block=block, timeout=timeout + ) + finally: + self._channel_one_map = tmp + + if not block: + self._pulse_count_capture = (channel, started) + return None + + return self._count_pulses_from_timestamps(timestamps[0], interval) + + def fetch_pulse_count(self) -> int: + """Estimate pulses since starting a nonblocking pulse count. + + The estimate uses the measured period and elapsed time, not a firmware + counter. Fetching does not wait for another event or stop the capture. + The signal must remain periodic, and another capture invalidates the + pending pulse count. This method cannot run alongside the oscilloscope. + + Returns + ------- + int + Estimated pulse count, or 0 if two distinct events are unavailable. + + Raises + ------ + RuntimeError + If no nonblocking pulse count is active. + """ + if self._pulse_count_capture is None: + raise RuntimeError("No nonblocking pulse count is active.") + + channel, started = self._pulse_count_capture + tmp = self._channel_one_map + self._channel_one_map = channel + try: + timestamps = self.fetch_data()[0] finally: self._channel_one_map = tmp + return self._count_pulses_from_timestamps( + timestamps, time.monotonic() - started + ) + + @staticmethod + def _count_pulses_from_timestamps(timestamps: np.ndarray, interval: float) -> int: try: # Sixteen rising edges are captured, so the time between two # captured events covers 16 periods of the signal. @@ -785,6 +842,7 @@ def _reset_prescaler(self): self._prescaler = 0 def _invalidate_buffer(self): + self._pulse_count_capture = None for c in self._channels.values(): c.events_in_buffer = 0 c.buffer_idx = None diff --git a/tests/test_logic_analyzer.py b/tests/test_logic_analyzer.py index 65b2d1d..abdf6b9 100644 --- a/tests/test_logic_analyzer.py +++ b/tests/test_logic_analyzer.py @@ -18,7 +18,6 @@ from pslab.instrument.logic_analyzer import LogicAnalyzer from pslab.instrument.waveform_generator import PWMGenerator - EVENTS = 2495 FREQUENCY = 1e5 DUTY_CYCLE = 0.5 @@ -372,6 +371,100 @@ def test_count_pulses_rejects_a_negative_interval(mocker): assert not capture.called +@pytest.mark.parametrize("timeout", [0, 0.05, 1]) +def test_count_pulses_keeps_the_positional_timeout(mocker, timeout): + la = LogicAnalyzer(FakeDevice()) + capture = mocker.patch.object(la, "capture", return_value=[np.array([0, 160])]) + + assert la.count_pulses("LA2", 0.2, timeout) == 20000 + assert capture.call_args.kwargs["timeout"] == timeout + assert capture.call_args.kwargs["block"] is True + + +def test_count_pulses_keeps_the_nonblocking_api(mocker): + la = LogicAnalyzer(FakeDevice()) + capture = mocker.patch.object(la, "capture", return_value=None) + clock = mocker.patch( + "pslab.instrument.logic_analyzer.time.monotonic", return_value=10 + ) + + assert la.count_pulses("LA2", 0.1, False) is None + assert capture.call_args.kwargs["block"] is False + + fetch = mocker.patch.object(la, "fetch_data", return_value=[np.array([0, 160])]) + clock.return_value = 10.2 + assert la.fetch_pulse_count() == 20000 + fetch.assert_called_once_with() + assert la._channel_one_map == "LA1" + + +def test_nonblocking_pulse_capture_returns_before_fetching(mocker): + la = LogicAnalyzer(FakeDevice()) + clock = mocker.patch( + "pslab.instrument.logic_analyzer.time.monotonic", return_value=10 + ) + fetch = mocker.patch.object(la, "fetch_data", return_value=[np.array([0, 160])]) + + assert la.count_pulses("LA2", block=False) is None + fetch.assert_not_called() + assert la._channel_one_map == "LA1" + + def fetched_channel(): + assert la._channel_one_map == "LA2" + return [np.array([0, 160])] + + fetch.side_effect = fetched_channel + clock.return_value = 10.2 + assert la.fetch_pulse_count() == 20000 + clock.return_value = 10.4 + assert la.fetch_pulse_count() == 40000 + assert la._channel_one_map == "LA1" + + +@pytest.mark.parametrize( + "timestamps", [np.array([]), np.array([160]), np.array([160, 160])] +) +def test_nonblocking_pulse_fetch_waits_for_a_measurable_period(mocker, timestamps): + la = LogicAnalyzer(FakeDevice()) + mocker.patch.object(la, "capture", return_value=None) + la.count_pulses("LA2", block=False) + mocker.patch.object(la, "fetch_data", return_value=[timestamps]) + assert la.fetch_pulse_count() == 0 + + +def test_nonblocking_pulse_fetch_restores_channel_map_after_error(mocker): + la = LogicAnalyzer(FakeDevice()) + mocker.patch.object(la, "capture", return_value=None) + la.count_pulses("LA2", block=False) + mocker.patch.object(la, "fetch_data", side_effect=OSError("read failed")) + with pytest.raises(OSError, match="read failed"): + la.fetch_pulse_count() + assert la._channel_one_map == "LA1" + + +def test_nonblocking_pulse_capture_failure_leaves_no_pending_count(mocker): + la = LogicAnalyzer(FakeDevice()) + capture = mocker.patch.object(la, "capture", return_value=None) + la.count_pulses("LA2", block=False) + capture.side_effect = OSError("capture failed") + with pytest.raises(OSError, match="capture failed"): + la.count_pulses("LA3", block=False) + with pytest.raises(RuntimeError, match="No nonblocking pulse count is active"): + la.fetch_pulse_count() + assert la._channel_one_map == "LA1" + + +def test_another_capture_invalidates_the_pending_pulse_count(mocker): + la = LogicAnalyzer(FakeDevice()) + mocker.patch.object(la, "capture", return_value=None) + la.count_pulses("LA2", block=False) + + la._invalidate_buffer() + + with pytest.raises(RuntimeError, match="No nonblocking pulse count is active"): + la.fetch_pulse_count() + + def test_count_pulses_across_a_counter_rollover(mocker): la = LogicAnalyzer(FakeDevice()) # Same 100 kHz signal, but the second event is seen after the 32-bit From a214f52ee5d61945d085f03fbef0a625f57fb38f Mon Sep 17 00:00:00 2001 From: Kartik Khandelwal <78846877+Illtrapx@users.noreply.github.com> Date: Mon, 9 Nov 2026 07:55:52 +0100 Subject: [PATCH 5/6] fix(logic_analyzer): reject pulse counts after buffer writes --- pslab/instrument/buffer.py | 10 ++++ pslab/instrument/logic_analyzer.py | 17 +++++-- pslab/instrument/oscilloscope.py | 1 + tests/test_logic_analyzer.py | 82 ++++++++++++++++++++++++++++-- 4 files changed, 103 insertions(+), 7 deletions(-) diff --git a/pslab/instrument/buffer.py b/pslab/instrument/buffer.py index a2a5cdb..a2aa331 100644 --- a/pslab/instrument/buffer.py +++ b/pslab/instrument/buffer.py @@ -6,6 +6,12 @@ class ADCBufferMixin: """Mixin for classes that need to read or write to the ADC buffer.""" + def _get_buffer_generation(self) -> int: + return getattr(self._device, "_adc_buffer_generation", 0) + + def _mark_buffer_write(self): + self._device._adc_buffer_generation = self._get_buffer_generation() + 1 + def fetch_buffer(self, samples: int, starting_position: int = 0): """Fetch a section of the ADC buffer. @@ -51,6 +57,8 @@ def clear_buffer(self, samples: int, starting_position: int = 0): Location in the ADC buffer to start from. By default samples will be cleared from the beginning of the buffer. """ + if samples: + self._mark_buffer_write() self._device.send_byte(CP.COMMON) self._device.send_byte(CP.CLEAR_BUFFER) self._device.send_int(starting_position) @@ -71,6 +79,8 @@ def fill_buffer(self, data: list[int], starting_position: int = 0): buf_size = 128 idx = starting_position remaining = len(data) + if remaining: + self._mark_buffer_write() while remaining > 0: self._device.send_byte(CP.COMMON) diff --git a/pslab/instrument/logic_analyzer.py b/pslab/instrument/logic_analyzer.py index ee58b37..1b93b08 100644 --- a/pslab/instrument/logic_analyzer.py +++ b/pslab/instrument/logic_analyzer.py @@ -773,7 +773,11 @@ def count_pulses( self._channel_one_map = tmp if not block: - self._pulse_count_capture = (channel, started) + self._pulse_count_capture = ( + channel, + started, + self._get_buffer_generation(), + ) return None return self._count_pulses_from_timestamps(timestamps[0], interval) @@ -783,8 +787,9 @@ def fetch_pulse_count(self) -> int: The estimate uses the measured period and elapsed time, not a firmware counter. Fetching does not wait for another event or stop the capture. - The signal must remain periodic, and another capture invalidates the - pending pulse count. This method cannot run alongside the oscilloscope. + The signal must remain periodic. A capture, buffer clear, or buffer fill + on any instrument sharing this connection invalidates the pending count. + This method cannot run alongside the oscilloscope. Returns ------- @@ -799,7 +804,11 @@ def fetch_pulse_count(self) -> int: if self._pulse_count_capture is None: raise RuntimeError("No nonblocking pulse count is active.") - channel, started = self._pulse_count_capture + channel, started, generation = self._pulse_count_capture + if generation != self._get_buffer_generation(): + self._pulse_count_capture = None + raise RuntimeError("No nonblocking pulse count is active.") + tmp = self._channel_one_map self._channel_one_map = channel try: diff --git a/pslab/instrument/oscilloscope.py b/pslab/instrument/oscilloscope.py index b8d3e30..32db95b 100644 --- a/pslab/instrument/oscilloscope.py +++ b/pslab/instrument/oscilloscope.py @@ -186,6 +186,7 @@ def _lookup_mininum_timegap(self, channels: int) -> float: return min_timegaps[channels_idx[channels]][self.trigger_enabled] def _capture(self, channels: int, samples: int, timegap: float): + self._mark_buffer_write() self._invalidate_buffer() chosa = self._channels[self._channel_one_map].chosa self._channels[self._channel_one_map].resolution = 10 diff --git a/tests/test_logic_analyzer.py b/tests/test_logic_analyzer.py index abdf6b9..2cdac2c 100644 --- a/tests/test_logic_analyzer.py +++ b/tests/test_logic_analyzer.py @@ -16,6 +16,7 @@ import pslab.protocol as CP from pslab.instrument.logic_analyzer import LogicAnalyzer +from pslab.instrument.oscilloscope import Oscilloscope from pslab.instrument.waveform_generator import PWMGenerator EVENTS = 2495 @@ -281,7 +282,7 @@ def test_count_pulses(la): assert expected_pulses == pytest.approx(pulses, rel=0.1) # Pretty bad accuracy. -# The tests below do not need a connected PSLab, since the capture is mocked. +# The tests below use a stand-in transport and do not need a connected PSLab. class FakeDevice: @@ -456,10 +457,9 @@ def test_nonblocking_pulse_capture_failure_leaves_no_pending_count(mocker): def test_another_capture_invalidates_the_pending_pulse_count(mocker): la = LogicAnalyzer(FakeDevice()) - mocker.patch.object(la, "capture", return_value=None) la.count_pulses("LA2", block=False) - la._invalidate_buffer() + la.capture("LA3", events=2, block=False) with pytest.raises(RuntimeError, match="No nonblocking pulse count is active"): la.fetch_pulse_count() @@ -472,3 +472,79 @@ def test_count_pulses_across_a_counter_rollover(mocker): wrap = 2**32 / CP.CLOCK_RATE * 1e6 mocker.patch.object(la, "capture", return_value=[np.array([wrap - 80, 80])]) assert la.count_pulses("LA2", 0.2) == FREQUENCY * 0.2 + + +@pytest.mark.parametrize("writer", ["same_analyzer", "other_analyzer", "scope"]) +@pytest.mark.parametrize("operation", ["fill", "clear", "capture"]) +def test_buffer_writers_invalidate_the_pending_pulse_count(mocker, writer, operation): + device = FakeDevice() + la = LogicAnalyzer(device) + la.count_pulses("LA2", block=False) + mocker.patch.object(la, "fetch_data", return_value=[np.array([0, 160])]) + if writer == "same_analyzer": + instrument = la + elif writer == "other_analyzer": + instrument = LogicAnalyzer(device) + else: + instrument = Oscilloscope(device) + + if operation == "fill": + instrument.fill_buffer([1, 2, 3, 4]) + elif operation == "clear": + instrument.clear_buffer(4) + elif writer == "scope": + instrument.capture(1, 4, 1, block=False) + else: + instrument.capture("LA3", events=2, block=False) + + with pytest.raises(RuntimeError, match="No nonblocking pulse count is active"): + la.fetch_pulse_count() + + +@pytest.mark.parametrize( + "operation", ["read", "empty_fill", "empty_clear", "other_device_write"] +) +def test_buffer_operations_preserve_an_unmodified_pulse_capture(mocker, operation): + device = FakeDevice() + la = LogicAnalyzer(device) + clock = mocker.patch( + "pslab.instrument.logic_analyzer.time.monotonic", return_value=10 + ) + la.count_pulses("LA2", block=False) + mocker.patch.object(la, "fetch_data", return_value=[np.array([0, 160])]) + other = LogicAnalyzer(device) + + if operation == "read": + other.fetch_buffer(4) + elif operation == "empty_fill": + other.fill_buffer([]) + elif operation == "empty_clear": + other.clear_buffer(0) + else: + LogicAnalyzer(FakeDevice()).fill_buffer([1, 2, 3, 4]) + + clock.return_value = 10.2 + assert la.fetch_pulse_count() == 20000 + + +@pytest.mark.parametrize("operation", ["fill", "clear", "capture"]) +def test_failed_buffer_writes_invalidate_the_pending_pulse_count(mocker, operation): + device = FakeDevice() + la = LogicAnalyzer(device) + la.count_pulses("LA2", block=False) + scope = Oscilloscope(device) + # Bypass PGA setup so the failed ACK belongs to the buffer-writing command. + mocker.patch.object(scope, "_set_gain") + mocker.patch.object(device, "get_ack", side_effect=OSError("ack failed")) + mocker.patch.object(la, "fetch_data", return_value=[np.array([0, 160])]) + + with pytest.raises(OSError, match="ack failed"): + if operation == "fill": + scope.fill_buffer([1, 2, 3, 4]) + elif operation == "clear": + scope.clear_buffer(4) + else: + scope.capture(1, 4, 1, block=False) + + with pytest.raises(RuntimeError, match="No nonblocking pulse count is active"): + la.fetch_pulse_count() From 19478233e5a828b64ad25a0390a4d7a674dc28cc Mon Sep 17 00:00:00 2001 From: Kartik Khandelwal <78846877+Illtrapx@users.noreply.github.com> Date: Mon, 9 Nov 2026 11:08:50 +0100 Subject: [PATCH 6/6] fix(logic_analyzer): reject ambiguous multi-wrap pulse estimates --- pslab/instrument/logic_analyzer.py | 26 ++++++++---- tests/test_logic_analyzer.py | 65 ++++++++++++++++++++++++++++++ 2 files changed, 84 insertions(+), 7 deletions(-) diff --git a/pslab/instrument/logic_analyzer.py b/pslab/instrument/logic_analyzer.py index 1b93b08..553dc1c 100644 --- a/pslab/instrument/logic_analyzer.py +++ b/pslab/instrument/logic_analyzer.py @@ -727,7 +727,9 @@ def count_pulses( is measured by capturing logic events. This method cannot be used at the same time as the oscilloscope. The signal must be slow enough for the capture to resolve the time between two events, and fast enough for two - events to be captured within the timeout. + events to be captured within the timeout. Captures lasting a full + 32-bit counter cycle (about 67 seconds) return 0 because the number of + wraps between events cannot be determined. Parameters ---------- @@ -780,7 +782,9 @@ def count_pulses( ) return None - return self._count_pulses_from_timestamps(timestamps[0], interval) + return self._count_pulses_from_timestamps( + timestamps[0], interval, time.monotonic() - started + ) def fetch_pulse_count(self) -> int: """Estimate pulses since starting a nonblocking pulse count. @@ -789,7 +793,10 @@ def fetch_pulse_count(self) -> int: counter. Fetching does not wait for another event or stop the capture. The signal must remain periodic. A capture, buffer clear, or buffer fill on any instrument sharing this connection invalidates the pending count. - This method cannot run alongside the oscilloscope. + This method cannot run alongside the oscilloscope. Fetch within one + 32-bit counter cycle (about 67 seconds) of starting the count; later + fetches return 0 because multiple counter wraps cannot be ruled out, + even if an earlier fetch succeeded. Returns ------- @@ -816,12 +823,17 @@ def fetch_pulse_count(self) -> int: finally: self._channel_one_map = tmp - return self._count_pulses_from_timestamps( - timestamps, time.monotonic() - started - ) + elapsed = time.monotonic() - started + return self._count_pulses_from_timestamps(timestamps, elapsed, elapsed) @staticmethod - def _count_pulses_from_timestamps(timestamps: np.ndarray, interval: float) -> int: + def _count_pulses_from_timestamps( + timestamps: np.ndarray, interval: float, capture_duration: float + ) -> int: + # After a full counter cycle, even an increasing pair may hide wraps. + if capture_duration >= 2**32 / CP.CLOCK_RATE: + return 0 + try: # Sixteen rising edges are captured, so the time between two # captured events covers 16 periods of the signal. diff --git a/tests/test_logic_analyzer.py b/tests/test_logic_analyzer.py index 2cdac2c..8fb6b7c 100644 --- a/tests/test_logic_analyzer.py +++ b/tests/test_logic_analyzer.py @@ -548,3 +548,68 @@ def test_failed_buffer_writes_invalidate_the_pending_pulse_count(mocker, operati with pytest.raises(RuntimeError, match="No nonblocking pulse count is active"): la.fetch_pulse_count() + + +@pytest.mark.parametrize("block", [False, True]) +def test_pulse_count_rejects_ambiguous_long_gap(mocker, block): + la = LogicAnalyzer(FakeDevice()) + clock = mocker.patch( + "pslab.instrument.logic_analyzer.time.monotonic", return_value=10 + ) + wrap = 2**32 / CP.CLOCK_RATE + # A 0.1 Hz signal has 160 seconds between every 16th rising edge. + timestamps = np.array([1, (161 % wrap)]) * 1e6 + + def capture(*args, **kwargs): + clock.return_value = 171 + return [timestamps] if block else None + + mocker.patch.object(la, "capture", side_effect=capture) + mocker.patch.object(la, "fetch_data", return_value=[timestamps]) + result = la.count_pulses("LA2", interval=161, timeout=200, block=block) + if not block: + result = la.fetch_pulse_count() + assert result == 0 + + +@pytest.mark.parametrize("block", [False, True]) +@pytest.mark.parametrize("offset", [-1e-6, 0, 1e-6]) +def test_pulse_count_bounds_capture_duration_not_count_interval(mocker, block, offset): + la = LogicAnalyzer(FakeDevice()) + clock = mocker.patch( + "pslab.instrument.logic_analyzer.time.monotonic", return_value=0 + ) + elapsed = 2**32 / CP.CLOCK_RATE + offset + timestamps = np.array([100, 260]) + + def capture(*args, **kwargs): + if block: + clock.return_value = elapsed + return [timestamps] + + def fetch(): + # The duration check must include time spent retrieving timestamps. + clock.return_value = elapsed + return [timestamps] + + mocker.patch.object(la, "capture", side_effect=capture) + mocker.patch.object(la, "fetch_data", side_effect=fetch) + result = la.count_pulses("LA2", interval=1000, block=block) + if not block: + result = la.fetch_pulse_count() + expected = round((1000 if block else elapsed) * FREQUENCY) if offset < 0 else 0 + assert result == expected + assert la._channel_one_map == "LA1" + + +def test_repeated_pulse_fetch_rejects_a_later_ambiguous_capture(mocker): + la = LogicAnalyzer(FakeDevice()) + clock = mocker.patch( + "pslab.instrument.logic_analyzer.time.monotonic", return_value=0 + ) + la.count_pulses("LA2", block=False) + mocker.patch.object(la, "fetch_data", return_value=[np.array([100, 260])]) + clock.return_value = 0.2 + assert la.fetch_pulse_count() == 20000 + clock.return_value = 160 + assert la.fetch_pulse_count() == 0