-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path98_SmarterCoffee.pm
1840 lines (1531 loc) · 83.2 KB
/
98_SmarterCoffee.pm
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#############################################################
#
# Copyright notice
#
# (c) 2016
# Copyright: Juergen Kellerer (juergen at k123 dot eu)
# All rights reserved
#
# This script free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# The GNU General Public License can be found at
# http://www.gnu.org/copyleft/gpl.html.
# A copy is found in the textfile GPL.txt and important notices to the license
# from the author is found in LICENSE.txt distributed with these scripts.
#
# This script is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# This copyright notice MUST APPEAR in all copies of the script!
#
# $Id$
#
#############################################################
#
# SmaterCoffee.pm by Juergen Kellerer, 2016
#
# FHEM module to communicate with a Smarter Coffee machine
#
# Credits:
# Thanks to creators and contributors of:
# - https://github.com/nanab/smartercoffee
# - https://github.com/petermajor/SmartThingsSmarterCoffee
# - https://github.com/Tristan79/iBrew
# .. and to all the volunteers crafting the FHEM project.
#
# Version: 0.9.1
#
#############################################################
#
# v0.9.1 - 2017-04-25
# - fixed "stop" detection interfering with "extra" strength.
# - added new state "grinding".
#
# v0.9 - 2017-04-24
# - added "strength-extra-start-on-device-strength" which allows
# brewing with "extra" strength using device buttons.
# - added "INITIATED_BREWING" internals to see if FHEM started it.
# - fixed timing problem when forcing "grinder" in extra mode.
# - fixed "stop" using device button doesn't reset extra mode.
# - fixed incorrect placement of start and end anchors in event
# regex leading to a too broad event handling for INITIALIZED
# events.
# - fixed "hotplate off" didn't reset state to "ready".
#
# v0.8 - 2017-03-18
# - added "controls.txt" to support automatic updates in FHEM.
# - changed default value of 'strength extra' to 140% to match
# 6 gramms coffee per cup by default.
# - improved dev-state icon and documentation.
# - fixed possible fallthrough to brew in pre-brew phase.
# - fixed a problem that strength extra could be started without
# also enabling grinder.
# - fixed 'strength extra' not being restored when restarting.
#
# v0.7 - 2016-08-28
# - added 'reset' defaults to factory settings command.
# - added 'get_defaults'.
# - added 'strength-extra-pre-brew-*'.
#
# v0.6 - 2016-08-20
# - final updates & cleanup, preparation for initial checking.
#
# v0.5 - 2016-08-19
# - added strength "extra"
# - added descale detection and descale command
# - improvements in connection handling
#
# v0.4 - 2016-08-17
# - added "set defaults" command
# - support reading device type and firmware version
# - changed status detection from simple mapping to bitmasks
# - handling carafe required dealing with "ready" state
#
# v0.3 - 2016-08-06
# - added custom state icon (embedded SVG)
#
# v0.2 - 2016-07-30
# - support auto discovery via UPD broadcast
# - start brewing with custom / default settings
# - stop brewing while running
#
# v0.1 - 2016-07-29
# - define Smarter Coffee based on fixed IP or hostname
# - set cups, strength, grinder and toggle hotplate
# - start brewing
# - view detailed status
#
#############################################################
package main;
use strict;
use warnings;
use Data::Dumper;
use Socket;
use IO::Select;
use DevIo;
use HttpUtils;
my $SmarterCoffee_Port = 2081;
my $SmarterCoffee_DiscoveryInterval = 60 * 15;
my $SmarterCoffee_IOReadStatusTimeout = 30;
my $SmarterCoffee_IOReadCommandTimeout = 5;
my $SmarterCoffee_StrengthExtraDefaultPercent = 1.2;
my $SmarterCoffee_StrengthDefaultWeights = "3.5 3.9 4.3";
my $SmarterCoffee_DefaultCupsPerCarafeRemoved = "3";
my $SmarterCoffee_MaxCupsInSingleCupMode = 3;
my %SmarterCoffee_Hotplate = (default => 15, min => 5, max => 40);
my %SmarterCoffee_MessageMaps = (
status_bitmasks => [
# BIT 1 = ???
# BIT 2 = hotplate
# BIT 3 = idle/heating
# BIT 4 = brewing/descaling
# BIT 5 = grinding
# BIT 6 = ready/done
# BIT 7 = grinder
# BIT 8 = carafe
[ '00000000' => { grinder => "disabled", carafe => "missing", hotplate => "off", state => "maintenance" } ],
[ '01000000' => { hotplate => "on" } ],
[ '00000100' => { state => "ready" } ],
[ '00100000' => { state => "ready" } ], # Set when hotplate is off after being in "heating" state.
[ '01000100' => { state => "done" } ],
[ '00001000' => { state => "grinding" } ],
[ '01010000' => { state => "brewing" } ],
[ '01100000' => { state => "heating" } ],
[ '00000010' => { grinder => "enabled" } ],
[ '00000001' => { carafe => "present" } ],
],
water => {
# HEX key, only lower 4 bits are used.
'00' => { water => "none", water_level => 0 },
'01' => { water => "low", water_level => 25 },
'02' => { water => "half", water_level => 50 },
'03' => { water => "full", water_level => 100 },
},
strength => {
# HEX key, only lower 4 bits are used.
'00' => { strength => "weak", strength_level => 1 },
'01' => { strength => "medium", strength_level => 2 },
'02' => { strength => "strong", strength_level => 3 },
},
cups => {
# HEX key, only lower 4 bits are used.
'01' => 1, '02' => 2, '03' => 3, '04' => 4, '05' => 5, '06' => 6,
'07' => 7, '08' => 8, '09' => 9, '0a' => 10, '0b' => 11, '0c' => 12
},
grinder => {
'00' => "disabled", '01' => "enabled"
}
);
my %SmarterCoffee_Commands = (
reset => "107e",
brew => "377e",
brew_with_settings => "33########7e",
adjust_defaults => "38########7e",
get_defaults => "487e",
stop => "347e",
strength => "35##7e",
cups => "36##7e",
grinder => "3c7e",
hotplate_on_for_minutes => "3e##7e",
hotplate_off => "4a7e",
carafe_required_status => "4c7e",
cups_single_mode_status => "4f7e",
info => "647e",
history => "467e"
);
my @SmarterCoffee_GetCommands = ("info", "carafe_required_status", "cups_single_mode_status", "get_defaults"); #, "history"
my %SmarterCoffee_ResponseCodes = (
'00' => { message => 'Ok', success => 'yes' },
'01' => { message => 'Ok, brewing in progress', success => 'yes' },
'04' => { message => 'Ok, stopped', success => 'yes' },
'05' => { message => 'No carafe, brewing not possible', success => 'no' },
'06' => { message => 'No water, brewing not possible', success => 'no' },
'69' => { message => 'Invalid command', success => 'no' },
);
sub SmarterCoffee_ParseMessage {
my ($hash, $message) = @_;
$message = ($hash->{PARTIAL} // "") if (not defined($message));
if ($message =~ /^(32|03|47|49|4d|50|65)[0-9a-f]+7e.*/) {
Log3 $hash->{NAME}, 5, "Connection :: Received from ".($hash->{DeviceName} // "unknown").": $message";
# Handle multiple messages in one frame:
my @messages = split("7e", $message);
if (int(@messages) > 1) {
my $failed;
for (@messages) {
$failed = 1 if (not SmarterCoffee_ParseMessage($hash, $_."7e"));
}
return not $failed;
}
# Handle single message:
$hash->{".last_response"} = $message if $message =~ /^(03|49|4d|50|65).+7e.*/;
# Parse response of a command.
if ($message =~ /^03([0-9a-f]{2})7e.*/) {
if (my $response = ($SmarterCoffee_ResponseCodes{$1} // 0)) {
SmarterCoffee_UpdateReadings($hash,
sub($) {
my ($updateReading) = @_;
while (my ($key, $value) = each %{$response}) {
$updateReading->( "last_command_$key", $value );
}
$updateReading->( "last_command", $hash->{".last_set_command"} );
}, 1
, 1);
} else {
Log3 $hash->{NAME}, 3, "Connection :: Unknown command response '$message'.";
}
}
# Parse history message.
if ($message =~ /^47([0-9a-f]{2})(.+)7e.*/) {
my @history = split("7d", $2);
Log 2, Dumper(@history); #TODO
}
# Parse default settings message.
if ($message =~ /^49([0-9a-f]+)7e.*/) {
my %values = (
cups => '0'.substr($1, 1, 1),
strength => substr($1, 2, 2),
grinder => '0'.substr($1, 5, 1),
hotplate => substr($1, 6, 2),
);
SmarterCoffee_ParseStatusValues($hash, \%values);
DoTrigger($hash->{NAME}, "get_defaults");
SmarterCoffee_Set($hash, @{[ $hash->{NAME}, "defaults" ]});
}
# Parse carafe detection status message.
if ($message =~ /^4d([0-9a-f]{2})7e.*/) {
SmarterCoffee_UpdateReading($hash, "carafe_required", ($1 eq "01" ? "no" : "yes"));
}
# Parse single cup mode status message.
if ($message =~ /^50([0-9a-f]{2})7e.*/) {
SmarterCoffee_UpdateReading($hash, "cups_single_mode", ($1 eq "00" ? "no" : "yes"));
}
# Parse info & discovery message.
if ($message =~ /^65([0-9a-f]{2})([0-9a-f]{2})7e.*/) {
$hash->{FIRMWARE} = ord(pack("H2", $2));
return 0 if ($1 ne "02");
}
# Parse status message.
if ($message =~ /^(32[0-9a-f]+7e).*/ and $message ne $hash->{".raw_last_status"}) {
$hash->{".last_status"} = $hash->{".raw_last_status"} = $message = $1;
my %values = (
status => substr($message, 2, 2),
water => '0'.substr($message, 5, 1),
strength => substr($message, 8, 2),
cups => '0'.substr($message, 11, 1),
);
SmarterCoffee_ParseStatusValues($hash, \%values);
}
$hash->{CONNECTION} = ""
."STATUS: ".($hash->{".last_status"} // "n/a")
." | COMMAND: ".($hash->{".last_command"} // "n/a")
." => ".($hash->{".last_response"} // "n/a");
return 1;
}
return 0;
}
sub SmarterCoffee_DumpToExpression($) {
my $d = Dumper($_[0]);
$d =~ s/\s+/ /g;
$d =~ s/[^\}]*(\{.+\})[^\}]*/$1/;
return $d;
}
sub SmarterCoffee_ParseStatusValues {
my ($hash, $values) = @_;
while (my ($mappingKey, $rawValue) = each %{$values}) {
if ($mappingKey eq "status") {
my %status = ();
my $unpackedStatusBits = sprintf('%08b', ord(pack("H2", $rawValue)));
$hash->{".last_status"} .= " ($unpackedStatusBits)";
for (@{$SmarterCoffee_MessageMaps{"status_bitmasks"}}) {
my ($unpackedBitmask, $statusInfo) = @{$_};
my $bitmask = ord(pack("B8", $unpackedBitmask));
if (($bitmask & ord(pack("B8", $unpackedStatusBits))) == $bitmask) {
while (my ($k, $v) = each(%{$statusInfo})) { $status{$k} = $v }
Log3 $hash->{NAME}, 5, "Connection :: Matched all bits of $unpackedBitmask in $unpackedStatusBits. Setting: ".SmarterCoffee_DumpToExpression($statusInfo);
}
}
$values->{$mappingKey} = { %status };
} else {
if (defined($SmarterCoffee_MessageMaps{$mappingKey}{$rawValue})) {
$values->{$mappingKey} = $SmarterCoffee_MessageMaps{$mappingKey}{$rawValue};
} elsif ($mappingKey eq "hotplate") {
$values->{$mappingKey} = { "hotplate_on_for_minutes" => hex($rawValue) };
} else {
Log3 $hash->{NAME}, 3, "Connection :: Unknown value '$rawValue' for $mappingKey message part.";
$values->{$mappingKey} = { };
}
}
}
Log3 $hash->{NAME}, 5, "Connection :: Parsed message: ".Dumper($values);
SmarterCoffee_UpdateReadings($hash,
sub($) {
my ($updateReading) = @_;
my $state = 0;
while (my ($n, $readings) = each %{$values}) {
$readings = { $n => $readings } if (ref($readings) ne "HASH");
while (my ($name, $value) = each %{$readings}) {
if ($name eq "state") {
$state = $value;
} else {
$updateReading->( $name, $value );
}
}
}
# Adding calculated readings
if (defined($values->{"water"})) {
my $maxCups = int(($values->{"water"}{"water_level"} // 0) / 100 * 12);
if ($maxCups > 3 and ReadingsVal($hash->{NAME}, "cups_single_mode", "") eq "yes") {
$maxCups = $SmarterCoffee_MaxCupsInSingleCupMode;
}
$updateReading->( "cups_max", $maxCups );
}
# Overriding "ready" state if carafe or water is missing.
if ($state eq "ready") {
my $cupsOk = (AttrVal($hash->{NAME}, "ignore-max-cups", 1)
or (ReadingsNum($hash->{NAME}, "cups_max", 0) >= ReadingsNum($hash->{NAME}, "cups", 0)));
my $carafeOk = (ReadingsVal($hash->{NAME}, "carafe_required", "yes") ne "yes"
or (($values->{"status"}{"carafe"} // "") eq "present"));
my $waterOk = (($values->{"water"}{"water_level"} // 0) > 0);
$state = "maintenance" if (not $carafeOk or not $waterOk or not $cupsOk);
}
# Setting status at last when all other readings are updated.
$updateReading->( "state", $state ) if $state;
}
);
}
sub SmarterCoffee_Connect($;$) {
my ($hash, $noImplicitDiscovery) = @_;
my $isNewConnection = $hash->{STATE} eq "initializing";
$hash->{STATE} = "disconnected";
delete $hash->{INVALID_DEVICE} if defined($hash->{INVALID_DEVICE});
if ($hash->{AUTO_DETECT} and not $noImplicitDiscovery) {
SmarterCoffee_RunDiscoveryProcess($hash, 1);
}
if (defined($hash->{DeviceName})) {
if (not ($hash->{DeviceName} =~ m/^(.+):([0-9]+)$/)) {
$hash->{DeviceName} .= ":$SmarterCoffee_Port";
}
Log3 $hash->{NAME}, 3, "Connection :: Connecting to " . $hash->{DeviceName};
DevIo_CloseDev($hash) if DevIo_IsOpen($hash);
delete $hash->{DevIoJustClosed} if ($hash->{DevIoJustClosed});
return SmarterCoffee_OpenIfRequiredAndWritePending($hash, $isNewConnection);
}
return 0;
}
sub SmarterCoffee_Disconnect($;$) {
my ($hash, $noReconnect) = @_;
Log3 $hash->{NAME}, 3, "Connection :: Disconnecting from " . ($hash->{DeviceName} // "unknown");
# Setting state to allow listening to "off"
SmarterCoffee_UpdateReading($hash, "state", "disconnected");
# Disconnecting DevIo and resetting state.
DevIo_Disconnected($hash);
SmarterCoffee_HandleInitialConnectState($hash);
# Reconnecting when device gets available again (if not skipped).
SmarterCoffee_Connect($hash, 1) if (not $noReconnect);
}
sub SmarterCoffee_OpenIfRequiredAndWritePending($;$) {
my ($hash, $initial) = @_;
return DevIo_OpenDev($hash, ($initial ? 0 : 1), "SmarterCoffee_WritePending");
}
sub SmarterCoffee_HandleInitialConnectState($) {
my ($hash) = @_;
if (DevIo_IsOpen($hash)) {
if (($hash->{STATE} eq "disconnected" or $hash->{STATE} eq "opened")) {
$hash->{STATE} = "connected";
if (not defined($hash->{".device-state-known"})) {
$hash->{".device-state-known"} = 1;
SmarterCoffee_Get($hash, @{[ $hash->{NAME}, "info" ]}) if (not $hash->{AUTO_DETECT});
SmarterCoffee_Get($hash, @{[ $hash->{NAME}, "carafe_required_status" ]});
SmarterCoffee_Get($hash, @{[ $hash->{NAME}, "cups_single_mode_status" ]});
}
}
} else {
delete $hash->{".device-state-known"} if (defined($hash->{".device-state-known"}));
}
}
sub SmarterCoffee_WritePending {
my ($hash, $mustSucceed) = @_;
if (DevIo_IsOpen($hash)) {
my $pending = ($hash->{PENDING_COMMAND} // 0);
# Handling initial call on a fresh connection
SmarterCoffee_HandleInitialConnectState($hash);
# Processing pending commands
if (($hash->{INVALID_DEVICE} // "0") eq "1") {
$hash->{STATE} = "invalid";
} else {
if ($pending) {
delete $hash->{PENDING_COMMAND} if defined($hash->{PENDING_COMMAND});
Log3 $hash->{NAME}, 4, "Connection :: Sending to ".$hash->{DeviceName}.": $pending";
DevIo_SimpleWrite($hash, $pending, 1);
$hash->{".raw_last_status"} = "";
my $result = DevIo_SimpleReadWithTimeout($hash, $SmarterCoffee_IOReadCommandTimeout);
if ($result) {
$result = SmarterCoffee_Read($hash, $result);
} else {
DevIo_Disconnected($hash);
}
$hash->{INVALID_DEVICE} = "1" if ($mustSucceed and not $result);
$hash->{PENDING_COMMAND} = $pending if (not $result);
}
}
}
return undef;
}
sub SmarterCoffee_Read($;$) {
my ($hash, $buffer) = @_;
# Handle case that fhem reconnected a broken connection and state is "opened".
SmarterCoffee_HandleInitialConnectState($hash) if (not defined($buffer));
# Abort read if we already detected that the device is invalid.
return 0 if ($hash->{INVALID_DEVICE} // 0);
# Reset partial data buffer if it exceeds length of 512 (256 bytes) or when $buffer was specified explicitly.
$hash->{PARTIAL} = "" if (not defined($hash->{PARTIAL}) or defined($buffer) or length($hash->{PARTIAL} // "") >= 512);
# Adding a watchdog that disconnects when no answer is received within the specified timeout (fixes broken timeout in DevIo).
RemoveInternalTimer($hash, "SmarterCoffee_Disconnect");
if (not defined($buffer)) {
if (DevIo_IsOpen($hash)) {
InternalTimer(gettimeofday() + $SmarterCoffee_IOReadStatusTimeout, "SmarterCoffee_Disconnect", $hash);
}
# Reading available bytes from the socket (if not specified from external).
$buffer = DevIo_SimpleRead($hash);
}
return 0 if (not defined($buffer));
# Appending message bytes as hex string.
$hash->{PARTIAL} .= unpack('H*', $buffer);
# Parsing the message and populate readings.
if ($hash->{PARTIAL} ne "") {
if (SmarterCoffee_ParseMessage($hash)) {
delete $hash->{PARTIAL};
} else {
Log3 $hash->{NAME}, 2, "Connection :: Failed parsing buffer content: ".$hash->{PARTIAL};
return 0;
}
}
return 1;
}
sub SmarterCoffee_Initialize($) {
my ($hash) = @_;
$hash->{DefFn} = 'SmarterCoffee_Define';
$hash->{UndefFn} = 'SmarterCoffee_Undefine';
$hash->{GetFn} = 'SmarterCoffee_Get';
$hash->{SetFn} = 'SmarterCoffee_Set';
$hash->{ReadFn} = 'SmarterCoffee_Read';
$hash->{ReadyFn} = 'SmarterCoffee_OpenIfRequiredAndWritePending';
$hash->{NotifyFn} = 'SmarterCoffee_Notify';
$hash->{AttrList} = ""
."default-hotplate-on-for-minutes "
."ignore-max-cups "
."cups-per-carafe-removed "
."set-on-brews-coffee "
."strength-coffee-weights "
."strength-extra-percent "
."strength-extra-pre-brew-delay-seconds "
."strength-extra-start-on-device-strength:off,weak,medium,strong "
.$readingFnAttributes;
Log 5, "Initialized module 'SmarterCoffee'";
}
sub SmarterCoffee_Define($$) {
my ($hash, $def) = @_;
my @param = split('[ \t]+', $def);
my $name = $hash->{NAME};
# set default settings on first define
if ($init_done) {
$attr{$name}{alias} = "Coffee Machine";
$attr{$name}{webCmd} = "strength:cups:start:hotplate:off";
$attr{$name}{'strength-extra-percent'} = $SmarterCoffee_StrengthExtraDefaultPercent;
$attr{$name}{'default-hotplate-on-for-minutes'} = "15 5=20 8=30 10=35";
$attr{$name}{'event-on-change-reading'} = ".*";
$attr{$name}{'event-on-update-reading'} = "last_command.*";
}
$attr{$name}{devStateIcon} = '{ SmarterCoffee_GetDevStateIcon($name) }' if not defined($attr{$name}{devStateIcon});
if (int(@param) < 3) {
$hash->{AUTO_DETECT} = 1;
} else {
delete $hash->{AUTO_DETECT};
$hash->{DeviceName} = $param[2];
}
$hash->{NOTIFYDEV} = "global,$name";
$hash->{STATE} = "initializing";
$hash->{".last_command"} =
$hash->{".last_response"} =
$hash->{".last_status"} =
$hash->{".raw_last_status"} = "";
SmarterCoffee_Connect($hash);
Log3 $hash->{NAME}, 4, "Instance :: Defined module 'SmarterCoffee': ".Dumper($hash);
}
sub SmarterCoffee_Undefine($$) {
my ($hash, $arg) = @_;
RemoveInternalTimer($hash);
DevIo_CloseDev($hash);
Log3 $hash->{NAME}, 4, "Instance :: Closed module 'SmarterCoffee': ".Dumper($hash);
return undef;
}
sub SmarterCoffee_Get {
my ($hash, @param) = @_;
if (grep {$_ eq ($param[1] // "")} @SmarterCoffee_GetCommands) {
return SmarterCoffee_Set($hash, @param) // "Ok :: ".$hash->{".last_response"};
} else {
return "Unknown argument $param[1], choose one of ".join(":noArg ", @SmarterCoffee_GetCommands).":noArg";
}
}
sub SmarterCoffee_Set {
my ($hash, @param) = @_;
my $desiredCups = defined($hash->{".extra_strength.original_desired_cups"})
? $hash->{".extra_strength.original_desired_cups"}
: ReadingsVal($hash->{NAME}, "cups", 1);
my $optionToMessage = sub($$;$) {
my ($option, $optionValue, $value) = @_;
# Remembering "cups" when a message part is looked-up.
$desiredCups = int($optionValue) if ($option eq "cups" and $optionValue =~ /^[0-9]+$/);
# Special treatment for hotplate, syntax: "set hotplate (on|off) [5-40]"
if ($option =~ /^hotplate.*/) {
# Select default time from "[minutes] [cups=minutes]", e.g.: "15 5=20 10=35" means: 15 default, 20 from 5 cups and 35 from 10 cups.
my ($defaultOnForMinutes, $overrides) = parseParams(AttrVal($hash->{NAME}, "default-hotplate-on-for-minutes", $SmarterCoffee_Hotplate{default}));
$defaultOnForMinutes = $defaultOnForMinutes->[0] if (defined($defaultOnForMinutes) and int($defaultOnForMinutes) > 0);
for my $key (sort { $a <=> $b } (keys %{$overrides})) {
$defaultOnForMinutes = $overrides->{$key} if (int($desiredCups) >= int($key));
}
$value = $optionValue if (not defined($value));
$value = $value =~ /^[0-9]+$/ ? int($value) : int($defaultOnForMinutes);
$value = $SmarterCoffee_Hotplate{max} if ($value > $SmarterCoffee_Hotplate{max});
$value = $SmarterCoffee_Hotplate{min} if ($value < $SmarterCoffee_Hotplate{min});
SmarterCoffee_UpdateReading($hash, "hotplate_on_for_minutes", ($option eq "hotplate_off" ? 0 : $value));
return unpack('H*', pack('C', $value));
} elsif (defined($SmarterCoffee_MessageMaps{$option}) and defined($optionValue)) {
# Ordinary values are looked up in the message maps (looking up the HEX code that backs a setting).
for my $key (keys %{$SmarterCoffee_MessageMaps{$option}}) {
my $v = $SmarterCoffee_MessageMaps{$option}{$key};
if ((ref($v) eq "HASH" ? grep(/^$optionValue$/, values %{$v}) : $v eq $optionValue)) {
return $key;
}
}
}
return undef;
};
# Command & params pre-processing
my ($instanceName, $option, $messagePart) = (shift @param, shift @param, undef);
# Security guard, support only "set off/stop/reset" and "set strength extra" when brewing is in progress.
if ((my $bc = ($hash->{".brew-state"} // 0))
and ($option // "?") ne "?"
and not $option =~ /^(off|stop|reset)$/i
and not ($option eq "brew" and $hash->{".brew-state"} eq "transitioning")
and not ($option eq "strength" and ($param[0] // "") eq "extra")) {
my $m = ("Brewing in progress (state: $bc), [set $option " . join(" ", @param) . "] is not available. Only off/stop/reset is supported.");
Log3 $hash->{NAME}, 3, "Set :: Not Available: $m";
return $m;
}
# Support "set <name> off"
if ($option =~ /^off$/i) {
SmarterCoffee_UpdateReading($hash, "state", "off"); # Setting state to allow listening to "off"
$option = "stop";
}
# Support "set <name> on" and "set <name> start"
if (($option =~ /^on$/i and AttrVal($hash->{NAME}, "set-on-brews-coffee", "0") =~ /^(yes|true|1|always)$/i)
or $option =~ /^start$/i) {
SmarterCoffee_UpdateReading($hash, "state", $option); # Setting state to allow listening on ("on" & "start")
if (not ($1 // "") eq "always" and $option =~ /^on$/i and ReadingsNum($hash->{NAME}, "cups_remaining", 0) > 0) {
$option = "hotplate_on_for_cups";
} else {
$option = "brew";
}
}
# Support "set 6-cups" as alias to "set brew 6" (for better readable webCmds)
if ($option =~ /^([0-9]+)-cups(|[\-_,:;][a-z]+)$/i) {
unshift(@param, substr($2, 1)) if ($2); # supporting "set 3-cups,strong"
unshift(@param, $1);
$option = "brew";
}
if ($option eq "brew" or $option eq "defaults") {
# Handle extra strong coffee
if (($param[1] // ReadingsVal($hash->{NAME}, "strength", "")) =~ /^extra.*/) {
# Enable grinder in extra mode if required and option is not defaults.
my $grinderEnabled = (($param[3] // ReadingsVal($hash->{NAME}, "grinder", "")) eq "enabled");
if ($option ne "defaults" and not $grinderEnabled and ($param[3] // "") ne "disabled") {
SmarterCoffee_Set($hash, @{[ $hash->{NAME}, "grinder", "enabled" ]});
$grinderEnabled = 1;
$param[3] = "enabled" if defined($param[3]);
}
if ($option ne "defaults" and $grinderEnabled) {
if (SmarterCoffee_TranslateParamsForExtraStrength($hash, \@param, "grind")) {
my ($cups, $error, $cycle, $cycles) = (
$hash->{".extra_strength.desired_cups"},
$hash->{".extra_strength.error_rate"},
$hash->{".extra_strength.current_grind_cycle"},
$hash->{".extra_strength.grind_cycles"});
Log3 $hash->{NAME}, 3, "Extra Strength :: Grinding [".join(" ", @param)."] to get $cups cups (cycle: $cycle of $cycles, deviation: $error%).";
} else {
return "strength 'extra' failed. check water level.";
}
} else {
Log3 $hash->{NAME}, 3, "Extra Strength :: Downgrading strength extra to 'strong' for set $option.";
$param[1] = "strong";
}
}
# Prevent setting anything except stop requests while brew is requested.
SmarterCoffee_ResetBrewState($hash, "requested") if ($option eq "brew");
# Handle normal brew or set defaults
if (not defined($param[0]) or $param[0] ne "current") {
# Get message parts
my %input = ("cups" => $param[0], "strength" => $param[1], "hotplate" => $param[2], "grinder" => $param[3]);
my %readingsValues = ( %input );
my $inputsDefined = 0;
for my $key (keys %input) {
# Translating input to message part.
$input{$key} = $optionToMessage->( $key, $input{$key} ) if defined($input{$key});
# Taking message part from readings if input didn't specify it (using "on" for "hotplate" as the reading would be misleading.
if (not defined($input{$key})) {
$readingsValues{$key} = ($key eq "hotplate"
? (ReadingsVal($hash->{NAME}, "cups_single_mode", "") eq "yes" ? 0 : "on")
: ReadingsVal($hash->{NAME}, $key, ""));
$input{$key} = $optionToMessage->( $key, $readingsValues{$key} );
}
# Count if message part was retrieved
$inputsDefined++ if defined($input{$key});
}
if ($inputsDefined == 4) {
if ($option eq "defaults") {
$option = "adjust_defaults";
$messagePart = $input{strength}.$input{cups}.$input{grinder}.$input{hotplate};
} else {
$option = "brew_with_settings";
$messagePart = $input{cups}.$input{strength}.$input{hotplate}.$input{grinder};
SmarterCoffee_UpdateReadings($hash,
sub($) {
my ($updateReading) = @_;
for my $key (keys %readingsValues) { $updateReading->( $key, $readingsValues{$key} ) }
}
);
}
}
}
# Aborting if option "defaults" was not properly prepared to "adjust_defaults".
return undef if $option eq "defaults";
} elsif ($option =~ /^hotplate.*/) {
if (not defined($param[0])) {
$param[0] = ($option ne "hotplate_on_for_minutes" and ReadingsVal($hash->{NAME}, "hotplate", "") ne "off") ? "off" : "on";
}
if ($option eq "hotplate_on_for_cups" or ($param[0] eq "on-for-cups" and ($param[1] // 0) > 0)) {
# Adjust desired cups when value is "on-for-cups [cups]" and cups are defined.
$param[0] = $param[1] if (($param[1] // "") =~ /^[0-9]+$/);
$desiredCups = int($param[0]) if (($param[0] // "") =~ /^[0-9]+$/);
$param[0] = "";
$param[1] = "";
}
$option = $param[0] =~ /^(0|no|disable|off).*$/i
? "hotplate_off"
: "hotplate_on_for_minutes";
$messagePart = $optionToMessage->( $option, $param[0], $param[1] );
} else {
if (defined($param[0])) {
# Resetting "extra" strength mode when strength is updated.
delete $hash->{".extra_strength.enabled"} if ($option eq "strength" and $param[0] ne "extra" and $hash->{".extra_strength.enabled"});
# Eager updating strength, cups and grinder reading to avoid that widget updates are slower than starting a "brew".
SmarterCoffee_UpdateReading($hash, $option, $param[0]) if ($option =~ /^(strength|cups|grinder)$/);
# Aborting device update when strength is "extra".
return undef if ($option eq "strength" and $param[0] eq "extra");
# Aborting device update if grinder is not changed (every command sent to the coffee machine flips the grinder setting).
return undef if ($option eq "grinder" and $param[0] eq ReadingsVal($hash->{NAME}, "grinder", ""));
}
# Resetting internal states before executing "stop".
if ($option eq "stop" and ($param[0] // "") ne "no-reset") {
SmarterCoffee_ResetState($hash);
}
$messagePart = $optionToMessage->( $option, $param[0] );
}
# Command execution
if (defined($SmarterCoffee_Commands{$option})) {
my $message = $SmarterCoffee_Commands{$option};
# Replacing placeholders with value.
$message =~ s/#+/$messagePart/ if (defined($messagePart) and $messagePart =~ /^[a-f0-9]{2,}$/);
if ($message =~ /.*#.*/) {
return "Option $option: Unsupported params: ".join(" ", @param);
} else {
$hash->{".last_set_command"} = $option.(int(@param) ? " ".join(" ", @param) : "");
$hash->{"PENDING_COMMAND"} = $hash->{".last_command"} = $message;
Log3 $hash->{NAME}, 4, "Connection :: Sending message: $message [".$hash->{".last_set_command"}."]";
SmarterCoffee_WritePending($hash, ($option eq "info"));
}
return undef;
} elsif ($option eq "disconnect" or $option eq "reconnect") {
# This option is primarily to test if reconnect works.
SmarterCoffee_Disconnect($hash, ($option ne "reconnect"));
return undef;
} elsif ($option ne "?" and $option ne "help") {
return "Unknown option: $option with params: ".join(" ", @param)
}
my @strength = split(",", "weak,medium,strong,extra");
pop(@strength) if (not SmarterCoffee_IsExtraStrengthModeAvailable($hash));
return "Unknown argument $option, choose one of"
." brew"
." defaults"
." reset:noArg"
." stop:noArg"
." strength:".join(",", @strength)
." cups:slider,1,1,12"
." grinder:enabled,disabled"
." hotplate"
." hotplate_on_for_minutes:slider,5,5,40"
." hotplate_on_for_cups:slider,1,1,12"
." reconnect:noArg";
}
sub SmarterCoffee_ResetState($) {
my ($hash) = @_;
SmarterCoffee_ResetBrewState($hash);
SmarterCoffee_ResetExtraStrengthMode($hash);
}
sub SmarterCoffee_Notify($$) {
my ($hash, $eventHash) = @_;
my $name = $hash->{NAME};
my $senderName = $eventHash->{NAME};
# Return without any further action if the module is disabled or the event is not from this module or global.
return "" if (IsDisabled($name) or ($senderName ne $name and $senderName ne "global"));
if (my $events = deviceEvents($eventHash, 1)) {
if ($senderName eq "global") {
SmarterCoffee_ReadConfiguration($hash) if (grep(m/^(INITIALIZED|REREADCFG)$/, @{$events}));
} else {
for (@{$events}) {
if ($_) {
SmarterCoffee_LogCommands($hash, $_);
SmarterCoffee_ProcessBrewStateEvents($hash, $_);
SmarterCoffee_ProcessCarafeRemovedEvents($hash, $_);
SmarterCoffee_ProcessEventForExtraStrength($hash, $_);
}
}
}
}
}
sub SmarterCoffee_ReadConfiguration($$) {
my ($hash) = @_;
# Restoring extra strength
$hash->{".extra_strength.enabled"} = 1 if (ReadingsVal($hash->{NAME}, "strength", "") =~ /^extra.*/);
}
sub SmarterCoffee_LogCommands($$) {
my ($hash, $event) = @_;
if ($event =~ /^last_command_success:\s*(yes|no)\s*$/i and (my $command = ReadingsVal($hash->{NAME}, "last_command", 0))) {
my $message = ReadingsVal($hash->{NAME}, "last_command_message", "");
if ($1 eq "yes") {
Log3 $hash->{NAME}, 4, "Command :: Success [$command]; Message: $message";
} else {
Log3 $hash->{NAME}, 3, "Command :: Failed [$command]; Cause: $message";
}
}
}
sub SmarterCoffee_ProcessCarafeRemovedEvents($$) {
my ($hash, $event) = @_;
my $carafeRequired = (ReadingsVal($hash->{NAME}, "carafe_required", "no") eq "yes");
# Resetting count when starting brewing.
if ($event =~ /^state:\s*(brewing|grinding)$/) {
my $count = int(ReadingsNum($hash->{NAME}, "carafe_removed_count", -1));
my $cups = int($hash->{".extra_strength.original_desired_cups"} // ReadingsNum($hash->{NAME}, "cups", 0));
if ($carafeRequired) {
SmarterCoffee_UpdateReading($hash, "carafe_removed_count", 0) if ($count > 0);
SmarterCoffee_UpdateReading($hash, "cups_remaining", $cups);
} elsif ($count > -1) {
fhem("deletereading " . $hash->{NAME} . " (cups_remaining|carafe_removed_.+)");
}
} elsif ($event =~ /^carafe:\s*missing$/ and $carafeRequired) {
my $count = int(ReadingsNum($hash->{NAME}, "carafe_removed_count", 0));
SmarterCoffee_UpdateReading($hash, "carafe_removed_count", $count + 1);
my $remainingCups = int(ReadingsNum($hash->{NAME}, "cups_remaining", -1));
my $cupsPerRemoved = int(AttrVal($hash->{NAME}, "cups-per-carafe-removed", $SmarterCoffee_DefaultCupsPerCarafeRemoved));
$remainingCups -= $cupsPerRemoved;
$remainingCups = 0 if ($remainingCups < 0);
SmarterCoffee_UpdateReading($hash, "cups_remaining", $remainingCups);
}
}
sub SmarterCoffee_ProcessBrewStateEvents($$) {
my ($hash, $event) = @_;
# Handling invocation from timer
if (($hash->{".watchdog"} // 0) and defined($hash->{"hash"})) {
$event = $hash->{"token"} // "";
$hash = $hash->{"hash"};
if ($event eq ($hash->{".brew-state.token"} // "undefined")) {
Log3 $hash->{NAME}, 2, "Brew-State :: Watchdog aborts brewing. Expected state change to (brewing/grinding) but didn't see the change in time.";
$event = "state: aborted-by-watchdog";
}
}
# Setting "INITIATED_BREWING" when brewing was initiated by a command (and not by using the machine's buttons)
if ($event =~ /^last_command_success:\s*(yes|no)\s*$/i
and (my $success = $1)
and ReadingsVal($hash->{NAME}, "last_command", 0) =~ /^brew.*/) {
$hash->{"INITIATED_BREWING"} = 1;
$hash->{".brew-state"} = "brewing";
if ($success eq "yes") {
Log3 $hash->{NAME}, 4, "Brew-State :: Brewing initiated in FHEM.";
# Installing a watchdog: We must see a state change to "brewing/grinding" after 5 seconds, otherwise abort was initiated by the device.
if (AttrVal($hash->{NAME}, , "brewing-watchdog-disabled", "no") ne "yes") {
my $token = $hash->{".brew-state.token"} = "wd-token-" . srand();
my $args = {".watchdog" => 1, "hash" => $hash, "token" => $token};
InternalTimer(gettimeofday() + 5, "SmarterCoffee_ProcessBrewStateEvents", $args);
}
} else {
Log3 $hash->{NAME}, 2, "Brew-State :: Brewing failed to get initiated in FHEM, sending stop command.";
SmarterCoffee_Set($hash, @{[ $hash->{NAME}, "stop" ]});
}
} elsif ($event =~ /^state:\s*(brewing|grinding)/) {
Log3 $hash->{NAME}, 4, "Brew-State :: State '$1'.";
$hash->{".brew-state"} = $1;
delete $hash->{".brew-state.token"} if (defined($hash->{".brew-state.token"}));
} elsif ($event =~ /^state:\s*done/) {
SmarterCoffee_ResetBrewState($hash);
} elsif ($event =~ /^state:\s*(.+)$/) {
my ($state, $brewState) = ($1, ($hash->{".brew-state"} // ""));