Compare commits

..

16 Commits

Author SHA1 Message Date
a6c852369f ctrl_panel: Reformat SpinBox text always if valid
The parameter SpinBoxes previously would only update if the interpreted
value was changed, missing cases where the text would have changed but
the value stays the same, e.g. removing trailing decimal zeros.
2024-08-07 17:59:32 +08:00
3ed181403f ctrl_panel: Move postfilter into its own group 2024-08-07 17:59:27 +08:00
205f5c0ae9 ctrl_panel: Use new locking mechanism from Kirdy 2024-08-07 17:59:07 +08:00
3c4bc4b50c ctrl_panel: Fix editing fields with unit "°C"
A faulty regular expression within PyQtGraph causes any Parameter with a
suffix that doesn't begin with an alphanumeric character (as matched
with \w) to act abnormally. For instance, entering "100 °C" into the
input boxes gets interpreted as 10 °C.

Patch the FLOAT_REGEX in PyQtGraph to simply match for any character in
the suffix group.
2024-08-07 17:59:06 +08:00
3a0bb66212 ctrl_panel: More appropriate steps and fixes 2024-08-07 17:59:06 +08:00
9ebdcfc54f ctrl_panel: Put plotted values into readings group
For more intuitiveness to first-time users
2024-08-07 17:59:06 +08:00
980cabefb5 ctrl_panel: Fix max_v to only have unit "V"
As most users do not need to limit TEC voltage with accuracy of less
than 1mV.
2024-08-07 17:59:06 +08:00
e1861263b2 ctrl_panel: Indicate active parameter of control
Instead of hiding the inactive control parameter, underline and bold the
active control parameter title, e.g. "Set Current" when control method
is constant current, and "Setpoint" when it is temperature PID.
2024-08-07 17:59:06 +08:00
dbbf30bfeb ctrl_panel: Limits fixes
* PID Autotune test current should be positive

* max_v should be 4 V not 5 V

* r0 should not be negative
2024-08-07 17:59:06 +08:00
159c70972e ctrl_panel: Code cleanup
* Remove unnecessary duplication of `THERMOSTAT_PARAMETERS`

* i -> ch

* Separate ParameterTree and Parameter initiation

* Remove extra "channel" option to root parameters, as the "value"
option is already the channel number
2024-08-07 17:59:06 +08:00
651e323206 ctrl_panel: PID Auto Tune -> PID Autotune 2024-08-07 17:59:06 +08:00
d6ba9be20c ctrl_panel: Stop crushing spinboxes
It might not be the case on some themes, but on the default Qt theme the
spinbox are a bit too short for the containing numbers. See
https://github.com/pyqtgraph/pyqtgraph/issues/701.
2024-08-07 17:59:06 +08:00
66556f4c29 ctrl_panel: Pin down units for editable fields
User input always has the same order of magnitude, so allowing multiple
siPrefixes would be unwanted complexity. Don't allow them to be changed.

The Parameter option "noUnitEditing" is added to do so by the following
measures:

1. Don't validate for changed siPrefix (if pinned) and suffix, which
avoids their removal.

2. Avoid getting the cursor embedded within the unit.
2024-08-07 17:59:06 +08:00
c59e3e7ac4 ctrl_panel: Remove need for "mA" hack
Remove all instances of mA scaling scattered all around the code and
specify it in the parameter tree with a single source of truth.

Done by adding the option "pinSiPrefix" for all Parameters of type `int`
or `float`, and using it for current Parameters with unit "mA".
2024-08-07 17:59:06 +08:00
d96d36fb0c ctrl_panel: Appropriate units for measured current
Allow the readonly display of current to vary its SI prefix in the unit,
since as a display entry it won't have the unit adjustment problem.
2024-08-07 17:59:06 +08:00
ef7dbf9b5e ctrl_panel: Improve postfilter description 2024-08-07 17:59:03 +08:00
3 changed files with 116 additions and 99 deletions

View File

