-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path98_PID20.pm
1038 lines (931 loc) · 38.7 KB
/
98_PID20.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: 98_PID20.pm 28754 2024-11-29 Beta-User $
=for comment
####################################################################################################
#
# 98_PID20.pm
# The PID device is a loop controller, used to set the value e.g of a heating
# valve dependent of the current and desired temperature.
#
# This module is derived from the contrib/99_PID.pm by Alexander Titzel.
# The framework of the module is derived from proposals by betateilchen.
# PID calculations developed and provided by John
#
# 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/>.
#
#
# V 1.00.c
# 03.12.2013 - bugfix : pidActorLimitUpper wrong assignment
# V 1.00.d
# 09.12.2013 - verbose-level adjusted
# 20.12.2013 - bugfix: actorErrorPos: wrong assignment by pidCalcInterval-attribute, if defined
# V 1.00.e
# 01.01.2014 - fix: {helper}{actorCommand} assigned to an emptry string if not defined
# V 1.00.f
# 22.01.2014 fix:pidDeltaTreshold only int was assignable, now even float
# V 1.00.g
# 29.01.2014 fix:calculation of i-portion is independent from pidCalcInterval
# V 1.00.h
# 26.02.2014 fix:new logging format; adjusting verbose-levels
#
# 26.03.2014 (betateilchen)
# code review, pod added, removed old version info (will be provided via SVN)
# V 1.01
# 19.10.2014 fix in sub PID20_Set : wrong parameter $hash instead of $name, when calling PID20_Calc
# V 1.0.0.2 30.10.14 - fix in PID20_Calc when setting $retStr (thanks to Thorsten Pferdekaemper)
# V 1.0.0.3
# 20.11.2014 Bug: processing of D-Portion and handling of disable
# V 1.0.0.4
# 27.11.2014 Change: all readings are updated cyclically
# V 1.0.0.5
# 06.11.2015 Fix: reg expression in sub PID20_Notify modifed. Thanks to user gero
# V 1.0.0.6
# 12.11.2015 Fix: wrong evaluation of Sensor String, when value was 0 than sensor timeout was detected
# Feature: added <Internal> VERSION
# V 1.0.0.7 Feature: new attribute pidActorCallBeforeSetting for user specific callback
# before setting a new value to actor
# V 1.0.0.8 Feature: attribute handling accelerates some actions
# Fix: update of state triggers force a notify
# Fix: adjust commandref
# V 1.0.0.9 Feature: new attribute pidIPortionCallBeforeSetting for user specific callback
# before setting a new value to p-portion
#
=cut
=for comment
####################################################################################################
#
# Maintainer CHANGED
#
# 2023-05-14 patches (betateilchen)
#
# attribute disabledForIntervals (added)
# improved handling for disabled devices (uses IsDisabled() now)
#
# attribute pidRoundReadings (added)
# rounding values if desired (implemented)
# commandref for new attribute (added)
#
# attribute pidActorMapCmd (added)
# syntax check for attribute value (added)
# map actuation value to command (implemented)
# commandref for new attribute (added)
#
# id-Tags added to commandref (for define/set/get/attributes)
#
# 2023-08-08 patches
#
# invalid name of sensor / reading / actor will no longer
# prevent the definition, but will write log entries with errors.
#
# 2024-04-05 remove smartmatch issues
#
####################################################################################################
=cut
package main;
use strict;
use warnings;
use vars qw(%defs);
use vars qw($readingFnAttributes);
use vars qw(%modules);
my $PID20_Version = "1.0.0.10";
sub PID20_Calc($);
########################################
sub PID20_Log($$$)
{
my ( $hash, $loglevel, $text ) = @_;
my $xline = ( caller(0) )[2];
my $xsubroutine = ( caller(1) )[3];
my $sub = ( split( ':', $xsubroutine ) )[2];
$sub = substr( $sub, 6 ); # without PID20
my $instName = ( ref($hash) eq "HASH" ) ? $hash->{NAME} : "PID20";
Log3 $hash, $loglevel, "PID20 $instName: $sub.$xline " . $text;
}
########################################
sub PID20_Initialize($)
{
my ($hash) = @_;
$hash->{DefFn} = 'PID20_Define';
$hash->{UndefFn} = 'PID20_Undef';
$hash->{SetFn} = 'PID20_Set';
$hash->{GetFn} = 'PID20_Get';
$hash->{NotifyFn} = 'PID20_Notify';
$hash->{AttrFn} = 'PID20_Attr';
$hash->{AttrList} =
'pidActorValueDecPlaces:0,1,2,3,4,5 '
. 'pidActorInterval '
. 'pidActorTreshold '
. 'pidActorErrorAction:freeze,errorPos '
. 'pidActorErrorPos '
. 'pidActorKeepAlive '
. 'pidActorLimitLower '
. 'pidActorLimitUpper '
. 'pidActorMapCmd:textField-long '
. 'pidActorCallBeforeSetting '
. 'pidIPortionCallBeforeSetting '
. 'pidCalcInterval '
. 'pidDeltaTreshold '
. 'pidDesiredName '
. 'pidFactor_P '
. 'pidFactor_I '
. 'pidFactor_D '
. 'pidMeasuredName '
. 'pidSensorTimeout '
. 'pidReverseAction '
. 'pidUpdateInterval '
. 'pidDebugSensor:0,1 '
. 'pidDebugActuation:0,1 '
. 'pidDebugCalc:0,1 '
. 'pidDebugDelta:0,1 '
. 'pidDebugUpdate:0,1 '
. 'pidDebugNotify:0,1 '
. 'pidRoundReadings:2,3,4,5 '
. 'disable:0,1 '
. 'disabledForIntervals:textField-long '
. $readingFnAttributes;
}
##########################
sub PID20_RestartTimer($$)
{
my ( $hash, $seconds ) = @_;
my $name = $hash->{NAME};
$seconds = 1 if ( $seconds <= 0 );
RemoveInternalTimer($name);
my $sdNextScan = gettimeofday() + $seconds;
InternalTimer( $sdNextScan, 'PID20_Calc', $name, 0 );
PID20_Log $hash, 5, 'name:'.$name.' seconds:'.$seconds;
}
########################################
sub PID20_TimeDiff($)
{
my ($strTS) = @_;
#my ( $package, $filename, $line ) = caller(0);
#print "PID $strTS line $line \n";
my $serTS = ( defined($strTS) && $strTS ne "" ) ? time_str2num($strTS) : gettimeofday();
my $timeDiff = gettimeofday() - $serTS;
$timeDiff = 0 if ( $timeDiff < 0 );
return $timeDiff;
}
########################################
sub PID20_Define($$$)
{
my ( $hash, $def ) = @_;
my @a = split( "[ \t][ \t]*", $def );
my $name = $a[0];
if ( @a != 4 )
{
return "wrong syntax: define <name> PID20 "
. "<sensor>:reading:[regexp] <actor>[:cmd] ";
}
return if !$init_done;
return PID20_Check($hash, $a[2], $a[3]);
}
sub PID20_Check($$$)
{ my ( $hash, $sensorinfo, $actorinfo ) = @_;
###################
# Sensor
my ( $sensor, $reading, $regexp ) = split( ":", $sensorinfo, 3 );
my $msg;
# if sensor unkonwn
my $name = $hash->{NAME};
my $err = 0;
if ( !$defs{$sensor} )
{
my $msg = "$name: Unknown sensor device $sensor specified";
PID20_Log $hash, 1, $msg;
#return $msg;
$err = 1;
}
# if reading of sender is unknown
if ( ReadingsVal( $sensor, $reading, 'unknown' ) eq 'unkown' )
{
$msg = "$name: Unknown reading $reading for sensor device $sensor specified";
PID20_Log $hash, 1, $msg;
#return $msg;
$err = 1;
}
#my $reFloat = '^([\\+,\\-]?\\d+\\.?\d*$)'; # gleitpunkt
# defaults for regexp
if ( !$regexp )
{
#$regexp = $reFloat;
$regexp = '^([\\+,\\-]?\\d+\\.?\d*$)';
}
# Actor
my ( $actor, $cmd ) = split( ":", $actorinfo, 2 );
if ( !$defs{$actor} )
{
$msg .= '\n' if $msg;
$msg .= "$name: Unknown actor device $actor specified";
PID20_Log $hash, 1, $msg;
#return $msg;
$err = 1;
}
$hash->{VERSION} = $PID20_Version;
if (!$err) {
$hash->{helper}{sensor} = $sensor;
$hash->{helper}{reading} = $reading;
$hash->{helper}{regexp} = $regexp;
$hash->{helper}{actor} = $actor;
$hash->{helper}{actorCommand} = ( defined($cmd) ) ? $cmd : '';
$hash->{helper}{stopped} = 0;
$hash->{helper}{adjust} = '';
$modules{PID20}{defptr}{$name} = $hash;
readingsSingleUpdate( $hash, 'state', 'initializing', 1 );
RemoveInternalTimer($name);
InternalTimer( gettimeofday() + 10, 'PID20_Calc', $name, 0 );
} else {
readingsSingleUpdate( $hash, 'state', 'PID defined with errors! See logfile for details.', 0 );
}
return $msg;
}
########################################
sub PID20_Undef($$)
{
my ( $hash, $arg ) = @_;
RemoveInternalTimer( $hash->{NAME} );
return undef;
}
########################################
# we need a gradient for delta as base for d-portion calculation
#
sub PID20_Notify($$)
{
my ( $hash, $dev ) = @_;
my $name = $hash->{NAME};
my $sensorName = $hash->{helper}{sensor};
my $DEBUG = AttrVal( $name, 'pidDebugNotify', '0' ) eq '1';
# no action if disabled
return if IsDisabled($name);
if ( $dev->{NAME} eq 'global' ) {
my $events = $dev->{CHANGED};
return if !$events; # Some previous notify deleted the array.
for my $evnt(@{$events}){
if ($evnt =~ m/INITIALIZED|REREADCFG/){
my ($sensorinfo, $actorinfo) = split m{\s+}xms, $hash->{DEF};
return PID20_Check($hash, $sensorinfo, $actorinfo );
}
}
}
return if ( $dev->{NAME} ne $sensorName );
my $sensorReadingName = $hash->{helper}{reading};
my $regexp = $hash->{helper}{regexp};
my $desiredName = AttrVal( $name, 'pidDesiredName', 'desired' );
my $desired = ReadingsVal( $name, $desiredName, undef );
my $max = int( @{ $dev->{CHANGED} } );
PID20_Log $hash, 4, "check $max readings for " . $sensorReadingName;
for ( my $i = 0 ; $i < $max ; $i++ )
{
my $s = $dev->{CHANGED}[$i];
# continue, if no match with reading-name
$s = '' if ( !defined($s) );
PID20_Log $hash, 5, "check event:<$s>";
next if ( $s !~ m/^$sensorReadingName:.*$/ );
# ---- build difference current - old value
# get sensor value
my $sensorStr = ReadingsVal( $sensorName, $sensorReadingName, undef );
$sensorStr =~ m/$regexp/;
my $sensorValue = $1;
# calc difference of delta/deltaOld
my $delta = $desired - $sensorValue if ( defined($desired) );
my $deltaOld = ( $hash->{helper}{deltaOld} + 0 ) if ( defined( $hash->{helper}{deltaOld} ) );
my $deltaDiff = ( $delta - $deltaOld ) if ( defined($delta) && defined($deltaOld) );
PID20_Log $hash, 5,
"Diff: delta["
. sprintf( "%.2f", $delta ) . "]"
. " - deltaOld["
. sprintf( "%.2f", $deltaOld ) . "]"
. "= Diff["
. sprintf( "%.2f", $deltaDiff ) . "]"
if ($DEBUG);
# ----- build difference of timestamps (ok)
my $deltaOldTsStr = $hash->{helper}{deltaOldTS};
my $deltaOldTsNum = time_str2num($deltaOldTsStr) if ( defined($deltaOldTsStr) );
my $nowTsNum = gettimeofday();
my $tsDiff = ( $nowTsNum - $deltaOldTsNum )
if ( defined($deltaOldTsNum) && ( ( $nowTsNum - $deltaOldTsNum ) > 0 ) );
PID20_Log $hash, 5, "tsDiff: tsDiff = $tsDiff " if ($DEBUG);
# ----- calculate gradient of delta
my $deltaGradient = $deltaDiff / $tsDiff
if ( defined($deltaDiff) && defined($tsDiff) && ( $tsDiff > 0 ) );
$deltaGradient = 0 if ( !defined($deltaGradient) );
my $sdeltaDiff = ($deltaDiff) ? sprintf( "%.2f", $deltaDiff ) : '';
my $sTSDiff = ($tsDiff) ? sprintf( "%.2f", $tsDiff ) : '';
my $sDeltaGradient = ($deltaGradient) ? sprintf( "%.6f", $deltaGradient ) : '';
PID20_Log $hash, 5,
"deltaGradient: (Diff[$sdeltaDiff]" . "/tsDiff[$sTSDiff]" . "=deltaGradient per sec [$sDeltaGradient]"
if ($DEBUG);
# ----- store results
$hash->{helper}{deltaGradient} = $deltaGradient;
$hash->{helper}{deltaOld} = $delta;
$hash->{helper}{deltaOldTS} = TimeNow();
last;
}
return '';
}
########################################
sub PID20_Get($@)
{
my ( $hash, @a ) = @_;
my $name = $hash->{NAME};
my $usage = "Unknown argument $a[1], choose one of params:noArg";
return $usage if ( @a < 2 );
my $cmd = lc( $a[1] );
if ($cmd eq 'params') {
my $ret = "Defined parameters for PID20 $name:\n\n";
$ret .= 'Actor name : ' . $hash->{helper}{actor} . "\n";
$ret .= 'Actor cmd : ' . $hash->{helper}{actorCommand} . "\n\n";
$ret .= 'Sensor name : ' . $hash->{helper}{sensor} . "\n";
$ret .= 'Sensor reading : ' . $hash->{helper}{reading} . "\n\n";
$ret .= 'Sensor regexp : ' . $hash->{helper}{regexp} . "\n\n";
$ret .= 'Factor P : ' . $hash->{helper}{factor_P} . "\n";
$ret .= 'Factor I : ' . $hash->{helper}{factor_I} . "\n";
$ret .= 'Factor D : ' . $hash->{helper}{factor_D} . "\n\n";
$ret .= 'Actor lower limit: ' . $hash->{helper}{actorLimitLower} . "\n";
$ret .= 'Actor upper limit: ' . $hash->{helper}{actorLimitUpper} . "\n";
return $ret;
} else {
return $usage;
}
}
########################################
sub PID20_Set($@)
{
my ( $hash, @a ) = @_;
my $name = $hash->{NAME};
my $reFloat = '^([\\+,\\-]?\\d+\\.?\d*$)';
my $usage =
"Unknown argument $a[1], choose one of stop:noArg start:noArg restart "
. AttrVal( $name, 'pidDesiredName', 'desired' );
return $usage if ( @a < 2 );
my $cmd = lc( $a[1] );
my $desiredName = lc( AttrVal( $name, 'pidDesiredName', 'desired' ) );
#PID20_Log $hash, 3, "name:$name cmd:$cmd $desired:$desired";
if ($cmd eq '?') {
return $usage;
} elsif ($cmd eq $desiredName) {
return "Set " . AttrVal( $name, 'pidDesiredName', 'desired' ) . " needs a <value> parameter"
if ( @a != 3 );
my $value = $a[2];
$value = ( $value =~ m/$reFloat/ ) ? $1 : undef;
return "value " . $a[2] . " is not a number"
if ( !defined($value) );
readingsSingleUpdate( $hash, $cmd, $value, 1 );
PID20_Log $hash, 3, "set $name $cmd $a[2]";
} elsif ($cmd eq 'start') {
return 'Set start needs a <value> parameter'
if ( @a != 2 );
$hash->{helper}{stopped} = 0;
PID20_RestartTimer($hash,1);
} elsif ($cmd eq 'stop') {
return 'Set stop needs a <value> parameter'
if ( @a != 2 );
$hash->{helper}{stopped} = 1;
PID20_RestartTimer($hash,1);
} elsif ($cmd eq 'restart') {
return 'Set restart needs a <value> parameter'
if ( @a != 3 );
my $value = $a[2];
$value = ( $value =~ m/$reFloat/ ) ? $1 : undef;
#PID20_Log $hash, 1, "value:$value";
return "value " . $a[2] . " is not a number"
if ( !defined($value) );
$hash->{helper}{stopped} = 0;
$hash->{helper}{adjust} = $value;
PID20_RestartTimer($hash,1);
PID20_Log $hash, 3, "set $name $cmd $value";
} elsif ($cmd eq 'calc') {
PID20_Calc($name);
} else {
return $usage;
}
return;
}
########################################
# disabled = 0
# idle = 1
# processing = 2
# stopped = 3
# alarm = 4
sub PID20_Calc($)
{
my $reUINT = '^([\\+]?\\d+)$'; # uint without whitespaces
my $re01 = '^([0,1])$'; # only 0,1
my $reINT = '^([\\+,\\-]?\\d+$)'; # int
my $reFloatpos = '^([\\+]?\\d+\\.?\d*$)'; # gleitpunkt positiv float
my $reFloat = '^([\\+,\\-]?\\d+\\.?\d*$)'; # float
my ($name) = @_;
my $hash = $defs{$name};
my $sensor = $hash->{helper}{sensor};
my $reading = $hash->{helper}{reading};
my $regexp = $hash->{helper}{regexp};
my $DEBUG_Sensor = AttrVal( $name, 'pidDebugSensor', '0' ) eq '1';
my $DEBUG_Actuation = AttrVal( $name, 'pidDebugActuation', '0' ) eq '1';
my $DEBUG_Delta = AttrVal( $name, 'pidDebugDelta', '0' ) eq '1';
my $DEBUG_Calc = AttrVal( $name, 'pidDebugCalc', '0' ) eq '1';
my $DEBUG_Update = AttrVal( $name, 'pidDebugUpdate', '0' ) eq '1';
my $DEBUG = $DEBUG_Sensor || $DEBUG_Actuation || $DEBUG_Calc || $DEBUG_Delta || $DEBUG_Update;
my $actuation = '';
my $actuationDone = ReadingsVal( $name, 'actuation', '' );
my $actuationCalc = ReadingsVal( $name, 'actuationCalc', '' );
my $actuationCalcOld = $actuationCalc;
my $actorTimestamp =
( $hash->{helper}{actorTimestamp} )
? $hash->{helper}{actorTimestamp}
: FmtDateTime( gettimeofday() - 3600 * 24 );
my $sensorStr = ReadingsVal( $sensor, $reading, '' );
my $sensorValue = '';
my $sensorTS = ReadingsTimestamp( $sensor, $reading, undef );
my $sensorIsAlive = 0;
my $iPortion = ReadingsVal( $name, 'p_i', 0 );
my $pPortion = ReadingsVal( $name, 'p_p', '' );
my $dPortion = ReadingsVal( $name, 'p_d', '' );
my $stateStr = '';
my $deltaOld = ReadingsVal( $name, 'delta', 0 );
my $delta = '';
my $deltaGradient = ( $hash->{helper}{deltaGradient} ) ? $hash->{helper}{deltaGradient} : 0;
my $calcReq = 0;
my $readingUpdateReq = '';
# ---------------- check conditions
while (1)
{
# --------------- retrive values from attributes
$hash->{helper}{actorInterval} = ( AttrVal( $name, 'pidActorInterval', 180 ) =~ m/$reUINT/ ) ? $1 : 180;
$hash->{helper}{actorThreshold} = ( AttrVal( $name, 'pidActorTreshold', 1 ) =~ m/$reUINT/ ) ? $1 : 1;
$hash->{helper}{actorKeepAlive} = ( AttrVal( $name, 'pidActorKeepAlive', 1800 ) =~ m/$reUINT/ ) ? $1 : 1800;
$hash->{helper}{actorValueDecPlaces} = ( AttrVal( $name, 'pidActorValueDecPlaces', 0 ) =~ m/$reUINT/ ) ? $1 : 0;
$hash->{helper}{actorErrorAction} =
( AttrVal( $name, 'pidActorErrorAction', 'freeze' ) eq 'errorPos' ) ? 'errorPos' : 'freeze';
$hash->{helper}{actorErrorPos} = ( AttrVal( $name, 'pidActorErrorPos', 0 ) =~ m/$reINT/ ) ? $1 : 0;
$hash->{helper}{calcInterval} = ( AttrVal( $name, 'pidCalcInterval', 60 ) =~ m/$reUINT/ ) ? $1 : 60;
$hash->{helper}{deltaTreshold} = ( AttrVal( $name, 'pidDeltaTreshold', 0 ) =~ m/$reFloatpos/ ) ? $1 : 0;
$hash->{helper}{disable} = ( AttrVal( $name, 'disable', 0 ) =~ m/$re01/ ) ? $1 : '';
$hash->{helper}{sensorTimeout} = ( AttrVal( $name, 'pidSensorTimeout', 3600 ) =~ m/$reUINT/ ) ? $1 : 3600;
$hash->{helper}{reverseAction} = ( AttrVal( $name, 'pidReverseAction', 0 ) =~ m/$re01/ ) ? $1 : 0;
$hash->{helper}{updateInterval} = ( AttrVal( $name, 'pidUpdateInterval', 600 ) =~ m/$reUINT/ ) ? $1 : 600;
$hash->{helper}{measuredName} = AttrVal( $name, 'pidMeasuredName', 'measured' );
$hash->{helper}{desiredName} = AttrVal( $name, 'pidDesiredName', 'desired' );
$hash->{helper}{actorLimitLower} = ( AttrVal( $name, 'pidActorLimitLower', 0 ) =~ m/$reFloat/ ) ? $1 : 0;
my $actorLimitLower = $hash->{helper}{actorLimitLower};
$hash->{helper}{actorLimitUpper} = ( AttrVal( $name, 'pidActorLimitUpper', 100 ) =~ m/$reFloat/ ) ? $1 : 100;
my $actorLimitUpper = $hash->{helper}{actorLimitUpper};
$hash->{helper}{factor_P} = ( AttrVal( $name, 'pidFactor_P', 25 ) =~ m/$reFloatpos/ ) ? $1 : 25;
$hash->{helper}{factor_I} = ( AttrVal( $name, 'pidFactor_I', 0.25 ) =~ m/$reFloatpos/ ) ? $1 : 0.25;
$hash->{helper}{factor_D} = ( AttrVal( $name, 'pidFactor_D', 0 ) =~ m/$reFloatpos/ ) ? $1 : 0;
if ( $hash->{helper}{disable} )
{
$stateStr = 'disabled';
last;
}
if ( $hash->{helper}{stopped} )
{
$stateStr = 'stopped';
last;
}
my $desired = ReadingsVal( $name, $hash->{helper}{desiredName}, '' );
# sensor found
PID20_Log $hash, 2, '--------------------------' if ($DEBUG);
PID20_Log $hash, 2, "S1 sensorStr:$sensorStr sensorTS:$sensorTS" if ($DEBUG_Sensor);
$stateStr = "alarm - no $reading yet for $sensor" if ( $sensorStr eq '' && $stateStr eq '' );
# sensor alive
if ( $sensorStr ne '' && $sensorTS )
{
my $timeDiff = PID20_TimeDiff($sensorTS);
$sensorIsAlive = 1 if ( $timeDiff <= $hash->{helper}{sensorTimeout} );
$sensorStr =~ m/$regexp/;
$sensorValue = $1;
$sensorValue = '' if ( !defined($sensorValue) );
PID20_Log $hash, 2,
'S2 timeOfDay:'
. gettimeofday()
. " timeDiff:$timeDiff sensorTimeout:"
. $hash->{helper}{sensorTimeout}
. " --> sensorIsAlive:$sensorIsAlive"
if ($DEBUG_Sensor);
}
# sensor dead
$stateStr = 'alarm - dead sensor' if ( !$sensorIsAlive && $stateStr eq '' );
# missing desired
$stateStr = 'alarm - missing desired' if ( $desired eq '' && $stateStr eq '' );
# check delta threshold
$delta = ( $desired ne '' && $sensorValue ne '' ) ? $desired - $sensorValue : '';
$calcReq = 1 if ( $stateStr eq '' && $delta ne '' && ( abs($delta) >= abs( $hash->{helper}{deltaTreshold} ) ) );
PID20_Log $hash, 2,
"D1 desired[" . ( $desired ne '' ) ? sprintf( "%.1f", $desired )
: "" . "] - sensorValue: [" . ( $sensorValue ne '' ) ? sprintf( "%.1f", $sensorValue )
: "" . "] = delta[" . ( $delta ne "" ) ? sprintf( "%.2f", $delta )
: "" . "] calcReq:$calcReq"
if ($DEBUG_Delta);
#request for calculation
# ---------------- calculation request
if ($calcReq)
{
# reverse action requested
my $workDelta = ( $hash->{helper}{reverseAction} == 1 ) ? -$delta : $delta;
my $deltaOld = -$deltaOld if ( $hash->{helper}{reverseAction} == 1 );
# calc p-portion
$pPortion = $workDelta * $hash->{helper}{factor_P};
# calc d-Portion
$dPortion = ($deltaGradient) * $hash->{helper}{calcInterval} * $hash->{helper}{factor_D};
# calc i-portion respecting windUp
# freeze i-portion if windUp is active
my $isWindup = $actuationCalcOld
&& ( ( $workDelta > 0 && $actuationCalcOld > $actorLimitUpper )
|| ( $workDelta < 0 && $actuationCalcOld < $actorLimitLower ) );
if ( $hash->{helper}{adjust} ne '' )
{
$iPortion = $hash->{helper}{adjust} - ( $pPortion + $dPortion );
$iPortion = $actorLimitUpper if ( $iPortion > $actorLimitUpper );
$iPortion = $actorLimitLower if ( $iPortion < $actorLimitLower );
PID20_Log $hash, 5, "adjust request with:" . $hash->{helper}{adjust} . " ==> p_i:$iPortion";
$hash->{helper}{adjust} = '';
} elsif ( !$isWindup ) # integrate only if no windUp
{
# normalize the intervall to minute=60 seconds
$iPortion = $iPortion + $workDelta * $hash->{helper}{factor_I} * $hash->{helper}{calcInterval} / 60;
$hash->{helper}{isWindUP} = 0;
}
$hash->{helper}{isWindUP} = $isWindup;
# check callback for iPortion
my $iportionCallBeforeSetting = AttrVal( $name, 'pidIPortionCallBeforeSetting', undef );
if ( defined($iportionCallBeforeSetting) && exists &$iportionCallBeforeSetting )
{
PID20_Log $hash, 5, 'start callback ' . $iportionCallBeforeSetting . ' with iPortion:' . $iPortion;
no strict "refs";
$iPortion = &$iportionCallBeforeSetting( $name, $iPortion );
use strict "refs";
PID20_Log $hash, 5, 'return value of ' . $iportionCallBeforeSetting . ':' . $iPortion;
}
# calc actuation
$actuationCalc = $pPortion + $iPortion + $dPortion;
PID20_Log $hash, 2, 'P1 delta:' . sprintf( "%.2f", $delta ) . " isWindup:$isWindup" if ($DEBUG_Calc);
PID20_Log $hash, 2,
'P2 pPortion:'
. sprintf( "%.2f", $pPortion )
. " iPortion:"
. sprintf( "%.2f", $iPortion )
. " dPortion:"
. sprintf( "%.2f", $dPortion )
. " actuationCalc:"
. sprintf( "%.2f", $actuationCalc )
if ($DEBUG_Calc);
}
$readingUpdateReq = 1; # in each case update readings
# ---------------- acutation request
my $noTrouble = ( $desired ne "" && $sensorIsAlive );
# check actor fallback in case of sensor fault
if ( !$sensorIsAlive && ( $hash->{helper}{actorErrorAction} eq "errorPos" ) )
{
$stateStr .= '- force pid-output to errorPos';
$actuationCalc = $hash->{helper}{actorErrorPos};
$actuationCalc = '' if ( !defined($actuationCalc) );
}
# check acutation diff
$actuation = $actuationCalc;
# limit $actuation
$actuation = $actorLimitUpper if ( $actuation ne '' && ( $actuation > $actorLimitUpper ) );
$actuation = $actorLimitLower if ( $actuation ne '' && ( $actuation < $actorLimitLower ) );
# check if round request
my $fmt = "%." . $hash->{helper}{actorValueDecPlaces} . "f";
$actuation = sprintf( $fmt, $actuation ) if ( $actuation ne '' );
my $actuationDiff = abs( $actuation - $actuationDone )
if ( $actuation ne '' && $actuationDone ne '' );
PID20_Log $hash, 2,
"A1 act:$actuation actDone:$actuationDone "
. " actThreshold:"
. $hash->{helper}{actorThreshold}
. " actDiff:$actuationDiff"
if ($DEBUG_Actuation);
# check threshold-condition for actuation
my $rsTS = $actuationDone ne '' && $actuationDiff >= $hash->{helper}{actorThreshold};
# ...... special handling if acutation is in the black zone between actorLimit and (actorLimit - actorThreshold)
# upper range
my $rsUp =
$actuationDone ne ''
&& $actuation > $actorLimitUpper - $hash->{helper}{actorThreshold}
&& $actuationDiff != 0
&& $actuation >= $actorLimitUpper;
# low range
my $rsDown =
$actuationDone ne ''
&& $actuation < $actorLimitLower + $hash->{helper}{actorThreshold}
&& $actuationDiff != 0
&& $actuation <= $actorLimitLower;
# upper or lower limit are exceeded
my $rsLimit = $actuationDone ne '' && ( $actuationDone < $actorLimitLower || $actuationDone > $actorLimitUpper );
my $actuationByThreshold = ( ( $rsTS || $rsUp || $rsDown ) && $noTrouble );
PID20_Log $hash, 2, "A2 rsTS:$rsTS rsUp:$rsUp rsDown:$rsDown noTrouble:$noTrouble"
if ($DEBUG_Actuation);
# check time condition for actuation
my $actTimeDiff = PID20_TimeDiff($actorTimestamp); # $actorTimestamp is valid in each case
my $actuationByTime = ($noTrouble) && ( $actTimeDiff > $hash->{helper}{actorInterval} );
PID20_Log $hash, 2,
"A3 actTS:$actorTimestamp"
. " actTimeDiff:"
. sprintf( "%.2f", $actTimeDiff )
. " actInterval:"
. $hash->{helper}{actorInterval}
. "-->actByTime:$actuationByTime "
if ($DEBUG_Actuation);
# check keep alive condition for actuation
my $actuationKeepAliveReq = ( $actTimeDiff >= $hash->{helper}{actorKeepAlive} )
if ( defined($actTimeDiff) && $actuation ne "" );
# build total actuation request
my $actuationReq = (
( $actuationByThreshold && $actuationByTime )
|| $actuationKeepAliveReq # request by keep alive
|| $rsLimit # upper or lower limit are exceeded
|| $actuationDone eq '' # startup condition
) && $actuation ne ''; # acutation is initialized
PID20_Log $hash, 2,
"A4 (actByTh:$actuationByThreshold && actByTime:$actuationByTime)"
. "||actKeepAlive:$actuationKeepAliveReq"
. "||rsLimit:$rsLimit=actnReq:$actuationReq"
if ($DEBUG_Actuation);
# ................ perform output to actor
if ($actuationReq)
{
$readingUpdateReq = 1; # update the readings
# check callback for actuation
my $actorCallBeforeSetting = AttrVal( $name, 'pidActorCallBeforeSetting', undef );
if ( defined($actorCallBeforeSetting) && exists &$actorCallBeforeSetting )
{
PID20_Log $hash, 5, 'start callback ' . $actorCallBeforeSetting . ' with actuation:' . $actuation;
no strict "refs";
$actuation = &$actorCallBeforeSetting( $name, $actuation );
use strict "refs";
PID20_Log $hash, 5, 'return value of ' . $actorCallBeforeSetting . ':' . $actuation;
}
#build command for fhem
my $cmd = '';
my $mapping = AttrVal($name,'pidActorMapCmd',undef);
if (defined($mapping)){
eval "\$mapping = $mapping";
if($@) {
$cmd = "ERROR in cmdMap $@";
} else {
my $mapCmd = undef;
$mapCmd = $mapping->{default} if (defined ($mapping->{default}));
$mapCmd = $mapping->{$actuation} if (defined ($mapping->{$actuation}));
$cmd = sprintf( "set %s %s", $hash->{helper}{actor}, $mapCmd );
}
} else {
$cmd = sprintf( "set %s %s %g", $hash->{helper}{actor}, $hash->{helper}{actorCommand}, $actuation );
}
PID20_Log $hash, 5, $cmd;
# execute command
my $ret;
$ret = fhem $cmd;
# note timestamp
$hash->{helper}{actorTimestamp} = TimeNow();
$actuationDone = $actuation;
my $retStr = '';
$retStr = ' with return-value:' . $ret if ( defined($ret) && ( $ret ne '' ) );
PID20_Log $hash, 3, "<$cmd> " . $retStr;
}
my $updateAlive = ( $actuation ne '' )
&& PID20_TimeDiff( ReadingsTimestamp( $name, 'actuation', gettimeofday() ) ) >= $hash->{helper}{updateInterval};
# my $updateReq = ( ( $actuationReq || $updateAlive ) && $actuation ne "" );
# PID20_Log $hash, 2, "U1 actReq:$actuationReq updateAlive:$updateAlive --> updateReq:$updateReq" if ($DEBUG_Update);
# ---------------- update request
if ($readingUpdateReq)
{
my $r = AttrVal($name,'pidRoundReadings',-1);
if ($r != -1) {
$pPortion = round($pPortion,$r) if looks_like_number($pPortion);
$dPortion = round($dPortion,$r) if looks_like_number($dPortion);
$iPortion = round($iPortion,$r) if looks_like_number($iPortion);
$delta = round($delta,$r) if looks_like_number($delta);
$actuationCalc = round($actuationCalc,$r) if looks_like_number($actuationCalc);
}
readingsBeginUpdate($hash);
readingsBulkUpdate( $hash, $hash->{helper}{desiredName}, $desired ) if ( $desired ne '' );
readingsBulkUpdate( $hash, $hash->{helper}{measuredName}, $sensorValue ) if ( $sensorValue ne '' );
readingsBulkUpdate( $hash, 'p_p', $pPortion ) if ( $pPortion ne '' );
readingsBulkUpdate( $hash, 'p_d', $dPortion ) if ( $dPortion ne '' );
readingsBulkUpdate( $hash, 'p_i', $iPortion ) if ( $iPortion ne '' );
readingsBulkUpdate( $hash, 'actuation', $actuationDone ) if ( $actuationDone ne '' );
readingsBulkUpdate( $hash, 'actuationCalc', $actuationCalc ) if ( $actuationCalc ne '' );
readingsBulkUpdate( $hash, 'delta', $delta ) if ( $delta ne '' );
readingsEndUpdate( $hash, 1 );
PID20_Log $hash, 5, "readings updated";
}
last;
} # end while
# ........ update statePID.
$stateStr = 'idle' if ( $stateStr eq '' && !$calcReq );
$stateStr = 'processing' if ( $stateStr eq '' && $calcReq );
readingsSingleUpdate( $hash, 'state', $stateStr, 1 );
PID20_Log $hash, 2, "C1 stateStr:$stateStr calcReq:$calcReq" if ($DEBUG_Calc);
#......... timer setup
my $next = gettimeofday() + $hash->{helper}{calcInterval};
RemoveInternalTimer($name); # prevent multiple timers for same hash
InternalTimer( $next, 'PID20_Calc', $name, 1 );
#PID20_Log $hash, 2, "InternalTimer next:".FmtDateTime($next)." PID20_Calc name:$name DEBUG_Calc:$DEBUG_Calc";
return;
}
########################################
# attribute handling
sub PID20_Attr($$$$)
{
my ( $command, $name, $attribute, $value ) = @_;
my $msg = undef;
my $hash = $defs{$name};
my $reUINT = '^([\\+]?\\d+)$';
PID20_Log $hash, 5, 'name:' . $name . ' attribute:' . $attribute . ' value:' . $value . ' command:' . $command;
if ( $attribute eq 'disable' )
{
# PID20_Log $hash, 5, 'disable';
PID20_RestartTimer($hash,2);
}
if ( $attribute eq 'pidActorMapCmd' )
{
my $test;
eval "\$test = $value";
if($@) {
$msg = "ERROR in pidActorMapCmd: $@";
}
}
return $msg;
}
1;
=pod
=item helper
=item summary create a PID device based on any combination of sensor and actor
=item summary_DE erzeugt ein PID device aus beliebigem Sensor und Aktor
=begin html
<a id="PID20"></a>
<h3>PID20</h3>
<ul>
<a id="PID20-define"></a>
<b>Define</b>
<ul>
<br/>
<code>define <name> PID20 <sensor[:reading[:regexp]]> <actor:cmd ></code>
<br/><br/>
This module provides a PID device, using <sensor> and <actor><br/>
</ul>
<br/><br/>
<a id="PID20-set"></a>
<b>Set-Commands</b><br/>
<ul>
<br/>
<a id="PID20-set-desired"></a>
<code>set <name> desired <value></code>
<br/><br/>
<ul>Set desired value for PID</ul>
<br/>
<br/>
<a id="PID20-set-start"></a>
<code>set <name> start</code>
<br/><br/>
<ul>Start PID processing again, using frozen values from former stop.</ul>
<br/>
<br/>
<a id="PID20-set-stop"></a>
<code>set <name> stop</code>
<br/><br/>
<ul>PID stops processing, freezing all values.</ul>
<br/>
<br/>
<a id="PID20-set-restart"></a>
<code>set <name> restart <value></code>
<br/><br/>
<ul>Same as start, but uses value as start value for actor</ul>
<br/>
</ul>
<br/><br/>
<a id="PID20-get"></a>
<b>Get-Commands</b><br/>
<ul>
<br/>
<a id="PID20-get-params"></a>
<code>get <name> params</code>
<br/><br/>
<ul>Get list containing current parameters.</ul>
<br/>
</ul>
<br/><br/>
<a id="PID20-attr"></a>
<b>Attributes</b><br/><br/>
<ul>
<li><a href="#readingFnAttributes">readingFnAttributes</a></li>
<li><a href="#disable">disable</a></li>
<li><a href="#disabledForIntervals">disabledForIntervals</a></li>
<br/>
<a id="PID20-attr-pidActorValueDecPlaces"></a>
<li><b>pidActorValueDecPlaces</b> - number of demicals, possible values: 0..5; default: 0</li><br>
<a id="PID20-attr-pidRoundReadings"></a>
<li><b>pidRoundReadings</b> - round readings to number of demicals, possible values: 2..5; default: not rounded</li><br>
<a id="PID20-attr-pidActorInterval"></a>
<li><b>pidActorInterval</b> - number of seconds to wait between to commands sent to actor; default: 180</li>
<a id="PID20-attr-pidActorTreshold"></a>
<li><b>pidActorTreshold</b> - threshold to be reached before command will be sent to actor; default: 1</li>
<a id="PID20-attr-pidActorErrorAction"></a>
<li><b>pidActorErrorAction</b> - required action on error, possible values: freeze,errorPos; default: freeze</li>
<a id="PID20-attr-pidActorErrorPos"></a>
<li><b>pidActorErrorPos</b> - actor's position to be used in case of error; default: 0</li>
<a id="PID20-attr-pidActorKeepAlive"></a>
<li><b>pidActorKeepAlive</b> - number of seconds to force command to be sent to actor; default: 1800</li>
<a id="PID20-attr-pidActorLimitLower"></a>
<li><b>pidActorLimitLower</b> - lower limit for actor; default: 0</li>
<a id="PID20-attr-pidActorLimitUpper"></a>
<li><b>pidActorLimitUpper</b> - upper limit for actor; default: 100</li>
<a id="PID20-attr-pidCalcInterval"></a>
<li><b>pidCalcInterval</b> - interval (seconds) to calculate new pid values; default: 60</li>
<a id="PID20-attr-pidDeltaTreshold"></a>
<li><b>pidDeltaTreshold</b> - if delta < delta-threshold the pid will enter idle state; default: 0</li>
<a id="PID20-attr-pidDesiredName"></a>
<li><b>pidDesiredName</b> - reading's name for desired value; default: desired</li>
<a id="PID20-attr-pidFactor_P"></a>
<li><b>pidFactor_P</b> - P value for PID; default: 25</li>
<a id="PID20-attr-pidFactor_I"></a>
<li><b>pidFactor_I</b> - I value for PID; default: 0.25</li>
<a id="PID20-attr-pidFactor_D"></a>
<li><b>pidFactor_D</b> - D value for PID; default: 0</li>
<a id="PID20-attr-pidMeasuredName"></a>
<li><b>pidMeasuredName</b> - reading's name for measured value; default: measured</li>
<a id="PID20-attr-pidSensorTimeout"></a>
<li><b>pidSensorTimeout</b> - number of seconds to wait before sensor will be recognized n/a; default: 3600</li>
<a id="PID20-attr-pidReverseAction"></a>
<li><b>pidReverseAction</b> - reverse PID operation mode, possible values: 0,1; default: 0</li>
<a id="PID20-attr-pidUpdateInterval"></a>
<li><b>pidUpdateInterval</b> - number of seconds to wait before an update will be forced for plotting; default: 300</li>
<a id="PID20-attr-pidActorCallBeforeSetting"></a>
<li><b>pidActorCallBeforeSetting</b> - an optional callback-function,which can manipulate the actorValue; default: not defined
<pre>
# Exampe for callback-function
# 1. argument = name of PID20
# 2. argument = current actor value
sub PIDActorSet($$)
{
my ( $name, $actValue ) = @_;
if ($actValue>70)
{
$actValue=100;
}
return $actValue;
}</pre>
</li>
<a id="PID20-attr-pidIPortionCallBeforeSetting"></a>
<li><b>pidIPortionCallBeforeSetting</b> - an optional callback-function, which can manipulate the value of I-Portion; default: not defined
<pre>
# Exampe for callback-function
# 1. argument = name of PID20
# 2. argument = current i-portion value
sub PIDIPortionSet($$)
{
my ( $name, $actValue ) = @_;
if ($actValue>70)
{
$actValue=70;
}
return $actValue;
}</pre>
</li>
<a id="PID20-attr-pidActorMapCmd"></a>
<li><b>pidActorMapCmd</b> - add an optional hash for mapping actuation value to user-defined actor command.
<pre>