-
Notifications
You must be signed in to change notification settings - Fork 0
/
32_fitbit.pm
executable file
·2040 lines (1647 loc) · 78.4 KB
/
32_fitbit.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: 32_fitbit.pm
#
# 32_fitbit.pm
#
# 2017 Tobias Vaupel
# Based on code from 32_withings
#
# https://forum.fhem.de/index.php/topic,73285
#
# ToDo:
#
##############################################################################
# Release 05 / 2019-03-10
# Fixed sleep values. Fitbit api was changed and sleep level were renamed.
# Module is now using the updated sleep levels. This causes the readings to have new names as well...
# Added support for heart rate. Module is reading summary of today as well as the values of previous day.
#
# Modification Strategy / 2019-03-09
# Added attribute createFriends - by default friends are no longer created
# Added attribute createDevices - by default devices are created but creation can be disabled.
# Added setWeight to insert a weigth value.
# Added setFat to insert a fat value
#Release 03 / 2017-09-03
# -match deviceID with "eq" instead of "==" to prevent warnings when device ID contains characters
# -battery readings content in lower case
# -added floors and elevation as USER reading
# Release 02 / 2017-07-01
# -commandref EN erstellt
# -reading summary_activeScore entfernt
# -fitbit_parseUserWeight: set reading weight
# -fhem() is used with silent param
# Release 01 / 2017-06-25
# -fitbit_initDevice: reading von battery auf batteryLevel geändert.
# Release 00 / 2017-06-24
# -Einige INTERNALs als Readings zur Verfügung gestellt
# -FHEM sollte nicht mehr abstürzen, wenn der Token ungültig ist
# -"weight" Daten werden zur Verfügung gestellt (API: Get Weight Logs)
# -Sleep Daten der letzten Nacht werden ausgelesen (API: Get Sleep Logs by Date)
# -Die eigentlich statischen Daten (Name,Geburtsdatum, Geschlecht etc.) je Device werden alle 6 Stunden neu ausgelesen
# -Alle 6 Stunden wird nach neuen FRIEND, DEVICE, oder USER gesucht.
# -Error Meldungen im JSON werden erkannt und ausgegeben.
# -STATE per Reading state beschrieben.
package main;
use strict;
use warnings;
use HttpUtils;
use JSON;
use POSIX qw( strftime );
use Time::Local qw(timelocal);
use Digest::SHA qw(hmac_sha1_base64);
use Data::Dumper;
#ToDo: Per eval ausführen und Fehler abfangen + Fehlermeldung
sub fitbit_Initialize($) {
my ($hash) = @_;
Log3 "fitbit", 4, "fitbit: initialize";
$hash->{DefFn} = "fitbit_Define";
$hash->{SetFn} = "fitbit_Set";
#$hash->{GetFn} = "fitbit_Get";
#$hash->{NOTIFYDEV} = "global";
#$hash->{NotifyFn} = "fitbit_Notify";
$hash->{UndefFn} = "fitbit_Undefine";
$hash->{AttrFn} = "fitbit_Attr";
$hash->{AttrList} = "IODev ".
"disable:0,1 ".
"interval ".
"createFriends:0,1 ".
"createDevices:0,1 ";
$hash->{AttrList} .= $readingFnAttributes;
}
# Used by Subtype: ACCOUNT
sub fitbit_setWeight($$$) {
my ($hash, $weight, $withTime) = @_;
my $name = $hash->{NAME};
my $token = fitbit_decrypt( $hash->{helper}{token} );
Log3 $name, 5, "$name: fitbit_setWeight()";
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime();
$year = $year+1900;
$mon = $mon+1;
my $params = "weight=$weight&date=$year-$mon-$mday";
if ($withTime) {
$params.="&time=$hour:$min:$sec";
}
my $url = "https://api.fitbit.com/1/user/-/body/log/weight.json/";
Log3 $name, 4, "$name: fitbit_setWeight() - Sending data to fitbit web api.";
Log3 $name, 4, "FHEM -> fitbit URL: " . $url;
Log3 $name, 4, "FHEM -> fitbit Params: " . $params;
#ToDo: Nonblocking?!
my ($err,$data) = HttpUtils_BlockingGet({
url => $url,
timeout => 10,
noshutdown => 1,
data => $params,
method => 'POST',
header => {"Authorization" => 'Bearer '. $token, "Accept-Locale" => 'de_DE'},
});
Log3 $name, 4, "$name: fitbit_setWeight() - Received data from fitbit web api.";
Log3 $name, 4, "fitbit -> FHEM: " . $data;
Log3 $name, 5, '$err: ' . $err;
if (!defined($data)) {
return undef;
}
my $d = decode_json($data) if( !$err );
Log3 $name, 5, 'Decoded: ' . Dumper($d);
return $d->{weightLog}->{logId};
}
# Used by Subtype: ACCOUNT
sub fitbit_setFat($$$) {
my ($hash, $fat, $withTime) = @_;
my $name = $hash->{NAME};
my $token = fitbit_decrypt( $hash->{helper}{token} );
Log3 $name, 5, "$name: fitbit_setFat()";
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime();
$year = $year+1900;
$mon = $mon+1;
my $params = "fat=$fat&date=$year-$mon-$mday";
if ($withTime) {
$params.="&time=$hour:$min:$sec";
}
my $url = "https://api.fitbit.com/1/user/-/body/log/fat.json/";
Log3 $name, 4, "$name: fitbit_setFat() - Sending data to fitbit web api.";
Log3 $name, 4, "FHEM -> fitbit URL: " . $url;
Log3 $name, 4, "FHEM -> fitbit Params: " . $params;
#ToDo: Nonblocking?!
my ($err,$data) = HttpUtils_BlockingGet({
url => $url,
timeout => 10,
noshutdown => 1,
data => $params,
method => 'POST',
header => {"Authorization" => 'Bearer '. $token, "Accept-Locale" => 'de_DE'},
});
Log3 $name, 4, "$name: fitbit_setFat() - Received data from fitbit web api.";
Log3 $name, 4, "fitbit -> FHEM: " . $data;
Log3 $name, 5, '$err: ' . $err;
if (!defined($data)) {
return undef;
}
my $d = decode_json($data) if( !$err );
Log3 $name, 5, 'Decoded: ' . Dumper($d);
return $d->{fatLog}->{logId};
}
# Used by Subtype: ACCOUNT, DEVICE, USER, FRIEND
sub fitbit_Define($$) {
my ($hash, $def) = @_;
Log3 "fitbit", 3, "fitbit_Define() ".$def;
my @a = split("[ \t][ \t]*", $def);
my $subtype;
my $name = $a[0];
if( $a[2] eq "ACCOUNT" && @a == 4) {
Log3 $name, 4, "$name: Define an account";
my $tokenClear = $a[3];
$subtype = "ACCOUNT";
my $token = fitbit_encrypt($tokenClear);
Log3 $name, 3, "$name: encrypt $tokenClear to $token" if($tokenClear ne $token);
$hash->{DEF} = "ACCOUNT $token";
$hash->{Clients} = ":fitbit:";
$hash->{helper}{token} = $token;
}
else {
return "Usage: define <name> fitbit ACCOUNT <OAuth 2.0 token>" if(@a < 3 || @a > 4);
}
if( $a[2] eq "DEVICE" && @a == 4 ) {
Log3 $name, 4, "$name: Define an DEVICE";
$subtype = "DEVICE";
my $deviceID = $a[3];
$hash->{DEVICEID} = $deviceID;
my $d = $modules{$hash->{TYPE}}{defptr}{"D$deviceID"};
return "device $deviceID already defined as $d->{NAME}" if( defined($d) && $d->{NAME} ne $name );
$modules{$hash->{TYPE}}{defptr}{"D$deviceID"} = $hash;
}
else {
return "Usage: define <name> fitbit DEVICE <Device ID>" if(@a < 3 || @a > 4);
}
if( $a[2] eq "USER" && @a == 4 ) {
Log3 $name, 4, "$name: Define an USER";
$subtype = "USER";
my $userID = $a[3];
$hash->{USERID} = $userID;
readingsSingleUpdate($hash, "isFriend", "no", 1);
my $d = $modules{$hash->{TYPE}}{defptr}{"U$userID"};
return "device $userID already defined as $d->{NAME}" if( defined($d) && $d->{NAME} ne $name );
$modules{$hash->{TYPE}}{defptr}{"U$userID"} = $hash;
}
else {
return "Usage: define <name> fitbit USER <User ID>" if(@a < 3 || @a > 4);
}
if( $a[2] eq "FRIEND" && @a == 4 ) {
Log3 $name, 4, "$name: Define an FRIEND";
$subtype = "FRIEND";
my $userID = $a[3];
$hash->{USERID} = $userID;
readingsSingleUpdate($hash, "isFriend", "yes", 1);
my $d = $modules{$hash->{TYPE}}{defptr}{"F$userID"};
return "device $userID already defined as $d->{NAME}" if( defined($d) && $d->{NAME} ne $name );
$modules{$hash->{TYPE}}{defptr}{"F$userID"} = $hash;
}
else {
return "Usage: define <name> fitbit FRIEND <User ID>" if(@a < 3 || @a > 4);
}
$hash->{NAME} = $name;
$hash->{SUBTYPE} = $subtype;
if(!defined( fitbit_isDNS() )) {
Log3 $name, 3, "DNS Error";
readingsSingleUpdate($hash, "state", "DNS Error", 1);
InternalTimer( gettimeofday() + 900, "fitbit_InitWait", $hash, 0);
return undef;
}
readingsSingleUpdate($hash, "state", "Initialized", 1);
# is FHEM finished with initialize?
if( $init_done ) {
fitbit_initUser($hash, 0) if( $hash->{SUBTYPE} eq "USER" );
fitbit_initFriend($hash, 0) if( $hash->{SUBTYPE} eq "FRIEND" );
fitbit_connect($hash, 0) if( $hash->{SUBTYPE} eq "ACCOUNT" );
fitbit_initDevice($hash) if( $hash->{SUBTYPE} eq "DEVICE" );
}
else {
InternalTimer(gettimeofday()+15, "fitbit_InitWait", $hash, 0);
}
return undef;
}
sub fitbit_Get($$@) {
# my ($hash, $name, $cmd) = @_;
# my $list;
# if( $hash->{SUBTYPE} eq "USER" ) {
# $list = "update:noArg updateAll:noArg";
# if( $cmd eq "updateAll" ) {
# fitbit_poll($hash,2);
# return undef;
# }
# elsif( $cmd eq "update" ) {
# fitbit_poll($hash,1);
# return undef;
# }
# } elsif( $hash->{SUBTYPE} eq "DEVICE" || $hash->{SUBTYPE} eq "DUMMY" ) {
# $list = "update:noArg updateAll:noArg";
# $list .= " videoLink:noArg" if(defined($hash->{modelID}) && $hash->{modelID} eq '21');
# $list .= " videoCredentials:noArg" if(defined($hash->{modelID}) && $hash->{modelID} eq '22');
# $list .= " settings:noArg" if(defined($hash->{modelID}) && $hash->{modelID} eq '60' && AttrVal($name,"IP",undef));
# if( $cmd eq "videoCredentials" ) {
# my $credentials = fitbit_getS3Credentials($hash);
# return undef;
# }
# elsif( $cmd eq "videoLink" ) {
# my $ret = "Flash Player Links:\n";
# my $videolinkdata = fitbit_getVideoLink($hash);
# if(defined($videolinkdata->{body}{device}))
# {
# #$hash->{videolink_ext} = "http://fpdownload.adobe.com/strobe/FlashMediaPlayback_101.swf?streamType=live&autoPlay=true&playButtonOverlay=false&src=rtmp://".$videolinkdata->{body}{device}{proxy_ip}.":".$videolinkdata->{body}{device}{proxy_port}."/".$videolinkdata->{body}{device}{kp_hash}."/";
# #$hash->{videolink_int} = "http://fpdownload.adobe.com/strobe/FlashMediaPlayback_101.swf?streamType=live&autoPlay=true&playButtonOverlay=false&src=rtmp://".$videolinkdata->{body}{device}{private_ip}.":".$videolinkdata->{body}{device}{proxy_port}."/".$videolinkdata->{body}{device}{kd_hash}."/";
# $ret .= " <a href='".$hash->{videolink_ext}."'>Play video from internet (Flash)</a>\n";
# $ret .= " <a href='".$hash->{videolink_int}."'>Play video from local network (Flash)</a>\n";
# }
# else
# {
# $ret .= " no links available";
# }
# return $ret;
# }
# elsif( $cmd eq "updateAll" ) {
# fitbit_poll($hash,2);
# return undef;
# }
# elsif( $cmd eq "update" ) {
# fitbit_poll($hash,1);
# return undef;
# }
# elsif( $cmd eq "settings" ) {
# fitbit_readAuraAlarm($hash);
# return undef;
# }
# } elsif( $hash->{SUBTYPE} eq "ACCOUNT" ) {
# $list = "users:noArg devices:noArg showAccount:noArg";
# if( $cmd eq "users" ) {
# my $users = fitbit_getUsers($hash);
# my $ret;
# foreach my $user (@{$users}) {
# $ret .= "$user->{id}\t\[$user->{shortname}\]\t$user->{publickey}\t$user->{firstname} $user->{lastname}\n";
# }
# $ret = "id\tshort\tpublickey\t\tname\n" . $ret if( $ret );;
# $ret = "no users found" if( !$ret );
# return $ret;
# }
# if( $cmd eq "devices" ) {
# my $devices = fitbit_getDevices($hash);
# my $ret;
# foreach my $device (@{$devices}) {
# my $detail = $device->{deviceproperties};
# $ret .= "$detail->{id}\t$device_types{$detail->{type}}\t$detail->{batterylvl}\t$detail->{sn}\n";
# }
# $ret = "id\ttype\t\tbattery\tSN\n" . $ret if( $ret );;
# $ret = "no devices found" if( !$ret );
# return $ret;
# }
# if( $cmd eq 'showAccount' )
# {
# my $username = $hash->{helper}{username};
# my $password = $hash->{helper}{password};
# return 'no username set' if( !$username );
# return 'no password set' if( !$password );
# $username = fitbit_decrypt( $username );
# $password = fitbit_decrypt( $password );
# return "username: $username\npassword: $password";
# }
# }
# return "Unknown argument $cmd, choose one of $list";
}
sub fitbit_Set($$@) {
my ( $hash, $name, $cmd, @arg ) = @_;
my $list="";
Log3 $name, 4, "$name fitbit_Set()";
if( $hash->{SUBTYPE} eq "ACCOUNT") {
$list = "getFriends:noArg setWeight setFat setWeight_WithTime setFat_WithTime";
if($cmd eq "getFriends") {
#Add friends
if( !defined( $attr{$name}{createFriends} ) || $attr{$name}{createFriends} eq '0' ) {
return 'Cannot get friends. Please set attribute createFriends to 1 before executing function.';
}
my $friends = fitbit_getFriends($hash);
Log3 $name, 5, "$name: fitbit_Set JSON Dump ".Dumper($friends);
foreach my $friend (@{$friends}) {
Log3 $name, 5, "$name: fitbit_Set JSON Dump foreach ".Dumper($friend);
if( defined($modules{$hash->{TYPE}}{defptr}{"F$friend->{user}->{encodedId}"}) ) {
Log3 $name, 2, "$name: friend '$friend->{user}->{encodedId}' already defined";
next;
}
my $id = $friend->{user}->{encodedId};
my $devname = "fitbit_F". $id;
my $define= "$devname fitbit FRIEND $id";
Log3 $name, 2, "$name: create new device '$devname' for friend '$id' $friend->{user}->{displayName}";
my $cmdret= CommandDefine(undef,$define);
if($cmdret) {
Log3 $name, 1, "$name: Autocreate: An error occurred while creating user for id '$id': $cmdret";
} else {
$cmdret= CommandAttr(undef,"$devname alias ".$friend->{user}->{displayName});
$cmdret= CommandAttr(undef,"$devname IODev $name");
}
}
}
if($cmd eq "setWeight_WithTime") {
return "logged weight data with log-id " . fitbit_setWeight($hash, $arg[0], 1);
}
if($cmd eq "setFat_WithTime") {
return "logged fat data with log-id " . fitbit_setFat($hash, $arg[0], 1);
}
if($cmd eq "setWeight") {
return "logged weight data with log-id " . fitbit_setWeight($hash, $arg[0], 0);
}
if($cmd eq "setFat") {
return "logged fat data with log-id " . fitbit_setFat($hash, $arg[0], 0);
}
else {
return "Unknown argument $cmd, choose one of $list";
}
}
elsif( $hash->{SUBTYPE} eq "USER") {
}
elsif( $hash->{SUBTYPE} eq "FRIEND") {
}
elsif( $hash->{SUBTYPE} eq "DEVICE") {
}
else {
}
}
#Used by Subtype: ACCOUNT, USER, DEVICE, FRIEND
sub fitbit_Attr($$$) {
my ($cmd, $name, $attrName, $attrVal) = @_;
Log3 $name, 4, "fitbit_Attr()";
return undef if(!defined($defs{$name}));
my $orig = $attrVal;
$attrVal = int($attrVal) if($attrName eq "interval");
#comment out for debug interval < 300 seconds...
#$attrVal = 300 if($attrName eq "interval" && $attrVal < 300 );
if( $attrName eq "disable" ) {
my $hash = $defs{$name};
RemoveInternalTimer($hash);
if( $cmd eq "set" && $attrVal ne "0" ) {
} else {
$attr{$name}{$attrName} = 0;
fitbit_poll($hash,0);
}
}
if( $cmd eq "set" ) {
if( $orig ne $attrVal ) {
$attr{$name}{$attrName} = $attrVal;
return $attrName ." set to ". $attrVal;
}
}
return;
}
sub fitbit_Notify($$) {
# my ($hash,$dev) = @_;
# return if($dev->{NAME} ne "global");
# return if(!grep(m/^INITIALIZED|REREADCFG$/, @{$dev->{CHANGED}}));
# Log3 "fitbit", 5, "fitbit: notify";
# my $resolve = inet_aton("healthmate.withings.com");
# if(!defined($resolve))
# {
# $hash->{STATE} = "DNS error";
# InternalTimer( gettimeofday() + 3600, "fitbit_InitWait", $hash, 0);
# return undef;
# }
# fitbit_initUser($hash, 0) if( $hash->{SUBTYPE} eq "USER" );
# fitbit_connect($hash) if( $hash->{SUBTYPE} eq "ACCOUNT" );
# fitbit_initDevice($hash) if( $hash->{SUBTYPE} eq "DEVICE" );
}
# Used by Subtype: ACCOUNT, DEVICE, USER
sub fitbit_Undefine($$) {
my ($hash, $arg) = @_;
Log3 "fitbit", 4, "fitbit: undefine";
RemoveInternalTimer($hash);
delete( $modules{$hash->{TYPE}}{defptr}{"U$hash->{USERID}"} ) if( $hash->{SUBTYPE} eq "USER" );
delete( $modules{$hash->{TYPE}}{defptr}{"F$hash->{USERID}"} ) if( $hash->{SUBTYPE} eq "FRIEND" );
delete( $modules{$hash->{TYPE}}{defptr}{"D$hash->{DEVICEID}"} ) if( $hash->{SUBTYPE} eq "DEVICE" );
return undef;
}
# Used by Subtype: ACCOUNT, DEVICE, USER
sub fitbit_isDNS() {
Log3 "fitbit", 4, "fitbit_isDNS()";
my $resolve = inet_aton("www.fitbit.com");
if(!defined($resolve))
{
Log3 "fitbit", 1, "fitbit_isDNS(): Failed to resolve www.fitbit.com";
return undef;
}
$resolve = inet_aton("api.fitbit.com");
if(!defined($resolve))
{
Log3 "fitbit", 1, "fitbit_isDNS(): Failed to resolve api.fitbit.com";
return undef;
}
return "ok";
}
# Used by Subtype: ACCOUNT, DEVICE, USER
sub fitbit_InitWait($) {
my ($hash) = @_;
Log3 $hash->{NAME}, 4, "$hash->{NAME}: fitbit_InitWait()";
RemoveInternalTimer($hash, "fitbit_InitWait");
if(!defined( fitbit_isDNS() )) {
readingsSingleUpdate($hash, "state", "DNS Error", 1);
InternalTimer( gettimeofday() + 1800, "fitbit_InitWait", $hash, 0);
return undef;
}
if( $init_done ) {
Log3 "fitbit", 5, "fitbit: Init done";
fitbit_initUser($hash, 0) if( $hash->{SUBTYPE} eq "USER" );
fitbit_initFriend($hash, 0) if( $hash->{SUBTYPE} eq "FRIEND" );
fitbit_connect($hash, 0) if( $hash->{SUBTYPE} eq "ACCOUNT" );
fitbit_initDevice($hash) if( $hash->{SUBTYPE} eq "DEVICE" );
}
else {
Log3 "fitbit", 5, "fitbit: Init NOT done";
InternalTimer(gettimeofday()+30, "fitbit_InitWait", $hash, 0);
}
return undef;
}
# Used by Subtype: ACCOUNT
sub fitbit_connect($;$) {
my ($hash, $silent) = @_;
my $name = $hash->{NAME};
$silent = 1 if(!defined($silent)); #if InternalTimer calls this function, silent is NOT set. Don't print IODev Msg...
Log3 $name, 4, "$name: fitbit_connect()";
foreach my $d (keys %defs) {
next if(!defined($defs{$d}));
next if($defs{$d}{TYPE} ne "autocreate");
return undef if(AttrVal($defs{$d}{NAME},"disable",undef));
}
my $autocreated = 0;
#add user
my $users = fitbit_getUsers($hash);
foreach my $user (@{$users}) {
readingsSingleUpdate( $hash, "state", "API ok", 1);
if( defined($modules{$hash->{TYPE}}{defptr}{"U$user->{encodedId}"}) ) {
Log3 $name, ($silent == 0?2:4), "$name: user '$user->{encodedId}' already defined";
next;
}
my $id = $user->{encodedId};
my $devname = "fitbit_U". $id;
my $define= "$devname fitbit USER $id";
Log3 $name, 2, "$name: create new device '$devname' for user '$id' $user->{displayName}";
my $cmdret= CommandDefine(undef,$define);
if($cmdret) {
Log3 $name, 1, "$name: Autocreate: An error occurred while creating user for id '$id': $cmdret";
} else {
$cmdret= CommandAttr(undef,"$devname alias ".$user->{displayName});
$cmdret= CommandAttr(undef,"$devname room fitbit");
$cmdret= CommandAttr(undef,"$devname IODev $name");
fhem("setreading $devname isFriend no", 1);
$autocreated++;
}
}
#Add friends
my $friends = fitbit_getFriends($hash);
Log3 $name, 5, "$name: fitbit_connect JSON Dump ".Dumper($friends);
foreach my $friend (@{$friends}) {
Log3 $name, 5, "$name: fitbit_connect JSON Dump foreach ".Dumper($friend);
if( defined($modules{$hash->{TYPE}}{defptr}{"F$friend->{user}->{encodedId}"}) ) {
Log3 $name, ($silent == 0?2:4), "$name: friend '$friend->{user}->{encodedId}' already defined";
next;
}
my $id = $friend->{user}->{encodedId};
my $devname = "fitbit_F". $id;
my $define= "$devname fitbit FRIEND $id";
Log3 $name, 2, "$name: create new device '$devname' for friend '$id' $friend->{user}->{displayName}";
my $cmdret= CommandDefine(undef,$define);
if($cmdret) {
Log3 $name, 1, "$name: Autocreate: An error occurred while creating user for id '$id': $cmdret";
} else {
$cmdret= CommandAttr(undef,"$devname alias ".$friend->{user}->{displayName});
$cmdret= CommandAttr(undef,"$devname room fitbit");
$cmdret= CommandAttr(undef,"$devname IODev $name");
$autocreated++;
}
}
#add devices
my $devices = fitbit_getDevices($hash);
foreach my $device (@{$devices}) {
if( defined($modules{$hash->{TYPE}}{defptr}{"D$device->{id}"}) ) {
Log3 $name, ($silent == 0?2:4), "$name: device '$device->{id}' already defined";
next;
}
next if( !defined($device->{id}) );
my $id = $device->{id};
my $devname = "fitbit_D". $id;
my $define= "$devname fitbit DEVICE $id";
Log3 $name, 2, "$name: create new device '$devname' for deviceID '$id' $device->{type} $device->{deviceVersion}";
my $cmdret= CommandDefine(undef,$define);
if($cmdret) {
Log3 $name, 1, "$name: Autocreate: An error occurred while creating device for id '$id': $cmdret";
} else {
$cmdret= CommandAttr(undef,"$devname alias $device->{type} $device->{deviceVersion}");
$cmdret= CommandAttr(undef,"$devname room fitbit");
$cmdret= CommandAttr(undef,"$devname IODev $name");
$autocreated++;
}
}
CommandSave(undef,undef) if( $autocreated && AttrVal( "autocreate", "autosave", 1 ) );
RemoveInternalTimer($hash, "fitbit_connect");
InternalTimer(gettimeofday()+(6*60*60), "fitbit_connect", $hash, 0); #every 6 hours
}
sub fitbit_autocreate($) {
# my ($hash) = @_;
# my $name = $hash->{NAME};
# Log3 "fitbit", 5, "$name: autocreate";
# $hash->{'.https'} = "https";
# $hash->{'.https'} = "http" if( AttrVal($name, "nossl", 0) );
# fitbit_getSessionKey( $hash );
# my $autocreated = 0;
# my $users = fitbit_getUsers($hash);
# foreach my $user (@{$users}) {
# if( defined($modules{$hash->{TYPE}}{defptr}{"U$user->{id}"}) ) {
# Log3 $name, 2, "$name: user '$user->{id}' already defined";
# next;
# }
# next if($user->{firstname} eq "Repository-User");
# my $id = $user->{id};
# my $devname = "fitbit_U". $id;
# my $define= "$devname fitbit $id $user->{publickey}";
# Log3 $name, 2, "$name: create new device '$devname' for user '$id'";
# my $cmdret= CommandDefine(undef,$define);
# if($cmdret) {
# Log3 $name, 1, "$name: Autocreate: An error occurred while creating device for id '$id': $cmdret";
# } else {
# $cmdret= CommandAttr(undef,"$devname alias ".$user->{shortname});
# $cmdret= CommandAttr(undef,"$devname IODev $name");
# $cmdret= CommandAttr(undef,"$devname room fitbit");
# $autocreated++;
# }
# }
# my $devices = fitbit_getDevices($hash);
# foreach my $device (@{$devices}) {
# if( defined($modules{$hash->{TYPE}}{defptr}{"D$device->{deviceid}"}) ) {
# my $d = $modules{$hash->{TYPE}}{defptr}{"D$device->{deviceid}"};
# $d->{association} = $device->{association} if($device->{association});
# Log3 $name, 2, "$name: device '$device->{deviceid}' already defined";
# next;
# }
# my $detail = $device->{deviceproperties};
# next if( !defined($detail->{id}) );
# my $id = $detail->{id};
# my $devname = "fitbit_D". $id;
# my $define= "$devname fitbit $id";
# Log3 $name, 2, "$name: create new device '$devname' for device '$id'";
# my $cmdret= CommandDefine(undef,$define);
# if($cmdret) {
# Log3 $name, 1, "$name: Autocreate: An error occurred while creating device for id '$id': $cmdret";
# } else {
# $cmdret= CommandAttr(undef,"$devname alias ".$device_types{$detail->{type}}) if( defined($device_types{$detail->{type}}) );
# $cmdret= CommandAttr(undef,"$devname alias ".$device_models{$detail->{type}}->{$detail->{model}}) if( defined($device_models{$detail->{type}}) && defined($device_models{$detail->{type}}->{$detail->{model}}) );
# $cmdret= CommandAttr(undef,"$devname IODev $name");
# $cmdret= CommandAttr(undef,"$devname room fitbit");
# $autocreated++;
# }
# }
# CommandSave(undef,undef) if( $autocreated && AttrVal( "autocreate", "autosave", 1 ) );
}
# Used by Subtype: DEVICE
# Called from: fitbit_Define. fitbit_InitWait
sub fitbit_initDevice($) {
my ($hash) = @_;
my $name = $hash->{NAME};
Log3 $name, 4, "$name: fitbit_initDevice() ".$hash->{DEVICEID};
AssignIoPort($hash);
if(defined($hash->{IODev}->{NAME})) {
Log3 $name, 2, "$name: I/O device is " . $hash->{IODev}->{NAME};
} else {
Log3 $name, 1, "$name: no I/O device";
}
my $device = fitbit_getDeviceDetail( $hash );
Log3 $name, 5, "$name: InitDevice DeviceDetails: ".Dumper($device);
$hash->{DEVICEVERSION} = $device->[0]->{deviceVersion};
$hash->{FITBIT_TYPE} = $device->[0]->{type};
$hash->{DEVICEID} = $device->[0]->{id};
$hash->{MAC} = $device->[0]->{mac};
$hash->{DeviceType} = $device->[0]->{type};
readingsBeginUpdate($hash);
readingsBulkUpdateIfChanged( $hash, "lastSyncTime", $device->[0]->{lastSyncTime}, 1 );
readingsBulkUpdateIfChanged( $hash, "batteryLevel", lc($device->[0]->{battery}), 1 );
readingsBulkUpdateIfChanged( $hash, "state", "API ok");
readingsEndUpdate($hash,1);
if( !defined( $attr{$name}{stateFormat} ) ) {
$attr{$name}{stateFormat} = "Batt. batteryLevel";
}
readingsSingleUpdate($hash, "state", "API ok", 1);
InternalTimer(gettimeofday()+10, "fitbit_poll", $hash, 0);
}
# Used by Subtype: FRIEND
sub fitbit_initFriend($;$) {
my ($hash, $silent) = @_;
$silent = 1 if(!defined($silent)); #if InternalTimer calls this function, silent is NOT set. Don't print IODev Msg...
my $name = $hash->{NAME};
Log3 $name, 4, "$name: fitbit_initFriend() $hash->{USERID} silent='$silent'";
AssignIoPort($hash);
if(defined($hash->{IODev}->{NAME})) {
Log3 $name, ($silent == 0?2:4), "$name: I/O device is " . $hash->{IODev}->{NAME};
} else {
Log3 $name, 1, "$name: no I/O device";
}
my $user = fitbit_getFriendDetail( $hash );
Log3 $name, 5, "$name: fitbit_initFriend JSON Dump: ".Dumper($user);
readingsBeginUpdate($hash);
readingsBulkUpdateIfChanged( $hash, "displayName", $user->{displayName}, 1 );
readingsBulkUpdateIfChanged( $hash, "gender", $user->{gender}, 1 );
readingsBulkUpdateIfChanged( $hash, "fullName", $user->{fullName}, 1 );
readingsBulkUpdateIfChanged( $hash, "dateOfBirth", $user->{dateOfBirth}, 1 );
readingsBulkUpdateIfChanged( $hash, "weight", $user->{weight}, 1 ) if($user->{weight} > 0);
readingsBulkUpdateIfChanged( $hash, "state", "API ok");
readingsEndUpdate($hash,1);
$attr{$name}{stateFormat} = "weight kg" if( !defined( $attr{$name}{stateFormat} ) );
#ToDo: stateFormat anpassen an Daten, die auch voprhanden sind.
readingsSingleUpdate($hash, "state", "API ok", 1);
InternalTimer(gettimeofday()+10, "fitbit_poll", $hash, 0);
RemoveInternalTimer($hash, "fitbit_initFriend");
InternalTimer(gettimeofday()+(6*60*60), "fitbit_initFriend", $hash, 0); #every 6 hours
}
# Used by Subtype: USER
sub fitbit_initUser($;$) {
my ($hash, $silent) = @_;
my $name = $hash->{NAME};
$silent = 1 if(!defined($silent)); #if InternalTimer calls this function, silent is NOT set. Don't print IODev Msg...
Log3 $name, 4, "$name: fitbit_initUser() $hash->{USERID} silent='$silent'";
AssignIoPort($hash);
if(defined($hash->{IODev}->{NAME})) {
Log3 $name, ($silent == 0?2:4), "$name: I/O device is " . $hash->{IODev}->{NAME};
} else {
Log3 $name, 1, "$name: no I/O device";
}
my $user = fitbit_getUserDetail( $hash );
Log3 $name, 5, "$name: fitbit_initUser UserDetails: ".Dumper($user);
readingsBeginUpdate($hash);
readingsBulkUpdateIfChanged( $hash, "displayName", $user->{displayName}, 1 );
readingsBulkUpdateIfChanged( $hash, "gender", $user->{gender}, 1 );
readingsBulkUpdateIfChanged( $hash, "fullName", $user->{fullName}, 1 );
readingsBulkUpdateIfChanged( $hash, "dateOfBirth", $user->{dateOfBirth}, 1 );
readingsBulkUpdateIfChanged( $hash, "memberSince", $user->{memberSince}, 1 );
readingsBulkUpdateIfChanged( $hash, "weight", $user->{weight}, 1 ) if ($user->{weight} > 0);
readingsBulkUpdateIfChanged( $hash, "state", "API ok");
readingsEndUpdate($hash,1);
$attr{$name}{stateFormat} .= "weight kg" if( !defined( $attr{$name}{stateFormat} ) && defined($user->{weight}) && $user->{weight} > 0 );
#ToDO: stateFormat anpassen. weight und Steps nur dann, wenn Daten vorhanden sind.
readingsSingleUpdate($hash, "state", "API ok", 1);
InternalTimer(gettimeofday()+10, "fitbit_poll", $hash, 0);
RemoveInternalTimer($hash, "fitbit_initUser");
InternalTimer(gettimeofday()+(6*60*60), "fitbit_initUser", $hash, 0); #every 6 hours
}
# Used by Subtype: ACCOUNT
sub fitbit_getFriends($) {
my ($hash) = @_;
my $name = $hash->{NAME};
if( !defined( $attr{$name}{createFriends} ) || $attr{$name}{createFriends} eq '0' ) {
Log3 $name, 4, "$name: fitbit_getFriends Skipped loading friends as attribute 'createFriends' is not set or set to 0";
return undef;
}
my $token = fitbit_decrypt( $hash->{helper}{token} );
Log3 $name, 4, "$name: fitbit_getFriends()";
#ToDo: Nonblocking?!
my ($err,$data) = HttpUtils_BlockingGet({
url => "https://api.fitbit.com/1/user/-/friends.json",
timeout => 10,
noshutdown => 1,
header => {"Authorization" => 'Bearer '. $token, "Accept-Locale" => 'de_DE'},
});
return undef if(!defined($data));
#simulate JSON example
#$data = '{"friends":[{"user":{"aboutMe":"I live in San Francisco.","avatar":"http://www.fitbit.com/images/profile/defaultProfile_100_male.gif","city":"San Francisco","country":"US","dateOfBirth":"1970-02-18","displayName":"Nick","encodedId":"257V3V","fullName":"Fitbit","gender":"MALE","height":176.7,"offsetFromUTCMillis":25200000,"state":"CA","strideLengthRunning":0,"strideLengthWalking":0,"timezone":"America/Los_Angeles","weight":80.5}},{"user":{"aboutMe":"","avatar":"http://www.fitbit.com/images/profile/defaultProfile_100_male.gif","city":"","country":"","dateOfBirth":"","displayName":"Fitbit U.","encodedId":"2246K9","fullName":"Fitbit User","gender":"NA","height":190.7,"offsetFromUTCMillis":14400000,"state":"","strideLengthRunning":0,"strideLengthWalking":0,"timezone":"Europe/Moscow","weight":0}}]}';
my $json = eval { JSON->new->utf8(0)->decode($data) };
if($@)
{
Log3 $name, 2, "$name: json evaluation error on fitbit_getFriends ".$@;
return undef;
}
Log3 $name, 5, "$name: fitbit_getFriends JSON Dump ".Dumper($json);
return undef if(defined(fitbit_parseJsonForError($hash, $json)));
my @users = ();
foreach my $user (@{$json->{friends}}) {
#Log3 $name, 5, "$name: fitbit_getFriends JSON Dump foreach ".Dumper($user);
#Log3 $name, 5, "$name: fitbit_getFriends JSON Test $user->{user}->{displayName}";
next if( !defined($user->{user}->{encodedId}) );
push( @users, $user );
}
Log3 $name, 5, "$name: fitbit_getFriends Dump ".Dumper(@users);
return \@users;
}
# Used by Subtype: ACCOUNT
sub fitbit_getUsers($) {
my ($hash) = @_;
my $name = $hash->{NAME};
my $token = fitbit_decrypt( $hash->{helper}{token} );
Log3 $name, 4, "$name: fitbit_getUsers()";
#ToDo: Nonblocking?!
my ($err,$data) = HttpUtils_BlockingGet({
url => "https://api.fitbit.com/1/user/-/profile.json",
timeout => 10,
noshutdown => 1,
header => {"Authorization" => 'Bearer '. $token, "Accept-Locale" => 'de_DE'},
});
return undef if(!defined($data));
my $json = eval { JSON->new->utf8(0)->decode($data) };
if($@) {
Log3 $name, 2, "$name: json evaluation error on getUsers ".$@;
return undef;
}
Log3 $name, 5, "$name: getUsers JSON Dump ".Dumper($json);
#xToDo: Fehlerabfangen, wenn Fitbit API mit Error antwortet!
return undef if(defined(fitbit_parseJsonForError($hash, $json)));
my @users = ();
foreach my $user ($json->{user}) {
next if( !defined($user->{encodedId}) );
push( @users, $user );
}
return \@users;
}
# Used by Subtype: ACCOUNT
sub fitbit_getDevices($) {
my ($hash) = @_;
my $name = $hash->{NAME};
if( defined( $attr{$name}{createDevices} ) && $attr{$name}{createDevices} eq '0' ) {
Log3 $name, 4, "$name: fitbit_getDevices Skipped loading devices as attribute 'createDevices' is set to 0";
return undef;
}
my $token = fitbit_decrypt( $hash->{helper}{token} );
Log3 $name, 4, "$name: fitbit_getDevices()";
#ToDo: Nonblocking?
my ($err,$data) = HttpUtils_BlockingGet({
url => "https://api.fitbit.com/1/user/-/devices.json",
timeout => 10,
noshutdown => 1,
header => {"Authorization" => 'Bearer '. $token, "Accept-Locale" => 'de_DE'},
});
return undef if(!defined($data));
my $json = eval { JSON->new->utf8(0)->decode($data) };
if($@) {
Log3 $name, 2, "$name: json evaluation error on getDevices ".$@;
return undef;
}
Log3 $name, 5, "$name: fitbit_getDevices JSON Dump ".Dumper($json);
#xToDo: Fehlerabfangen, wenn Fitbit API mit Error antwortet!
return undef if(defined(fitbit_parseJsonForError($hash, $json)));
my @devices = ();
foreach my $item (@$json) {
next if( !defined($item->{id}) );
push( @devices, $item );
}
return \@devices;
}