@ -30,6 +30,11 @@ class CtrlPanel(QObject):
self.trees_ui = trees_ui
self.NUM_CHANNELS = len(trees_ui)
def _set_value_with_lock(self, value):
if not self.opts.get("lock"):
self.setValue(value)
Parameter.set_value_with_lock = _set_value_with_lock
self.params = [
Parameter.create(
name=f"Thermostat Channel {ch} Parameters",
@ -47,49 +52,28 @@ class CtrlPanel(QObject):
set_tree_label_tips(tree)
for ch, param in enumerate(self.params):
self.params[ch].setValue = self._setValue
param.sigTreeStateChanged.connect(sigTreeStateChanged_handle)
for handle in sigActivated_handles[ch]:
param.child(*handle[0]).sigActivated.connect(handle[1])
param.child("output", "control_method").sigValueChanged.connect(
lambda param, value: param.child("i_set").setWritable(
value == "constant_current"
)
)
def _highlight_usage(param, control_method):
for item in param.child("i_set").items:
font = item.font(0)
font.setUnderline(control_method == "constant_current")
font.setBold(control_method == "constant_current")
item.setFont(0, font)
for item in param.child("target").items:
font = item.font(0)
font.setUnderline(control_method == "temperature_pid")
font.setBold(control_method == "temperature_pid")
item.setFont(0, font)
param.child("output", "control_method").sigValueChanged.connect(
lambda param, value: param.child("target").show(
value == "temperature_pid"
)
)
def _setValue(self, value, blockSignal=None):
"""
Implement 'lock' mechanism for Parameter Type
Modified from the source
"""
try:
if blockSignal is not None:
self.sigValueChanged.disconnect(blockSignal)
value = self._interpretValue(value)
if fn.eq(self.opts["value"], value):
return value
if "lock" in self.opts.keys():
if self.opts["lock"]:
return value
self.opts["value"] = value
self.sigValueChanged.emit(
self, value
) # value might change after signal is received by tree item
finally:
if blockSignal is not None:
self.sigValueChanged.connect(blockSignal)
return self.opts["value"]
param.child("output", "control_method").sigValueChanged.connect(_highlight_usage)
for item in param.child("output", "control_method").items:
font = item.font(0)
font.setBold(True)
item.setFont(0, font)
def change_params_title(self, channel, path, title):
self.params[channel].child(*path).setOpts(title=title)
@ -99,57 +83,59 @@ class CtrlPanel(QObject):
for settings in pid_settings:
channel = settings["channel"]
with QSignalBlocker(self.params[channel]):
self.params[channel].child("pid", "kp").setValue(
self.params[channel].child("pid", "kp").set_value_with_lock(
settings["parameters"]["kp"]
)
self.params[channel].child("pid", "ki").setValue(
self.params[channel].child("pid", "ki").set_value_with_lock(
settings["parameters"]["ki"]
)
self.params[channel].child("pid", "kd").setValue(
self.params[channel].child("pid", "kd").set_value_with_lock(
settings["parameters"]["kd"]
)
self.params[channel].child(
"pid", "pid_output_clamping", "output_min"
).setValue(settings["parameters"]["output_min"])
).set_value_with_lock(settings["parameters"]["output_min"])
self.params[channel].child(
"pid", "pid_output_clamping", "output_max"
).setValue(settings["parameters"]["output_max"])
).set_value_with_lock(settings["parameters"]["output_max"])
self.params[channel].child(
"output", "control_method", "target"
).setValue(settings["target"])
).set_value_with_lock(settings["target"])
@pyqtSlot("QVariantList")
def update_report(self, report_data):
for settings in report_data:
channel = settings["channel"]
with QSignalBlocker(self.params[channel]):
self.params[channel].child("output", "control_method").setValue(
self.params[channel].child(
"output", "control_method"
).set_value_with_lock(
"temperature_pid" if settings["pid_engaged"] else "constant_current"
)
self.params[channel].child(
"output", "control_method", "i_set"
).setValue(settings["i_set"])
).set_value_with_lock(settings["i_set"])
if settings["temperature"] is not None:
self.params[channel].child("readings", "temperature").setValue(
settings["temperature"]
)
self.params[channel].child(
"readings", "temperature"
).set_value_with_lock(settings["temperature"])
if settings["tec_i"] is not None:
self.params[channel].child("readings", "tec_i").setValue(
settings["tec_i"]
)
self.params[channel].child(
"readings", "tec_i"
).set_value_with_lock(settings["tec_i"])
@pyqtSlot("QVariantList")
def update_thermistor(self, sh_data):
for sh_param in sh_data:
channel = sh_param["channel"]
with QSignalBlocker(self.params[channel]):
self.params[channel].child("thermistor", "t0").setValue(
self.params[channel].child("thermistor", "t0").set_value_with_lock(
sh_param["params"]["t0"] - 273.15
)
self.params[channel].child("thermistor", "r0").setValue(
self.params[channel].child("thermistor", "r0").set_value_with_lock(
sh_param["params"]["r0"]
)
self.params[channel].child("thermistor", "b").setValue(
self.params[channel].child("thermistor", "b").set_value_with_lock(
sh_param["params"]["b"]
)
@ -160,15 +146,15 @@ class CtrlPanel(QObject):
for pwm_params in pwm_data:
channel = pwm_params["channel"]
with QSignalBlocker(self.params[channel]):
self.params[channel].child("output", "limits", "max_v").setValue(
pwm_params["max_v"]["value"]
)
self.params[channel].child("output", "limits", "max_i_pos").setValue(
pwm_params["max_i_pos"]["value"]
)
self.params[channel].child("output", "limits", "max_i_neg").setValue(
pwm_params["max_i_neg"]["value"]
)
self.params[channel].child(
"output", "limits", "max_v"
).set_value_with_lock(pwm_params["max_v"]["value"])
self.params[channel].child(
"output", "limits", "max_i_pos"
).set_value_with_lock(pwm_params["max_i_pos"]["value"])
self.params[channel].child(
"output", "limits", "max_i_neg"
).set_value_with_lock(pwm_params["max_i_neg"]["value"])
for limit in "max_i_pos", "max_i_neg", "max_v":
if pwm_params[limit]["value"] == 0.0:
@ -180,6 +166,6 @@ class CtrlPanel(QObject):
for postfilter_params in postfilter_data:
channel = postfilter_params["channel"]
with QSignalBlocker(self.params[channel]):
self.params[channel].child("thermistor", "rate").setValue(
self.params[channel].child("postfilter", "rate").set_value_with_lock(
postfilter_params["rate"]
)

View File

@ -80,7 +80,6 @@
"name": "target",
"title": "Setpoint",
"type": "float",
"visible": false,
"value": 25,
"step": 0.1,
"limits": [
@ -89,7 +88,6 @@
],
"format": "{value:.4f} {suffix}",
"suffix": "°C",
"regex": "(?P<number>[+-]?((((\\d+(\\.\\d*)?)|(\\d*\\.\\d+))([eE][+-]?\\d+)?)|((?i:nan)|(inf))))\\s*((?P<siPrefix>[uyzafpnµm kMGTPEZY]?)(?P<suffix>.*))?$",
"noUnitEditing": true,
"compactHeight": false,
"param": [
@ -188,7 +186,7 @@
"title": "Thermistor Settings",
"expanded": true,
"type": "group",
"tip": "Settings of the connected thermistor\n- Parameters for the resistance to temperature conversion (with the B-Parameter equation)\n- Settings for the 50/60 Hz filter with the thermistor",
"tip": "Parameters for the resistance to temperature conversion with the B-Parameter equation",
"children": [
{
"name": "t0",
@ -202,7 +200,6 @@
],
"format": "{value:.4f} {suffix}",
"suffix": "°C",
"regex": "(?P<number>[+-]?((((\\d+(\\.\\d*)?)|(\\d*\\.\\d+))([eE][+-]?\\d+)?)|((?i:nan)|(inf))))\\s*((?P<siPrefix>[uyzafpnµm kMGTPEZY]?)(?P<suffix>.*))?$",
"noUnitEditing": true,
"compactHeight": false,
"param": [
@ -219,7 +216,9 @@
"type": "float",
"value": 10000,
"step": 100,
"min": 0,
"siPrefix": true,
"pinSiPrefix": "k",
"suffix": "Ω",
"noUnitEditing": true,
"compactHeight": false,
@ -248,10 +247,18 @@
],
"tip": "The Beta Parameter",
"lock": false
}
]
},
{
"name": "postfilter",
"title": "50/60 Hz filter settings",
"type": "group",
"tip": "Settings for the 50/60 Hz filter with the thermistor",
"children": [
{
"name": "rate",
"title": "50/60 Hz filter rejection",
"title": "Rejection",
"type": "list",
"value": 16.67,
"param": [
@ -260,7 +267,7 @@
"rate"
],
"limits": {
"Off": null,
"Off @ 10 Hz": null,
"47 dB @ 10.41 Hz": 27.0,
"62 dB @ 10 Hz": 21.25,
"86 dB @ 9.1 Hz": 20.0,
@ -394,7 +401,6 @@
"step": 0.1,
"format": "{value:.4f} {suffix}",
"suffix": "°C",
"regex": "(?P<number>[+-]?((((\\d+(\\.\\d*)?)|(\\d*\\.\\d+))([eE][+-]?\\d+)?)|((?i:nan)|(inf))))\\s*((?P<siPrefix>[uyzafpnµm kMGTPEZY]?)(?P<suffix>.*))?$",
"noUnitEditing": true,
"compactHeight": false,
"pid_autotune": [
@ -432,8 +438,7 @@
"value": 1.5,
"step": 0.1,
"format": "{value:.4f} {suffix}",
"suffix": "°C",
"regex": "(?P<number>[+-]?((((\\d+(\\.\\d*)?)|(\\d*\\.\\d+))([eE][+-]?\\d+)?)|((?i:nan)|(inf))))\\s*((?P<siPrefix>[uyzafpnµm kMGTPEZY]?)(?P<suffix>.*))?$",
"suffix": "K",
"noUnitEditing": true,
"compactHeight": false,
"pid_autotune": [

View File

@ -1,12 +1,18 @@
import re
from PyQt6.QtCore import QSignalBlocker
from PyQt6.QtGui import QValidator
from pyqtgraph import SpinBox
import pyqtgraph.functions as fn
from pyqtgraph.parametertree.parameterTypes import (
SimpleParameter,
NumericParameterItem,
registerParameterItemType,
from pyqtgraph.parametertree import registerParameterItemType
from pyqtgraph.parametertree.parameterTypes import SimpleParameter, NumericParameterItem
# See https://github.com/pyqtgraph/pyqtgraph/issues/3115
fn.FLOAT_REGEX = re.compile(
r"(?P<number>[+-]?((((\d+(\.\d*)?)|(\d*\.\d+))([eE][+-]?\d+)?)|((?i:nan)|(inf))))\s*"
+ r"((?P<siPrefix>[u" + fn.SI_PREFIXES + r"]?)(?P<suffix>.*))?$"
)
@ -24,9 +30,8 @@ class UnitfulSpinBox(SpinBox):
def __init__(self, parent=None, value=0.0, **kwargs):
super().__init__(parent, value, **kwargs)
self._current_si_prefix = ""
self.lineEdit().cursorPositionChanged.connect(
self.editor_cursor_position_changed
self._editor_cursor_position_changed
)
def validate(self, strn, pos):
@ -34,31 +39,36 @@ class UnitfulSpinBox(SpinBox):
if self.opts.get("noUnitEditing") is True:
suffix = self.opts["suffix"]
pinned_si_prefix = self.opts.get("pinSiPrefix")
# When the unit is edited / removed
if not (
strn.endswith(suffix)
and strn.removesuffix(suffix).endswith(self._current_si_prefix)
):
# Then the input is invalid instead of incomplete, reject this change
suffix_edited = not strn.endswith(suffix)
pinned_si_prefix_edited = (
pinned_si_prefix is not None
and not strn.removesuffix(suffix).endswith(pinned_si_prefix)
)
if suffix_edited or pinned_si_prefix_edited:
ret = QValidator.State.Invalid
return ret, strn, pos
def editor_cursor_position_changed(self, oldpos, newpos):
"""
Modified from the original Qt C++ source,
QAbstractSpinBox::editorCursorPositionChanged
def _editor_cursor_position_changed(self, oldpos, newpos):
# Called on cursor position change
# Skips over the suffix and pinned SI prefix on cursor navigation if option
# noUnitEditing is enabled.
# Modified from the original Qt C++ source,
# QAbstractSpinBox::editorCursorPositionChanged.
# Their suffix is different than our suffix; there's no obvious way to set
# theirs here in the derived class since it is private.
Their suffix is different than our suffix; there's no obvious
way to set that one here.
"""
if self.opts.get("noUnitEditing") is True:
edit = self.lineEdit()
if edit.hasSelectedText():
return # Allow for selecting units, for copy-and-paste
unit_len = len(self._current_si_prefix) + len(self.opts["suffix"])
pinned_si_prefix = self.opts.get("pinSiPrefix") or ""
unit_len = len(pinned_si_prefix) + len(self.opts["suffix"])
text_len = len(edit.text())
pos = -1
@ -81,13 +91,30 @@ class UnitfulSpinBox(SpinBox):
super().setOpts(**opts)
def editingFinishedEvent(self):
# Modified from pyqtgraph.SpinBox.editingFinishedEvent source
new_text = self.lineEdit().text()
if new_text == self.lastText:
return
try:
val = self.interpret()
except Exception:
return
if val is False:
return
if val == self.val:
self.updateText() # still update text so that values are reformatted pretty-like
return
self.setValue(val, delaySignal=False) ## allow text update so that values are reformatted pretty-like
def formatText(self, prev=None):
"""
Implement 'pinSiPrefix' mechanism for pyqtgraph.SpinBox, where
SI prefixes could be pinned down.
Code modified from the PyQtGraph source
In addition to pyqtgraph.SpinBox's formatting, incorporate the
'pinSiPrefix' mechanism, where SI prefixes could be fixed.
"""
# Code modified from the PyQtGraph source
# get the number of decimal places to print
decimals = self.opts['decimals']
@ -109,7 +136,6 @@ class UnitfulSpinBox(SpinBox):
else:
(s, p) = fn.siScale(val)
parts = {'value': val, 'suffix': suffix, 'decimals': decimals, 'siPrefix': p, 'scaledValue': s*val, 'prefix':prefix}
self._current_si_prefix = p
else:
# no SI prefix /suffix requested; scale is 1