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

filter: Statementstmt 0.0% 0 / 117 Branchbran 0.0% 0 / 44 Conditioncond 0.0% 0 / 20 MC/DCmcdc 0.0% 0 / 11 Subroutinesub 0.0% 0 / 28 Podpod 0.0% 0 / 22 totaltotal 0.0% 0 / 242 CC 23 SCAR 23.9
CC
23
Cov
0%
_find_sensor_values
42.0
subscribe_mqtt
12.0
_handle_lwt
12.0
CRAP 10.9
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::Device;
21 our $VERSION = '0.1.0';
22  
23 use Fugu::Log;
24 require Protocol::HAP::Accessory;
25 our @ISA = qw(Protocol::HAP::Accessory);
26  
27 use JSON::XS;
28  
29 use constant {
30  
31 # Device availability states
32 AVAILABILITY_UNKNOWN => 0,
33 AVAILABILITY_ONLINE => 1,
34 AVAILABILITY_OFFLINE => 2,
35 };
36  
37 # The sensor types the walk below knows (H5). Thermostat and Sensor
38 # share this one list.
39 use constant SENSOR_TYPES =>
40 qw(DS18B20 DHT11 DHT22 AM2301 BME280 BMP280 SHT3X SI7021);
41  
42 sub new ( $class, %args )
43 {
44 my $self = $class->SUPER::new(%args);
45  
46 $self->{mqtt_topic} = $args{mqtt_topic};
47 $self->{mqtt_client} = $args{mqtt_client};
48 $self->{relay_index} = $args{relay_index} // 0; # 0 = no index
49 $self->{availability} = AVAILABILITY_UNKNOWN;
50 $self->{temp_unit} = 'C'; # Default to Celsius
51  
52 return $self;
53 }
54  
55 # $self->subscribe_mqtt():
56 # Subscribe to all standard Tasmota topics.
57 # Subclasses must call SUPER::subscribe_mqtt() first.
58 sub subscribe_mqtt ($self)
59 {
60 return unless $self->{mqtt_client}->is_connected();
61  
62 Fugu::Log->default->debug(
63 'Tasmota %s subscribing to MQTT topics for %s',
64 ref($self), $self->{name} );
65  
66 # C1: Subscribe to LWT for device availability
67 $self->{mqtt_client}->subscribe(
68 $self->_build_topic( 'tele', 'LWT' ),
69 sub ( $recv_topic, $payload ) {
70 $self->_handle_lwt($payload);
71 } );
72  
73 # C2: Subscribe to tele/STATE for periodic state updates
74 $self->{mqtt_client}->subscribe(
75 $self->_build_topic( 'tele', 'STATE' ),
76 sub ( $recv_topic, $payload ) {
77 my $data = $self->_decode( $payload, 'STATE' )
78 or return;
79 $self->_process_state_data($data);
80 } );
81  
82 # C3: Subscribe to stat/RESULT for command responses
83 $self->{mqtt_client}->subscribe(
84 $self->_build_topic( 'stat', 'RESULT' ),
85 sub ( $recv_topic, $payload ) {
86 my $data = $self->_decode( $payload, 'RESULT' )
87 or return;
88 $self->_process_result_data($data);
89 } );
90  
91 # Subscribe to tele/SENSOR for sensor data
92 $self->{mqtt_client}->subscribe(
93 $self->_build_topic( 'tele', 'SENSOR' ),
94 sub ( $recv_topic, $payload ) {
95 my $data = $self->_decode( $payload, 'SENSOR' )
96 or return;
97  
98 # Extract the temperature unit if it is present (H4)
99 if ( exists $data->{TempUnit} ) {
100 $self->{temp_unit} = $data->{TempUnit};
101 }
102  
103 $self->_process_sensor_data($data);
104 } );
105  
106 # C1/H1: Subscribe to STATUS11 for full state reconciliation
107 $self->{mqtt_client}->subscribe(
108 $self->_build_topic( 'stat', 'STATUS11' ),
109 sub ( $recv_topic, $payload ) {
110 $self->_handle_status11($payload);
111 } );
112 }
113  
114 # $self->_subscribe_status_sns($status):
115 # Subscribe to one STATUS8/STATUS10 sensor response (H5). The
116 # device sends STATUS8 after an active query, and the spec
117 # recommends STATUS10. Both wrap the sensor data in StatusSNS.
118 sub _subscribe_status_sns ( $self, $status )
119 {
120 $self->{mqtt_client}->subscribe(
121 $self->_build_topic( 'stat', $status ),
122 sub ( $recv_topic, $payload ) {
123 $self->_handle_status_sns( $payload, $status );
124 } );
125 }
126  
127 # $self->_handle_status_sns($payload, $label):
128 # Process one STATUS8/STATUS10 response: unwrap StatusSNS, track
129 # the temperature unit (H4), and hand the data to the sensor
130 # extractor of the subclass.
131 sub _handle_status_sns ( $self, $payload, $label )
132 {
133 my $data = $self->_decode( $payload, $label ) or return;
134 my $sns = $data->{StatusSNS} or return;
135  
136 if ( exists $sns->{TempUnit} ) {
137 $self->{temp_unit} = $sns->{TempUnit};
138 }
139  
140 $self->_process_sensor_data($sns);
141 }
142  
143 # $self->query_initial_state():
144 # Query the device for the current state after a connect or
145 # an LWT Online. The method uses Status 11 for full state
146 # reconciliation (C1/H1).
147 sub query_initial_state ($self)
148 {
149 return unless $self->{mqtt_client}->is_connected();
150  
151 Fugu::Log->default->debug( 'Querying initial state for %s',
152 $self->{name} );
153  
154 # Request the full status (Status 11). Spec ยง6.1 recommends
155 # this query.
156 $self->query_status(11);
157 }
158  
159 # $self->is_online():
160 # Check if the device is online.
161 sub is_online ($self)
162 {
163 return $self->{availability} == AVAILABILITY_ONLINE;
164 }
165  
166 # $self->_handle_lwt($payload):
167 # Process the LWT (Last Will and Testament) message (C1).
168 sub _handle_lwt ( $self, $payload )
169 {
170 if ( $payload eq 'Online' ) {
171 $self->{availability} = AVAILABILITY_ONLINE;
172 Fugu::Log->default->info( 'Device %s is online',
173 $self->{name} );
174  
175 # Query the initial state when the device comes online (H3)
176 $self->query_initial_state();
177 }
178 elsif ( $payload eq 'Offline' ) {
179 $self->{availability} = AVAILABILITY_OFFLINE;
180 Fugu::Log->default->warning( 'Device %s is offline',
181 $self->{name} );
182 }
183 else {
184 Fugu::Log->default->debug( 'Unknown LWT payload for %s: %s',
185 $self->{name}, $payload );
186 }
187 }
188  
189 # $self->_decode($payload, $label):
190 # Decode one JSON payload from the device. The method returns
191 # the decoded data, or undef with the parse error in the log.
192 # Everything from the broker is external input, so a payload
193 # that does not parse is logged and dropped, never fatal.
194 sub _decode ( $self, $payload, $label )
195 {
196 my $data = eval { decode_json($payload) };
197 if ($@) {
198 Fugu::Log->default->error( 'Error parsing %s for %s: %s',
199 $label, $self->{name}, $@ );
200 return;
201 }
202  
203 return $data;
204 }
205  
206 # $self->_handle_status11($payload):
207 # Process the STATUS11 response for state reconciliation (C1/H1).
208 sub _handle_status11 ( $self, $payload )
209 {
210 my $data = $self->_decode( $payload, 'STATUS11' ) or return;
211  
212 # STATUS11 wraps the data in StatusSTS. The format is the
213 # same as the periodic STATE.
214 if ( exists $data->{StatusSTS} ) {
215 Fugu::Log->default->debug( 'STATUS11 received for %s',
216 $self->{name} );
217 $self->_process_state_data( $data->{StatusSTS} );
218 }
219 }
220  
221 # $self->_process_state_data($data):
222 # Process the parsed STATE data. Subclasses can override
223 # this method.
224 sub _process_state_data ( $self, $data )
225 {
226 # The default implementation checks for the POWER state
227 $self->_extract_power_state($data);
228 }
229  
230 # $self->_process_result_data($data):
231 # Process the parsed RESULT data. Subclasses can override
232 # this method.
233 sub _process_result_data ( $self, $data )
234 {
235 # The default implementation checks for the POWER state
236 $self->_extract_power_state($data);
237 }
238  
239 # $self->_process_sensor_data($data):
240 # Process the parsed SENSOR data. Subclasses can override
241 # this method.
242 sub _process_sensor_data ( $self, $data )
243 {
244 # The default does nothing. Subclasses can override this
245 # method.
246 }
247  
248 # $self->_extract_power_state($data):
249 # Extract the power state from the JSON data. The method
250 # supports multi-relay devices (H1).
251 sub _extract_power_state ( $self, $data )
252 {
253 my $power_key = $self->_get_power_key();
254  
255 if ( exists $data->{$power_key} ) {
256 my $power = $data->{$power_key};
257 $self->_on_power_update( $power eq 'ON' ? 1 : 0 );
258 }
259 }
260  
261 # $self->_get_power_key():
262 # Get the power key name for this device (H1 multi-relay
263 # support).
264 sub _get_power_key ($self)
265 {
266 if ( $self->{relay_index} && $self->{relay_index} > 0 ) {
267 return 'POWER' . $self->{relay_index};
268 }
269  
270 return 'POWER';
271 }
272  
273 # $self->_get_power_topic():
274 # Get the power topic for commands (H1 multi-relay support).
275 sub _get_power_topic ($self)
276 {
277 if ( $self->{relay_index} && $self->{relay_index} > 0 ) {
278 return $self->_build_topic( 'cmnd',
279 'Power' . $self->{relay_index} );
280 }
281  
282 return $self->_build_topic( 'cmnd', 'Power' );
283 }
284  
285 # $self->_build_topic($prefix, $command):
286 # Build a topic with the default Tasmota FullTopic pattern,
287 # %prefix%/%topic%/ (H2).
288 # $prefix: 'cmnd', 'stat', or 'tele'
289 # $command: The command/topic suffix
290 sub _build_topic ( $self, $prefix, $command )
291 {
292 return "$prefix/$self->{mqtt_topic}/$command";
293 }
294  
295 # $self->_subscribe_plain_power($field, $iid):
296 # Subscribe to the plain-text POWER response (M2, SetOption4
297 # support). The payload updates $self->{$field} and notifies
298 # the characteristic $iid on a change.
299 sub _subscribe_plain_power ( $self, $field, $iid )
300 {
301 $self->{mqtt_client}->subscribe(
302 $self->_build_topic( 'stat', $self->_get_power_key() ),
303 sub ( $recv_topic, $payload ) {
304 my $state = ( $payload eq 'ON' ) ? 1 : 0;
305 return if $self->{$field} == $state;
306  
307 $self->{$field} = $state;
308 Fugu::Log->default->debug( '%s power state: %s',
309 $self->{name}, $payload );
310 $self->notify_change($iid);
311 } );
312 }
313  
314 # $self->_on_power_update($state):
315 # The base class calls this method when the power state
316 # updates. Subclasses can override it.
317 sub _on_power_update ( $self, $state )
318 {
319 # Default: no-op
320 }
321  
322 # $self->convert_temperature($temp):
323 # Convert the temperature to Celsius if necessary (H4).
324 sub convert_temperature ( $self, $temp )
325 {
326 return $temp unless defined $temp;
327  
328 if ( $self->{temp_unit} eq 'F' ) {
329  
330 # Convert Fahrenheit to Celsius
331 return ( $temp - 32 ) * 5 / 9;
332 }
333  
334 return $temp;
335 }
336  
337 # $self->_find_sensor_values($data):
338 # Find the temperature and the humidity in the sensor data
339 # (H5). The method supports multiple sensor types and indexed
340 # sensors, and remembers the type it detected.
341 sub _find_sensor_values ( $self, $data )
342 {
343 # If the configuration sets a sensor type, look for that sensor
344 if ( defined $self->{sensor_type} ) {
345 my $key = $self->{sensor_type};
346  
347 # Add the index for indexed sensors, for example DS18B20-1
348 if ( defined $self->{sensor_index} ) {
349 $key .= '-' . $self->{sensor_index};
350 }
351  
352 return unless exists $data->{$key};
353 return ( $data->{$key}{Temperature}, $data->{$key}{Humidity} );
354 }
355  
356 # Auto-detect: try each known sensor type (H5)
357 for my $type (SENSOR_TYPES) {
358 if ( exists $data->{$type} ) {
359 $self->{sensor_type} = $type;
360 return (
361 $data->{$type}{Temperature},
362 $data->{$type}{Humidity} );
363 }
364  
365 # Check for indexed sensors, for example DS18B20-1
366 for my $i ( 1 .. 8 ) {
367 my $indexed = "$type-$i";
368 next unless exists $data->{$indexed};
369  
370 $self->{sensor_type} = $type;
371 $self->{sensor_index} = $i;
372 return (
373 $data->{$indexed}{Temperature},
374 $data->{$indexed}{Humidity} );
375 }
376 }
377  
378 return;
379 }
380  
381 # $self->set_power($state):
382 # Set the power state (0=OFF, 1=ON).
383 sub set_power ( $self, $state )
384 {
385 my $command = $state ? 'ON' : 'OFF';
386 my $topic = $self->_get_power_topic();
387  
388 Fugu::Log->default->debug( '%s power set to %s',
389 $self->{name}, $command );
390 $self->{mqtt_client}->publish( $topic, $command );
391 }
392  
393 # $self->query_status($type):
394 # Query the device status.
395 # $type: 0 = all, 8 = sensors, 11 = full state, and other STATUS codes
396 sub query_status ( $self, $type = 11 )
397 {
398 $self->{mqtt_client}
399 ->publish( $self->_build_topic( 'cmnd', 'Status' ), "$type" );
400 }
401  
402 1;