gea-pushbutton-hmi 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,67 @@
1
+ """gea_pushbutton_hmi — backward-compatible API for PB-DEV-HMI (firmware 4.1)."""
2
+
3
+ # ── primary class (same name as old pb_api) ──────────────────
4
+ from .core.device_manager import PushButtonLightControl, PushButtonHMI, PushButtonDeviceManager
5
+
6
+ # ── protocol ────────────────────────────────────────────────
7
+ from .core.protocol import PushButtonProtocol
8
+
9
+ # ── constants (old-style flat names) ────────────────────────
10
+ from .core.constants import (
11
+ # commands
12
+ CMD_CONTROL_MODE, CMD_SETTING, CMD_OPERATING, CMD_LUMIN,
13
+ # modes
14
+ CTRL_SW_STATE, CTRL_SW_LUMIN, CTRL_SW_AN0, CTRL_SW_PWM, CTRL_UART,
15
+ CTRL_MODE_BYTES, CTRL_MODES,
16
+ # LED indices
17
+ LED_UR, LED_UL, LED_LR, LED_LL,
18
+ # addressing
19
+ DEVICE_ID_MASK, CMD_MASK, BROADCAST_ID, DEFAULT_DEVICE_ID, VALID_DEVICE_IDS,
20
+ # response codes
21
+ ACK_FIRMWARE_BASE, ACK_SUCCESS,
22
+ NACK_INVALID_HEADER, NACK_INVALID_DC, NACK_INVALID_GS,
23
+ NACK_INVALID_MODE, NACK_CHECKSUM_ERROR,
24
+ # sizes
25
+ CONTROL_PACKET_SIZE, SETTING_PACKET_SIZE, OPERATING_PACKET_SIZE, LUMIN_PACKET_SIZE,
26
+ # value limits
27
+ DC_MAX, DC_HW_MAX, GS_MAX,
28
+ # preset dicts
29
+ COLOR_BITS, COLOR_PRESETS_DC, GS_PRESETS, LUMINOSITY_PRESETS, LIGHT_COLORS,
30
+ )
31
+
32
+ # ── enums (new-style, drop-in) ──────────────────────────────
33
+ from .core.constants import ControlMode, Color, GrayscalePreset
34
+
35
+ # ── exceptions ──────────────────────────────────────────────
36
+ from .core.exceptions import (
37
+ PushButtonError, CommunicationError, TimeoutError,
38
+ ProtocolError, DeviceError, ConfigurationError,
39
+ )
40
+
41
+ # ── state ───────────────────────────────────────────────────
42
+ from .models.device_state import DeviceState
43
+
44
+ __version__ = "1.0.0"
45
+
46
+ __all__ = [
47
+ # classes
48
+ "PushButtonLightControl", "PushButtonHMI", "PushButtonDeviceManager",
49
+ "PushButtonProtocol", "DeviceState",
50
+ # enums
51
+ "ControlMode", "Color", "GrayscalePreset",
52
+ # exceptions
53
+ "PushButtonError", "CommunicationError", "TimeoutError",
54
+ "ProtocolError", "DeviceError", "ConfigurationError",
55
+ # flat constants (all the ones old code imported)
56
+ "CMD_CONTROL_MODE", "CMD_SETTING", "CMD_OPERATING", "CMD_LUMIN",
57
+ "CTRL_SW_STATE", "CTRL_SW_LUMIN", "CTRL_SW_AN0", "CTRL_SW_PWM", "CTRL_UART",
58
+ "CTRL_MODE_BYTES", "CTRL_MODES",
59
+ "LED_UR", "LED_UL", "LED_LR", "LED_LL",
60
+ "DEVICE_ID_MASK", "CMD_MASK", "BROADCAST_ID", "DEFAULT_DEVICE_ID", "VALID_DEVICE_IDS",
61
+ "ACK_FIRMWARE_BASE", "ACK_SUCCESS",
62
+ "NACK_INVALID_HEADER", "NACK_INVALID_DC", "NACK_INVALID_GS",
63
+ "NACK_INVALID_MODE", "NACK_CHECKSUM_ERROR",
64
+ "CONTROL_PACKET_SIZE", "SETTING_PACKET_SIZE", "OPERATING_PACKET_SIZE", "LUMIN_PACKET_SIZE",
65
+ "DC_MAX", "DC_HW_MAX", "GS_MAX",
66
+ "COLOR_BITS", "COLOR_PRESETS_DC", "GS_PRESETS", "LUMINOSITY_PRESETS", "LIGHT_COLORS",
67
+ ]
@@ -0,0 +1,101 @@
1
+ """`gea-pb-hmi` command-line interface."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import logging
8
+ import sys
9
+
10
+ from .core.device_manager import PushButtonHMI
11
+ from .core.constants import BROADCAST_ID, ControlMode, Color, VALID_DEVICE_IDS
12
+ from .core.exceptions import PushButtonError
13
+
14
+
15
+ def _setup_logging(verbose: bool) -> None:
16
+ logging.basicConfig(
17
+ level=logging.DEBUG if verbose else logging.INFO,
18
+ format="%(asctime)s %(levelname)-7s %(name)s: %(message)s",
19
+ )
20
+
21
+
22
+ def _device(s: str) -> int:
23
+ v = int(s)
24
+ if v != BROADCAST_ID and v not in VALID_DEVICE_IDS:
25
+ raise argparse.ArgumentTypeError(f"device must be 0 or 1..62, got {v}")
26
+ return v
27
+
28
+
29
+ def _build_parser() -> argparse.ArgumentParser:
30
+ p = argparse.ArgumentParser(
31
+ prog="gea-pb-hmi",
32
+ description="PB-DEV-HMI RS-485 driver CLI",
33
+ )
34
+ p.add_argument("--port", required=True, help="COM3 / /dev/ttyUSB0")
35
+ p.add_argument("--baud", type=int, default=115200)
36
+ p.add_argument("--verbose", "-v", action="store_true")
37
+
38
+ sub = p.add_subparsers(dest="cmd", required=True)
39
+ sub.add_parser("ports", help="List serial ports")
40
+
41
+ sp = sub.add_parser("mode", help="Set control mode")
42
+ sp.add_argument("--device", type=_device, default=BROADCAST_ID)
43
+ sp.add_argument("--mode", required=True, choices=[m.name for m in ControlMode])
44
+
45
+ sp = sub.add_parser("color", help="Set color preset")
46
+ sp.add_argument("--device", type=_device, default=BROADCAST_ID)
47
+ sp.add_argument("--color", required=True, choices=[c.name for c in Color])
48
+
49
+ sp = sub.add_parser("lumin", help="Set grayscale (0..100%%)")
50
+ sp.add_argument("--device", type=_device, default=BROADCAST_ID)
51
+ sp.add_argument("--percent", type=int, default=100)
52
+
53
+ sp = sub.add_parser("off", help="Turn everything off")
54
+ sp.add_argument("--device", type=_device, default=BROADCAST_ID)
55
+
56
+ sp = sub.add_parser("firmware", help="Read firmware version")
57
+ sp.add_argument("--device", type=_device, required=True)
58
+
59
+ return p
60
+
61
+
62
+ def main(argv: list[str] | None = None) -> int:
63
+ args = _build_parser().parse_args(argv)
64
+ _setup_logging(args.verbose)
65
+
66
+ if args.cmd == "ports":
67
+ for port in PushButtonHMI.list_ports():
68
+ print(port)
69
+ return 0
70
+
71
+ try:
72
+ with PushButtonHMI(args.port, baudrate=args.baud) as hmi:
73
+ if args.cmd == "mode":
74
+ r = hmi.set_control_mode(args.device, args.mode)
75
+ elif args.cmd == "color":
76
+ r = hmi.set_color_preset(args.device, args.color)
77
+ elif args.cmd == "lumin":
78
+ r = hmi.set_luminosity(args.device, 0x0F, args.percent)
79
+ elif args.cmd == "off":
80
+ r = hmi.all_off(args.device)
81
+ elif args.cmd == "firmware":
82
+ major, minor = hmi.read_firmware(args.device)
83
+ print(json.dumps({"device": args.device, "firmware": [major, minor]}))
84
+ return 0
85
+ else:
86
+ return 1
87
+
88
+ print(json.dumps({
89
+ "ok": r.ok,
90
+ "device": r.device_id,
91
+ "cmd": f"0x{r.cmd:02X}",
92
+ "error": r.error_name,
93
+ }))
94
+ return 0 if r.ok else 1
95
+ except PushButtonError as exc:
96
+ print(f"error: {exc}", file=sys.stderr)
97
+ return 1
98
+
99
+
100
+ if __name__ == "__main__":
101
+ raise SystemExit(main())
@@ -0,0 +1,13 @@
1
+ from abc import ABC, abstractmethod
2
+ from typing import Any
3
+
4
+ class BaseCommand(ABC):
5
+ """Base class for device commands"""
6
+
7
+ def __init__(self, device_manager):
8
+ self.device = device_manager
9
+
10
+ @abstractmethod
11
+ def execute(self, *args, **kwargs) -> Any:
12
+ """Execute command - must be implemented by subclasses"""
13
+ pass
@@ -0,0 +1,228 @@
1
+ """Color commands — identical signatures to old pb_api."""
2
+
3
+ from __future__ import annotations
4
+ import math, random, time
5
+ from typing import List, Tuple
6
+
7
+ from .base import BaseCommand
8
+ from ..core.protocol import PushButtonProtocol
9
+ from ..core.constants import *
10
+
11
+
12
+ class ColorCommand(BaseCommand):
13
+ """Same as old pb_api ColorCommand — firmware 4.1 aware."""
14
+
15
+ def __init__(self, device):
16
+ super().__init__(device)
17
+ self._current_state = [0] * 12
18
+
19
+ # ── abstract impl ────────────────────────────────────
20
+ def execute(self, device_id: int, color_values: List[int]) -> bool:
21
+ return self.set_color_values(device_id, color_values)
22
+
23
+ # ── core ────────────────────────────────────────────
24
+ def set_color_values(self, device_id: int, dc_values: List[int]) -> bool:
25
+ if len(dc_values) != 12:
26
+ raise ValueError("DC values must contain exactly 12 values")
27
+ if any(not (0 <= dc <= 63) for dc in dc_values):
28
+ raise ValueError("DC values must be between 0-63")
29
+
30
+ packet = PushButtonProtocol.encode_setting_command(device_id, dc_values)
31
+ response = self.device.send_command(packet)
32
+
33
+ rtype = response.get("type")
34
+ if rtype == "setting_response":
35
+ return response.get("error_code", 0) == 0
36
+ if rtype == "command_response":
37
+ return response.get("response_code") == ACK_SUCCESS
38
+ if rtype == "firmware_ack":
39
+ return True
40
+ return False
41
+
42
+ # ── stateful helpers (identical signature) ──────────
43
+ def set_led_color_preserve(self, device_id: int, led_position: int, color_name: str) -> bool:
44
+ if color_name not in COLOR_PRESETS_DC:
45
+ raise ValueError(f"Unknown color: {color_name}")
46
+ cv = COLOR_PRESETS_DC[color_name]
47
+ base = {0: 0, 1: 3, 2: 6, 3: 9}[led_position]
48
+ self._current_state[base] = cv["G"]
49
+ self._current_state[base + 1] = cv["B"]
50
+ self._current_state[base + 2] = cv["R"]
51
+ return self.set_color_values(device_id, self._current_state)
52
+
53
+ def get_current_state(self) -> List[int]:
54
+ return self._current_state.copy()
55
+
56
+ def reset_state(self) -> None:
57
+ self._current_state = [0] * 12
58
+
59
+ def set_multiple_leds_color(self, device_id: int, led_colors: dict) -> bool:
60
+ led_mapping = {0: 0, 1: 3, 2: 6, 3: 9}
61
+ for pos, name in led_colors.items():
62
+ if name not in COLOR_PRESETS_DC:
63
+ raise ValueError(f"Unknown color: {name}")
64
+ cv = COLOR_PRESETS_DC[name]
65
+ base = led_mapping[pos]
66
+ self._current_state[base] = cv["G"]
67
+ self._current_state[base + 1] = cv["B"]
68
+ self._current_state[base + 2] = cv["R"]
69
+ return self.set_color_values(device_id, self._current_state)
70
+
71
+ def set_all_leds_color(self, device_id: int, color_name: str) -> bool:
72
+ if color_name not in COLOR_PRESETS_DC:
73
+ raise ValueError(f"Unknown color: {color_name}")
74
+ cv = COLOR_PRESETS_DC[color_name]
75
+ arr: list[int] = []
76
+ for _ in range(4):
77
+ arr.extend([cv["G"], cv["B"], cv["R"]])
78
+ return self.set_color_values(device_id, arr)
79
+
80
+ def set_led_color(self, device_id: int, led_position: int, color_name: str,
81
+ current_state: List[int] | None = None) -> bool:
82
+ if color_name not in COLOR_PRESETS_DC:
83
+ raise ValueError(f"Unknown color: {color_name}")
84
+ arr = list(current_state) if current_state is not None else [0] * 12
85
+ cv = COLOR_PRESETS_DC[color_name]
86
+ base = {0: 0, 1: 3, 2: 6, 3: 9}[led_position]
87
+ arr[base] = cv["G"]
88
+ arr[base + 1] = cv["B"]
89
+ arr[base + 2] = cv["R"]
90
+ return self.set_color_values(device_id, arr)
91
+
92
+ def set_custom_rgb_dc(self, device_id: int, led_position: int,
93
+ red_dc: int, green_dc: int, blue_dc: int) -> bool:
94
+ if not all(0 <= v <= 63 for v in (red_dc, green_dc, blue_dc)):
95
+ raise ValueError("DC values must be between 0-63")
96
+ arr = [0] * 12
97
+ base = led_position * 3
98
+ arr[base], arr[base + 1], arr[base + 2] = green_dc, blue_dc, red_dc
99
+ return self.set_color_values(device_id, arr)
100
+
101
+ def set_custom_rgb_percentage(self, device_id: int, led_position: int,
102
+ red_percent: int, green_percent: int, blue_percent: int) -> bool:
103
+ if not all(0 <= v <= 100 for v in (red_percent, green_percent, blue_percent)):
104
+ raise ValueError("Percentage values must be between 0-100")
105
+ return self.set_custom_rgb_dc(
106
+ device_id, led_position,
107
+ int(red_percent * DC_MAX / 100),
108
+ int(green_percent * DC_MAX / 100),
109
+ int(blue_percent * DC_MAX / 100),
110
+ )
111
+
112
+ def set_all_leds_rgb_dc(self, device_id: int,
113
+ red_dc: int, green_dc: int, blue_dc: int) -> bool:
114
+ if not all(0 <= v <= 63 for v in (red_dc, green_dc, blue_dc)):
115
+ raise ValueError("DC values must be between 0-63")
116
+ arr: list[int] = []
117
+ for _ in range(4):
118
+ arr.extend([green_dc, blue_dc, red_dc])
119
+ return self.set_color_values(device_id, arr)
120
+
121
+ # ── effects ─────────────────────────────────────────
122
+ def smooth_color_transition(self, device_id: int,
123
+ start_color: Tuple[int, int, int],
124
+ end_color: Tuple[int, int, int],
125
+ duration: float = 3.0, steps: int = 30) -> bool:
126
+ sr, sg, sb = start_color
127
+ er, eg, eb = end_color
128
+ for s in range(steps + 1):
129
+ p = s / steps
130
+ if not self.set_all_leds_rgb_dc(
131
+ device_id,
132
+ int(sr + (er - sr) * p),
133
+ int(sg + (eg - sg) * p),
134
+ int(sb + (eb - sb) * p),
135
+ ):
136
+ return False
137
+ time.sleep(duration / steps)
138
+ return True
139
+
140
+ def rainbow_cycle(self, device_id: int, cycles: int = 3,
141
+ duration_per_cycle: float = 5.0) -> bool:
142
+ steps = 36
143
+ delay = duration_per_cycle / steps
144
+ for _ in range(cycles):
145
+ for s in range(steps):
146
+ r, g, b = self._hsv_to_rgb_dc((s * 360 / steps) % 360, 1.0, 1.0)
147
+ if not self.set_all_leds_rgb_dc(device_id, r, g, b):
148
+ return False
149
+ time.sleep(delay)
150
+ return True
151
+
152
+ def breathing_effect(self, device_id: int, base_color: Tuple[int, int, int],
153
+ breaths: int = 5, breath_duration: float = 2.0) -> bool:
154
+ br, bg, bb = base_color
155
+ steps = 36
156
+ delay = breath_duration / steps
157
+ for _ in range(breaths):
158
+ for s in range(steps):
159
+ k = math.sin(s / steps * math.pi)
160
+ if not self.set_all_leds_rgb_dc(device_id, int(br*k), int(bg*k), int(bb*k)):
161
+ return False
162
+ time.sleep(delay)
163
+ for s in range(steps, 0, -1):
164
+ k = math.sin(s / steps * math.pi)
165
+ if not self.set_all_leds_rgb_dc(device_id, int(br*k), int(bg*k), int(bb*k)):
166
+ return False
167
+ time.sleep(delay)
168
+ return True
169
+
170
+ def color_wave(self, device_id: int, wave_colors: List[Tuple[int, int, int]],
171
+ wave_duration: float = 8.0) -> bool:
172
+ if len(wave_colors) < 2:
173
+ raise ValueError("need at least 2 colors")
174
+ segs = len(wave_colors)
175
+ steps_per_seg = 25
176
+ delay = wave_duration / (segs * steps_per_seg)
177
+ ext = wave_colors + [wave_colors[0]]
178
+ for i in range(segs):
179
+ sc, ec = ext[i], ext[i + 1]
180
+ for s in range(steps_per_seg + 1):
181
+ p = s / steps_per_seg
182
+ if not self.set_all_leds_rgb_dc(
183
+ device_id,
184
+ int(sc[0] + (ec[0]-sc[0])*p),
185
+ int(sc[1] + (ec[1]-sc[1])*p),
186
+ int(sc[2] + (ec[2]-sc[2])*p),
187
+ ):
188
+ return False
189
+ time.sleep(delay)
190
+ return True
191
+
192
+ def random_color_transition(self, device_id: int, transitions: int = 10,
193
+ transition_duration: float = 2.0) -> bool:
194
+ cur = (random.randint(0, 63), random.randint(0, 63), random.randint(0, 63))
195
+ for _ in range(transitions):
196
+ nxt = (random.randint(0, 63), random.randint(0, 63), random.randint(0, 63))
197
+ if not self.smooth_color_transition(device_id, cur, nxt, transition_duration):
198
+ return False
199
+ cur = nxt
200
+ return True
201
+
202
+ def temperature_colors(self, device_id: int, temperature: str = "warm") -> bool:
203
+ presets = {
204
+ "warm": (63, 20, 45),
205
+ "cool": (40, 40, 63),
206
+ "daylight": (50, 45, 55),
207
+ "candle": (63, 10, 15),
208
+ }
209
+ if temperature not in presets:
210
+ raise ValueError(f"Unknown temperature: {temperature}")
211
+ r, g, b = presets[temperature]
212
+ return self.set_all_leds_rgb_dc(device_id, r, g, b)
213
+
214
+ @staticmethod
215
+ def _hsv_to_rgb_dc(h: float, s: float, v: float) -> Tuple[int, int, int]:
216
+ h /= 360.0
217
+ i = math.floor(h * 6)
218
+ f = h * 6 - i
219
+ p = v * (1 - s)
220
+ q = v * (1 - f * s)
221
+ t = v * (1 - (1 - f) * s)
222
+ if i % 6 == 0: r, g, b = v, t, p
223
+ elif i % 6 == 1: r, g, b = q, v, p
224
+ elif i % 6 == 2: r, g, b = p, v, t
225
+ elif i % 6 == 3: r, g, b = p, q, v
226
+ elif i % 6 == 4: r, g, b = t, p, v
227
+ else: r, g, b = v, p, q
228
+ return int(r * 44), int(g * 44), int(b * 44)
@@ -0,0 +1,29 @@
1
+ from .base import BaseCommand
2
+ from ..core.protocol import PushButtonProtocol
3
+ from ..core.constants import *
4
+
5
+
6
+ class ControlModeCommand(BaseCommand):
7
+ """Same signature as old pb_api."""
8
+
9
+ def execute(self, device_id: int, control_mode: int) -> bool:
10
+ return self.set_control_mode(device_id, control_mode)
11
+
12
+ def set_control_mode(self, device_id: int, control_mode: int) -> bool:
13
+ packet = PushButtonProtocol.encode_control_mode(device_id, int(control_mode))
14
+ response = self.device.send_command(packet)
15
+
16
+ rtype = response.get("type")
17
+ if rtype == "control_mode_response":
18
+ # success ⇔ firmware echoed the SAME mode AND no error bits
19
+ if response.get("error_code", 0) != 0:
20
+ return False
21
+ return response["control_mode"] == int(control_mode)
22
+ if rtype == "command_response":
23
+ return response["response_code"] == ACK_SUCCESS
24
+ return False
25
+
26
+ def set_control_mode_by_name(self, device_id: int, control_mode_name: str) -> bool:
27
+ if control_mode_name not in CTRL_MODE_BYTES:
28
+ raise ValueError(f"Invalid control mode name: {control_mode_name}")
29
+ return self.set_control_mode(device_id, CTRL_MODE_BYTES[control_mode_name])
@@ -0,0 +1,69 @@
1
+ from typing import List
2
+ from .base import BaseCommand
3
+ from ..core.protocol import PushButtonProtocol
4
+ from ..core.constants import *
5
+
6
+
7
+ class LuminosityCommand(BaseCommand):
8
+ """Same signatures as old pb_api."""
9
+
10
+ def execute(self, device_id: int, led_states: int, luminosity_values: List[int]) -> bool:
11
+ return self.set_luminosity_values(device_id, led_states, luminosity_values)
12
+
13
+ def set_luminosity_values(self, device_id: int, led_states: int,
14
+ luminosity_values: List[int]) -> bool:
15
+ if len(luminosity_values) != 12:
16
+ raise ValueError("Luminosity values must contain exactly 12 values")
17
+ if any(not (0 <= v <= 100) for v in luminosity_values):
18
+ raise ValueError("Luminosity values must be between 0-100")
19
+
20
+ packet = PushButtonProtocol.encode_operating_command(
21
+ device_id, led_states, luminosity_values,
22
+ )
23
+ response = self.device.send_command(packet)
24
+
25
+ rtype = response.get("type")
26
+ if rtype == "operating_response":
27
+ return response.get("error_code", 0) == 0
28
+ if rtype == "command_response":
29
+ return response.get("response_code") == ACK_SUCCESS
30
+ if rtype == "firmware_ack":
31
+ return True
32
+ return False
33
+
34
+ def set_led_luminosity(self, device_id: int, led_position: int, luminosity: int) -> bool:
35
+ if not (0 <= luminosity <= 100):
36
+ raise ValueError("Luminosity must be between 0-100")
37
+ arr = [0] * 12
38
+ base = {0: 0, 1: 3, 2: 6, 3: 9}[led_position]
39
+ arr[base] = arr[base + 1] = arr[base + 2] = luminosity
40
+ led_states = {0: 0x08, 1: 0x04, 2: 0x02, 3: 0x01}[led_position]
41
+ return self.set_luminosity_values(device_id, led_states, arr)
42
+
43
+ def set_all_luminosity(self, device_id: int, luminosity: int, all_leds_on: bool = True) -> bool:
44
+ arr = [luminosity] * 12
45
+ led_states = 0x0F if all_leds_on else 0x00
46
+ return self.set_luminosity_values(device_id, led_states, arr)
47
+
48
+ def set_luminosity_preset(self, device_id: int, preset_name: str) -> bool:
49
+ if preset_name not in GS_PRESETS:
50
+ raise ValueError(f"Unknown preset: {preset_name}")
51
+ return self.set_all_luminosity(
52
+ device_id, GS_PRESETS[preset_name], all_leds_on=(preset_name != "OFF"),
53
+ )
54
+
55
+ def test_luminosity_functions(self, device_id: int):
56
+ import time
57
+ tests = [
58
+ ("OFF", lambda: self.set_all_luminosity(device_id, 0)),
59
+ ("50%", lambda: self.set_all_luminosity(device_id, 50)),
60
+ ("100%", lambda: self.set_all_luminosity(device_id, 100)),
61
+ ("UR 80%", lambda: self.set_led_luminosity(device_id, 0, 80)),
62
+ ("UL 60%", lambda: self.set_led_luminosity(device_id, 1, 60)),
63
+ ("LR 40%", lambda: self.set_led_luminosity(device_id, 2, 40)),
64
+ ("LL 20%", lambda: self.set_led_luminosity(device_id, 3, 20)),
65
+ ]
66
+ for name, fn in tests:
67
+ print(f"Testing {name}... {'OK' if fn() else 'FAILED'}")
68
+ time.sleep(1.0)
69
+ return True
@@ -0,0 +1,33 @@
1
+ from .base import BaseCommand
2
+ from ..core.protocol import PushButtonProtocol
3
+ from ..core.constants import *
4
+
5
+
6
+ class SystemConfigCommand(BaseCommand):
7
+ """Same signatures as old pb_api."""
8
+
9
+ def execute(self, device_id: int, gs_max: int, gs_day: int, gs_night: int) -> bool:
10
+ return self.set_luminosity_presets(device_id, gs_max, gs_day, gs_night)
11
+
12
+ def set_luminosity_presets(self, device_id: int,
13
+ gs_max: int, gs_day: int, gs_night: int) -> bool:
14
+ if not all(0 <= v <= GS_MAX for v in (gs_max, gs_day, gs_night)):
15
+ raise ValueError("GS values must be between 0-4095")
16
+ packet = PushButtonProtocol.encode_lumin_command(device_id, gs_max, gs_day, gs_night)
17
+ response = self.device.send_command(packet)
18
+ rtype = response.get("type")
19
+ if rtype == "lumin_response":
20
+ return response.get("error_code", 0) == 0
21
+ if rtype == "command_response":
22
+ return response.get("response_code") == ACK_SUCCESS
23
+ return False
24
+
25
+ def set_luminosity_percentages(self, device_id: int,
26
+ max_percent: int, day_percent: int,
27
+ night_percent: int) -> bool:
28
+ return self.set_luminosity_presets(
29
+ device_id,
30
+ PushButtonProtocol.convert_percentage_to_12bit(max_percent),
31
+ PushButtonProtocol.convert_percentage_to_12bit(day_percent),
32
+ PushButtonProtocol.convert_percentage_to_12bit(night_percent),
33
+ )
@@ -0,0 +1,127 @@
1
+ """Protocol constants — MUST match firmware 4.1 (RS-485)."""
2
+
3
+ from __future__ import annotations
4
+ from enum import Enum, IntEnum
5
+
6
+ # ── Command types ────────────────────────────────────────────
7
+ CMD_CONTROL_MODE = 0x00
8
+ CMD_SETTING = 0x40
9
+ CMD_OPERATING = 0x80
10
+ CMD_LUMIN = 0xC0
11
+
12
+ # ── Control modes (old-style plain ints) ─────────────────────
13
+ CTRL_SW_STATE = 0b00000001
14
+ CTRL_SW_LUMIN = 0b00000011
15
+ CTRL_SW_AN0 = 0b00000101
16
+ CTRL_SW_PWM = 0b00001001
17
+ CTRL_UART = 0b00010000
18
+
19
+ CTRL_MODE_BYTES = {
20
+ "SWITCH_MODE": CTRL_SW_STATE,
21
+ "SWITCH_LUMIN_MODE": CTRL_SW_LUMIN,
22
+ "ANALOG_MODE": CTRL_SW_AN0,
23
+ "PWM_MODE": CTRL_SW_PWM,
24
+ "UART_MODE": CTRL_UART,
25
+ }
26
+
27
+ CTRL_MODES = {
28
+ CTRL_SW_STATE: "SWITCH_MODE",
29
+ CTRL_SW_LUMIN: "SWITCH_LUMIN_MODE",
30
+ CTRL_SW_AN0: "ANALOG_MODE",
31
+ CTRL_SW_PWM: "PWM_MODE",
32
+ CTRL_UART: "UART_MODE",
33
+ }
34
+
35
+ # ── LED indices (logical, match commands) ────────────────────
36
+ LED_UR = 0
37
+ LED_UL = 1
38
+ LED_LR = 2
39
+ LED_LL = 3
40
+
41
+ # ── Response codes ───────────────────────────────────────────
42
+ ACK_FIRMWARE_BASE = 0xC0
43
+ ACK_SUCCESS = 0xDD
44
+ NACK_INVALID_HEADER = 0x33
45
+ NACK_INVALID_DC = 0x34
46
+ NACK_INVALID_GS = 0x35
47
+ NACK_INVALID_MODE = 0x36
48
+ NACK_CHECKSUM_ERROR = 0x44
49
+
50
+ # ── Addressing ───────────────────────────────────────────────
51
+ DEVICE_ID_MASK = 0x3F
52
+ CMD_MASK = 0xC0
53
+ BROADCAST_ID = 0x00
54
+ DEFAULT_DEVICE_ID = 0x3F
55
+ VALID_DEVICE_IDS = list(range(1, 63))
56
+
57
+ # ── Packet sizes (4.1: control = 4 bytes, was 3 in 4.0) ──────
58
+ CONTROL_PACKET_SIZE = 4
59
+ SETTING_PACKET_SIZE = 15
60
+ OPERATING_PACKET_SIZE = 15
61
+ LUMIN_PACKET_SIZE = 8
62
+
63
+ # ── Value limits ─────────────────────────────────────────────
64
+ DC_MAX = 44 # old UI max; firmware accepts 0–63
65
+ DC_HW_MAX = 63 # absolute hardware limit
66
+ GS_MAX = 4095
67
+
68
+ # ── Color presets (old-style dicts) ──────────────────────────
69
+ COLOR_BITS = {
70
+ "OFF": (0, 0, 0),
71
+ "RED": (0, 0, 1),
72
+ "GREEN": (1, 0, 0),
73
+ "BLUE": (0, 1, 0),
74
+ "ORANGE": (1, 0, 1),
75
+ "MAGENTA": (0, 1, 1),
76
+ "CYAN": (1, 1, 0),
77
+ "WHITE": (1, 1, 1),
78
+ }
79
+
80
+ COLOR_PRESETS_DC = {
81
+ "OFF": {'G': 0, 'B': 0, 'R': 0},
82
+ "RED": {'G': 0, 'B': 0, 'R': 44},
83
+ "GREEN": {'G': 44, 'B': 0, 'R': 0},
84
+ "BLUE": {'G': 0, 'B': 44, 'R': 0},
85
+ "ORANGE": {'G': 15, 'B': 0, 'R': 44},
86
+ "MAGENTA": {'G': 0, 'B': 44, 'R': 44},
87
+ "CYAN": {'G': 44, 'B': 44, 'R': 0},
88
+ "WHITE": {'G': 44, 'B': 44, 'R': 44},
89
+ }
90
+
91
+ LUMINOSITY_PRESETS = {"OFF": 0, "NIGHT": 20, "DAY": 50, "MAX": 100}
92
+ GS_PRESETS = LUMINOSITY_PRESETS # alias kept for compat
93
+
94
+ LIGHT_COLORS = {
95
+ "OFF": "#000000", "RED": "#FF4C4C", "GREEN": "#75FF75",
96
+ "BLUE": "#4DBEFF", "ORANGE": "#FFC558", "MAGENTA": "#FF6BFF",
97
+ "CYAN": "#8FFFFF", "WHITE": "#FFFFFF",
98
+ }
99
+
100
+ IGNORE_UNKNOWN_SINGLE_BYTES = True
101
+
102
+ # ── Enum versions (new style, drop-in replacement) ───────────
103
+ class ControlMode(IntEnum):
104
+ SWITCH = CTRL_SW_STATE
105
+ SWITCH_LUMIN = CTRL_SW_LUMIN
106
+ ANALOG = CTRL_SW_AN0
107
+ PWM = CTRL_SW_PWM
108
+ UART = CTRL_UART
109
+
110
+ class Color(str, Enum):
111
+ OFF = "OFF"; RED = "RED"; GREEN = "GREEN"; BLUE = "BLUE"
112
+ ORANGE = "ORANGE"; MAGENTA = "MAGENTA"; CYAN = "CYAN"; WHITE = "WHITE"
113
+
114
+ @property
115
+ def bits(self) -> tuple[int, int, int]:
116
+ return COLOR_BITS[self.value]
117
+
118
+ class GrayscalePreset(IntEnum):
119
+ OFF = 0; NIGHT = 20; DAY = 50; MAX = 100
120
+
121
+ NACK_NAMES = {
122
+ NACK_INVALID_HEADER: "invalid header",
123
+ NACK_INVALID_DC: "invalid DC value",
124
+ NACK_INVALID_GS: "invalid GS value",
125
+ NACK_INVALID_MODE: "invalid control mode",
126
+ NACK_CHECKSUM_ERROR: "checksum error",
127
+ }