-
Notifications
You must be signed in to change notification settings - Fork 1
/
fhem.pl
6453 lines (5600 loc) · 170 KB
/
fhem.pl
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
#!/usr/bin/perl
################################################################
#
# Copyright notice
#
# (c) 2005-2020
# Copyright: Rudolf Koenig (rudolf dot koenig at fhem dot de)
# All rights reserved
#
# This program free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License V2, which is also
# distributed together with this program in the file GPL_V2.txt
#
# This program 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 V2 for more details.
#
# Homepage: http://fhem.de
#
# $Id: fhem.pl 25517 2022-01-20 16:06:47Z rudolfkoenig $
use strict;
use warnings;
use lib '.';
use IO::Socket;
use IO::Socket::INET;
use Time::HiRes qw(gettimeofday);
use Scalar::Util qw(looks_like_number);
use POSIX;
use File::Copy qw(copy);
##################################################
# Forward declarations
#
sub AddDuplicate($$);
sub AnalyzeCommand($$;$);
sub AnalyzeCommandChain($$;$);
sub AnalyzeInput($);
sub AnalyzePerlCommand($$;$);
sub AssignIoPort($;$);
sub AttrVal($$$);
sub AttrNum($$$;$);
sub Authorized($$$;$);
sub Authenticate($$);
sub CallFn(@);
sub CallInstanceFn(@);
sub CheckDuplicate($$@);
sub CheckRegexp($$);
sub Debug($);
sub DoSet(@);
sub Dispatch($$;$$);
sub DoTrigger($$@);
sub EvalSpecials($%);
sub Each($$;$);
sub FileDelete($);
sub FileRead($);
sub FileWrite($@);
sub FmtDateTime($);
sub FmtTime($);
sub GetDefAndAttr($;$);
sub GetLogLevel(@);
sub GetTimeSpec($);
sub GetType($;$);
sub GlobalAttr($$$$);
sub HandleArchiving($;$);
sub HandleTimeout();
sub IOWrite($@);
sub InternalTimer($$$;$);
sub InternalVal($$$);
sub InternalNum($$$;$);
sub IsDevice($;$);
sub IsDisabled($);
sub IsDummy($);
sub IsIgnored($);
sub IsIoDummy($);
sub IsWe(;$$);
sub LoadModule($;$);
sub Log($$);
sub Log3($$$);
sub OldTimestamp($);
sub OldValue($);
sub OldReadingsAge($$$);
sub OldReadingsNum($$$;$);
sub OldReadingsTimestamp($$$);
sub OldReadingsVal($$$);
sub OpenLogfile($);
sub PrintHash($$);
sub ReadingsAge($$$);
sub ReadingsNum($$$;$);
sub ReadingsTimestamp($$$);
sub ReadingsVal($$$);
sub RefreshAuthList();
sub RemoveInternalTimer($;$);
sub ReplaceEventMap($$$);
sub ResolveDateWildcards($@);
sub SecurityCheck();
sub SemicolonEscape($);
sub SignalHandling();
sub TimeNow();
sub Value($);
sub WriteStatefile();
sub XmlEscape($);
sub addEvent($$;$);
sub addToDevAttrList($$;$);
sub applyGlobalAttrFromEnv();
sub delFromDevAttrList($$);
sub addToAttrList($;$);
sub delFromAttrList($);
sub addToWritebuffer($$@);
sub attrSplit($);
sub computeClientArray($$);
sub concatc($$$);
sub configDBUsed();
sub createNtfyHash();
sub createUniqueId();
sub devspec2array($;$$);
sub doGlobalDef($);
sub escapeLogLine($);
sub evalStateFormat($);
sub execFhemTestFile();
sub fhem($@);
sub fhemTimeGm($$$$$$);
sub fhemTimeLocal($$$$$$);
sub fhemTzOffset($);
sub getAllAttr($;$$);
sub getAllGets($;$);
sub getAllSets($;$);
sub getPawList($);
sub getUniqueId();
sub hashKeyRename($$$);
sub json2nameValue($;$$$$);
sub json2reading($$;$$$$);
sub latin1ToUtf8($);
sub myrename($$$);
sub notifyRegexpChanged($$;$);
sub parseParams($;$$$);
sub prepareFhemTestFile();
sub perlSyntaxCheck($%);
sub readingsBeginUpdate($);
sub readingsBulkUpdate($$$@);
sub readingsEndUpdate($$);
sub readingsSingleUpdate($$$$;$);
sub readingsDelete($$);
sub redirectStdinStdErr();
sub rejectDuplicate($$$);
sub resolveAttrRename($$);
sub restoreDir_init(;$);
sub restoreDir_rmTree($);
sub restoreDir_saveFile($$);
sub restoreDir_mkDir($$$);
sub setGlobalAttrBeforeFork($);
sub setReadingsVal($$$$);
sub setAttrList($$);
sub setDevAttrList($;$);
sub toJSON($);
sub utf8ToLatin1($);
sub CommandAttr($$);
sub CommandCancel($$);
sub CommandDefaultAttr($$);
sub CommandDefine($$);
sub CommandDefMod($$);
sub CommandDelete($$);
sub CommandDeleteAttr($$);
sub CommandDeleteReading($$);
sub CommandDisplayAttr($$);
sub CommandGet($$);
sub CommandIOWrite($$);
sub CommandInclude($$);
sub CommandList($$);
sub CommandModify($$);
sub CommandQuit($$);
sub CommandReload($$;$);
sub CommandRename($$);
sub CommandRereadCfg($$);
sub CommandSave($$);
sub CommandSet($$);
sub CommandSetReading($$);
sub CommandSetstate($$);
sub CommandSetuuid($$);
sub CommandShutdown($$;$$$);
sub CommandSleep($$);
sub CommandTrigger($$);
# configDB special
sub cfgDB_Init;
sub cfgDB_ReadAll;
sub cfgDB_SaveState;
sub cfgDB_SaveCfg;
sub cfgDB_AttrRead;
sub cfgDB_FileRead;
sub cfgDB_FileUpdate;
sub cfgDB_FileWrite;
##################################################
# Variables:
# global, to be able to access them from modules
#Special values in %modules (used if set):
# AttrFn - called for attribute changes
# DefFn - define a "device" of this type
# DeleteFn - clean up (delete logfile), called by delete after UndefFn
# ExceptFn - called if the global select reports an except field
# FingerprintFn - convert messages for duplicate detection
# GetFn - get some data from this device
# NotifyFn - call this if some device changed its properties
# ParseFn - Interpret a raw message
# ReadFn - Reading from a Device (see FHZ/WS300)
# ReadyFn - check for available data, if no FD
# RenameFn - inform the device about its renaming
# SetFn - set/activate this device
# DelayedShutdownFn - used to delay shutdown for some seconds
# ShutdownFn-called before shutdown, if DelayedShutdownFn is "over"
# StateFn - set local info for this device, do not activate anything
# UndefFn - clean up (delete timer, close fd), called by delete and rereadcfg
#Special values in %defs:
# TYPE - The name of the module it belongs to
# STATE - Oneliner describing its state
# NR - its "serial" number
# DEF - its definition
# READINGS- The readings. Each value has a "VAL" and a "TIME" component.
# FD - FileDescriptor. Used by selectlist / readyfnlist
# IODev - attached to io device
# CHANGED - Currently changed attributes of this device. Used by NotifyFn
# VOLATILE- Set if the definition should be saved to the "statefile"
# NOTIFYDEV - if set, the notifyFn will only be called for this device
use vars qw($addTimerStacktrace);# set to 1 by fhemdebug
use vars qw($auth_refresh);
use vars qw($cmdFromAnalyze); # used by the warnings-sub
use vars qw($devcount); # Maximum device number, used for storing
use vars qw($featurelevel);
use vars qw($fhemForked); # 1 in a fhemFork()'ed process, else undef
use vars qw($fhemTestFile); # file to include if -t is specified
use vars qw($fhem_started); # used for uptime calculation
use vars qw($haveInet6); # Using INET6
use vars qw($init_done); #
use vars qw($internal_data); # FileLog/DbLog -> SVG data transport
use vars qw($lastDefChange); # number of last def/attr change
use vars qw($lastWarningMsg); # set by the warnings-sub
use vars qw($nextat); # Time when next timer will be triggered.
use vars qw($reread_active);
use vars qw($selectTimestamp); # used to check last select exit timestamp
use vars qw($winService); # the Windows Service object
use vars qw(%attr); # Attributes
use vars qw(%cmds); # Global command name hash.
use vars qw(%data); # Hash for user data
use vars qw(%defaultattr); # Default attributes, used by FHEM2FHEM
use vars qw(%defs); # FHEM device/button definitions
use vars qw(%inform); # Used by telnet_ActivateInform
use vars qw(%intAt); # Internal timer hash, used by apptime
use vars qw(%logInform); # Used by FHEMWEB/Event-Monitor
use vars qw(%modules); # List of loaded modules (device/log/etc)
use vars qw(%ntfyHash); # hash of devices needed to be notified.
use vars qw(%prioQueues); #
use vars qw(%readyfnlist); # devices which want a "readyfn"
use vars qw(%selectlist); # devices which want a "select"
use vars qw(%value); # Current values, see commandref.html
use vars qw(@intAtA); # Internal timer array
use vars qw(@structChangeHist); # Contains the last 10 structural changes
use vars qw($numCPUs); # Number of CPUs on Linux, else 1
use constant {
DAYSECONDS => 86400,
HOURSECONDS => 3600,
MINUTESECONDS => 60
};
$selectTimestamp = gettimeofday();
my $cvsid = '$Id: fhem.pl 25517 2022-01-20 16:06:47Z rudolfkoenig $';
my $AttrList = "alias comment:textField-long eventMap:textField-long ".
"group room suppressReading userattr ".
"userReadings:textField-long verbose:0,1,2,3,4,5 ";
my @authenticate; # List of authentication devices
my @authorize; # List of authorization devices
my $currcfgfile=""; # current config/include file
my $currlogfile; # logfile, without wildcards
my $duplidx=0; # helper for the above pool
my $evalSpecials; # Used by EvalSpecials->AnalyzeCommand
my $intAtCnt=0;
my $logopened = 0; # logfile opened or using stdout
my $namedef = "where <name> is a single device name, a list separated by comma (,) or a regexp. See the devspec section in the commandref.html for details.\n";
my $rcvdquit; # Used for quit handling in init files
my $readingsUpdateDelayTrigger; # needed internally
my $gotSig; # non-undef if got a signal
my %oldvalue; # Old values, see commandref.html
my $wbName = ".WRITEBUFFER"; # Buffer-name for delayed writing via select
my %comments; # Comments from the include files
my %duplicate; # Pool of received msg for multi-fhz/cul setups
my @cmdList; # Remaining commands in a chain. Used by sleep
my %sleepers; # list of sleepers
my %delayedShutdowns; # definitions needing delayed shutdown
my %fuuidHash; # for duplicate checking
my $globalUniqueID; # cache it
my $readytimeout = ($^O eq "MSWin32") ? 0.1 : 5.0;
$init_done = 0;
$lastDefChange = 0;
$featurelevel = 6.1; # see also GlobalAttr
$numCPUs = `grep -c ^processor /proc/cpuinfo 2>&1` if($^O eq "linux");
$numCPUs = ($numCPUs && $numCPUs =~ m/(\d+)/ ? $1 : 1);
$modules{Global}{ORDER} = -1;
$modules{Global}{LOADED} = 1;
no warnings 'qw';
my @globalAttrList = qw(
altitude
apiversion
archivecmd
archivedir
archivesort:timestamp,alphanum
archiveCompress
autoload_undefined_devices:0,1
autosave:1,0
backup_before_update
backupcmd
backupdir
backupsymlink
blockingCallMax
commandref:modular,full
configfile
disableFeatures:multiple-strict,attrTemplate,securityCheck,saveuuid
dnsHostsFile
dnsServer
dupTimeout
exclude_from_update
hideExcludedUpdates:1,0
featurelevel:6.1,6.0,5.9,5.8,5.7,5.6,5.5,99.99
genericDisplayType:switch,outlet,light,blind,speaker,thermostat
holiday2we
httpcompress:0,1
ignoreRegexp
keyFileName
language:EN,DE
lastinclude
latitude
logdir
logfile
longitude
maxChangeLog
maxShutdownDelay
modpath
motd
mseclog:1,0
nofork:1,0
nrarchive
perlSyntaxCheck:0,1
pidfilename
proxy
proxyAuth
proxyExclude
restartDelay
restoreDirs
sendStatistics:onUpdate,manually,never
showInternalValues:1,0
sslVersion
stacktrace:1,0
statefile
title
updateInBackground:1,0
updateNoFileCheck:1,0
useInet6:1,0
version
);
use warnings 'qw';
$modules{Global}{AttrList} = join(" ", @globalAttrList);
$modules{Global}{AttrFn} = "GlobalAttr";
use vars qw($readingFnAttributes);
no warnings 'qw';
my @attrList = qw(
event-aggregator
event-min-interval
event-on-change-reading
event-on-update-reading
oldreadings
stateFormat:textField-long
timestamp-on-change-reading
);
$readingFnAttributes = join(" ", @attrList);
my %attrSource = map { s/:.*//; $_ => "framework" } @attrList;
map { $attrSource{$_} = "framework" } qw(
ignore
disable
disabledForIntervals
);
my %ra = (
"suppressReading" => { s=>"\n" },
"event-aggregator" => { s=>",", c=>".attraggr" },
"event-on-update-reading" => { s=>",", c=>".attreour" },
"event-on-change-reading" => { s=>",", c=>".attreocr", r=>":.*" },
"timestamp-on-change-reading"=> { s=>",", c=>".attrtocr" },
"event-min-interval" => { s=>",", c=>".attrminint", r=>":.*" },
"oldreadings" => { s=>",", c=>".or" },
"devStateIcon" => { s=>" ", r=>":.*", p=>"^{.*}\$",
pv=>{"%name"=>1, "%state"=>1, "%type"=>1} },
);
%cmds = (
"?" => { ReplacedBy => "help" },
"attr" => { Fn=>"CommandAttr",
Hlp=>"[-a] [-r] [-silent] <devspec> <attrname> [<attrval>],".
"set attribute for <devspec>"},
"cancel" => { Fn=>"CommandCancel",
Hlp=>"[<id> [quiet]],list sleepers, cancel sleeper with <id>" },
"createlog"=> { ModuleName => "autocreate" },
"define" => { Fn=>"CommandDefine",
Hlp=>"[option] <name> <type> <options>,define a device" },
"defmod" => { Fn=>"CommandDefMod",
Hlp=>"[-temporary] <name> <type> <options>,".
"define or modify a device" },
"deleteattr" => { Fn=>"CommandDeleteAttr",
Hlp=>"[-silent] <devspec> [<attrname>],delete attribute for <devspec>" },
"deletereading" => { Fn=>"CommandDeleteReading",
Hlp=>"<devspec> <readingname> [older-than-seconds],".
"delete user defined readings" },
"delete" => { Fn=>"CommandDelete",
Hlp=>"<devspec>,delete the corresponding definition(s)"},
"displayattr"=> { Fn=>"CommandDisplayAttr",
Hlp=>"<devspec> [attrname],display attributes" },
"get" => { Fn=>"CommandGet",
Hlp=>"<devspec> <type-specific>,request data from <devspec>" },
"include" => { Fn=>"CommandInclude",
Hlp=>"<filename>,read the commands from <filename>" },
"iowrite" => { Fn=>"CommandIOWrite",
Hlp=>"<iodev> <data>,write raw data with iodev" },
"list" => { Fn=>"CommandList",
Hlp=>"[-r] [devspec] [value],list definitions and status info" },
"modify" => { Fn=>"CommandModify",
Hlp=>"device <type-dependent-options>,modify the definition" },
"quit" => { Fn=>"CommandQuit",
ClientFilter => "telnet",
Hlp=>",end the client session" },
"exit" => { Fn=>"CommandQuit",
ClientFilter => "telnet",
Hlp=>",end the client session" },
"reload" => { Fn=>"CommandReload",
Hlp=>"<module>,reload the given module (e.g. 99_PRIV)" },
"rename" => { Fn=>"CommandRename",
Hlp=>"<old> <new>,rename a definition" },
"rereadcfg" => { Fn=>"CommandRereadCfg",
Hlp=>"[configfile],read in the config after deleting everything" },
"restore" => {
Hlp=>"[list] [<filename|directory>],restore files saved by update"},
"save" => { Fn=>"CommandSave",
Hlp=>"[configfile],write the configfile and the statefile" },
"set" => { Fn=>"CommandSet",
Hlp=>"<devspec> <type-specific>,transmit code for <devspec>" },
"setreading" => { Fn=>"CommandSetReading",
Hlp=>"<devspec> [YYYY-MM-DD HH:MM:SS] <reading> <value>,".
"set reading for <devspec>" },
"setstate"=> { Fn=>"CommandSetstate",
Hlp=>"<devspec> <state>,set the state shown in the command list" },
"setuuid" => { Fn=>"CommandSetuuid", Hlp=>"" },
"setdefaultattr" => { Fn=>"CommandDefaultAttr",
Hlp=>"[<attrname> [<attrvalue>]],".
"set attr for following definitions" },
"shutdown"=> { Fn=>"CommandShutdown",
Hlp=>"[restart|exitValue],terminate the server" },
"sleep" => { Fn=>"CommandSleep",
Hlp=>"<sec|timespec|regex> [<id>] [quiet],".
"sleep for sec, 3 decimal places" },
"trigger" => { Fn=>"CommandTrigger",
Hlp=>"<devspec> <state>,trigger notify command" },
"update" => {
Hlp => "[<fileName>|all|check|checktime|force] ".
"[http://.../controlfile],update FHEM" },
"updatefhem" => { ReplacedBy => "update" },
"usb" => { ModuleName => "autocreate" }
);
###################################################
# Start the program
my $fhemdebug;
$fhemdebug = shift @ARGV if($ARGV[0] && $ARGV[0] eq "-d");
prepareFhemTestFile();
if(int(@ARGV) < 1) {
print "Usage:\n";
print "as server: perl fhem.pl [-d] {<configfile>|configDB}\n";
print "as client: perl fhem.pl [host:]port cmd cmd cmd...\n";
print "testing: perl fhem.pl -t <testfile>.t\n";
if($^O =~ m/Win/) {
print "install as windows service: perl fhem.pl configfile -i\n";
print "uninstall the windows service: perl fhem.pl -u\n";
}
exit(1);
}
# If started as root, and there is a fhem user in the /etc/passwd, su to it
if($^O !~ m/Win/ && $< == 0) {
my @pw = getpwnam("fhem");
if(@pw) {
use POSIX qw(setuid setgid);
# set primary group
setgid($pw[3]);
# read all secondary groups into an array:
my @groups;
while ( my ($name, $pw, $gid, $members) = getgrent() ) {
push(@groups, $gid) if ( grep($_ eq $pw[0],split(/\s+/,$members)) );
}
# set the secondary groups via $)
if (@groups) {
$) = "$pw[3] ".join(" ",@groups);
} else {
$) = "$pw[3] $pw[3]";
}
setuid($pw[2]);
}
}
###################################################
# Client code
if(int(@ARGV) > 1 && $ARGV[$#ARGV] ne "-i") {
my $buf;
my $addr = shift @ARGV;
$addr = "localhost:$addr" if($addr !~ m/:/);
my $client = IO::Socket::INET->new(PeerAddr => $addr);
die "Can't connect to $addr\n" if(!$client);
for(my $i=0; $i < int(@ARGV); $i++) {
syswrite($client, $ARGV[$i]."\n");
}
shutdown($client, 1);
alarm(30); #117226
while(sysread($client, $buf, 256) > 0) {
$buf =~ s/\xff\xfb\x01Password: //;
$buf =~ s/\xff\xfc\x01\r\n//;
$buf =~ s/\xff\xfd\x00//;
print($buf);
}
exit(0);
}
# End of client code
###################################################
SignalHandling();
###################################################
# Windows Service Support: install/remove or start the fhem service
if($^O =~ m/Win/) {
(my $dir = $0) =~ s+[/\\][^/\\]*$++; # Find the FHEM directory
chdir($dir);
$winService = eval {require FHEM::WinService; FHEM::WinService->new(\@ARGV);};
if((!$winService || $@) && ($ARGV[$#ARGV] eq "-i" || $ARGV[$#ARGV] eq "-u")) {
print "Cannot initialize FHEM::WinService: $@, exiting.\n";
exit 0;
}
}
$winService ||= {};
###################################################
# Server initialization
doGlobalDef($ARGV[0]);
if(configDBUsed()) {
eval "use configDB";
Log 1, $@ if($@);
cfgDB_Init();
}
# As newer Linux versions reset serial parameters after fork, we parse the
# config file after the fork. But we need some global attr parameters before,
# so we read them here. FHEM_GLOBALATTR is for docker, as it needs to overwrite
# fhem.cfg
my (undef, $globalAttrFromEnv) = parseParams($ENV{FHEM_GLOBALATTR});
setGlobalAttrBeforeFork($attr{global}{configfile});
applyGlobalAttrFromEnv();
Log 1, $_ for eval{@{$winService->{ServiceLog}};};
# Go to background if the logfile is a real file (not stdout)
if($^O =~ m/Win/ && !$attr{global}{nofork}) {
$attr{global}{nofork}=1;
}
if($attr{global}{logfile} ne "-" && !$attr{global}{nofork}) {
defined(my $pid = fork) || die "Can't fork: $!";
exit(0) if $pid;
}
# FritzBox special: Wait until the time is set via NTP,
# but not more than 2 hours
if(gettimeofday() < 2*3600) {
Log 1, "date/time not set, waiting up to 2 hours to be set.";
while(gettimeofday() < 2*3600) {
sleep(5);
}
}
###################################################
# initialize the readings semantics meta information
require RTypes;
RTypes_Initialize();
$defs{global}{init_errors}="";
if(configDBUsed()) {
my $ret = cfgDB_ReadAll(undef);
$defs{global}{init_errors} .= "configDB: $ret\n" if($ret);
} else {
my $ret = CommandInclude(undef, $attr{global}{configfile});
$defs{global}{init_errors} .= "configfile: $ret\n" if($ret);
my $stateFile = $attr{global}{statefile};
if($stateFile) {
my @t = localtime(gettimeofday());
$stateFile = ResolveDateWildcards($stateFile, @t);
if(-r $stateFile) {
$ret = CommandInclude(undef, $stateFile);
$defs{global}{init_errors} .= "$stateFile: $ret\n" if($ret);
}
}
}
applyGlobalAttrFromEnv();
my $pfn = $attr{global}{pidfilename};
if($pfn) {
die "$pfn: $!\n" if(!open(PID, ">$pfn"));
print PID $$ . "\n";
close(PID);
}
$init_done = 1;
$lastDefChange = 1;
sub
finish_init()
{
foreach my $d (keys %defs) {
my $hash = $defs{$d};
if($hash->{IODevMissing}) {
if($hash->{IODevName} && $defs{$hash->{IODevName}}) {
fhem_setIoDev($hash, $hash->{IODevName});
} else {
AssignIoPort($hash); # For fhem.cfg editors?
}
delete $hash->{IODevMissing};
delete $hash->{IODevName};
}
}
my $init_errors_first = ($defs{global}{init_errors} ? 1 : 0);
SecurityCheck();
if($defs{global}{init_errors}) {
$attr{global}{autosave} = 0 if($init_errors_first);
$defs{global}{init_errors} =
"Messages collected while initializing FHEM:".
"$defs{global}{init_errors}\n".
($init_errors_first ? "Autosave deactivated" : "");
Log 1, $defs{global}{init_errors}
if(AttrVal("global","motd","") ne "none");
}
}
finish_init();
$fhem_started = int(gettimeofday());
DoTrigger("global", "INITIALIZED", 1);
my $osuser = "os:$^O user:".(getlogin || getpwuid($<) || "unknown");
Log 0, "Featurelevel: $featurelevel";
Log 0, "Server started with ".int(keys %defs).
" defined entities ($attr{global}{version} perl:$] $osuser pid:$$)";
execFhemTestFile();
################################################
# Main Loop
sub MAIN {MAIN:}; #Dummy
my $errcount= 0;
$gotSig = undef if($gotSig && $gotSig eq "HUP");
while (1) {
my ($rout,$rin, $wout,$win, $eout,$ein) = ('','', '','', '','');
my $nfound = 0;
my $timeout = HandleTimeout();
foreach my $p (keys %selectlist) {
my $hash = $selectlist{$p};
if(defined($hash->{FD})) {
vec($rin, $hash->{FD}, 1) = 1
if(!defined($hash->{directWriteFn}) && !$hash->{wantWrite} );
vec($win, $hash->{FD}, 1) = 1
if( (defined($hash->{directWriteFn}) ||
defined($hash->{$wbName}) ||
$hash->{wantWrite} ) && !$hash->{wantRead} );
}
vec($ein, $hash->{EXCEPT_FD}, 1) = 1
if(defined($hash->{"EXCEPT_FD"}));
if($hash->{SSL} && $hash->{CD} &&
$hash->{CD}->can('pending') && $hash->{CD}->pending()) {
vec($rout, $hash->{FD}, 1) = 1;
$nfound++;
}
}
$timeout = $readytimeout if(keys(%readyfnlist) &&
(!defined($timeout) || $timeout > $readytimeout));
$timeout = 5 if $winService->{AsAService} && $timeout > 5;
$nfound = select($rout=$rin, $wout=$win, $eout=$ein, $timeout) if(!$nfound);
$winService->{serviceCheck}->() if($winService->{serviceCheck});
if($gotSig) {
CommandShutdown(undef, undef) if($gotSig eq "TERM");
CommandRereadCfg(undef, "") if($gotSig eq "HUP");
$attr{global}{verbose} = 5 if($gotSig eq "USR1");
$gotSig = undef;
}
if($nfound < 0) {
my $err = int($!);
next if($err==0 || $err==4); # 4==EINTR
Log 1, "ERROR: Select error $nfound ($err), error count= $errcount";
$errcount++;
# Handling "Bad file descriptor". This is a programming error.
if($err == 9 || $err == 10038) { # BADF, don't want to "use errno.ph"
my $nbad = 0;
foreach my $p (keys %selectlist) {
my ($tin, $tout) = ('', '');
vec($tin, $selectlist{$p}{FD}, 1) = 1;
if(select($tout=$tin, undef, undef, 0) < 0) {
Log 1, "Found and deleted bad fileno for $p";
delete($selectlist{$p});
$nbad++;
}
}
next if($nbad > 0);
next if($errcount <= 3);
}
die("Select error $nfound ($err)\n");
} else {
$errcount= 0;
}
###############################
# Message from the hardware (FHZ1000/WS3000/etc) via select or the Ready
# Function. The latter ist needed for Windows, where USB devices are not
# reported by select, but is used by unix too, to check if the device is
# attached again.
foreach my $p (keys %selectlist) {
next if(!$p); # Deleted in the loop
my $hash = $selectlist{$p};
my $isDev = ($hash && $hash->{NAME} && $defs{$hash->{NAME}});
my $isDirect = ($hash && ($hash->{directReadFn} || $hash->{directWriteFn}));
next if(!$isDev && !$isDirect);
if(defined($hash->{FD}) && vec($rout, $hash->{FD}, 1)) {
delete $hash->{wantRead};
if($hash->{directReadFn}) {
$hash->{directReadFn}($hash);
} else {
CallFn($hash->{NAME}, "ReadFn", $hash);
}
}
if( defined($hash->{FD}) && vec($wout, $hash->{FD}, 1)) {
delete $hash->{wantWrite};
if($hash->{directWriteFn}) {
$hash->{directWriteFn}($hash);
} elsif(defined($hash->{$wbName})) {
my $wb = $hash->{$wbName};
alarm($hash->{ALARMTIMEOUT}) if($hash->{ALARMTIMEOUT});
my $ret;
eval { $ret = syswrite($hash->{CD}, $wb); };
if($@) {
Log 4, "$hash->{NAME} syswrite: $@";
if($hash->{TEMPORARY}) {
TcpServer_Close($hash);
CommandDelete(undef, $hash->{NAME});
}
next;
}
my $werr = int($!);
alarm(0) if($hash->{ALARMTIMEOUT});
if(!defined($ret) && $werr == EWOULDBLOCK ) {
$hash->{wantRead} = 1
if(TcpServer_WantRead($hash));
} elsif(!$ret) { # zero=EOF, undef=error
Log 4, "$hash->{NAME} write error to $p";
if($hash->{TEMPORARY}) {
TcpServer_Close($hash);
CommandDelete(undef, $hash->{NAME})
}
} else {
if($ret >= length($wb)) { # for the > see Forum #29963
delete($hash->{$wbName});
if($hash->{WBCallback}) {
no strict "refs";
my $ret = &{$hash->{WBCallback}}($hash);
use strict "refs";
delete $hash->{WBCallback};
}
} else {
$hash->{$wbName} = substr($wb, $ret);
}
}
}
}
if(defined($hash->{"EXCEPT_FD"}) && vec($eout, $hash->{EXCEPT_FD}, 1)) {
CallFn($hash->{NAME}, "ExceptFn", $hash);
}
}
foreach my $p (keys %readyfnlist) {
next if(!$readyfnlist{$p}); # due to rereadcfg / delete
if(CallFn($readyfnlist{$p}{NAME}, "ReadyFn", $readyfnlist{$p})) {
if($readyfnlist{$p}) { # delete itself inside ReadyFn
CallFn($readyfnlist{$p}{NAME}, "ReadFn", $readyfnlist{$p});
}
}
}
}
################################################
#Functions ahead, no more "plain" code
################################################
sub
IsDevice($;$)
{
my $devname = shift;
my $devtype = shift;
return 1
if ( defined($devname)
&& defined( $defs{$devname} )
&& (!$devtype || $devtype eq "" ) );
return 1
if ( defined($devname)
&& defined( $defs{$devname} )
&& defined( $defs{$devname}{TYPE} )
&& $defs{$devname}{TYPE} =~ m/^$devtype$/ );
return 0;
}
sub
IsDummy($)
{
my $devname = shift;
return 1 if(defined($attr{$devname}) && $attr{$devname}{dummy});
return 0;
}
sub
IsIgnored($)
{
my $devname = shift;
if($devname &&
defined($attr{$devname}) && $attr{$devname}{ignore}) {
Log 4, "Ignoring $devname";
return 1;
}
return 0;
}
sub
IsDisabled($)
{
my $devname = shift;
return 0 if(!$devname); # no check for $attr{$devname}, #92623
return 1 if($attr{$devname}{disable});
return 3 if($defs{$devname} && $defs{$devname}{STATE} &&
$defs{$devname}{STATE} eq "inactive");
return 3 if(ReadingsVal($devname, "state", "") eq "inactive");
my $dfi = $attr{$devname}{disabledForIntervals};
if(defined($dfi)) {
$dfi =~ s/{([^\x7d]*)}/$cmdFromAnalyze=$1; eval $1/ge; # Forum #69787
my ($sec,$min,$hour,$mday,$month,$year,$wday,$yday,$isdst) =
localtime(gettimeofday());
my $dhms = sprintf("%s\@%02d:%02d:%02d", $wday, $hour, $min, $sec);
foreach my $ft (split(" ", $dfi)) {
my ($from, $to) = split("-", $ft);
if(defined($from) && defined($to)) {
$from = "$wday\@$from" if(index($from,"@") < 0);
$to = "$wday\@$to" if(index($to, "@") < 0);
return 2 if($from le $dhms && $dhms le $to);
}
}
}
return 0;
}
################################################
sub
IsIoDummy($)
{
my $name = shift;
return IsDummy($defs{$name}{IODev}{NAME})
if($defs{$name} && $defs{$name}{IODev});
return 1;
}
################################################
sub
GetLogLevel(@)
{
my ($dev,$deflev) = @_;
my $df = defined($deflev) ? $deflev : 2;
return $df if(!defined($dev));
return $attr{$dev}{loglevel}
if(defined($attr{$dev}) && defined($attr{$dev}{loglevel}));
return $df;
}
sub
GetVerbose($)
{
my ($dev) = @_;
if(defined($dev) &&
defined($attr{$dev}) &&
defined (my $devlevel = $attr{$dev}{verbose})) {
return $devlevel;
} else {
return $attr{global}{verbose};
}
}
sub
GetType($;$)
{
my $devname = shift;
my $default = shift;
return $default unless ( IsDevice($devname) && $defs{$devname}{TYPE} );
return $defs{$devname}{TYPE};
}
################################################
# the new Log with integrated loglevel checking
sub
Log3($$$)
{
my ($dev, $loglevel, $text) = @_;
$dev = $dev->{NAME} if(defined($dev) && ref($dev) eq "HASH");
if(defined($dev) &&
defined($attr{$dev}) &&
defined (my $devlevel = $attr{$dev}{verbose})) {
return if($loglevel > $devlevel);
} else {
return if($loglevel > $attr{global}{verbose});
}
return if(defined($defs{global}{ignoreRegexpObj}) &&
$text =~ $defs{global}{ignoreRegexpObj});
my ($seconds, $microseconds) = gettimeofday();
my @t = localtime($seconds);
my $nfile = ResolveDateWildcards($attr{global}{logfile}, @t);
OpenLogfile($nfile) if(!$currlogfile || $currlogfile ne $nfile);
my $tim = sprintf("%04d.%02d.%02d %02d:%02d:%02d",