"""Shared Qt controls and worker for online logic analyzer acquisition.""" from threading import Event try: from PySide6.QtCore import QThread, Signal from PySide6.QtWidgets import QCheckBox, QComboBox, QGroupBox, QHBoxLayout, QLabel, QPushButton, QVBoxLayout, QWidget except ImportError: from PySide2.QtCore import QThread, Signal from PySide2.QtWidgets import QCheckBox, QComboBox, QGroupBox, QHBoxLayout, QLabel, QPushButton, QVBoxLayout, QWidget from logic_analyzer.files import ImportCancelled class CaptureWorker(QThread): """Run device discovery or acquisition using the driver's callbacks.""" devices = Signal(object) captured = Signal(object) status = Signal(str) failed = Signal(str) def __init__(self, parent, *, discover=None, acquire=None, repeat=False): super().__init__(parent) if (discover is None) == (acquire is None): raise ValueError("Provide one discovery or acquisition callback") self.discover = discover self.acquire = acquire self.repeat = repeat self.stop_event = Event() def run(self): try: if self.discover is not None: devices = self.discover(self.isInterruptionRequested) if not self.isInterruptionRequested(): self.devices.emit(devices) return while not self.isInterruptionRequested(): capture = self.acquire(self.stop_event.is_set, self.isInterruptionRequested, self.status.emit) if self.isInterruptionRequested(): return self.captured.emit(capture) if not self.repeat or self.stop_event.wait(.25): return except ImportCancelled: pass except Exception as error: if not self.isInterruptionRequested(): self.failed.emit(str(error)) class CapturePanel(QGroupBox): """Manage one worker and the common controls of an analyzer panel. The device panel implements find_devices, start_capture, _devices and _device_changed. It fills config_layout before adding the capture controls. """ captured = Signal(object) busy_changed = Signal(bool) def __init__(self, title, device_name, settings, parent=None): super().__init__(title, parent) self._device_name = device_name self.settings = settings self.worker = None self.configuration = QWidget() self.config_layout = QVBoxLayout(self.configuration) self.config_layout.setContentsMargins(0, 0, 0, 0) QVBoxLayout(self).addWidget(self.configuration) self.refresh = QPushButton('Найти устройства') self.device = QComboBox() self.device.setMinimumWidth(210) self.mode = QComboBox() self.mode.addItems(('Один захват', 'Повторять', 'До остановки')) self.mode.setCurrentIndex(int(self.settings.value('mode', 0))) def add_channel_controls(self): row = QHBoxLayout() row.addWidget(QLabel('Каналы:')) self.channels = [] selected = str(self.settings.value('channels', '0,1')).split(',') for index in range(16): check = QCheckBox('D%d' % index) check.setChecked(str(index) in selected) row.addWidget(check) self.channels.append(check) self.config_layout.addLayout(row) def selected_channels(self): return tuple(i for i, check in enumerate(self.channels) if check.isEnabled() and check.isChecked()) def add_capture_controls(self, status_text): row = QHBoxLayout() self.start = QPushButton('Начать захват') self.stop = QPushButton('Стоп и показать') self.cancel = QPushButton('Отменить') for button in (self.start, self.stop, self.cancel): button.setEnabled(False) row.addWidget(button) self.status = QLabel(status_text + ' График обновляется после захвата; повторные окна имеют разрывы.') self.status.setWordWrap(True) row.addWidget(self.status, 1) self.layout().addLayout(row) self.refresh.clicked.connect(self.find_devices) self.start.clicked.connect(self.start_capture) self.stop.clicked.connect(self.stop_capture) self.cancel.clicked.connect(self.cancel_capture) self.device.currentIndexChanged.connect(self._device_changed) self.mode.currentIndexChanged.connect(self._mode_changed) self._mode_changed() def _mode_changed(self): self.duration.setEnabled(self.mode.currentIndex() != 2) def _invalidate_devices(self): self.device.clear() self.start.setEnabled(False) def _show_devices(self, devices, title, empty_message): self.device.clear() saved = self.settings.value('device', '') for device in devices: self.device.addItem(title(device), device) if device.device_id == saved: self.device.setCurrentIndex(self.device.count() - 1) self.status.setText('Выберите параметры и начните захват.' if devices else empty_message) def _launch(self, worker): self.worker = worker worker.devices.connect(self._devices) worker.captured.connect(self._captured) worker.status.connect(self._status) worker.failed.connect(self._failed) worker.finished.connect(self._finished) self.configuration.setEnabled(False) self.start.setEnabled(False) self.stop.setEnabled(worker.acquire is not None) self.cancel.setEnabled(True) self.busy_changed.emit(True) worker.start() def _captured(self, capture): if self.worker and not self.worker.isInterruptionRequested(): self.captured.emit(capture) self.status.setText('Получено %d каналов · %.6g с' % (len(capture.channels), capture.end - capture.start)) def _failed(self, text): self.status.setText(f'Ошибка {self._device_name}: {text}') def _status(self, text): if self.worker and not self.worker.isInterruptionRequested(): self.status.setText(text) def stop_capture(self): if self.worker: self.worker.stop_event.set() self.stop.setEnabled(False) self.status.setText('Остановка и получение записи…') def cancel_capture(self): if self.worker: self.worker.requestInterruption() self.worker.stop_event.set() self.status.setText('Отмена… Предыдущая запись сохранена.') self.stop.setEnabled(False) self.cancel.setEnabled(False) def _finished(self): worker = self.sender() worker.deleteLater() if worker is not self.worker: return self.worker = None self.configuration.setEnabled(True) self._device_changed() self.stop.setEnabled(False) self.cancel.setEnabled(False) self.busy_changed.emit(False) def shutdown(self): if self.worker: self.worker.requestInterruption() self.worker.stop_event.set() self.worker.wait()