summaryrefslogtreecommitdiff
path: root/ui/control_editor.py
blob: 5140bf3f1ad33a2aa87b7682ff3a933bca14193d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
"""
ui/control_editor.py

Dialog for adding or editing a control widget.
Lets the operator choose:
  • Control type  (On/Off, Motor, PWM, Setpoint, Analog Out)
  • Title & icon
  • Target device + channel
  • Type-specific parameters (max RPM, unit, min/max, step...)
"""

from __future__ import annotations
from dataclasses import dataclass, field, asdict
from typing import Any, Dict, Optional

from PyQt6.QtWidgets import (
    QDialog, QVBoxLayout, QHBoxLayout, QFormLayout,
    QLabel, QLineEdit, QComboBox, QDoubleSpinBox,
    QSpinBox, QPushButton, QGroupBox, QWidget,
    QStackedWidget, QFrame, QCheckBox, QSizePolicy,
    QTextEdit, QScrollArea,
)
from PyQt6.QtCore import Qt
from PyQt6.QtGui import QFont, QFontMetrics


class _DynStack(QStackedWidget):
    """QStackedWidget that sizes to current page only."""
    def sizeHint(self):
        w = self.currentWidget()
        return w.sizeHint() if w else super().sizeHint()
    def minimumSizeHint(self):
        w = self.currentWidget()
        return w.minimumSizeHint() if w else super().minimumSizeHint()

from devices.device_registry import DeviceRegistry


# ── Data model ────────────────────────────────────────────────────────────────

CONTROL_TYPES = [
    "On/Off Switch",
    "Motor Control",
    "PWM Output",
    "Setpoint",
    "Analog Output",
]

CONTROL_ICONS = {
    "On/Off Switch":  "⏻",
    "Motor Control":  "⟳",
    "PWM Output":     "⊓",
    "Setpoint":       "◎",
    "Analog Output":  "↗",
}


@dataclass
class ControlSpec:
    """Serialisable description of one control widget."""
    control_type: str   = "On/Off Switch"
    title:        str   = "Control"
    icon:         str   = "⏻"
    device_id:    str   = ""
    channel_id:   str   = ""
    active_low:   bool  = False
    # Type-specific params
    unit:         str   = ""
    min_val:      float = 0.0
    max_val:      float = 100.0
    step:         float = 1.0
    max_rpm:      int   = 3000
    # Optional Python snippet executed on every value change
    on_action_script: str = ""

    def to_dict(self) -> dict:
        return asdict(self)

    @staticmethod
    def from_dict(d: dict) -> "ControlSpec":
        valid = {k: v for k, v in d.items() if k in ControlSpec.__dataclass_fields__}
        return ControlSpec(**valid)


# ── Per-type parameter panels ─────────────────────────────────────────────────

class OnOffParams(QWidget):
    def __init__(self): super().__init__()  # no extra params needed

    def load(self, spec: ControlSpec): pass
    def save(self, spec: ControlSpec): pass


class MotorParams(QWidget):
    def __init__(self):
        super().__init__()
        lay = QFormLayout(self); lay.setContentsMargins(0, 4, 0, 4)
        self._rpm = QSpinBox(); self._rpm.setRange(1, 100000); self._rpm.setValue(3000)
        self._rpm.setSuffix(" RPM")
        lay.addRow("Max RPM:", self._rpm)

    def load(self, spec: ControlSpec): self._rpm.setValue(spec.max_rpm)
    def save(self, spec: ControlSpec): spec.max_rpm = self._rpm.value()


class PwmParams(QWidget):
    def __init__(self): super().__init__()  # duty handled by slider, no extra params

    def load(self, spec: ControlSpec): pass
    def save(self, spec: ControlSpec): pass


