-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy path10_FRM.pm
2639 lines (2116 loc) · 82 KB
/
10_FRM.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
########################################################################################
# $Id: 10_FRM.pm 23393 2020-12-20 19:35:57Z jensb $
########################################################################################
=encoding UTF-8
=head1 NAME
FHEM module to communicate with Firmata devices
=head1 LICENSE AND COPYRIGHT
Copyright (C) 2013 ntruchess
Copyright (C) 2015 jensb
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 (at your option) any later version.
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.
You should have received a copy of the GNU General Public License
along with this script; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
A copy of the GNU General Public License, Version 2 can also be found at
http://www.gnu.org/licenses/old-licenses/gpl-2.0.
This copyright notice MUST APPEAR in all copies of the script!
=cut
package main;
use strict;
use warnings;
use vars qw{%attr %defs};
use DevIo;
#add FHEM/lib to @INC if it's not already included. Should rather be in fhem.pl than here though...
BEGIN {
if (!grep(/FHEM\/lib$/,@INC)) {
foreach my $inc (grep(/FHEM$/,@INC)) {
push @INC,$inc."/lib";
};
};
};
use feature qw(switch);
no if $] >= 5.017011, warnings => 'experimental';
use constant FRM_MIN_DEVICE_FIRMATA_VERSION => 0.69;
use constant FRM_DEVICE_FIRMATA_STATUS_INSTALLED => 1;
use constant FRM_DEVICE_FIRMATA_STATUS_NOT_INSTALLED => 0;
use constant FRM_DEVICE_FIRMATA_STATUS_WRONG_VERSION => -1;
use constant FRM_DEVICE_FIRMATA_STATUS_UNDEFINED => -9;
my $deviceFirmataStatus = FRM_DEVICE_FIRMATA_STATUS_UNDEFINED;
# number of arguments
my %sets = (
"reset:noArg" => 0,
"reinit:noArg" => 0,
"sendString" => 1
);
my %gets = (
"firmware" => "",
"version" => ""
);
my @clients = qw(
I2C_BH1750
I2C_BME280
I2C_BMP180
I2C_DS1307
I2C_INA219
I2C_K30
I2C_LCD
I2C_LM.*
I2C_MCP230.*
I2C_MCP342.*
I2C_PC.*
I2C_SHT.*
I2C_TSL2561
FRM_AD
FRM_I2C
FRM_IN
FRM_LCD
FRM_OUT
FRM_PWM
FRM_RGB
FRM_ROTENC
FRM_SERVO
FRM_STEPPER
OWX
OWX_ASYNC
);
sub FRM_Set;
sub FRM_Attr;
=head1 METHODS
=head2 FRM_Initialize($)
Returns:
nothing
Description:
FHEM module initialization function ($hash is FRM)
=cut
sub FRM_Initialize {
my $hash = shift @_;
# Producer
$hash->{Clients} = join (':',@clients);
$hash->{ReadyFn} = "FRM_Ready";
$hash->{ReadFn} = "FRM_Read";
$hash->{I2CWrtFn} = "FRM_I2C_Write";
$hash->{IOOpenFn} = "FRM_Serial_Open";
$hash->{IOWriteFn} = "FRM_Serial_Write";
$hash->{IOCloseFn} = "FRM_Serial_Close";
# Consumer
$hash->{DefFn} = "FRM_Define";
$hash->{UndefFn} = "FRM_Undef";
$hash->{GetFn} = "FRM_Get";
$hash->{SetFn} = "FRM_Set";
$hash->{AttrFn} = "FRM_Attr";
$hash->{NotifyFn} = "FRM_Notify";
$hash->{AttrList} = "disable:0,1 " .
"dummy:1,0 " .
"errorExclude " .
"i2c-config " .
"ping-interval " .
"receiveTimeout " .
"resetDeviceOnConnect:0,1 " .
"sampling-interval " .
"software-serial-config " .
"$main::readingFnAttributes";
}
=head2 FRM_Define($$)
Returns:
undef on success or error message
Description:
FHEM module DefFn ($hash is FRM)
=cut
sub FRM_Define {
my ( $hash, $def ) = @_;
my ($name, $type, $dev, $global) = split("[ \t]+", $def);
$hash->{DeviceName} = $dev;
$hash->{NOTIFYDEV} = "global";
if ($dev eq "none") {
main::Log3 $name, 3, "$name: device is none, commands will be echoed only";
$main::attr{$name}{dummy} = 1;
}
# check if Device::Firmata module is properly installed
FRM_Get_Device_Firmata_Status();
given($deviceFirmataStatus) {
when(FRM_DEVICE_FIRMATA_STATUS_INSTALLED) {
delete $main::defs{$name}{DRIVER_STATUS};
$main::defs{$name}{DRIVER_VERSION} = $Device::Firmata::VERSION;
}
when(FRM_DEVICE_FIRMATA_STATUS_NOT_INSTALLED) {
$main::defs{$name}{DRIVER_STATUS} = 'Perl module Device::Firmata not found, see Commandref for details how to fix';
delete $main::defs{$name}{DRIVER_VERSION};
main::Log3 $name, 1, "$name ERROR: " . $main::defs{$name}{DRIVER_STATUS};
readingsSingleUpdate($hash, 'state', 'error', 1);
return undef;
}
when(FRM_DEVICE_FIRMATA_STATUS_WRONG_VERSION) {
$main::defs{$name}{DRIVER_STATUS} = 'Perl module Device::Firmata version ' . FRM_MIN_DEVICE_FIRMATA_VERSION . ' or higher required, see Commandref for details how to fix';
$main::defs{$name}{DRIVER_VERSION} = $Device::Firmata::VERSION;
main::Log3 $name, 2, "$name WARNING: " . $main::defs{$name}{DRIVER_STATUS};
$deviceFirmataStatus = FRM_DEVICE_FIRMATA_STATUS_INSTALLED;
# @TODO readingsSingleUpdate($hash, 'state', 'error', 1);
# @TODO $deviceFirmataStatus = FRM_DEVICE_FIRMATA_STATUS_WRONG_VERSION;
# @TODO return undef;
}
default {
main::Log3 $name, 1, "$name ERROR: validation of Perl module Device::Firmata failed";
readingsSingleUpdate($hash, 'state', 'error', 1);
return undef;
}
}
readingsSingleUpdate($hash, 'state', 'defined', 1);
if ($main::init_done) {
# defined via mofiy or reload
my $pingInterval = AttrVal($name, 'ping-interval', 0);
if (looks_like_number($pingInterval) && $pingInterval > 0) {
InternalTimer(gettimeofday() + $pingInterval/1000.0, 'FRM_Timer_Ping', $hash, 0);
}
if (AttrVal($name, 'disable', 0) != 0) {
readingsSingleUpdate($hash, 'state', 'disabled', 1);
}
return FRM_Start($hash);
}
return undef;
}
=head2 FRM_Undef($)
Returns:
undef
Description:
FHEM module UndefFn ($hash is FRM)
=cut
sub FRM_Undef {
my $hash = shift;
RemoveInternalTimer($hash);
FRM_forall_clients($hash,\&FRM_Client_Unassign,undef);
if (defined $hash->{DeviceName}) {
DevIo_Disconnected($hash);
};
TcpServer_Close($hash);
foreach my $d ( sort keys %main::defs ) { # close and dispose open tcp-connection (if any) to free open filedescriptors
if ( defined( my $dev = $main::defs{$d} )) {
if ( defined( $main::defs{$d}{SNAME} )
&& $main::defs{$d}{SNAME} eq $hash->{NAME}) {
FRM_Tcp_Connection_Close($main::defs{$d});
}
}
}
FRM_FirmataDevice_Close($hash);
FRM_ClearConfiguration($hash);
return undef;
}
=head2 FRM_Start
Returns:
undef on success or error messages
Description:
FRM internal function ($hash is FRM)
=cut
sub FRM_Start {
my ($hash) = @_;
my $name = $hash->{NAME};
if ($deviceFirmataStatus != FRM_DEVICE_FIRMATA_STATUS_INSTALLED) {
return "$name Perl module Device::Firmata not properly installed";
}
if (AttrVal($name, 'disable', 0) != 0) {
return "$name is disabled";
}
# clear old device ids to force full init
FRM_ClearConfiguration($hash);
my ($dev, $global) = split("[ \t]+", $hash->{DEF});
$hash->{DeviceName} = $dev;
# make sure that fhem only runs once
my $isServer = 1 if($dev && $dev =~ m/^(IPV6:)?\d+$/);
if ($isServer) {
# set initial state
readingsSingleUpdate($hash, 'state', 'defined', 1);
# start TCP server
my $ret = TcpServer_Open($hash, $dev, $global);
if (!$ret) {
readingsSingleUpdate($hash, 'state', 'listening', 1);
}
RemoveInternalTimer($hash, 'FRM_Monitor');
InternalTimer(gettimeofday() + 1, 'FRM_Monitor', $hash, 0);
return $ret;
}
# close old DevIO (if any)
DevIo_CloseDev($hash);
readingsSingleUpdate($hash, 'state', 'defined', 1);
if (AttrVal($name, 'dummy', 0) == 0) {
# open DevIO
my $ret = DevIo_OpenDev($hash, 0, "FRM_DoInit");
return $ret;
}
}
=head2 FRM_Notify
Returns:
nothing
Description:
FHEM module NotifyFn ($hash is FRM)
=cut
sub FRM_Notify {
my ($hash, $dev) = @_;
my $name = $hash->{NAME};
my $type = $hash->{TYPE};
if (grep(m/^(INITIALIZED|REREADCFG)$/, @{$dev->{CHANGED}})) {
# FHEM (re-)initialized
FRM_Start($hash);
} elsif (grep(m/^DISCONNECTED$/, @{$dev->{CHANGED}}) && $type eq 'FRM' && defined($hash->{SocketDevice}) && $hash->{SocketDevice} eq $dev) {
# TCP socket closed
FRM_Tcp_Connection_Close($dev);
FRM_FirmataDevice_Close($hash);
}
}
=head2 FRM_is_firmata_connected
Returns:
true if Firmata device and Firmata device IO are defined
Description:
FRM internal utility function($hash is FRM)
=cut
sub FRM_is_firmata_connected {
my ($hash) = @_;
return defined($hash->{FirmataDevice}) && defined($hash->{FirmataDevice}->{io});
}
=head2 FRM_Set($@)
Returns:
undef or error message
Description:
FHEM module SetFn ($hash is FRM)
=cut
sub FRM_Set {
my ($hash, $name, $cmd, @a) = @_;
return "set command missing" if(!defined($cmd));
my @match = grep( $_ =~ /^$cmd($|:)/, keys %sets );
return "unknown set command '$cmd', choose one of " . join(" ", sort keys %sets) if ($cmd eq '?' || @match == 0);
return "$cmd requires $sets{$match[0]} argument(s)" unless (@a == $sets{$match[0]});
given($cmd) {
when("reset") {
return "not connected to Firmata device" unless (FRM_is_firmata_connected($hash) && (defined $hash->{FD} or ($^O=~/Win/ and defined $hash->{USBDev})));
$hash->{FirmataDevice}->system_reset();
FRM_ClearConfiguration($hash);
if (defined $hash->{SERVERSOCKET}) {
# dispose preexisting connections
foreach my $e ( sort keys %main::defs ) {
if ( defined( my $dev = $main::defs{$e} )) {
if ( defined( $dev->{SNAME} ) && ( $dev->{SNAME} eq $name )) {
FRM_Tcp_Connection_Close($dev);
}
}
}
FRM_FirmataDevice_Close($hash);
} else {
DevIo_Disconnected($hash);
FRM_FirmataDevice_Close($hash);
return DevIo_OpenDev($hash, 0, "FRM_DoInit");
}
};
when("reinit") {
FRM_forall_clients($hash, \&FRM_Init_Client, undef);
};
when("sendString") {
FRM_String_Write($hash, $a[0]);
};
}
return undef;
}
=head2 FRM_Get($@)
Returns:
requested data or error message
Description:
FHEM module GetFn ($hash is FRM)
=cut
sub FRM_Get {
my ($hash, $name, $cmd, @a) = @_;
return "get command missing" if(!defined($cmd));
return "unknown get command '$cmd', choose one of " . join(":noArg ", sort keys %gets) . ":noArg" if(!defined($gets{$cmd}));
GETHANDLER: {
$cmd eq "firmware" and do {
if (FRM_is_firmata_connected($hash)) {
return $hash->{FirmataDevice}->{metadata}->{firmware};
} else {
return "not connected to Firmata device";
}
};
$cmd eq "version" and do {
if (FRM_is_firmata_connected($hash)) {
return $hash->{FirmataDevice}->{metadata}->{firmware_version};
} else {
return "not connected to Firmata device";
}
};
}
}
=head2 FRM_Read($)
Returns:
nothing
Description:
FHEM module ReadFn, called by IODev of FRM ($hash is FRM, $chash is TCP client session)
called from the global loop, when the select for hash->{FD} reports data
=cut
sub FRM_Read {
my ( $hash ) = @_;
if($hash->{SERVERSOCKET}) { # Accept and create a child
my $chash = TcpServer_Accept($hash, "FRM");
return if(!$chash);
$chash->{DeviceName}=$hash->{PORT}; # required for DevIo_CloseDev and FRM_Ready
$chash->{TCPDev}=$chash->{CD};
# dispose preexisting connections
foreach my $e ( sort keys %main::defs ) {
if ( defined( my $dev = $main::defs{$e} )) {
if ( $dev != $chash && defined( $dev->{SNAME} ) && ( $dev->{SNAME} eq $chash->{SNAME} )) {
FRM_Tcp_Connection_Close($dev);
}
}
}
FRM_FirmataDevice_Close($hash);
FRM_DoInit($chash);
return;
}
my $device = $hash->{FirmataDevice} or return;
$device->poll();
FRM_SetupDevice($hash);
}
=head2 FRM_Ready($)
Returns:
number of bytes waiting to be read or nothing on error
Description:
FHEM module ReadyFn, called by IODev of FRM ($hash is IODev/master, $shash is FRM/slave)
=cut
sub FRM_Ready {
my ($hash) = @_;
my $name = $hash->{NAME};
if ($name=~/^^FRM:.+:\d+$/) { # this is a closed tcp-connection, remove it
FRM_Tcp_Connection_Close($hash);
FRM_FirmataDevice_Close($hash);
return;
}
main::Log3 $name, 5, "$name: FRM_Ready";
# reopen connection to DevIO if closed
return DevIo_OpenDev($hash, 1, "FRM_DoInit") if($hash->{STATE} eq "disconnected");
# This is relevant for windows/USB only
my $po = $hash->{USBDev};
my ($BlockingFlags, $InBytes, $OutBytes, $ErrorFlags);
if($po) {
($BlockingFlags, $InBytes, $OutBytes, $ErrorFlags) = $po->status;
}
return ($InBytes && $InBytes>0);
}
=head2 FRM_Tcp_Connection_Close($)
Returns:
undef
Description:
FRM internal function for IODev ($hash is IODev/master, $shash is FRM/slave)
=cut
sub FRM_Tcp_Connection_Close {
my $hash = shift;
TcpServer_Close($hash);
if ($hash->{SNAME}) {
my $shash = $main::defs{$hash->{SNAME}};
readingsSingleUpdate($shash, 'state', 'listening', 1);
if (defined $shash) {
delete $shash->{SocketDevice} if (defined $shash->{SocketDevice});
}
}
my $dev = $hash->{DeviceName};
my $name = $hash->{NAME};
if (defined $name) {
delete $main::readyfnlist{"$name.$dev"} if (defined $dev);
delete $main::attr{$name};
delete $main::defs{$name};
}
return undef;
}
=head2 FRM_FirmataDevice_Close($)
Returns:
nothing
Description:
FRM internal function ($hash is FRM)
=cut
sub FRM_FirmataDevice_Close {
my $hash = shift;
my $name = $hash->{NAME};
my $device = $hash->{FirmataDevice};
if (defined $device) {
if (defined $device->{io}) {
delete $hash->{FirmataDevice}->{io}->{handle} if defined $hash->{FirmataDevice}->{io}->{handle};
delete $hash->{FirmataDevice}->{io};
}
delete $device->{protocol} if defined $device->{protocol};
delete $hash->{FirmataDevice};
}
}
=head2 FRM_Attr(@)
Returns:
nothing
Description:
FHEM module AttrFn ($hash is FRM)
=cut
sub FRM_Attr {
my ($command, $name, $attribute, $value) = @_;
my $hash = $main::defs{$name};
given($command) {
when("set") {
given($attribute) {
when(["sampling-interval", "i2c-config"]) {
$main::attr{$name}{$attribute} = $value;
FRM_apply_attribute($main::defs{$name}, $attribute);
}
when("disable") {
my $disabled = main::ReadingsVal($name, 'state', '?') eq 'disabled';
if ($value) {
if (!$disabled) {
FRM_Undef($hash);
readingsSingleUpdate($hash, 'state', 'disabled', 1);
}
} else {
if ($main::init_done && $disabled) {
$main::attr{$name}{disable} = 0; # otherwise change of attr is not visible in FRM_Start()
readingsSingleUpdate($hash, 'state', 'defined', 1);
FRM_Start($hash);
}
}
}
when("ping-interval") {
my $pingInterval = (defined($value) && looks_like_number($value) && $value > 0) ? $value : 0;
if ($pingInterval > 0) {
InternalTimer(gettimeofday() + $pingInterval/1000.0, 'FRM_Timer_Ping', $hash, 0);
} else {
RemoveInternalTimer($hash, 'FRM_Timer_Ping');
}
}
}
}
when("del") {
given($attribute) {
when("disable") {
my $disabled = main::ReadingsVal($name, 'state', '?') eq 'disabled';
if ($main::init_done && $disabled) {
readingsSingleUpdate($hash, 'state', 'defined', 1);
FRM_Start($hash);
}
}
when("ping-interval") {
RemoveInternalTimer($hash, 'FRM_Timer_Ping');
}
}
}
}
return undef;
}
=head2 FRM_apply_attribute()
Returns:
nothing
Description:
FRM internal function ($hash is FRM)
=cut
sub FRM_apply_attribute {
my ($hash,$attribute) = @_;
my $firmata = $hash->{FirmataDevice};
my $name = $hash->{NAME};
if (defined $firmata) {
if ($attribute eq "sampling-interval") {
$firmata->sampling_interval(AttrVal($name,$attribute,"1000"));
} elsif ($attribute eq "i2c-config") {
my $i2cattr = AttrVal($name,$attribute,undef);
if (defined $i2cattr) {
my @a = split(" ", $i2cattr);
my $i2cpins = $firmata->{metadata}{i2c_pins};
my $err;
if (defined $i2cpins and scalar @$i2cpins) {
eval {
foreach my $i2cpin (@$i2cpins) {
$firmata->pin_mode($i2cpin, Device::Firmata::Constants->PIN_I2C);
}
$firmata->i2c_config(@a);
$firmata->observe_i2c(\&FRM_i2c_observer,$hash);
};
$err = FRM_Catch($@) if ($@);
} else {
$err = "Error, arduino doesn't support I2C";
}
main::Log3 $name, 2, "$name ERROR: $err" if ($err);
}
}
}
}
=head2 FRM_DoInit($)
Returns:
undef on success or 1 if Firmata platform attach fails
Description:
FRM internal function for IODev ($hash is IODev/master or FRM, $shash is FRM/slave)
try to reset Firmata device and start Firmata device initialization
=cut
sub FRM_DoInit {
my ($hash) = @_;
my $sname = $hash->{SNAME}; #is this a serversocket-connection?
my $shash = defined $sname ? $main::defs{$sname} : $hash;
my $name = $shash->{NAME};
main::Log3 $name, 5, "$name: FRM_DoInit";
readingsSingleUpdate($shash, 'state', 'connected', 1);
my $firmata_io = Firmata_IO->new($hash, $name);
my $device = Device::Firmata::Platform->attach($firmata_io) or return 1;
$shash->{FirmataDevice} = $device;
if (defined $sname) {
$shash->{SocketDevice} = $hash;
$shash->{LAST_RECEIVED} = main::TimeNow();
$hash->{FirmataDevice} = $device;
}
$device->observe_string(\&FRM_string_observer, $shash);
if (AttrVal($name, 'resetDeviceOnConnect', 1)) {
$device->system_reset();
FRM_ClearConfiguration($shash);
}
$shash->{SETUP_START} = gettimeofday();
$shash->{SETUP_STAGE} = 1; # detect connect mode (fhem startup, device startup or device reconnect) and query versions
$shash->{SETUP_TRIES} = 1;
return FRM_SetupDevice($shash);
}
=head2 FRM_ClearConfiguration()
Returns:
nothing
Description:
FRM internal function ($hash is FRM)
delete all version and capability readings
=cut
sub FRM_ClearConfiguration {
my $hash = shift;
my $name = $hash->{NAME};
delete $main::defs{$name}{protocol_version};
delete $main::defs{$name}{firmware};
delete $main::defs{$name}{firmware_version};
delete $main::defs{$name}{input_pins};
delete $main::defs{$name}{output_pins};
delete $main::defs{$name}{analog_pins};
delete $main::defs{$name}{pwm_pins};
delete $main::defs{$name}{servo_pins};
delete $main::defs{$name}{i2c_pins};
delete $main::defs{$name}{onewire_pins};
delete $main::defs{$name}{stepper_pins};
delete $main::defs{$name}{encoder_pins};
delete $main::defs{$name}{serial_pins};
delete $main::defs{$name}{pullup_pins};
delete $main::defs{$name}{analog_resolutions};
delete $main::defs{$name}{pwm_resolutions};
delete $main::defs{$name}{servo_resolutions};
delete $main::defs{$name}{encoder_resolutions};
delete $main::defs{$name}{stepper_resolutions};
delete $main::defs{$name}{serial_ports};
}
=head2 FRM_SetupDevice()
Returns:
undef
Description:
FRM internal function ($hash is IODev/master or FRM)
Monitor data received from Firmata device immediately after connect, perform
protocol, firmware and capability queries and configure device according to
the FRM device attributes.
=cut
sub FRM_SetupDevice {
my ($hash) = @_;
if (defined($hash->{SNAME})) {
$hash = $main::defs{$hash->{SNAME}};
}
return undef if (!defined($hash->{SETUP_START}));
my $name = $hash->{NAME};
main::Log3 $name, 5, "$name: setup stage $hash->{SETUP_STAGE}";
my $now = gettimeofday();
my $elapsed = $now - $hash->{SETUP_START};
my $device = $hash->{FirmataDevice};
if ($hash->{SETUP_STAGE} == 1) { # protocol and firmware version
RemoveInternalTimer($hash, 'FRM_SetupDevice');
InternalTimer($now + (($elapsed < 1)? 0.1 : 1), 'FRM_SetupDevice', $hash, 0);
# wait for protocol and firmware version
my $fhemRestart = !defined($main::defs{$name}{protocol_version});
my $versionsReceived = $device->{metadata}{firmware} && $device->{metadata}{firmware_version} && $device->{metadata}{protocol_version};
if ($versionsReceived) {
# clear old version and capability readings if not already done
if (!$fhemRestart) {
FRM_ClearConfiguration($hash);
}
# protocol and firmware versions have been received
$main::defs{$name}{firmware} = $device->{metadata}{firmware};
$main::defs{$name}{firmware_version} = $device->{metadata}{firmware_version};
$main::defs{$name}{protocol_version} = $device->{protocol}->get_max_supported_protocol_version($device->{metadata}{protocol_version});
main::Log3 $name, 3, "$name: Firmata Firmware Version ".$device->{metadata}{firmware}." ".$device->{metadata}{firmware_version}." (using Protocol Version ".$main::defs{$name}{protocol_version}.")";
# query capabilities
$device->analog_mapping_query();
$device->capability_query();
# wait for capabilities
$hash->{SETUP_STAGE} = 2;
} elsif ($elapsed >= 3) {
# protocol and firmware version still missing
if ($hash->{SETUP_TRIES} < 3) {
# requery versions
main::Log3 $name, 3, "$name: querying Firmata versions";
$device->protocol_version_query();
$device->firmware_version_query();
# restart setup
$hash->{SETUP_START} = gettimeofday();
$hash->{SETUP_STAGE} = 1;
$hash->{SETUP_TRIES}++;
} else {
# retry limit exceeded, abort
$hash->{SETUP_STAGE} = 4;
FRM_SetupDevice($hash);
}
} elsif ($elapsed >= 0.2 && defined($hash->{PORT})) {
# if we don't receive the protocol version within 200 millis, the device has reconnected (or has an old firmware)
my $deviceRestart = $device->{metadata}{protocol_version};
if (!$deviceRestart && !$fhemRestart) {
# probably a reconnect
main::Log3 $name, 3, "$name: Firmata device has reconnected";
#if ($skipSetupOnReconnect) {
# # skip capability queries and device setup, just reinit client modules
# $hash->{SETUP_STAGE} = 3;
# FRM_SetupDevice($hash);
# return undef;
#}
# clear old version and capability readings
FRM_ClearConfiguration($hash);
# query versions
main::Log3 $name, 3, "$name: querying Firmata versions";
$device->protocol_version_query();
$device->firmware_version_query();
}
}
} elsif ($hash->{SETUP_STAGE} == 2) { # device capabilities
RemoveInternalTimer($hash, 'FRM_SetupDevice');
InternalTimer(gettimeofday() + 1, 'FRM_SetupDevice', $hash, 0);
my $capabilitiesReceived = $device->{metadata}{capabilities} && ($device->{metadata}{analog_mappings} || ($elapsed >= 5));
if ($capabilitiesReceived) {
# device capabilities have been received, convert to readings
my $inputpins = $device->{metadata}{input_pins};
$main::defs{$name}{input_pins} = join(",", sort{$a<=>$b}(@$inputpins)) if (defined $inputpins and scalar @$inputpins);
my $outputpins = $device->{metadata}{output_pins};
$main::defs{$name}{output_pins} = join(",", sort{$a<=>$b}(@$outputpins)) if (defined $outputpins and scalar @$outputpins);
my $analogpins = $device->{metadata}{analog_pins};
$main::defs{$name}{analog_pins} = join(",", sort{$a<=>$b}(@$analogpins)) if (defined $analogpins and scalar @$analogpins);
my $pwmpins = $device->{metadata}{pwm_pins};
$main::defs{$name}{pwm_pins} = join(",", sort{$a<=>$b}(@$pwmpins)) if (defined $pwmpins and scalar @$pwmpins);
my $servopins = $device->{metadata}{servo_pins};
$main::defs{$name}{servo_pins} = join(",", sort{$a<=>$b}(@$servopins)) if (defined $servopins and scalar @$servopins);
my $i2cpins = $device->{metadata}{i2c_pins};
$main::defs{$name}{i2c_pins} = join(",", sort{$a<=>$b}(@$i2cpins)) if (defined $i2cpins and scalar @$i2cpins);
my $onewirepins = $device->{metadata}{onewire_pins};
$main::defs{$name}{onewire_pins} = join(",", sort{$a<=>$b}(@$onewirepins)) if (defined $onewirepins and scalar @$onewirepins);
my $stepperpins = $device->{metadata}{stepper_pins};
$main::defs{$name}{stepper_pins} = join(",", sort{$a<=>$b}(@$stepperpins)) if (defined $stepperpins and scalar @$stepperpins);
my $encoderpins = $device->{metadata}{encoder_pins};
$main::defs{$name}{encoder_pins} = join(",", sort{$a<=>$b}(@$encoderpins)) if (defined $encoderpins and scalar @$encoderpins);
my $serialpins = $device->{metadata}{serial_pins};
$main::defs{$name}{serial_pins} = join(",", sort{$a<=>$b}(@$serialpins)) if (defined $serialpins and scalar @$serialpins);
my $pulluppins = $device->{metadata}{pullup_pins};
$main::defs{$name}{pullup_pins} = join(",", sort{$a<=>$b}(@$pulluppins)) if (defined $pulluppins and scalar @$pulluppins);
if (defined $device->{metadata}{analog_resolutions}) {
my @analog_resolutions;
foreach my $pin (sort{$a<=>$b}(keys %{$device->{metadata}{analog_resolutions}})) {
push @analog_resolutions,$pin.":".$device->{metadata}{analog_resolutions}{$pin};
}
$main::defs{$name}{analog_resolutions} = join(",",@analog_resolutions) if (scalar @analog_resolutions);
}
if (defined $device->{metadata}{pwm_resolutions}) {
my @pwm_resolutions;
foreach my $pin (sort{$a<=>$b}(keys %{$device->{metadata}{pwm_resolutions}})) {
push @pwm_resolutions,$pin.":".$device->{metadata}{pwm_resolutions}{$pin};
}
$main::defs{$name}{pwm_resolutions} = join(",",@pwm_resolutions) if (scalar @pwm_resolutions);
}
if (defined $device->{metadata}{servo_resolutions}) {
my @servo_resolutions;
foreach my $pin (sort{$a<=>$b}(keys %{$device->{metadata}{servo_resolutions}})) {
push @servo_resolutions,$pin.":".$device->{metadata}{servo_resolutions}{$pin};
}
$main::defs{$name}{servo_resolutions} = join(",",@servo_resolutions) if (scalar @servo_resolutions);
}
if (defined $device->{metadata}{encoder_resolutions}) {
my @encoder_resolutions;
foreach my $pin (sort{$a<=>$b}(keys %{$device->{metadata}{encoder_resolutions}})) {
push @encoder_resolutions,$pin.":".$device->{metadata}{encoder_resolutions}{$pin};
}
$main::defs{$name}{encoder_resolutions} = join(",",@encoder_resolutions) if (scalar @encoder_resolutions);
}
if (defined $device->{metadata}{stepper_resolutions}) {
my @stepper_resolutions;
foreach my $pin (sort{$a<=>$b}(keys %{$device->{metadata}{stepper_resolutions}})) {
push @stepper_resolutions,$pin.":".$device->{metadata}{stepper_resolutions}{$pin};
}
$main::defs{$name}{stepper_resolutions} = join(",",@stepper_resolutions) if (scalar @stepper_resolutions);
}
if (defined $device->{metadata}{serial_resolutions}) {
my @serial_ports;
foreach my $pin (sort{$a<=>$b}(keys %{$device->{metadata}{serial_resolutions}})) {
push @serial_ports,$pin.":".int($device->{metadata}{serial_resolutions}{$pin}/2);
}
$main::defs{$name}{serial_ports} = join(",",@serial_ports) if (scalar @serial_ports);
}
# setup device
FRM_apply_attribute($hash, "sampling-interval");
FRM_apply_attribute($hash, "i2c-config");
FRM_serial_setup($hash);
# ready, init client modules
$hash->{SETUP_STAGE} = 3;
FRM_SetupDevice($hash);
} elsif ($elapsed >= 5) {
# capabilities receive timeout, abort
$hash->{SETUP_STAGE} = 4;
FRM_SetupDevice($hash);
}
} elsif ($hash->{SETUP_STAGE} == 3) { # client modules
# client module initialization
FRM_forall_clients($hash, \&FRM_Init_Client, undef);
readingsSingleUpdate($hash, 'state', "Initialized", 1);
# done, terminate setup sequence
$hash->{SETUP_STAGE} = 5;
FRM_SetupDevice($hash);
} elsif ($hash->{SETUP_STAGE} == 4) { # abort setup
# device setup has failed, cleanup connection
if (defined $hash->{SERVERSOCKET}) {
main::Log3 $name, 3, "$name: no response from Firmata, closing TCP connection";
foreach my $e (sort keys %main::defs) {
if (defined(my $dev = $main::defs{$e})) {
if (defined($dev->{SNAME}) && ($dev->{SNAME} eq $hash->{NAME})) {
FRM_Tcp_Connection_Close($dev);
}
}
}
} else {
main::Log3 $name, 3, "$name: no response from Firmata, closing DevIo";
DevIo_Disconnected($hash);
}
FRM_FirmataDevice_Close($hash);
# cleanup setup
$hash->{SETUP_STAGE} = 5;
FRM_SetupDevice($hash);
} elsif ($hash->{SETUP_STAGE} == 5) { # finish setup
# terminate setup sequence
RemoveInternalTimer($hash, 'FRM_SetupDevice');
delete $hash->{SETUP_START};
delete $hash->{SETUP_STAGE};
delete $hash->{SETUP_TRIES};
} else {
# invalid state, abort
$hash->{SETUP_STAGE} = 4;
FRM_SetupDevice($hash);
}
return undef;
}
=head2 FRM_Get_Device_Firmata_Status()
Returns:
main::FRM_DEVICE_FIRMATA_STATUS_INSTALLED
if Device::Firmata is installed and has the required version
main::FRM_DEVICE_FIRMATA_STATUS_NOT_INSTALLED
if the Perl module Device::Firmata is missing or does not have the required version
main::FRM_DEVICE_FIRMATA_STATUS_WRONG_VERSION
if Device::Firmata is installed but does not have the required version
Description:
FRM public function
=cut
sub FRM_Get_Device_Firmata_Status {
# check if Device::Firmata module is properly installed
if ($deviceFirmataStatus != FRM_DEVICE_FIRMATA_STATUS_INSTALLED) {
eval {
require Device::Firmata;
require Device::Firmata::Constants;
require Device::Firmata::Platform;
require Device::Firmata::Protocol;