-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path10_RHASSPY.pm
7094 lines (6025 loc) · 314 KB
/
10_RHASSPY.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
# $Id: 10_RHASSPY.pm 29310 2024-12-04 Beta-User $
###########################################################################
#
# FHEM RHASSPY module (https://github.com/rhasspy)
#
# Originally initiated 2018 by Tobias Wiedenmann (Thyraz)
# as FHEM Snips.ai module (thanks to Matthias Kleine)
#
# Adapted for RHASSPY 2020-2022 by Beta-User and drhirn
#
# Thanks to rudolfkoenig, JensS, cb2sela and all the others
# who did a great job getting this to work!
#
# This file is part of fhem.
#
# Fhem is 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.
#
# Fhem 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.
#
# You should have received a copy of the GNU General Public License
# along with fhem. If not, see <http://www.gnu.org/licenses/>.
#
###########################################################################
package RHASSPY; ##no critic qw(Package)
use strict;
use warnings;
use Carp qw(carp);
use GPUtils qw(GP_Import);
use JSON ();
use Encode;
use HttpUtils;
use utf8;
use List::Util 1.45 qw(max min uniq shuffle any);
use Scalar::Util qw(looks_like_number);
use Time::HiRes qw(gettimeofday);
use POSIX qw(strftime);
use FHEM::Core::Timer::Register qw(:ALL);
#use FHEM::Meta;
sub ::RHASSPY_Initialize { goto &Initialize }
my %gets = (
test_file => [],
test_sentence => [],
export_mapping => []
);
my %sets = (
speak => [],
play => [],
customSlot => [],
textCommand => [],
trainRhasspy => [qw(noArg)],
fetchSiteIds => [qw(noArg)],
update => [qw(devicemap devicemap_only slots slots_no_training language intent_filter all)],
volume => [],
msgDialog => [qw( enable disable )],
activateVoiceInput => []
#text2intent => []
);
my $languagevars = {
'units' => {
'unitHours' => {
0 => 'hours',
1 => 'one hour'
},
'unitMinutes' => {
0 => 'minutes',
1 => 'one minute'
},
'unitSeconds' => {
0 => 'seconds',
0 => 'seconds',
1 => 'one second'
}
},
'responses' => {
'DefaultError' => "Sorry but something seems not to work as expected!",
'ContinueSession' => "Something else? | Any more wishes?",
'NoValidResponse' => 'Error. respond function called without valid response!',
'NoValidIntentResponse' => 'Error. respond function called by $intent without valid response!',
'NoIntentRecognized' => 'Your input could not be assigned to one of the known intents!',
'NoValidData' => "Sorry but the received data is not sufficient to derive any action.",
'ParadoxData' => {
'hint' => 'The received data is paradoxical: $val[0] and $val[1] do not fit together.',,
'confirm' => 'Switch $val[0] based on name and site id?'
},
'NoDeviceFound' => "Sorry but I could not find a matching device.",
'NoTimedOnDeviceFound' => "Sorry but device does not support requested timed on or off command.",
'NoMappingFound' => "Sorry but I could not find a suitable mapping.",
'NoNewValDerived' => "Sorry but I could not calculate a new value to set.",
'NoActiveMediaDevice' => "Sorry no active playback device.",
'NoMediaChannelFound' => "Sorry but requested channel seems not to exist.",
'DefaultConfirmation' => "OK",
'DefaultConfirmationClosure' => "OK",
'DefaultConfirmationBack' => "So once more.",
'DefaultConfirmationTimeout' => "Sorry, too late to confirm.",
'DefaultCancelConfirmation' => "Thanks, aborted.",
'RetryIntent' => "Please try again",
'DefaultConfirmationReceived' => "Ok, will do it!",
'DefaultConfirmationNoOutstanding' => "No command is awaiting confirmation!",
'DefaultConfirmationRequestRawInput' => 'Please confirm: $rawInput!',
'DefaultChangeIntentRequestRawInput' => 'Change command to $rawInput!',
'RequestChoiceDevice' => 'There are several possible devices, choose between $first_items and $last_item.',
'RequestChoiceRoom' => 'More than one possible device, please choose one of the following rooms $first_items and $last_item.',
'RequestChoiceGeneric' => 'There are several options, choose between $options.',
'DefaultChoiceNoOutstanding' => "No choice expected!",
'NoMinConfidence' => 'Minimum confidence not given, level is $confidence',
'XtendAnswers' => {
'unknownDevs' => '$uknDevs could not be identified.'
},
'timerSet' => {
'0' => '$label in room $room has been set to $seconds seconds',
'1' => '$label in room $room has been set to $minutes minutes $seconds',
'2' => '$label in room $room has been set to $minutes minutes',
'3' => '$label in room $room has been set to $hours hours $minutetext',
'4' => '$label in room $room has been set to $hour o clock $minutes',
'5' => '$label in room $room has been set to tomorrow $hour o clock $minutes',
'6' => '$label in room $room is not existent',
},
'timerEnd' => {
'0' => '$label expired',
'1' => '$label in room $room expired'
},
'timerCancellation' => '$label for $room deleted',
'timeRequest' => 'It is $hour o clock $min minutes',
'weekdayRequest' => 'Today is $weekDay, $month the $day., $year',
'duration_not_understood' => "Sorry I could not understand the desired duration",
'reSpeak_failed' => 'I am sorry i can not remember',
'Change' => {
'humidity' => 'Air humidity in $location is $value percent',
'battery' => {
'0' => 'Battery level in $location is $value',
'1' => 'Battery level in $location is $value percent'
},
'brightness' => '$device was set to $value',
'setTarget' => '$device is set to $value',
'soilMoisture' => 'Soil moisture in $location is $value percent',
'temperature' => {
'0' => 'Temperature in $location is $value',
'1' => 'Temperature in $location is $value degrees',
},
'desired-temp' => 'Target temperature for $location is set to $value degrees',
'volume' => '$device set to $value',
'waterLevel' => 'Water level in $location is $value percent',
'knownType' => '$mappingType in $location is $value percent',
'unknownType' => 'Value in $location is $value percent'
},
'getStateResponses' => {
'STATE' => '$deviceName value is [$device:STATE]',
'price' => 'Current price of $reading in $deviceName is [$device:$reading:d]',
'reading' => '[$device:$reading]',
'update' => 'Initiated update for $deviceName'
},
'getRHASSPYOptions' => {
'generic' => 'Actions to devices may be initiated or information known by your automation can be requested',
'control' => 'In $room amongst others the following entities can be controlled $deviceNames',
'info' => 'Especially $deviceNames may serve as information source in $room',
'rooms' => 'Amongst others i know $roomNames as rooms',
'scenes' => '$deviceNames in $room may be able to be set to $sceneNames'
}
},
'stateResponses' => {
'inOperation' => {
'0' => '$deviceName is ready',
'1' => '$deviceName is still running'
},
'inOut' => {
'0' => '$deviceName is out',
'1' => '$deviceName is in'
},
'onOff' => {
'0' => '$deviceName is off',
'1' => '$deviceName is on'
},
'openClose' => {
'0' => '$deviceName is open',
'1' => '$deviceName is closed'
}
}
};
my $internal_mappings = {
'Change' => {
'lightUp' => {
'Type' => 'brightness',
'up' => '1'
},
'lightDown' => {
'Type' => 'brightness',
'up' => '0'
},
'tempUp' => {
'Type' => 'temperature',
'up' => '1'
},
'tempDown' => {
'Type' => 'temperature',
'up' => '0'
},
'volUp' => {
'Type' => 'volume',
'up' => '1'
},
'volDown' => {
'Type' => 'volume',
'up' => '0'
},
'setUp' => {
'Type' => 'setTarget',
'up' => '1'
},
'setDown' => {
'Type' => 'setTarget',
'up' => '0'
}
},
'regex' => {
'upward' => '(higher|brighter|louder|rise|warmer)',
'setTarget' => '(brightness|volume|target.volume)'
},
'stateResponseType' => {
'on' => 'onOff',
'off' => 'onOff',
'open' => 'openClose',
'closed' => 'openClose',
'in' => 'inOut',
'out' => 'inOut',
'ready' => 'inOperation',
'acting' => 'inOperation'
}
};
BEGIN {
GP_Import( qw(
addToAttrList delFromDevAttrList
addToDevAttrList delFromAttrList
readingsSingleUpdate
readingsBeginUpdate
readingsBulkUpdate
readingsEndUpdate
readingsDelete
Log3
defs attr cmds modules L
DAYSECONDS HOURSECONDS MINUTESECONDS
init_done fhem_started
InternalTimer
RemoveInternalTimer
AssignIoPort
CommandAttr
CommandDeleteAttr
IOWrite
readingFnAttributes
IsDisabled
AttrVal
InternalVal
ReadingsVal
ReadingsNum
devspec2array
toJSON
setVolume
AnalyzeCommandChain
AnalyzeCommand
CommandSet
CommandDefMod
CommandDelete
EvalSpecials
AnalyzePerlCommand
perlSyntaxCheck
parseParams
ResolveDateWildcards
HttpUtils_NonblockingGet
FmtDateTime
makeReadingName
FileRead FileWrite
getAllSets
notifyRegexpChanged setNotifyDev
deviceEvents
asyncOutput
trim
) )
};
# MQTT Topics die das Modul automatisch abonniert
my @topics = qw(
hermes/intent/+
hermes/dialogueManager/sessionStarted
hermes/dialogueManager/sessionQueued
hermes/dialogueManager/sessionEnded
hermes/nlu/intentNotRecognized
hermes/hotword/+/detected
hermes/hotword/toggleOn
hermes/hotword/toggleOff
hermes/tts/say
);
sub Initialize {
my $hash = shift // return;
# Consumer
$hash->{DefFn} = \&Define;
$hash->{UndefFn} = \&Undefine;
$hash->{DeleteFn} = \&Delete;
#$hash->{RenameFn} = \&Rename;
$hash->{SetFn} = \&Set;
$hash->{GetFn} = \&Get;
$hash->{AttrFn} = \&Attr;
$hash->{AttrList} = "IODev rhasspyIntents:textField-long rhasspyShortcuts:textField-long rhasspyTweaks:textField-long response:textField-long rhasspyHotwords:textField-long rhasspyMsgDialog:textField-long rhasspySpeechDialog:textField-long forceNEXT:0,1 disable:0,1 disabledForIntervals languageFile " . $readingFnAttributes; #rhasspyTTS:textField-long
$hash->{Match} = q{.*};
$hash->{ParseFn} = \&Parse;
$hash->{NotifyFn} = \&Notify;
$hash->{parseParams} = 1;
return;
}
# Device anlegen
sub Define {
my $hash = shift;
my $anon = shift;
my $h = shift;
#parseParams: my ( $hash, $a, $h ) = @_;
my $name = shift @{$anon};
my $type = shift @{$anon};
my $Rhasspy = $h->{baseUrl} // shift @{$anon} // q{http://127.0.0.1:12101};
my $defaultRoom = $h->{defaultRoom} // shift @{$anon} // q{default};
my @unknown;
for (keys %{$h}) {
push @unknown, $_ if $_ !~ m{\A(?:baseUrl|defaultRoom|language|devspec|fhemId|prefix|siteId|encoding|useGenericAttrs|sessionTimeout|handleHotword|noChangeover|experimental|Babble|autoTraining)\z}xm;
}
my $err = join q{, }, @unknown;
return "unknown key(s) in DEF: $err" if @unknown && $init_done;
Log3( $hash, 1, "[$name] unknown key(s) in DEF: $err") if @unknown;
$hash->{defaultRoom} = $defaultRoom;
my $language = $h->{language} // shift @{$anon} // lc AttrVal('global','language','en');
$hash->{baseUrl} = $Rhasspy;
initialize_Language($hash, $language) if !defined $hash->{LANGUAGE} || $hash->{LANGUAGE} ne $language;
$hash->{LANGUAGE} = $language;
my $defaultdevspec = defined $h->{useGenericAttrs} && $h->{useGenericAttrs} == 0 ? q{room=Rhasspy} : q{genericDeviceType=.+};
$hash->{devspec} = $h->{devspec} // $defaultdevspec;
$hash->{fhemId} = $h->{fhemId} // q{fhem};
initialize_prefix($hash, $h->{prefix}) if !defined $hash->{prefix} || defined $h->{prefix} && $hash->{prefix} ne $h->{prefix};
$hash->{prefix} = $h->{prefix} // q{rhasspy};
$hash->{siteId} = $h->{siteId} // qq{${language}$hash->{fhemId}};
$hash->{encoding} = $h->{encoding} // q{utf8};
$hash->{useGenericAttrs} = $h->{useGenericAttrs} // 1;
$hash->{autoTraining} = $h->{autoTraining} // 60;
for my $key (qw( experimental handleHotword sessionTimeout noChangeover Babble )) {
delete $hash->{$key};
$hash->{$key} = $h->{$key} if defined $h->{$key};
}
$hash->{'.asyncQueue'} = [];
#Beta-User: Für's Ändern von defaultRoom oder prefix vielleicht (!?!) hilfreich: https://forum.fhem.de/index.php/topic,119150.msg1135838.html#msg1135838 (Rudi zu resolveAttrRename)
if ($hash->{useGenericAttrs}) {
addToAttrList(q{genericDeviceType});
}
notifyRegexpChanged($hash,'',1);
return "No Babble device available with name $hash->{Babble}!" if $init_done && defined $hash->{Babble} && InternalVal($hash->{Babble},'TYPE','none') ne 'Babble';
return $init_done ? firstInit($hash) : InternalTimer(time+1, \&firstInit, $hash );
}
sub firstInit {
my $hash = shift // return;
my $name = $hash->{NAME};
notifyRegexpChanged($hash,'',1) if !$hash->{autoTraining};
# IO
AssignIoPort($hash);
my $IODev = AttrVal( $name, 'IODev', ReadingsVal( $name, 'IODev', defined InternalVal($name, 'IODev', undef ) ? InternalVal($name, 'IODev', undef )->{NAME} : undef ));
return if !$init_done; # || !defined $IODev;
RemoveInternalTimer($hash);
deleteAllRegIntTimer($hash);
fetchSiteIds($hash) if !ReadingsVal( $name, 'siteIds', 0 );
initialize_rhasspyTweaks($hash, AttrVal($name,'rhasspyTweaks', undef ));
initialize_rhasspyHotwords($hash, AttrVal($name,'rhasspyHotwords', undef ));
fetchIntents($hash);
delete $hash->{ERRORS};
if ( !defined InternalVal($name, 'IODev',undef) ) {
Log3( $hash, 1, "[$name] no suitable IO found, please define one and/or also add :RHASSPY: to clientOrder");
$hash->{ERRORS} = 'no suitable IO found, please define one and/or also add :RHASSPY: to clientOrder!';
}
IOWrite($hash, 'subscriptions', join q{ }, @topics)
if defined InternalVal($name, 'IODev',undef)
&& InternalVal( InternalVal($name, 'IODev',undef)->{NAME}, 'IODev', 'none') eq 'MQTT2_CLIENT';
initialize_devicemap($hash);
initialize_msgDialog($hash);
initialize_SpeechDialog($hash);
if ( 0 && $hash->{Babble} ) { #deactivated
InternalVal($hash->{Babble},'TYPE','none') eq 'Babble' ? $sets{Babble} = [qw( optionA optionB )]
: Log3($name, 1, "[$name] error: No Babble device available with name $hash->{Babble}!");
}
return;
}
sub initialize_Language {
my $hash = shift // return;
my $lang = shift // return;
my $cfg = shift // AttrVal($hash->{NAME},'languageFile',undef);
#my $cp = $hash->{encoding} // q{UTF-8};
#default to english first
$hash->{helper}->{lng} = $languagevars if !defined $hash->{helper}->{lng} || !$init_done;
return if !defined $cfg;
my ($ret, $content) = _readLanguageFromFile($hash, $cfg);
return $ret if $ret;
my $decoded;
#if ( !eval { $decoded = decode_json(encode($cp,$content)) ; 1 } ) {
if ( !eval { $decoded = JSON->new->decode($content) ; 1 } ) {
Log3($hash->{NAME}, 1, "JSON decoding error in languagefile $cfg: $@");
return "languagefile $cfg seems not to contain valid JSON!";
}
return if !defined $decoded;
my $slots = $decoded->{slots};
if ( defined $decoded->{default} && defined $decoded->{user} ) {
$decoded = _combineHashes( $decoded->{default}, $decoded->{user} );
Log3($hash->{NAME}, 4, "combined use user specific sentences and defaults provided in $cfg");
}
$hash->{helper}->{lng} = _combineHashes( $hash->{helper}->{lng}, $decoded );
return if !$init_done;
for my $key (keys %{$slots}) {
updateSingleSlot($hash, $key, $slots->{$key});
}
return if !$hash->{autoTraining};
resetRegIntTimer( 'autoTraining', time + $hash->{autoTraining}, \&RHASSPY_autoTraining, $hash, 0);
return;
}
sub initialize_prefix {
my $hash = shift // return;
my $prefix = shift // q{rhasspy};
my $old_prefix = $hash->{prefix}; #Beta-User: Marker, evtl. müssen wir uns was für Umbenennungen überlegen...
return if defined $old_prefix && $prefix eq $old_prefix;
# provide attributes "rhasspyName" etc. for all devices
addToAttrList("${prefix}Name",'RHASSPY');
addToAttrList("${prefix}Room",'RHASSPY');
addToAttrList("${prefix}Mapping:textField-long",'RHASSPY');
addToAttrList("${prefix}Group:textField",'RHASSPY');
addToAttrList("${prefix}Specials:textField-long",'RHASSPY');
for (devspec2array("${prefix}Colors=.+")) {
addToDevAttrList($_, "${prefix}Colors:textField-long",'RHASSPY');
}
for (devspec2array("${prefix}Channels=.+")) {
addToDevAttrList($_, "${prefix}Channels:textField-long",'RHASSPY');
}
return if !$init_done || !defined $old_prefix;
my @devs = devspec2array("$hash->{devspec}");
my @rhasspys = devspec2array("TYPE=RHASSPY:FILTER=prefix=$old_prefix");
for my $detail ( qw( Name Room Mapping Group Specials Channels Colors ) ) {
for my $device (@devs) {
my $aval = AttrVal($device, "${old_prefix}$detail", undef);
CommandAttr($hash, "$device ${prefix}$detail $aval") if $aval;
CommandDeleteAttr($hash, "$device ${old_prefix}$detail") if @rhasspys < 2;
delFromDevAttrList($device,"${old_prefix}$detail") if @rhasspys < 2 && ($detail eq "Channels" || $detail eq "Colors");
}
delFromAttrList("${old_prefix}$detail") if @rhasspys < 2;
}
return;
}
# Device löschen
sub Undefine {
my $hash = shift // return;
deleteAllRegIntTimer($hash);
RemoveInternalTimer($hash);
return;
}
sub Delete {
my $hash = shift // return;
deleteAllRegIntTimer($hash);
RemoveInternalTimer($hash);
return;
}
# Set Befehl aufgerufen
sub Set {
my $hash = shift;
my $anon = shift;
my $h = shift;
#parseParams: my ( $hash, $a, $h ) = @_;
my $name = shift @{$anon};
my $command = shift @{$anon} // q{};
my @values = @{$anon};
return "Unknown argument $command, choose one of "
. join(q{ }, map {
@{$sets{$_}} ? $_
.q{:}
.join q{,}, @{$sets{$_}} : $_} sort keys %sets)
if !defined $sets{$command};
Log3($name, 5, "set $command - value: " . join q{ }, @values);
my $dispatch = {
updateSlots => \&updateSlots,
trainRhasspy => \&trainRhasspy,
fetchSiteIds => \&fetchSiteIds
};
return $dispatch->{$command}->($hash) if ref $dispatch->{$command} eq 'CODE';
$values[0] = $h->{text} if ( $command eq 'speak' || $command eq 'textCommand' ) && defined $h->{text};
if ( $command eq 'play' || $command eq 'volume' ) {
$values[0] = $h->{siteId} if defined $h->{siteId};
$values[1] = $h->{path} if defined $h->{path};
$values[1] = $h->{volume} if defined $h->{volume};
}
if ($command eq 'activateVoiceInput') {
return activateVoiceInput($hash, $anon, $h);
}
$dispatch = {
speak => \&sendSpeakCommand,
textCommand => \&sendTextCommand,
play => \&setPlayWav,
volume => \&setVolume,
msgDialog => \&msgDialog
};
return Log3($name, 3, "set $name $command requires at least one argument!") if !@values;
my $params = join q{ }, @values; #error case: playWav => PERL WARNING: Use of uninitialized value within @values in join or string
$params = $h if defined $h->{text} || defined $h->{path} || defined $h->{volume};
return $dispatch->{$command}->($hash, $params) if ref $dispatch->{$command} eq 'CODE';
if ($command eq 'update') {
if ($values[0] eq 'language') {
return initialize_Language($hash, $hash->{LANGUAGE});
}
if ($values[0] eq 'devicemap') {
initialize_devicemap($hash);
$hash->{'.needTraining'} = 1;
deleteSingleRegIntTimer('autoTraining', $hash);
return updateSlots($hash);
}
if ($values[0] eq 'devicemap_only') {
return initialize_devicemap($hash);
}
if ($values[0] eq 'slots') {
$hash->{'.needTraining'} = 1;
deleteSingleRegIntTimer('autoTraining', $hash);
return updateSlots($hash);
}
if ($values[0] eq 'slots_no_training') {
initialize_devicemap($hash);
return updateSlots($hash);
}
if ($values[0] eq 'intent_filter') {
return fetchIntents($hash);
}
if ($values[0] eq 'all') {
initialize_Language($hash, $hash->{LANGUAGE});
initialize_devicemap($hash);
deleteSingleRegIntTimer('autoTraining', $hash);
$hash->{'.needTraining'} = 1;
updateSlots($hash);
return fetchIntents($hash);
}
}
if ($command eq 'customSlot') {
my $slotname = $h->{slotname} // shift @values;
my $slotdata = $h->{slotdata} // shift @values;
my $overwr = $h->{overwrite} // shift @values;
my $training = $h->{training} // shift @values;
return updateSingleSlot($hash, $slotname, $slotdata, $overwr, $training);
}
if ($command eq 'Babble') {
if ($values[0] eq 'optionA') {
return "rhasspy command Babble A called";
}
if ($values[0] eq 'optionB') {
return "rhasspy command Babble B called";
}
}
if ($command eq 'sayFinished') {
my $data;
$data->{id} = $h->{id} // shift @values // return;
my $siteId = $h->{siteId} // shift @values;
return sayFinished($hash,$data,$siteId);
}
return;
}
sub Get {
my $hash = shift;
my $anon = shift;
my $h = shift;
my $name = shift @{$anon};
my $command = shift @{$anon} // q{};
my @values = @{$anon};
return "Unknown argument $command, choose one of "
. join(q{ }, map {
@{$gets{$_}} ? $_
.q{:}
.join q{,}, @{$gets{$_}} : $_} sort keys %gets)
if !defined $gets{$command};
if ($command eq 'export_mapping') {
my $device = shift @{$anon} // return 'no device provided';
return 'no device from devicemap provided'
if !defined $hash->{helper}{devicemap}
|| !defined $hash->{helper}{devicemap}{devices}
|| !defined $hash->{helper}{devicemap}{devices}{$device};
return exportMapping($hash, $device);
}
if ($command eq 'test_file') {
return 'provide a filename' if !@values;
if ( $values[0] ne 'stop' && !defined $hash->{testline} ) {
if($hash->{CL}) {
my $start = gettimeofday();
my $tHash = { hash=>$hash, CL=>$hash->{CL}, reading=> 'testResult', start=>$start};
$hash->{asyncGet} = $tHash;
InternalTimer(gettimeofday()+30, sub {
asyncOutput($tHash->{CL}, "Test file $values[0] is initiated. See if internal 'testline' is rising and check testResult reading later");
delete($hash->{asyncGet});
}, $tHash, 0);
}
return testmode_start($hash, $values[0]);
}
}
if ($command eq 'test_sentence') {
return 'provide a sentence' if !@values;
if ( !defined $hash->{testline} ) {
if($hash->{CL}) {
my $start = gettimeofday();
my $tHash = { hash=>$hash, CL=>$hash->{CL}, reading=> 'testResult', start=>$start};
$hash->{asyncGet} = $tHash;
InternalTimer(gettimeofday()+4, sub { delete $hash->{testline};
asyncOutput($tHash->{CL}, "Timeout for test sentence - most likely this is no problem, check testResult reading later, but either intent was not recognized, RHASSPY's siteId is not configured for NLU or your system seems to be rather slow...");
delete($hash->{asyncGet});
}, $tHash, 0);
}
my $test = join q{ }, @values;
$hash->{testline} = 0;
$hash->{helper}->{test}->{content} = [$test];
$hash->{helper}->{test}->{filename} = 'none';
return testmode_next($hash);
}
}
delete $hash->{testline};
delete $hash->{helper}->{test};
readingsSingleUpdate($hash,'testResult','Test mode stopped (might have been running already)',1);
return 'Test mode stopped (might have been running already)';
}
# Attribute setzen / löschen
sub Attr {
my $command = shift;
my $name = shift;
my $attribute = shift // return;
my $value = shift;
my $hash = $defs{$name} // return;
# IODev Attribut gesetzt
if ($attribute eq 'IODev') {
return;
}
if ( $attribute eq 'rhasspyShortcuts' ) {
for ( keys %{ $hash->{helper}{shortcuts} } ) {
delete $hash->{helper}{shortcuts}{$_};
}
if ($command eq 'set') {
return init_shortcuts($hash, $value);
}
}
if ( $attribute eq 'rhasspyIntents' ) {
for ( keys %{ $hash->{helper}{custom} } ) {
delete $hash->{helper}{custom}{$_};
}
if ($command eq 'set') {
return init_custom_intents($hash, $value);
}
}
if ( $attribute eq 'rhasspyTweaks' ) {
for ( keys %{ $hash->{helper}{tweaks} } ) {
delete $hash->{helper}{tweaks}{$_};
}
if ($command eq 'set') {
return initialize_rhasspyTweaks($hash, $value) if $init_done;
}
}
if ( $attribute eq 'rhasspyHotwords' ) {
for ( keys %{ $hash->{helper}{hotwords} } ) {
delete $hash->{helper}{hotwords}{$_};
}
delete $hash->{helper}{hotwords};
if ($command eq 'set') {
return initialize_rhasspyHotwords($hash, $value) if $init_done;
}
}
if ( $attribute eq 'languageFile' ) {
if ($command ne 'set') {
delete $hash->{CONFIGFILE};
delete $attr{$name}{languageFile};
delete $hash->{helper}{lng};
$value = undef;
}
return initialize_Language($hash, $hash->{LANGUAGE}, $value);
}
if ( $attribute eq 'rhasspyMsgDialog' ) {
delete $hash->{helper}{msgDialog};
return if !$init_done;
return initialize_msgDialog($hash, $value, $command);
}
if ( $attribute eq 'rhasspyTTS' ) {
delete $hash->{helper}{TTS};
return if !$init_done;
return initialize_TTS($hash, $value, $command);
}
if ( $attribute eq 'rhasspySpeechDialog' ) {
delete $hash->{helper}{SpeechDialog};
return if !$init_done;
return initialize_SpeechDialog($hash, $value, $command);
}
return;
}
sub init_shortcuts {
my $hash = shift // return;
my $attrVal = shift // return;
my ($intent, $perlcommand, $device, $err );
for my $line (split m{\n}x, $attrVal) {
#old syntax
if ($line !~ m{\A[\s]*i=}x) {
($intent, $perlcommand) = split m{=}x, $line, 2;
$err = perlSyntaxCheck( $perlcommand );
return "$err in $line" if $err && $init_done;
$hash->{helper}{shortcuts}{$intent}{perl} = $perlcommand;
$hash->{helper}{shortcuts}{$intent}{NAME} = $hash->{NAME};
next;
}
next if !length $line;
my($unnamed, $named) = parseParams($line);
#return "unnamed parameters are not supported! (line: $line)" if ($unnamed) > 1 && $init_done;
$intent = $named->{i};
if (defined($named->{f})) {
$hash->{helper}{shortcuts}{$intent}{fhem} = $named->{f};
} elsif (defined($named->{p})) {
$err = perlSyntaxCheck( $perlcommand );
return "$err in $line" if $err && $init_done;
$hash->{helper}{shortcuts}{$intent}{perl} = $named->{p};
} elsif ($init_done && !defined $named->{r}) {
return "Either a fhem or perl command or a response have to be provided!";
}
$hash->{helper}{shortcuts}{$intent}{NAME} = $named->{d} if defined $named->{d};
$hash->{helper}{shortcuts}{$intent}{response} = $named->{r} if defined $named->{r};
if ( defined $named->{c} ) {
$hash->{helper}{shortcuts}{$intent}{conf_req} = !looks_like_number($named->{c}) ? $named->{c} : 'default';
if (defined $named->{ct}) {
$hash->{helper}{shortcuts}{$intent}{conf_timeout} = looks_like_number($named->{ct}) ? $named->{ct} : _getDialogueTimeout($hash, 'confirm');
} else {
$hash->{helper}{shortcuts}{$intent}{conf_timeout} = looks_like_number($named->{c}) ? $named->{c} : _getDialogueTimeout($hash, 'confirm');
}
}
}
return;
}
sub initialize_rhasspyTweaks {
my $hash = shift // return;
my $attrVal = shift // return;
my ($tweak, $values, $device, $err );
for my $line (split m{\n}x, $attrVal) {
next if !length $line;
if ($line =~ m{\A[\s]*timerLimits[\s]*=}x) {
($tweak, $values) = split m{=}x, $line, 2;
$tweak = trim($tweak);
return "Error in $line! Provide 5 comma separated numeric values!" if !length $values && $init_done;
my @test = split m{,}x, $values;
return "Error in $line! Provide 5 comma separated numeric values!" if @test != 5 && $init_done;
#$values = qq{($values)} if $values !~ m{\A([^()]*)\z}x;
$hash->{helper}{tweaks}{$tweak} = [@test];
next;
}
if ($line =~ m{\A[\s]*(timeouts|useGenericAttrs|timerSounds|confirmIntents|confirmIntentResponses|ignoreKeywords|gdt2groups)[\s]*=}x) {
($tweak, $values) = split m{=}x, $line, 2;
$tweak = trim($tweak);
return "Error in $line! No content provided!" if !length $values && $init_done;
my($unnamedParams, $namedParams) = parseParams($values);
return "Error in $line! Provide at least one key-value pair!" if ( @{$unnamedParams} || !keys %{$namedParams} ) && $init_done;
$hash->{helper}{tweaks}{$tweak} = $namedParams;
next;
}
if ($line =~ m{\A[\s]*(intentFilter)[\s]*=}x) {
($tweak, $values) = split m{=}x, $line, 2;
$tweak = trim($tweak);
return "Error in $line! No content provided!" if !length $values && $init_done;
my($unnamedParams, $namedParams) = parseParams($values);
return "Error in $line! Provide at least one item!" if ( !@{$unnamedParams} && !keys %{$namedParams} ) && $init_done;
for ( @{$unnamedParams} ) {
$namedParams->{$_} = 'false';
}
for ( keys %{$namedParams} ) {
$namedParams->{$_} = 'false' if $namedParams->{$_} ne 'false' && $namedParams->{$_} ne 'true';
}
$hash->{helper}{tweaks}{$tweak} = $namedParams;
next;
}
if ($line =~ m{\A[\s]*(extrarooms)[\s]*=}x) {
($tweak, $values) = split m{=}x, $line, 2;
$tweak = trim($tweak);
$values= join q{,}, split m{[\s]*,[\s]*}x, $values;
return "Error in $line! No content provided!" if !length $values && $init_done;
$hash->{helper}{tweaks}{$tweak} = $values;
next;
}
if ($line =~ m{\A[\s]*(confidenceMin)[\s]*=}x) {
($tweak, $values) = split m{=}x, $line, 2;
return "Error in $line! No content provided!" if !length $values && $init_done;
my($unnamedParams, $namedParams) = parseParams($values);
delete $hash->{helper}{tweaks}{confidenceMin};
return "Error in $line! Provide at least one item!" if ( !@{$unnamedParams} && !keys %{$namedParams} ) && $init_done;
for ( keys %{$namedParams} ) {
$hash->{helper}{tweaks}{confidenceMin}->{$_} = $namedParams->{$_} if looks_like_number($namedParams->{$_});
}
$hash->{helper}{tweaks}{confidenceMin}{default} = $unnamedParams->[0] if @{$unnamedParams} && looks_like_number($unnamedParams->[0]);
}
if ($line =~ m{\A[\s]*(mappingOverwrite)[\s]*=}x) {
($tweak, $values) = split m{=}x, $line, 2;
$tweak = trim($tweak);
$values= trim($values);
return "Error in $line! No content provided!" if !length $values && $init_done;
$hash->{helper}{tweaks}{$tweak} = $values;
}
}
return configure_DialogManager($hash) if $init_done;
return;
}
sub configure_DialogManager {
my $hash = shift // return;
my $siteId = shift // 'null'; #ReadingsVal( $hash->{NAME}, 'siteIds', 'default' ) // return;
my $toDisable = shift // [qw(ConfirmAction CancelAction Choice ChoiceRoom ChoiceDevice)];
my $enable = shift // q{false};
my $timer = shift;
#option to delay execution to make reconfiguration last action after everything else has been done and published.
if ( defined $timer ) {
my $fnHash = resetRegIntTimer( $siteId, time + looks_like_number($timer) ? $timer : 0, \&RHASSPY_configure_DialogManager, $hash, 0);
$fnHash->{toDisable} = $toDisable;
$fnHash->{enable} = $enable;
return;
}
#loop for global initialization or for several siteId's
if ( $siteId =~ m{,}xms ) {
my @siteIds = split m{,}xms, $siteId;
for (@siteIds) {
configure_DialogManager($hash, $_, $toDisable, $enable);
}
return;
}
my @intents = split m{,}xm, ReadingsVal( $hash->{NAME}, 'intents', '' );
my $language = $hash->{LANGUAGE};
my $fhemId = $hash->{fhemId};
=pod disable some intents by default https://rhasspy.readthedocs.io/en/latest/reference/#dialogue-manager
hermes/dialogueManager/configure (JSON)
Sets the default intent filter for all subsequent dialogue sessions
intents: [object] - Intents to enable/disable (empty for all intents)
intentId: string - Name of intent
enable: bool - true if intent should be eligible for recognition
siteId: string = "default" - Hermes site ID
Further reading on continuing sessions:
https://rhasspy-hermes-app.readthedocs.io/en/latest/usage.html#continuing-a-session
=cut
my @disabled;
my $matches = join q{|}, @{$toDisable};
for (@intents) {
last if $enable eq 'true';
next if $_ =~ m{$matches}xms;
my $defaults = {intentId => "$_", enable => 'true'} ;
$defaults = {intentId => "$_", enable => $hash->{helper}{tweaks}->{intentFilter}->{$_}} if defined $hash->{helper}->{tweaks} && defined $hash->{helper}{tweaks}->{intentFilter} && defined $hash->{helper}{tweaks}->{intentFilter}->{$_};
push @disabled, $defaults;
}
for (@{$toDisable}) {
my $id = qq(${language}.${fhemId}:$_);
my $disable = {intentId => "$id", enable => "$enable"};
push @disabled, $disable;
}
my $sendData = {
siteId => $siteId,
intents => [@disabled]
};
my $json = _toCleanJSON($sendData);
IOWrite($hash, 'publish', qq{hermes/dialogueManager/configure $json});
return;
}
sub RHASSPY_configure_DialogManager {
my $fnHash = shift // return;
return configure_DialogManager( $fnHash->{HASH}, $fnHash->{MODIFIER}, $fnHash->{toDisable}, $fnHash->{enable} );
}
sub init_custom_intents {
my $hash = shift // return;
my $attrVal = shift // return;
for my $line (split m{\n}x, $attrVal) {
next if !length $line;
#return "invalid line $line" if $line !~ m{(?<intent>[^=]+)\s*=\s*(?<perlcommand>(?<function>([^(]+))\((?<arg>.*)\)\s*)}x;
return "invalid line $line" if $line !~ m{
(?<intent>[^=]+)\s* #string up to =, w/o ending whitespace
=\s* #separator = and potential whitespace
(?<perlcommand> #identifier
(?<function>([^(]+))#string up to opening bracket
\( #opening bracket
(?<arg>.*)\))\s* #everything up to the closing bracket, w/o ending whitespace
}xms; ##no critic qw(Capture)
my $intent = trim($+{intent});
return "no intent found in $line!" if (!$intent || $intent eq q{}) && $init_done;
my $function = trim($+{function});
return "invalid function in line $line" if $function =~ m{\s+}x;
my $perlcommand = trim($+{perlcommand});
my $err = perlSyntaxCheck( $perlcommand );
return "$err in $line" if $err && $init_done;
$hash->{helper}{custom}{$intent}{function} = $function;
my $args = trim($+{arg});
my @params;
for my $ar (split m{,}x, $args) {
$ar =trim($ar);
#next if $ar eq q{}; #Beta-User having empty args might be intented...
push @params, $ar;
}
$hash->{helper}{custom}{$intent}{args} = \@params;
}