class SetpointParams(QWidget):
    def __init__(self):
        super().__init__()
        lay = QFormLayout(self); lay.setContentsMargins(0, 4, 0, 4)
        self._unit = QLineEdit(); self._unit.setPlaceholderText("e.g. °C, bar, rpm")
        self._min  = QDoubleSpinBox(); self._min.setRange(-1e9, 1e9); self._min.setValue(0.0)
        self._max  = QDoubleSpinBox(); self._max.setRange(-1e9, 1e9); self._max.setValue(100.0)
        self._step = QDoubleSpinBox(); self._step.setRange(0.001, 1e6); self._step.setValue(1.0)
        lay.addRow("Unit:",  self._unit)
        lay.addRow("Min:",   self._min)
        lay.addRow("Max:",   self._max)
        lay.addRow("Step:",  self._step)

    def load(self, spec: ControlSpec):
        self._unit.setText(spec.unit)
        self._min.setValue(spec.min_val)
        self._max.setValue(spec.max_val)
        self._step.setValue(spec.step)

    def save(self, spec: ControlSpec):
        spec.unit    = self._unit.text().strip()
        spec.min_val = self._min.value()
        spec.max_val = self._max.value()
        spec.step    = self._step.value()


class AnalogOutParams(QWidget):
    def __init__(self):
        super().__init__()
        lay = QFormLayout(self); lay.setContentsMargins(0, 4, 0, 4)
        self._unit = QLineEdit("V"); self._unit.setPlaceholderText("V, mA, …")
        self._min  = QDoubleSpinBox(); self._min.setRange(-1e9, 1e9); self._min.setValue(0.0)
        self._max  = QDoubleSpinBox(); self._max.setRange(-1e9, 1e9); self._max.setValue(10.0)
        lay.addRow("Unit:",  self._unit)
        lay.addRow("Min:",   self._min)
        lay.addRow("Max:",   self._max)

    def load(self, spec: ControlSpec):
        self._unit.setText(spec.unit)
        self._min.setValue(spec.min_val)
        self._max.setValue(spec.max_val)

    def save(self, spec: ControlSpec):
        spec.unit    = self._unit.text().strip()
        spec.min_val = self._min.value()
        spec.max_val = self._max.value()


_PARAM_PANELS = {
    "On/Off Switch":  OnOffParams,
    "Motor Control":  MotorParams,
    "PWM Output":     PwmParams,
    "Setpoint":       SetpointParams,
    "Analog Output":  AnalogOutParams,
}


# ── Editor dialog ─────────────────────────────────────────────────────────────

