blib/lib/App/OpenHAP/Tasmota/Lightbulb.pm untested

filter: Statementstmt 0.0% 0 / 157 Branchbran 0.0% 0 / 76 Conditioncond 0.0% 0 / 23 MC/DCmcdc 0.0% 0 / 15 Subroutinesub 0.0% 0 / 22 Podpod 0.0% 0 / 14 totaltotal 0.0% 0 / 307 CC 39 SCAR 40.0
CC
39
Cov
0%
_rgb_to_hsb
156.0
subscribe_mqtt
56.0
_extract_light_state
56.0
CRAP 54.5
1 # ex:ts=8 sw=4:
2 # $OpenBSD$
3 #
4 # Copyright (c) 2025 Dick Olsson <hi@senzilla.io>
5 #
6 # Permission to use, copy, modify, and distribute this software for any
7 # purpose with or without fee is hereby granted, provided that the above
8 # copyright notice and this permission notice appear in all copies.
9 #
10 # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  
18 use v5.36;
19  
20 package App::OpenHAP::Tasmota::Lightbulb;
21 our $VERSION = '0.1.0';
22  
23 use Fugu::Log;
24 require App::OpenHAP::Tasmota::Device;
25 our @ISA = qw(App::OpenHAP::Tasmota::Device);
26 use Protocol::HAP::Service;
27 use Protocol::HAP::Characteristic;
28  
29 use POSIX qw(fmod);
30  
31 # Light capabilities
32 use constant {
33 CAP_DIMMER => 1, # Brightness control
34 CAP_COLOR => 2, # RGB color control
35 CAP_CT => 4, # Color temperature control
36 };
37  
38 # The Tasmota color-temperature range in mireds (M4)
39 use constant {
40 CT_MIN => 153,
41 CT_MAX => 500,
42 };
43  
44 sub new ( $class, %args )
45 {
46 my $self = $class->SUPER::new(
47 %args,
48 model => 'Tasmota Light',
49 manufacturer => 'OpenHAP',
50 serial => $args{serial} // 'LIGHT-001',
51 );
52  
53 # Light state
54 $self->{power_state} = 0;
55 $self->{brightness} = 100;
56 $self->{hue} = 0;
57 $self->{saturation} = 0;
58 $self->{ct} = 370; # Default warm white (mireds)
59  
60 # Capabilities (H2)
61 $self->{capabilities} = $args{capabilities} // CAP_DIMMER;
62  
63 # Add the Lightbulb service. One row per characteristic:
64 # capability mask (0 = always), type, iid, format, and the
65 # extra arguments.
66 my $lightbulb = Protocol::HAP::Service->new(
67 logger => $self->{logger},
68 type => 'Lightbulb',
69 iid => 10,
70 primary => 1,
71 );
72  
73 my @rows = ( [
74 0, 'On', 11, 'bool',
75 {
76 value => \$self->{power_state},
77 on_set => sub { $self->set_power(@_) },
78 },
79 ],
80 [
81 CAP_DIMMER,
82 'Brightness',
83 12, 'int',
84 {
85 unit => 'percentage',
86 value => \$self->{brightness},
87 min => 0,
88 max => 100,
89 step => 1,
90 on_set => sub { $self->_set_brightness(@_) },
91 },
92 ],
93 [
94 CAP_COLOR,
95 'Hue', 13, 'float',
96 {
97 unit => 'arcdegrees',
98 value => \$self->{hue},
99 min => 0,
100 max => 360,
101 step => 1,
102 on_set => sub { $self->_set_hue(@_) },
103 },
104 ],
105 [
106 CAP_COLOR,
107 'Saturation',
108 14, 'float',
109 {
110 unit => 'percentage',
111 value => \$self->{saturation},
112 min => 0,
113 max => 100,
114 step => 1,
115 on_set => sub { $self->_set_saturation(@_) },
116 },
117 ],
118 [
119 CAP_CT,
120 'ColorTemperature',
121 15, 'uint32',
122 {
123 value => \$self->{ct},
124 min => CT_MIN, # M4: Match Tasmota range
125 max => CT_MAX,
126 step => 1,
127 on_set => sub { $self->_set_ct(@_) },
128 },
129 ],
130 );
131  
132 for my $row (@rows) {
133 my ( $cap, $type, $iid, $format, $extra ) = @$row;
134 next if $cap && !( $self->{capabilities} & $cap );
135  
136 $lightbulb->add_characteristic(
137 Protocol::HAP::Characteristic->new(
138 logger => $self->{logger},
139 type => $type,
140 iid => $iid,
141 format => $format,
142 perms => [ 'pr', 'pw', 'ev' ],
143 %$extra,
144 ) );
145 }
146  
147 $self->add_service($lightbulb);
148  
149 return $self;
150 }
151  
152 sub subscribe_mqtt ($self)
153 {
154 # Call the base class to set up the standard subscriptions
155 # (C1, C2, C3)
156 $self->SUPER::subscribe_mqtt();
157  
158 return unless $self->{mqtt_client}->is_connected();
159  
160 Fugu::Log->default->debug(
161 'Lightbulb %s subscribing to additional MQTT topics',
162 $self->{name} );
163  
164 # M2: The plain-text POWER response (SetOption4 support)
165 $self->_subscribe_plain_power( power_state => 11 );
166  
167 # M2: Subscribe to the DIMMER topic for SetOption4 devices
168 if ( $self->{capabilities} & CAP_DIMMER ) {
169 $self->{mqtt_client}->subscribe(
170 $self->_build_topic( 'stat', 'DIMMER' ),
171 sub ( $recv_topic, $payload ) {
172 if ( $payload =~ /^\d+$/ ) {
173 $self->{brightness} = int($payload);
174 Fugu::Log->default->debug(
175 'Lightbulb %s dimmer: %d',
176 $self->{name}, $payload );
177 $self->notify_change(12);
178 }
179 } );
180 }
181  
182 # M2: Subscribe to the HSBCOLOR topic for SetOption4 devices
183 if ( $self->{capabilities} & CAP_COLOR ) {
184 $self->{mqtt_client}->subscribe(
185 $self->_build_topic( 'stat', 'HSBCOLOR' ),
186 sub ( $recv_topic, $payload ) {
187 $self->_parse_hsbcolor($payload);
188 } );
189 }
190  
191 # M2: Subscribe to the CT topic for SetOption4 devices
192 if ( $self->{capabilities} & CAP_CT ) {
193 $self->{mqtt_client}->subscribe(
194 $self->_build_topic( 'stat', 'CT' ),
195 sub ( $recv_topic, $payload ) {
196 if ( $payload =~ /^\d+$/ ) {
197 my $ct = _clamp_ct( int($payload) );
198 $self->{ct} = $ct;
199 Fugu::Log->default->debug(
200 'Lightbulb %s CT: %d',
201 $self->{name}, $ct );
202 $self->notify_change(15);
203 }
204 } );
205 }
206 }
207  
208 # Override the base method to process the state data from
209 # periodic STATE messages
210 sub _process_state_data ( $self, $data )
211 {
212 $self->SUPER::_process_state_data($data);
213  
214 # Extract the light-specific state
215 $self->_extract_light_state($data);
216 }
217  
218 # Override the base method to process the command results
219 sub _process_result_data ( $self, $data )
220 {
221 $self->SUPER::_process_result_data($data);
222  
223 # Extract the light-specific state
224 $self->_extract_light_state($data);
225 }
226  
227 # Override _on_power_update to update the power state
228 sub _on_power_update ( $self, $state )
229 {
230 if ( $self->{power_state} != $state ) {
231 $self->{power_state} = $state;
232 Fugu::Log->default->debug( 'Lightbulb %s power updated: %s',
233 $self->{name}, $state ? 'ON' : 'OFF' );
234 $self->notify_change(11);
235 }
236 }
237  
238 # _clamp_ct($value):
239 # Clamp a color temperature to the Tasmota/HomeKit range (M4).
240 sub _clamp_ct ($value)
241 {
242 return CT_MIN if $value < CT_MIN;
243 return CT_MAX if $value > CT_MAX;
244  
245 return $value;
246 }
247  
248 # $self->_extract_light_state($data):
249 # Extract the light state from the JSON data.
250 sub _extract_light_state ( $self, $data )
251 {
252 # Brightness (Dimmer in Tasmota)
253 if ( exists $data->{Dimmer} && $self->{capabilities} & CAP_DIMMER ) {
254 my $brightness = $data->{Dimmer};
255 if ( $self->{brightness} != $brightness ) {
256 $self->{brightness} = $brightness;
257 Fugu::Log->default->debug(
258 'Lightbulb %s brightness: %d%%',
259 $self->{name}, $brightness );
260 $self->notify_change(12);
261 }
262 }
263  
264 # HSB Color. The Tasmota HSBColor value is a "h,s,b" string.
265 if ( exists $data->{HSBColor} && $self->{capabilities} & CAP_COLOR ) {
266 $self->_parse_hsbcolor( $data->{HSBColor} );
267 }
268  
269 # M3: Process the Color field for the SetOption17 decimal format
270 if ( exists $data->{Color} && $self->{capabilities} & CAP_COLOR ) {
271 $self->_parse_color( $data->{Color} );
272 }
273  
274 # Color Temperature (CT in Tasmota)
275 if ( exists $data->{CT} && $self->{capabilities} & CAP_CT ) {
276 my $ct = _clamp_ct( $data->{CT} );
277  
278 if ( $self->{ct} != $ct ) {
279 $self->{ct} = $ct;
280 Fugu::Log->default->debug( 'Lightbulb %s CT: %d mireds',
281 $self->{name}, $ct );
282 $self->notify_change(15);
283 }
284 }
285 }
286  
287 # $self->_set_brightness($value):
288 # Set the brightness level (0-100).
289 sub _set_brightness ( $self, $value )
290 {
291 Fugu::Log->default->debug( 'Lightbulb %s brightness set to %d%%',
292 $self->{name}, $value );
293  
294 $self->{mqtt_client}
295 ->publish( $self->_build_topic( 'cmnd', 'Dimmer' ), "$value" );
296 }
297  
298 # $self->_set_hue($value):
299 # Set the hue (0-360).
300 sub _set_hue ( $self, $value )
301 {
302 # Tasmota accepts 0-360 for the hue. The value 360 wraps to 0.
303 $value = int($value) % 360;
304  
305 Fugu::Log->default->debug( 'Lightbulb %s hue set to %d',
306 $self->{name}, $value );
307  
308 $self->{mqtt_client}
309 ->publish( $self->_build_topic( 'cmnd', 'HSBColor1' ), "$value" );
310 }
311  
312 # $self->_set_saturation($value):
313 # Set the saturation (0-100).
314 sub _set_saturation ( $self, $value )
315 {
316 Fugu::Log->default->debug( 'Lightbulb %s saturation set to %d%%',
317 $self->{name}, $value );
318  
319 $self->{mqtt_client}
320 ->publish( $self->_build_topic( 'cmnd', 'HSBColor2' ), "$value" );
321 }
322  
323 # $self->_set_ct($value):
324 # Set the color temperature in mireds (153-500).
325 sub _set_ct ( $self, $value )
326 {
327 # The Tasmota CT range is 153-500. Clamp the value to it.
328 $value = _clamp_ct($value);
329  
330 Fugu::Log->default->debug( 'Lightbulb %s CT set to %d mireds',
331 $self->{name}, $value );
332  
333 $self->{mqtt_client}
334 ->publish( $self->_build_topic( 'cmnd', 'CT' ), "$value" );
335 }
336  
337 # $self->_parse_hsbcolor($value):
338 # Parse the HSBColor string "h,s,b". Update the state.
339 sub _parse_hsbcolor ( $self, $value )
340 {
341 return unless $self->{capabilities} & CAP_COLOR;
342  
343 my @hsb = split /,/, $value;
344 return unless @hsb == 3;
345  
346 my ( $h, $s, $b ) = @hsb;
347  
348 if ( $self->{hue} != $h ) {
349 $self->{hue} = $h;
350 $self->notify_change(13);
351 }
352  
353 if ( $self->{saturation} != $s ) {
354 $self->{saturation} = $s;
355 $self->notify_change(14);
356 }
357  
358 # The brightness value from HSB also updates the Dimmer
359 if ( $self->{capabilities} & CAP_DIMMER
360 && $self->{brightness} != $b )
361 {
362 $self->{brightness} = $b;
363 $self->notify_change(12);
364 }
365 }
366  
367 # $self->_parse_color($value):
368 # Parse the Color field (M3: SetOption17 support).
369 # The method accepts the hex (FF5500) and decimal (255,85,0)
370 # formats.
371 sub _parse_color ( $self, $value )
372 {
373 return unless $self->{capabilities} & CAP_COLOR;
374  
375 my ( $r, $g, $b );
376  
377 # M3: Decimal format (SetOption17 1): "r,g,b"
378 if ( $value =~ /^(\d+),(\d+),(\d+)/ ) {
379 ( $r, $g, $b ) = ( $1, $2, $3 );
380 }
381  
382 # Hex format (default): "RRGGBB" or "RRGGBBWW"
383 elsif ( $value =~ /^([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})/ )
384 {
385 ( $r, $g, $b ) = ( hex($1), hex($2), hex($3) );
386 }
387 else {
388 return; # Unknown format
389 }
390  
391 # Convert RGB to HSB
392 my ( $h, $s, $br ) = $self->_rgb_to_hsb( $r, $g, $b );
393  
394 if ( $self->{hue} != $h ) {
395 $self->{hue} = $h;
396 $self->notify_change(13);
397 }
398  
399 if ( $self->{saturation} != $s ) {
400 $self->{saturation} = $s;
401 $self->notify_change(14);
402 }
403 }
404  
405 # $self->_rgb_to_hsb($r, $g, $b):
406 # Convert RGB (0-255) to HSB (h: 0-360, s: 0-100, b: 0-100).
407 sub _rgb_to_hsb ( $self, $r, $g, $b )
408 {
409 # Normalize the values to 0-1
410 my ( $rn, $gn, $bn ) = ( $r / 255, $g / 255, $b / 255 );
411  
412 my $max =
413 ( $rn > $gn )
414 ? ( $rn > $bn ? $rn : $bn )
415 : ( $gn > $bn ? $gn : $bn );
416 my $min =
417 ( $rn < $gn )
418 ? ( $rn < $bn ? $rn : $bn )
419 : ( $gn < $bn ? $gn : $bn );
420 my $delta = $max - $min;
421  
422 # Brightness
423 my $br = int( $max * 100 );
424  
425 # Saturation
426 my $s = ( $max == 0 ) ? 0 : int( ( $delta / $max ) * 100 );
427  
428 # Hue. The sector arithmetic is floating-point: Perl's % would
429 # truncate the red sector's fraction to 0 and report hue 0 for
430 # every red-dominant color, so the wrap uses fmod.
431 my $h = 0;
432 if ( $delta != 0 ) {
433 if ( $max == $rn ) {
434 $h = 60 * fmod( ( $gn - $bn ) / $delta, 6 );
435 }
436 elsif ( $max == $gn ) {
437 $h = 60 * ( ( ( $bn - $rn ) / $delta ) + 2 );
438 }
439 else {
440 $h = 60 * ( ( ( $rn - $gn ) / $delta ) + 4 );
441 }
442 }
443 $h = int($h);
444 $h += 360 if $h < 0;
445  
446 return ( $h, $s, $br );
447 }
448  
449 1;