/
84_IrBlaster.pm
937 lines (688 loc) · 31.9 KB
/
84_IrBlaster.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
###############################################################################
#
# All rights reserved
#
# This script 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
# 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.
#
###############################################################################
#
# (c) 2017 Copyright: Johannes Viegener fhem at viegener.de)
#
# This module handles sending remote codes to the IR WLAN Gateway
# https://forum.fhem.de/index.php/topic,72950.msg724807.html#msg724807
#
# $Id$
#
###############################################################################
##
## - base setup
## - implement send
## - present timer
## - test base with direct
## - kill queue after some time (also when disabled etc) - currently 30
## - add
## - send
## 0.0.2 first working version
## - correction for queue handling (timestamp not given)
## - added _send
## - send allows multiple codes
## 0.0.3 send improvements
## - Queuing and absent handling corrected
## 0.0.4 corrections on queuing
## - removed dumper
## - fixed eol issue - unix
## - added initial documentation
## 0.0.5 documentation
## - remove access still set somewhere
## - status
## - removed de doc to show english as fallback
## - presence also with SYN check
## - pingtype attribute added
## - configure timeout for queued commands
## - FIX: redefine without passcode : #msg762210
##
##
###############################################################################
###############################################################################
## TODO
###############################################################################
##
## - add sleep times for codes
## -
## -
## - attribute handling complete (remove unneeded attributes)
## -
## - prefix change option
##
## - IDEA: Grab received codes
## - IDEA: allow step by step configuration of commands
## -
###############################################################################
package main;
use strict;
use warnings;
# currently not used - use Data::Dumper::Simple; # for debug
my $missingModul = "";
eval "use LWP::UserAgent;1" or $missingModul .= "LWP::UserAgent ";
eval "use HTTP::Request::Common;1" or $missingModul .= "HTTP::Request::Common ";
use HttpUtils;
use Blocking;
my $version = "0.0.5";
# Declare functions
sub IrBlaster_Define($$);
sub IrBlaster_Reset($);
sub IrBlaster_Undef($$);
sub IrBlaster_Initialize($);
sub IrBlaster_Set($@);
sub IrBlaster_SendRequest($$;$$$);
sub IrBlaster_Presence($);
sub IrBlaster_PresenceRun($);
sub IrBlaster_PresenceDone($);
sub IrBlaster_PresenceAborted($);
sub IrBlaster_TimerStatusRequest($);
sub IrBlaster_Attr(@);
sub IrBlaster_IsPresent($);
sub IrBlaster_HU_RunQueue($);
#########################
# TYPE routines
sub IrBlaster_Initialize($) {
my ($hash) = @_;
$hash->{SetFn} = "IrBlaster_Set";
$hash->{DefFn} = "IrBlaster_Define";
$hash->{UndefFn} = "IrBlaster_Undef";
$hash->{AttrFn} = "IrBlaster_Attr";
$hash->{AttrList} =
"disable:1,0 disabledForIntervals ".
"interval ".
"timeout ".
"pingtype:shell,syn ".
"maxRetries:4,3,2,1,0 ".
$readingFnAttributes;
foreach my $d(sort keys %{$modules{IrBlaster}{defptr}}) {
my $hash = $modules{IrBlaster}{defptr}{$d};
$hash->{VERSION} = $version;
}
}
sub IrBlaster_Define($$) {
my ( $hash, $def ) = @_;
my @a = split( "[ \t][ \t]*", $def );
return "too few parameters: define <NAME> IrBlaster <HOST> <prefix> [ <passcode> ]" if( @a < 4 or @a > 5 );
return "Cannot define IrBlaster device. Perl modul ${missingModul}is missing." if ( $missingModul );
my $name = $hash->{NAME};
my $host = $a[2];
delete( $hash->{PASS} );
$hash->{HOST} = $host;
$hash->{PREFIX} = $a[3];
$hash->{PASS} = $a[4] if(defined($a[4]));
$hash->{INTERVAL} = 0;
$hash->{TIMEOUT} = 300;
addToDevAttrList( $name, $a[3].".*" );
$modules{IrBlaster}{defptr}{HOST} = $hash;
Log3 $name, 3, "IrBlaster $name: defined IrBlaster device";
IrBlaster_Reset($hash);
return undef;
}
sub IrBlaster_Reset($) {
my $hash = shift;
my $name = $hash->{NAME};
$hash->{VERSION} = $version;
RemoveInternalTimer($hash);
RemoveInternalTimer($hash->{HU_SR_PARAMS}) if ( defined($hash->{HU_SR_PARAMS}) );
Log3 $name, 3, "IrBlaster $name: reset IrBlaster device";
readingsBeginUpdate($hash);
readingsBulkUpdate($hash, "presence", 'initialized' );
readingsBulkUpdate($hash,'state','initialized');
readingsEndUpdate($hash, 1);
if( $init_done ) {
InternalTimer( gettimeofday()+5, "IrBlaster_TimerStatusRequest", $hash, 0 );
} else {
InternalTimer( gettimeofday()+30, "IrBlaster_TimerStatusRequest", $hash, 0 );
}
return undef;
}
sub IrBlaster_Undef($$) {
my ( $hash, $arg ) = @_;
RemoveInternalTimer($hash);
delete $modules{IrBlaster}{defptr}{HOST} if( defined($modules{IrBlaster}{defptr}{HOST}) );
return undef;
}
#########################
# Device Instance routines
sub IrBlaster_Attr(@) {
my ( $cmd, $name, $attrName, $attrVal ) = @_;
my $hash = $defs{$name};
my $orig = $attrVal;
if( $attrName eq "disable" ) {
if( $cmd eq "set" and $attrVal eq "1" ) {
readingsSingleUpdate ( $hash, "state", "disabled", 1 );
$hash->{PARTIAL} = '';
RemoveInternalTimer($hash);
Log3 $name, 3, "IrBlaster ($name) - disabled";
} elsif( $cmd eq "set" and $attrVal eq "0" ) {
RemoveInternalTimer($hash);
readingsSingleUpdate ( $hash, "state", "active", 1 );
Log3 $name, 3, "IrBlaster ($name) - enabled";
IrBlaster_TimerStatusRequest($hash);
} elsif( $cmd eq "del" ) {
RemoveInternalTimer($hash);
readingsSingleUpdate ( $hash, "state", "active", 1 );
Log3 $name, 3, "IrBlaster ($name) - enabled";
IrBlaster_TimerStatusRequest($hash);
}
}
elsif( $attrName eq "disabledForIntervals" ) {
if( $cmd eq "set" ) {
Log3 $name, 4, "IrBlaster ($name) - enable disabledForIntervals";
readingsSingleUpdate ( $hash, "state", "disabled temporarily", 1 );
}
elsif( $cmd eq "del" ) {
readingsSingleUpdate ( $hash, "state", "active", 1 );
Log3 $name, 4, "IrBlaster ($name) - delete disabledForIntervals";
}
}
elsif( $attrName eq "interval" ) {
if( $cmd eq "set" ) {
$hash->{INTERVAL} = $attrVal;
RemoveInternalTimer($hash);
Log3 $name, 4, "IrBlaster ($name) - set interval: $attrVal";
IrBlaster_TimerStatusRequest($hash);
}
elsif( $cmd eq "del" ) {
$hash->{INTERVAL} = 0;
RemoveInternalTimer($hash);
Log3 $name, 4, "IrBlaster ($name) - delete User interval";
IrBlaster_TimerStatusRequest($hash);
}
}
elsif( $attrName eq "timeout" ) {
if( $cmd eq "set" ) {
$hash->{TIMEOUT} = $attrVal;
}
elsif( $cmd eq "del" ) {
$hash->{TIMEOUT} = 300;
}
}
return undef;
}
#######################################################
############ set #################
#######################################################
sub IrBlaster_Set($@) {
my ($hash, $name, $cmd, @args) = @_;
if ( ( lc $cmd eq 'send' ) || ( lc $cmd eq '_send' ) ) {
return "$cmd needs code/alias " if ( scalar( @args ) < 1 );
my $action;
my $prefix = $hash->{PREFIX};
my $ret;
foreach my $alias ( @args ) {
my $action = AttrVal($name, $prefix.$alias, undef );
$action = AttrVal($name, $alias, undef ) if ( ( ! defined( $action) ) && ( $alias =~ /^$prefix.+/ ) );
if ( ! defined( $action) ) {
$ret = ($ret?$ret:"")."$cmd - attribute not found (".$alias.")";
} else {
my $tmp = IrBlaster_SendRequest( $hash, $action );
if ( $tmp ) {
$ret = ($ret?$ret:"").$tmp;
}
}
}
return $ret if ( $ret );
} elsif( lc $cmd eq 'direct' ) {
return "$cmd needs code/alias " if ( scalar( @args ) < 1 );
my $action = join(" ", @args);
my $ret = IrBlaster_SendRequest( $hash, $action );
return $ret if ( $ret );
} elsif( lc $cmd eq 'add' ) {
return "$cmd needs alias and code " if ( scalar( @args ) < 2 );
my $alias = shift @args;
my $code = join(" ", @args);
my $val = AttrVal($name, $hash->{PREFIX}.$alias, undef );
if ( ! defined( $val ) ) {
$val = AttrVal($name, $alias, undef );
if ( ! defined( $val ) ) {
$alias = $hash->{PREFIX}.$alias;
addToDevAttrList( $name, $alias );
}
} else {
$alias = $hash->{PREFIX}.$alias;
}
my $ret = CommandAttr( undef, $name." ".$alias." ".$code );
return $ret if ( $ret );
} elsif( lc $cmd eq 'reset' ) {
IrBlaster_Reset($hash);
} elsif( lc $cmd eq 'presence' ) {
RemoveInternalTimer($hash);
Log3 $name, 4, "IrBlaster ($name) - status run for presence";
IrBlaster_TimerStatusRequest($hash);
} else {
my $list = "_send send add reset:noArg presence:noArg direct";
return "Unknown argument $cmd, choose one of $list";
}
Log3 $name, 4, "IrBlaster $name: called function IrBlaster_Set()";
return undef;
}
#######################################################
############ timer handlng #################
#######################################################
sub IrBlaster_TimerStatusRequest($) {
my $hash = shift;
my $name = $hash->{NAME};
Log3 $name, 4, "Sub IrBlaster_TimerStatusRequest ($name) - started";
# Do nothing when disabled (also for intervals)
if ( ( $init_done ) && (! IsDisabled( $name )) ) {
if(IrBlaster_IsPresent( $hash )) {
Log3 $name, 4, "Sub IrBlaster_TimerStatusRequest ($name) - is present";
# restart queue processing if PAUSED status
if ( ( defined( $hash->{doStatus} ) ) && ( $hash->{doStatus} =~ /^PAUSED/ ) ) {
# set timer - use param hash here to get a different timer!!!!
Log3 $name, 4, "Sub IrBlaster_TimerStatusRequest ($name) - restart paused queuing";
RemoveInternalTimer($hash->{HU_SR_PARAMS});
$hash->{doStatus} = "";
InternalTimer(gettimeofday()+5, "IrBlaster_HU_RunQueue", $hash->{HU_SR_PARAMS},0);
}
} else {
# update state
readingsSingleUpdate($hash,'state','off',1);
}
# start blocking presence call
IrBlaster_Presence($hash);
}
Log3 $name, 5, "Sub IrBlaster_TimerStatusRequest ($name) - Done - new sequence - ".$hash->{INTERVAL}." s";
if ( $hash->{INTERVAL} > 0 ) {
InternalTimer( gettimeofday()+$hash->{INTERVAL}, "IrBlaster_TimerStatusRequest", $hash, 0 );
} elsif (! IsDisabled( $name )) {
readingsSingleUpdate ( $hash, "state", "static", 1 );
}
}
#######################################################
############ sending #################
#######################################################
# Pars
# hash
# action is urlpath
# opt: par1 (timestamp)
# opt: par2 (not yet used)
# opt: retrycount - will be set to 0 if not given (meaning first exec)
sub IrBlaster_SendRequest($$;$$$) {
my ( $hash, @args) = @_;
my ( $action, $actPar1, $actPar2, $retryCount) = @args;
my $name = $hash->{NAME};
my $ret;
my $alphabet;
my $url;
my $urlaction = "";
Log3 $name, 5, "IrBlaster_SendRequest $name: ";
if ( $action =~ /\[/ ) {
$action = "/json?plain=".$action;
} elsif ( $action =~ '/' ) {
# ok full path given
} else {
Log3 $name, 2, "IrBlaster_SendRequest $name: action needs to start with / or plain data starting with [ :".$action.":";
return "IrBlaster_SendRequest: action needs to start with / or plain data starting with [ ";
}
# dirty hack with internal knowledge about url being /json?plain=<parameter> also /....?....=....
if ( $action =~ /^([^?]+\?[^=]+=)(.+)$/ ) {
$urlaction = $1.urlEncode($2);
} else {
Log3 $name, 2, "IrBlaster_SendRequest $name: action url malformed (no ...?...=... format) in :".$action.":";
return "IrBlaster_SendRequest: action url malformed (no ...?...=... format) in $action";
}
$actPar1 = gettimeofday() if ( ! defined( $actPar1 ) );
$args[1] = $actPar1;
$retryCount = 0 if ( ! defined( $retryCount ) );
# increase retrycount for next try
$args[3] = $retryCount+1;
my $actionString = $action.(defined($actPar1)?" Par1:".$actPar1.":":"")." ".(defined($actPar2)?" Par2:".$actPar2.":":"");
Log3 $name, 4, "IrBlaster_SendRequest $name: called with action ".$actionString;
# ensure actionQueue exists
$hash->{actionQueue} = [] if ( ! defined( $hash->{actionQueue} ) );
# Queue if not yet retried and currently waiting
if ( ( ( defined( $hash->{doStatus} ) ) && ( $hash->{doStatus} =~ /^WAITING/ ) && ( $retryCount == 0 ) )
## queue if already in PAUSED status and polling
|| ( ( $hash->{INTERVAL} > 0 ) && ( defined( $hash->{doStatus} ) ) && ( $hash->{doStatus} =~ /^PAUSED/ ) )
## if polling then stop sending requests if not present and set special doStatus PAUSED
|| ( ( $hash->{INTERVAL} > 0 ) && ( ! IrBlaster_IsPresent( $hash ) ) )
) {
# add to queue
Log3 $name, 4, "IrBlaster_SendRequest $name: add action to queue - args: ".$actionString;
push( @{ $hash->{actionQueue} }, \@args );
$hash->{doStatus} = "PAUSED" if ( ( $hash->{INTERVAL} > 0 ) && ( ! IrBlaster_IsPresent( $hash ) ) );
Log3 $name, 4, "Sub IrBlaster_TimerStatusRequest ($name) - pause queuing " if ( $hash->{doStatus} eq "PAUSED" );
return;
}
$hash->{doStatus} = "WAITING";
$hash->{doStatus} .= " retry $retryCount" if ( $retryCount > 0 );
$url = "http://".$hash->{HOST}.":80".$urlaction.(defined($hash->{PASS})?"&pass=".urlEncode($hash->{PASS}):"");
Log3 $name, 5, "STARTING SENDREQUEST: $url";
# ??? hash for params need to be moved to initialize
my %hu_sr_params = (
url => $url,
timeout => 30,
method => "GET",
header => "",
callback => \&IrBlaster_HU_Callback
);
$hash->{HU_SR_PARAMS} = \%hu_sr_params;
# create hash for storing readings for update
my %hu_sr_readings = ();
$hash->{HU_SR_PARAMS}->{SR_READINGS} = \%hu_sr_readings;
$hash->{HU_SR_PARAMS}->{hash} = $hash;
$hash->{HU_SR_PARAMS}->{action} = $action;
Log3 $name, 5, "Sub IrBlaster_SendRequest ($name) - Action ".$actionString;
# send the request non blocking
$hash->{HU_SR_PARAMS}->{args} = \@args; # add args now always
if ( defined( $ret ) ) {
Log3 $name, 1, "IrBlaster_SendRequest $name: Failed with :$ret:";
IrBlaster_HU_Callback( $hash->{HU_SR_PARAMS}, $ret, "");
} else {
Log3 $name, 4, "IrBlaster_SendRequest $name: call url :".$hash->{HU_SR_PARAMS}->{url}.": ";
HttpUtils_NonblockingGet( $hash->{HU_SR_PARAMS} );
}
}
#####################################
# INTERNAL: Callback is the callback for any nonblocking call to the TV
# 3 params are defined for callbacks
# param-hash
# err
# data (returned from url call)
# empty string used instead of undef for no return/err value
sub IrBlaster_HU_Callback($$$)
{
my ( $param, $err, $data ) = @_;
my $hash= $param->{hash};
my $name = $hash->{NAME};
my $ret;
my $action = $param->{action};
my $doRetry = 1; # will be set to zero if error is found that should lead to no retry
Log3 $name, 4, "IrBlaster_HU_Callback $name: ".
(defined( $err )?"status err :".$err.":":"no error");
Log3 $name, 5, "IrBlaster_HU_Callback $name: data :".(( defined( $data ) )?$data:"<undefined>");
if ( $err ne "" ) {
$ret = "Error returned: $err";
$hash->{lastresponse} = $ret;
} elsif ( $param->{code} != 200 ) {
$ret = "HTTP-Error returned: ".$param->{code};
$hash->{lastresponse} = $ret;
$doRetry = 0;
} else {
Log3 $name, 4, "IrBlaster_HU_Callback $name: action: ".$action." code : ".$param->{code};
if ( ( defined($data) ) && ( $data ne "" ) ) {
# Log3 $name, 4, "IrBlaster_HU_Callback $name: handle data";
# ???
}
$hash->{lastresponse} = $data;
$ret = "SUCCESS";
}
# handle readings
readingsBeginUpdate($hash);
readingsBulkUpdate($hash, "requestAction", $action );
readingsBulkUpdate($hash, "requestResult", $ret );
Log3 $name, 4, "IrBlaster_HU_Callback $name: resulted in ".$ret;
my $doqueue = 1;
if ( $ret ne "SUCCESS" ) {
# not succesful
if ( ( $doRetry ) && ( defined( $param->{args} ) ) ) {
my $wait = $param->{args}[3];
my $maxRetries = AttrVal($name,'maxRetries',0);
Log3 $name, 4, "IrBlaster_HU_Callback $name: retry count so far $wait (max: $maxRetries) for send request ".
$param->{args}[0]." : ".
(defined($param->{args}[1])?$param->{args}[1]:"<undef>")." : ".
(defined($param->{args}[2])?$param->{args}[2]:"<undef>");
if ( $wait <= $maxRetries ) {
# calculate wait time 5s * retries (will be stopped anyhow if not present)
$wait = $wait*20;
Log3 $name, 4, "IrBlaster_HU_Callback $name: do retry for send request ".$param->{args}[0]." : ";
$hash->{actionQueue} = [] if ( ! defined( $hash->{actionQueue} ) );
push( @{ $hash->{actionQueue} }, $param->{args} );
# set timer - use param hash here to get a different timer!!!!
RemoveInternalTimer($hash->{HU_SR_PARAMS});
InternalTimer(gettimeofday()+$wait, "IrBlaster_HU_RunQueue", $hash->{HU_SR_PARAMS},0);
# ensure queue will not be called
$doqueue = 0;
} else {
Log3 $name, 3, "IrBlaster_HU_Callback $name: Reached max retries (ret: $ret) for msg ".$param->{args}[0]." : ".$param->{args}[1];
}
} elsif ( ! $doRetry ) {
Log3 $name, 3, "IrBlaster_HU_Callback $name: No retry for (ret: $ret) for send request ".$param->{args}[0]." : ";
}
}
readingsEndUpdate($hash, 1);
# clean param hash
delete( $param->{data} );
delete( $param->{code} );
$hash->{doStatus} = "";
#########################
# start next command in queue if available
IrBlaster_HU_RunQueue( $hash->{HU_SR_PARAMS} ) if ( $doqueue );
}
#######################################################
############ Presence Erkennung Begin #################
#######################################################
sub IrBlaster_PresenceRunShell($) {
my $string = shift;
my ($name, $host) = split("\\|", $string);
my $tmp;
my $response;
$tmp = qx(ping -c 3 -w 2 $host 2>&1);
if(defined($tmp) and $tmp ne "") {
chomp $tmp;
Log3 $name, 5, "IrBlaster ($name) - ping command returned with output:\n$tmp";
$response = "$name|".(($tmp =~ /\d+ [Bb]ytes (from|von)/ and not $tmp =~ /[Uu]nreachable/) ? "present" : "absent");
} else {
$response = "$name|Could not execute ping command";
}
Log3 $name, 4, "Sub IrBlaster_PresenceRunShell ($name) - Sub finish, Call IrBlaster_PresenceDone";
return $response;
}
sub IrBlaster_PresenceRunSyn($) {
my $string = shift;
my ($name, $host) = split("\\|", $string);
my $tmp;
my $response;
Log3 $name, 5, "Sub IrBlaster_PresenceRunSyn ($name) - start";
my $ping = Net::Ping->new("syn", 1);
$ping->source_verify(0); # do not verify source for responses
if ( $ping->ping($host)) {
if ( $ping->ack($host)) {
Log3 $name, 4, "Sub IrBlaster_PresenceRunSyn ($name) - alive :$host:";
$response = "present";
} else {
Log3 $name, 4, "Sub IrBlaster_PresenceRunSyn ($name) - not ack :$host: reason :".$ping->nack($host);
$response = "absent";
}
} else {
Log3 $name, 4, "Sub IrBlaster_PresenceRunSyn ($name) - ping failed :$host:";
$response = "absent";
}
$ping->close();
Log3 $name, 5, "Sub IrBlaster_PresenceRunSyn ($name) - Sub finish, Call IrBlaster_PresenceDone";
return "$name|$response";
}
sub IrBlaster_Presence($) {
my $hash = shift;
my $name = $hash->{NAME};
my $method = ( AttrVal($name, "pingtype", "shell") eq "syn" )?"IrBlaster_PresenceRunSyn":"IrBlaster_PresenceRunShell";
Log3 $name, 4, "Sub IrBlaster_Presence ($name) - Type: $method";
$hash->{helper}{RUNNING_PID} = BlockingCall($method, $name.'|'.$hash->{HOST}, "IrBlaster_PresenceDone", 15, "IrBlaster_PresenceAborted", $hash) unless(exists($hash->{helper}{RUNNING_PID}) );
}
sub IrBlaster_PresenceRun($) {
my $string = shift;
my ($name, $host) = split("\\|", $string);
my $tmp;
my $response;
$tmp = qx(ping -c 3 -w 2 $host 2>&1);
if(defined($tmp) and $tmp ne "") {
chomp $tmp;
Log3 $name, 5, "IrBlaster ($name) - ping command returned with output:\n$tmp";
$response = "$name|".(($tmp =~ /\d+ [Bb]ytes (from|von)/ and not $tmp =~ /[Uu]nreachable/) ? "present" : "absent");
} else {
$response = "$name|Could not execute ping command";
}
Log3 $name, 4, "Sub IrBlaster_PresenceRun ($name) - Sub finish, Call IrBlaster_PresenceDone";
return $response;
}
sub IrBlaster_PresenceDone($) {
my ($string) = @_;
my ($name,$response) = split("\\|",$string);
my $hash = $defs{$name};
delete($hash->{helper}{RUNNING_PID});
Log3 $name, 4, "Sub IrBlaster_PresenceDone ($name) - Der Helper ist disabled. Daher wird hier abgebrochen" if($hash->{helper}{DISABLED});
return if($hash->{helper}{DISABLED});
readingsBeginUpdate($hash);
readingsBulkUpdate ( $hash, "state", $response );
readingsBulkUpdate($hash, "presence", $response );
readingsEndUpdate($hash, 1);
Log3 $name, 4, "Sub IrBlaster_PresenceDone ($name) - Abschluss!";
}
sub IrBlaster_PresenceAborted($) {
my ($hash) = @_;
my $name = $hash->{NAME};
delete($hash->{helper}{RUNNING_PID});
readingsBeginUpdate($hash);
readingsBulkUpdate ( $hash, "state", "timedout" );
readingsBulkUpdate($hash, "presence", 'timedout' );
readingsEndUpdate($hash, 1);
Log3 $name, 4, "Sub IrBlaster_PresenceAborted ($name) - The BlockingCall Process terminated unexpectedly. Timedout!";
}
####### Presence Erkennung Ende ############
#######################################################
############# HELPER ################################
#######################################################
#####################################
# INTERNAL: Called to retry a send operation after wait time
# Gets the do params
sub IrBlaster_HU_RunQueue($)
{
my $param = shift;
my $hash= $param->{hash};
my $name = $hash->{NAME};
if ( ( defined( $hash->{actionQueue} ) ) && ( scalar( @{ $hash->{actionQueue} } ) > 0 ) ) {
my $ref;
while ( scalar( @{ $hash->{actionQueue} } ) > 0 ) {
$ref = shift @{ $hash->{actionQueue} };
# check for excess age
if ( $hash->{TIMEOUT} == -1 ) {
$ref = undef;
} elsif ( ((@$ref[1]) + $hash->{TIMEOUT} ) > gettimeofday() ) {
last;
} else {
Log3 $name, 4, "IrBlaster_HU_RunQueue $name: remove queued command with time :".(@$ref[1]).
": action :@$ref[0]: remaining: ".scalar( @{ $hash->{actionQueue} } );
$ref = undef;
}
}
if ( defined($ref) ) {
Log3 $name, 4, "IrBlaster_HU_RunQueue $name: handle queued cmd with :@$ref[0]: remaining: ".scalar( @{ $hash->{actionQueue} } );
IrBlaster_SendRequest( $hash, @$ref[0], @$ref[1], @$ref[2] );
}
}
}
sub IrBlaster_IsPresent($) {
my $hash = shift;
return (ReadingsVal($hash->{NAME},'presence','absent') eq 'present');
}
#######################################################
1;
=pod
=item summary send IR codes to IR WLAN Gateway
=item summary_DE IR Infrarot-Befehle via IR WLAN Gateway
=begin html
<a name="IrBlaster"></a>
<h3>IrBlaster</h3><ul>
This module allows the communication with the so-called (360 Grad) IR WLAN Gateway (in short IR gateway) a physical device to send and receive IR codes based on an ESP8266. The IR WLAN Gateway is described in this thread in the FHEM Forum:
<a href="https://forum.fhem.de/index.php/topic,72950.0.html">https://forum.fhem.de/index.php/topic,72950.0.html</a>
<br><br>
The IrBlaster module can send codes, that are stored in attributes to the corresponding IR gateway via http requests. The attributes share a common prefix that is created during definition of the device in FHEM. New codes are added by giving a specific name for the code (e.g. "tv_onoff") and specifying the code/url part that is used by the IR gateway. Codes are stored as attributes with a given prefix (see define).
<br><br>
The network presence of the IR gateway is checked regularly on request and commands are only sent if the device is present. Commands are queued to ensure proper reception and if needed can also be resend on failures or absence of the device.
<br><br>
<a name="IrBlasterdefine"></a>
<b>Define</b>
<ul>
<code>define <name> IrBlaster <hostname or IP> <prefix> [ <passcode> ]</code>
<br><br>
Defines a IrBlaster device under the given hostname (or IP address). IR codes will be stored with the given prefix (see add command) and if a passcode is configured in the IR gateway this needs to be specified as well.
<br><br>
Example: <code>define irblaster IrBlaster 192.168.100.200 IR_ acbdef</code><br>
<br>
All examples below will assume this defintion being given
<br><br>
IMPORTANT: The prefix should be selected in a way that collisions with other attributes are avoided
</ul>
<br>
<a name="IrBlasterset"></a>
<b>Set</b>
<ul>
<code>set <name> <what> [<value>]</code>
<br>
where <what> / <value> is one of
<br><br>
<li><code>add <name> <codevalue></code><br>Add (or update) a new IR command, that will be stored as an attribute with the given name. If name does not start with the given prefix (from the define), that this is added (see example). The codevalue has to be given either as value of the plain parameter in the url or as complete path and parameter part of the url (with out host but starting with /)
<br><br>
Exmple: <br>
<code>set irblaster add tv_onoff [{'data':'416', 'type':'RC5', 'length':12}]</code> <br> will add/change an attribute named IR_tv_onoff which will call http://192.168.100.200:80/json?plain=[{'data':'416', 'type':'RC5', 'length':12}] on the IR gateway
<br><br>
<code>set irblaster add tv_ok /json?plain=[{'data':'C0C', 'type':'RC5', 'length':12}]</code> <br> will add/change an attribute named tv_ok which will call http://192.168.100.200:80/json?plain=[{'data':'C0C', 'type':'RC5', 'length':12}] on the IR gateway
<br><br>
<code>set irblaster add IR_tv_mute [{'data':[850,2400, 400,1750, 400,1050, 400,1050, 400,1750, 400,1750, 400,1750, 400,1050, 400,1050, 400,1050, 400,1050, 400,1750, 400,1050, 400,1750, 400,1750, 400,1750, 400,1750, 400,1050, 400,1750, 400,1050, 400], 'type':'raw', 'khz':38}]</code> <br> will add/change an attribute named IR_tv_mute that will call the follwing url on send command <br>
http://192.168.100.200:80/json?plain=[{'data':[850,2400, 400,1750, 400,1050, 400,1050, 400,1750, 400,1750, 400,1750, 400,1050, 400,1050, 400,1050, 400,1050, 400,1750, 400,1050, 400,1750, 400,1750, 400,1750, 400,1750, 400,1050, 400,1750, 400,1050, 400], 'type':'raw', 'khz':38}] on the IR gateway
</li>
<br><br>
<li><code>_send <codename1> [ ... <codenameN> ] </code> <br> or <br> <code>send <name1> [ ... <namen> ] </code><br>Send the code that is stored as attribute under the codename in the device (you might ommit the prefix of the attribute).
<br><br>
Exmple: <br>
<code>set irblaster _send tv_onoff</code> <br> will send the code that is specified in attribute IR_tv_onoff which will call http://192.168.100.200:80/json?plain=[{'data':'416', 'type':'RC5', 'length':12}] on the IR gateway
<br><br>
<code>set irblaster send tv_ok IR_tv_mute</code> will send the codes specified in attribute IR_tv_ok and IR_tv_mute to the IR gateway
</li>
<br><br>
<li><code>direct <codevalue></code><br>Send the given code value directly to the IR gateway, without the need to create an attribute via add first. The codevalue has to be given either as value of the plain parameter in the url or as complete path and parameter part of the url (with out host but starting with /)
<br>
Exmple: <br> <br>
<code>set irblaster direct [{'data':'416', 'type':'RC5', 'length':12}]</code> <br> will call the following url http://192.168.100.200:80/json?plain=[{'data':'416', 'type':'RC5', 'length':12}] on the IR gateway
<br><br>
<li><code>presence</code><br> Check the presence of the IR gateway (via ping)
</li>
<li><code>reset</code><br>Reset the FHEM device (only used in case of something gets into an unknown or strange state)
</li>
</ul>
<br>
<a name="IrBlasterattr"></a>
<b>Attributes</b>
<br><br>
All IR codes are stored as attributes, with the given prefix, so please ensure the prefix is chosen without conflicts to user or generic attributes. These attributes are also added to the userattributes list.
<br><br>
<ul>
<li><code>maxRetries <0,1,2,3,4,5></code><br>Specify the number of retries for sending a code in case of a failure with increasing delays between retries. Specific failures that are non-recoverable will lead to no retry. Setting the value to 0 (default) will result in no retries.
</li>
<li><code>interval <seconds></code><br>Specify the interval (in seconds) for checking presence of the IR gateway device (using ping).
</li>
<li><code>timeout <seconds></code><br>Specify the timeout (in seconds) for queued commands to be send after an issue (non-presence or error), after the given time in seconds queued commands are not resend - with a value of -1 no queueing is done. Default is a value of 300.
</li>
<li><code>pingtype <syn|shell></code><br>Specify the type for checking presence of the IR gateway device (using either the default shell ping command - shell or using TCPSYN = syn).
</li>
</ul>
<br>
<a name="IrBlasterreadings"></a>
<b>Readings</b>
<ul>
<li><code>requestAction</code> / <code>requestResult</code><br>Gives information about the last code and the result received from the IR gateway </li>
<li><code>presence</code><br>specify presence state of the IR gateway as detected by the internal presence mechanism</li>
</ul>
<br><br>
</ul>
=end html
=cut