class ControlEditorDialog(QDialog):
    """Add or edit a control widget."""

    def __init__(self, registry: DeviceRegistry,
                 spec: Optional[ControlSpec] = None,
                 parent=None):
        super().__init__(parent)
        self.registry = registry
        self.spec     = spec or ControlSpec()
        self.result_spec: Optional[ControlSpec] = None

        self.setWindowTitle("Edit Control" if spec else "Add Control")
        self.setMinimumSize(440, 520)
        self.resize(460, 580)
        self._build()
        self._load_spec()

    def _build(self):
        root = QVBoxLayout(self); root.setSpacing(10)

        # ── Identity ────────────────────────────────────────────────────
        id_grp  = QGroupBox("Identity")
        id_form = QFormLayout(id_grp); id_form.setContentsMargins(10, 16, 10, 10)

        self._type_cb = QComboBox()
        self._type_cb.addItems(CONTROL_TYPES)
        self._type_cb.currentTextChanged.connect(self._on_type_changed)
        id_form.addRow("Control Type:", self._type_cb)

        self._title_edit = QLineEdit()
        self._title_edit.setPlaceholderText("e.g. Heater, Pump, Mixer")
        id_form.addRow("Label:", self._title_edit)

        root.addWidget(id_grp)

        # ── Device & channel ────────────────────────────────────────────
        hw_grp  = QGroupBox("Hardware Assignment")
        hw_form = QFormLayout(hw_grp); hw_form.setContentsMargins(10, 16, 10, 10)

        self._dev_cb = QComboBox()
        self._dev_cb.addItem("— none —", userData="")
        for dev in self.registry.all_instances():
            label = f"{dev.info.device_id}  ({dev.info.name})"
            self._dev_cb.addItem(label, userData=dev.info.device_id)
        self._dev_cb.currentIndexChanged.connect(self._on_dev_changed)
        hw_form.addRow("Device:", self._dev_cb)

        self._ch_cb = QComboBox()
        self._ch_cb.setEditable(True)   # allow typing custom pin like "D7"
        self._ch_cb.setInsertPolicy(QComboBox.InsertPolicy.NoInsert)
        hw_form.addRow("Channel / Pin:", self._ch_cb)

        self._active_low_chk = QCheckBox("Active-low output (ON sends LOW)")
        hw_form.addRow("Polarity:", self._active_low_chk)

        self._ch_hint = QLabel("")
        self._ch_hint.setObjectName("traceSource")
        self._ch_hint.setWordWrap(True)
        hw_form.addRow(self._ch_hint)

        root.addWidget(hw_grp)

        # ── Type-specific params ────────────────────────────────────────
        self._params_grp = QGroupBox("Parameters")
        self._params_grp.setSizePolicy(
            QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Minimum)
        params_lay = QVBoxLayout(self._params_grp)
        params_lay.setContentsMargins(10, 16, 10, 10)

        self._stack = _DynStack()
        self._stack.setSizePolicy(
            QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Minimum)
        self._param_panels: Dict[str, QWidget] = {}
        for name, cls in _PARAM_PANELS.items():
            panel = cls()
            self._param_panels[name] = panel
            self._stack.addWidget(panel)
        params_lay.addWidget(self._stack)
        root.addWidget(self._params_grp)

        # ── On-action script ───────────────────────────────────────────
        script_grp = QGroupBox("On Action Script  (optional)")
        script_lay = QVBoxLayout(script_grp); script_lay.setContentsMargins(10, 12, 10, 10)

        _help = QLabel(
            "Runs every time this control changes value.\n"
            "Available: value, channel_id, device_id, vars (shared dict), "
            "channels (latest values by channel_id), math"
        )
        _help.setObjectName("traceSource"); _help.setWordWrap(True)
        script_lay.addWidget(_help)

        _mono = QFont("IBM Plex Mono, Consolas, Monospace")
        _mono.setStyleHint(QFont.StyleHint.Monospace)
        self._script_edit = QTextEdit()
        self._script_edit.setFont(_mono)
        self._script_edit.setTabStopDistance(QFontMetrics(_mono).horizontalAdvance(" ") * 4)
        self._script_edit.setMinimumHeight(80); self._script_edit.setMaximumHeight(160)
        self._script_edit.setPlaceholderText(
            "# Example: zero a position offset when button is pressed\n"
            "# vars['zero_pos'] = channels.get('encoder_0', 0)"
        )
        script_lay.addWidget(self._script_edit)

        self._script_status = QLabel("")
        self._script_status.setObjectName("traceSource")
        check_btn = QPushButton("Check Syntax")
        check_btn.clicked.connect(self._check_script)
        btn_row = QHBoxLayout()
        btn_row.addWidget(self._script_status, 1)
        btn_row.addWidget(check_btn)
        script_lay.addLayout(btn_row)
        root.addWidget(script_grp)
        root.addStretch()

        # ── Buttons ────────────────────────────────────────────────────
        div = QFrame(); div.setFrameShape(QFrame.Shape.HLine)
        div.setObjectName("devWindowDivider"); root.addWidget(div)

        btn_row = QHBoxLayout(); btn_row.addStretch()
        cancel = QPushButton("Cancel"); cancel.clicked.connect(self.reject)
        ok     = QPushButton("Create Control")
        ok.setObjectName("applyButton"); ok.setDefault(True)
        ok.clicked.connect(self._on_ok)
        btn_row.addWidget(cancel); btn_row.addWidget(ok)
        root.addLayout(btn_row)

    def _check_script(self):
        src = self._script_edit.toPlainText().strip()
        if not src:
            self._script_status.setText(""); return
        try:
            compile(src, "<script>", "exec")
            self._script_status.setText("✓ OK")
            self._script_status.setStyleSheet("color:#22c55e;")
        except SyntaxError as e:
            self._script_status.setText(f"⚠ {e}")
            self._script_status.setStyleSheet("color:#ef4444;")

    def _load_spec(self):
        """Populate fields from self.spec."""
        # Type
        idx = CONTROL_TYPES.index(self.spec.control_type) \
              if self.spec.control_type in CONTROL_TYPES else 0
        self._type_cb.setCurrentIndex(idx)
        self._title_edit.setText(self.spec.title)

        # Device
        for i in range(self._dev_cb.count()):
            if self._dev_cb.itemData(i) == self.spec.device_id:
                self._dev_cb.setCurrentIndex(i); break

        # Channel (populated after device selection)
        self._on_dev_changed()
        found = False
        for i in range(self._ch_cb.count()):
            if self._ch_cb.itemData(i) == self.spec.channel_id:
                self._ch_cb.setCurrentIndex(i)
                found = True
                break
        if not found:
            self._ch_cb.setCurrentText(self.spec.channel_id)
        self._active_low_chk.setChecked(bool(self.spec.active_low))

        # Params
        for name, panel in self._param_panels.items():
            panel.load(self.spec)

        # Script
        self._script_edit.setPlainText(self.spec.on_action_script)

    def _on_type_changed(self, type_name: str):
        idx = list(_PARAM_PANELS.keys()).index(type_name)
        self._stack.setCurrentIndex(idx)
        self._stack.updateGeometry()
        self._params_grp.updateGeometry()
        self._active_low_chk.setEnabled(type_name == "On/Off Switch")
        # Auto-set title if still default
        if not self._title_edit.text() or \
           self._title_edit.text() in CONTROL_TYPES:
            self._title_edit.setText(type_name)

    def _on_dev_changed(self):
        self._ch_cb.clear()
        dev_id = self._dev_cb.currentData()
        if not dev_id:
            self._ch_hint.setText("No device selected — type a channel manually")
            return
        dev = self.registry.get_instance(dev_id)
        if not dev:
            return
        # Add actual channels (skip disabled — can't be driven while switched
        # off — and skip read-only channels — a control writes, so a channel
        # with no write mapping should never be offered as a target)
        for ch in dev.info.channels:
            if not ch.enabled or not ch.writable:
                continue
            self._ch_cb.addItem(f"{ch.channel_id}  ({ch.name})",
                                userData=ch.channel_id)
        # For Arduino backends also suggest digital pins for output
        if hasattr(dev, "backend") and dev.backend == "arduino":
            self._ch_cb.insertSeparator(self._ch_cb.count())
            for pin in ["D5", "D6", "D7", "D8", "D9", "D10", "D11", "D13"]:
                self._ch_cb.addItem(f"{pin}  (digital out)", userData=pin)
            self._ch_hint.setText(
                "Analog pins (A0…) for reading.\n"
                "Digital pins (D5…) for on/off output.\n"
                "D9, D10, D11 support PWM."
            )
        else:
            self._ch_hint.setText("")

    def _on_ok(self):
        ctype = self._type_cb.currentText()
        title = self._title_edit.text().strip() or ctype

        # Resolve channel_id — prefer userData if it's a real combo item
        ch_text = self._ch_cb.currentText().strip()
        ch_data = self._ch_cb.currentData()
        channel_id = ch_data if ch_data else ch_text.split()[0]  # strip "(name)" part

        spec = ControlSpec(
            control_type=ctype,
            title=title,
            icon=CONTROL_ICONS.get(ctype, "⚙"),
            device_id=self._dev_cb.currentData() or "",
            channel_id=channel_id,
            active_low=self._active_low_chk.isChecked(),
            on_action_script=self._script_edit.toPlainText().strip(),
        )
        # Save type-specific params
        panel = self._param_panels.get(ctype)
        if panel:
            panel.save(spec)

        self.result_spec = spec
        self.accept()