This repository has been archived by the owner on Sep 28, 2023. It is now read-only.
forked from thdankert/somfy-rts-fhem
-
Notifications
You must be signed in to change notification settings - Fork 0
/
10_SOMFY.pm
1918 lines (1550 loc) · 60.8 KB
/
10_SOMFY.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
##############################################################################
#
# 10_SOMFY.pm
#
# This file is part of Fhem.
#
# Fhem is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# Fhem is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Fhem. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
#
# $Id: 10_SOMFY.pm 62209 2019-08-10 13:10:00Z viegener $
#
# SOMFY RTS / Simu Hz protocol module for FHEM
# (c) Thomas Dankert <post@thomyd.de>
# (c) Johannes Viegener / https://github.com/viegener/Telegram-fhem/tree/master/Somfy
#
# Discussed in FHEM Forum: https://forum.fhem.de/index.php/topic,53319.msg450080.html#msg450080
#
##############################################################################
# History:
# 1.0 thomyd initial implementation
# 1.1 Elektrolurch state changed to open,close,pos <x>
# 1.2 Elektrolurch state is now set after reaching the position of the blind
# 1.3 thomyd Basic implementation of "parse" function, requires updated CULFW
# 1.4 thomyd Implemented fallback on/off-for-timer methods and only show warning about stop/go-my if the positioning attributes are set.
# 1.5 thomyd Bugfix for wrong attribute names when calculating the updatetime (drive-up-...)
# 1.6 viegener New state and action handling (trying to stay compatible also adding virtual receiver capabilities)
# 2016-12-30 viegener - New sets / code-commands 9 / a - wind_sun_9 / wind_only_a
# 2017-01-08 viegener - Handle fixed encryption A0 for switches - switchable fixed_enckey
# 2017-01-21 viegener - updatestate also called in non virtual mode to sent events
# 2017-02-19 viegener - Restructuring of method blocks
######################################################
#
# 1.9 Prep for rebuilt and signalduino
# - myUtilsSOMFY_Initialize removed
# - SOMFY_StartTime removed
# - prepare: restructure code
# - clean up history
# - modify of definition to replace attr handling for enc and rolling_code
# - remove attribute for enc_key and rollingcode
# - cleanup namings of globals
# - set default model as attribute to shutter
# - support different settings for different models
# - rawDevice attr
# - parse function calls dispatcher for rawDevices on remotes
# - changed errors in parseFn to log
# - some doc cleanup
# - remove dummy attribute
# - special cases for pos to avoid mypos being used since stop signal is sent after automatic stop
#
# - changed Ys format only . no 0
# - doc rework on set commands
# - allow define with encryption key without starting with A
# - added manual function for setting position manually without movement commands
#
# - remove any postfiy on position setting (like 50 pct)
# - allow set command position
# 2.0 Update for official version to allow further rework and Alexa handling
# - change log entries and remove debug in _Parse
# - added back parsestate temporarily - #msg743423
# - new attributes disable/disabledForIntervals
# - disabled will be honored - no updates/no sending/no received commands
#
###############################################################################
#
#
###############################################################################
###############################################################################
# Somfy Modul - OPEN
###############################################################################
#
# - Add disable functionality
# -
# - Doc rework on model, set commands, rawDevice, coupling remotes
# -
# - test parseFn / Remotes
# -
# - send also wind/sun sensor codes with code E and constant rolling code --> allow complete raw send (just address is added)
# -
# - Check readings set
# - add queuing for commands
# - Autocreate
# - Complete shutter / blind as different model
# - Make better distinction between different IoTypes - CUL+SCC / Signalduino
# - Known Issue - if timer is running and last command equals new command (only for open / close) - considered minor/but still relevant
# -
# - switch to standard 100 to 0 position
#
###############################################################################
#
# Idea rebuilt handling from scratch
#
#
#
###############################################################################
package main;
use strict;
use warnings;
#use List::Util qw(first max maxstr min minstr reduce shuffle sum);
my %somfy_codes = (
"10" => "go-my", # goto "my" position
"11" => "stop", # stop the current movement
"20" => "off", # go "up"
"40" => "on", # go "down"
"80" => "prog", # finish pairing
"90" => "wind_sun_9", # wind and sun (sun + flag)
"A0" => "wind_only_a", # wind only (flag)
"100" => "on-for-timer",
"101" => "off-for-timer",
"XX" => "z_custom", # custom control code
);
my %somfy_sets = (
"off" => "noArg",
"on" => "noArg",
"stop" => "noArg",
"prog" => "noArg",
"on-for-timer" => "textField",
"off-for-timer" => "textField",
"z_custom" => "textField",
);
my %somfy_sets_addition = (
"go-my" => "noArg",
"pos" => "100,90,80,70,60,50,40,30,20,10,0",
"position" => "100,90,80,70,60,50,40,30,20,10,0",
"manual" => "200,100,90,80,70,60,50,40,30,20,10,0,on,off",
"wind_sun_9" => "noArg",
"wind_only_a" => "noArg",
);
my %somfy_sendCommands = (
"open" => "off",
"close" => "on",
);
my %somfy_c2b;
my $somfy_defsymbolwidth = 1240; # Default Somfy frame symbol width
my $somfy_defrepetition = 6; # Default Somfy frame repeat counter
my $somfy_updateFreq = 3; # Interval for State update
######################################################
######################################################
##################################################
# new globals for new set
#
my $somfy_posAccuracy = 2;
my $somfy_maxRuntime = 50;
my %positions = (
"moving" => "50",
"go-my" => "50",
"open" => "0",
"off" => "0",
"down" => "150",
"closed" => "200",
"on" => "200"
);
my %translations = (
"0" => "open",
"150" => "down",
"200" => "closed"
);
my %translations100To0 = (
"100" => "open",
"10" => "down",
"0" => "closed"
);
##################################################
# Forward declarations
#
sub SOMFY_CalcCurrentPos($$$$);
sub SOMFY_isSwitch($);
sub SOMFY_SendCommand($@);
######################################################
######################################################
##############################################################################
##############################################################################
##
## Module operation - type + instance
##
##############################################################################
##############################################################################
#############################
sub SOMFY_Initialize($) {
my ($hash) = @_;
# map commands from web interface to codes used in Somfy RTS
foreach my $k ( keys %somfy_codes ) {
$somfy_c2b{ $somfy_codes{$k} } = $k;
}
# YsKKC0RRRRAAAAAA
# $hash->{Match} = "^Ys...0..........\$";
$hash->{Match} = "^Ys..............\$";
$hash->{SetFn} = "SOMFY_Set";
#$hash->{StateFn} = "SOMFY_SetState";
$hash->{DefFn} = "SOMFY_Define";
$hash->{UndefFn} = "SOMFY_Undef";
$hash->{ParseFn} = "SOMFY_Parse";
$hash->{AttrFn} = "SOMFY_Attr";
$hash->{AttrList} = " drive-down-time-to-100"
. " drive-down-time-to-close"
. " drive-up-time-to-100"
. " drive-up-time-to-open "
. " additionalPosReading "
. " positionInverse:1,0 "
. " IODev"
. " symbol-length"
. " repetition"
. " switch_rfmode:1,0"
. " fixed_enckey:1,0"
. " do_not_notify:1,0"
. " ignore:0,1"
. " disable:0,1"
. " disabledForIntervals "
. " model:somfyblinds,somfyshutter,somfyremote,somfyswitch2,somfyswitch4"
. " loglevel:0,1,2,3,4,5,6"
. " rawDevice"
. " $readingFnAttributes";
}
#############################
sub SOMFY_Define($$) {
my ( $hash, $def ) = @_;
my @a = split( "[ \t][ \t]*", $def );
my $u = "wrong syntax: define <name> SOMFY address "
. "[encryption-key] [rolling-code]";
# fail early and display syntax help
if ( int(@a) < 3 ) {
return $u;
}
# check address format (6 hex digits)
if ( ( $a[2] !~ m/^[a-fA-F0-9]{6}$/i ) ) {
return "Define $a[0]: wrong address format: specify a 6 digit hex value "
}
# group devices by their address
my $name = $a[0];
my $address = $a[2];
$hash->{ADDRESS} = uc($address);
# set default model if not yet set
if ( ! defined( $attr{$name}{model} ) ) {
$attr{$name}{model} = "somfyshutter";
}
# check optional arguments for device definition
if ( int(@a) > 3 ) {
# check encryption key (2 hex digits, first must be "A")
if ( ( $a[3] !~ m/^[a-fA-F0-9]{2}$/i ) ) {
return "Define $a[0]: wrong encryption key format:"
. "specify a 2 digits hex value "
}
# reset reading time on def to 0 seconds (1970)
my $tzero = FmtDateTime(0);
# store it as reading, so it is saved in the statefile
# only store it, if the reading does not exist yet
# if(! defined( ReadingsVal($name, "enc_key", undef) )) {
setReadingsVal($hash, "enc_key", uc($a[3]), $tzero);
# }
if ( int(@a) == 5 ) {
# check rolling code (4 hex digits)
if ( ( $a[4] !~ m/^[a-fA-F0-9]{4}$/i ) ) {
return "Define $a[0]: wrong rolling code format:"
. "specify a 4 digits hex value "
}
# store it, if old reading does not exist yet
# if(! defined( ReadingsVal($name, "rolling_code", undef) )) {
setReadingsVal($hash, "rolling_code", uc($a[4]), $tzero);
# }
}
}
my $code = uc($address);
my $ncode = 1;
$hash->{CODE}{ $ncode++ } = $code;
$modules{SOMFY}{defptr}{$code}{$name} = $hash;
$hash->{move} = 'stop';
AssignIoPort($hash);
}
#############################
sub SOMFY_Undef($$) {
my ( $hash, $name ) = @_;
foreach my $c ( keys %{ $hash->{CODE} } ) {
$c = $hash->{CODE}{$c};
# As after a rename the $name my be different from the $defptr{$c}{$n}
# we look for the hash.
foreach my $dname ( keys %{ $modules{SOMFY}{defptr}{$c} } ) {
if ( $modules{SOMFY}{defptr}{$c}{$dname} == $hash ) {
delete( $modules{SOMFY}{defptr}{$c}{$dname} );
}
}
}
return undef;
}
##############################
sub SOMFY_Attr(@) {
my ($cmd,$name,$aName,$aVal) = @_;
my $hash = $defs{$name};
return "\"SOMFY Attr: \" $name does not exist" if (!defined($hash));
# $cmd can be "del" or "set"
# $name is device name
# aName and aVal are Attribute name and value
# Convert in case of change to positionINverse --> but only after init is done on restart this should not be recalculated
if ( ($aName eq 'positionInverse') && ( $init_done ) ) {
my $rounded;
my $stateTrans;
my $pos = ReadingsVal($name,'exact',undef);
if ( !defined($pos) ) {
$pos = ReadingsVal($name,'position',undef);
}
if ($cmd eq "set") {
if ( ( $aVal ) && ( ! AttrVal( $name, "positionInverse", 0 ) ) ) {
# set to 1 and was 0 before - convert To100To10
# first exact then round to pos
$pos = SOMFY_ConvertTo100To0( $pos );
$rounded = SOMFY_Runden( $pos );
$stateTrans = SOMFY_Translate100To0( $rounded );
} elsif ( ( ! $aVal ) && ( AttrVal( $name, "positionInverse", 0 ) ) ) {
# set to 0 and was 1 before - convert From100To10
# first exact then round to pos
$pos = SOMFY_ConvertFrom100To0( $pos );
$rounded = SOMFY_Runden( $pos );
$stateTrans = SOMFY_Translate( $rounded );
}
} elsif ($cmd eq "del") {
if ( AttrVal( $name, "positionInverse", 0 ) ) {
# delete and was 1 before - convert From100To10
# first exact then round to pos
$pos = SOMFY_ConvertFrom100To0( $pos );
$rounded = SOMFY_Runden( $pos );
$stateTrans = SOMFY_Translate( $rounded );
}
}
if ( defined( $rounded ) ) {
readingsBeginUpdate($hash);
readingsBulkUpdate($hash,"position",$rounded);
readingsBulkUpdate($hash,"exact",$pos);
readingsBulkUpdate($hash,"state",$stateTrans);
$hash->{STATE} = $stateTrans;
readingsEndUpdate($hash,1);
}
} elsif ($cmd eq "set") {
if($aName eq 'drive-up-time-to-100') {
return "SOMFY_attr: value must be >=0 and <= 100" if($aVal < 0 || $aVal > 100);
} elsif ($aName =~/drive-(down|up)-time-to.*/) {
# check name and value
return "SOMFY_attr: value must be >0 and <= 100" if($aVal <= 0 || $aVal > 100);
}
if ($aName eq 'drive-down-time-to-100') {
$attr{$name}{'drive-down-time-to-100'} = $aVal;
$attr{$name}{'drive-down-time-to-close'} = $aVal if(!defined($attr{$name}{'drive-down-time-to-close'}) || ($attr{$name}{'drive-down-time-to-close'} < $aVal));
} elsif($aName eq 'drive-down-time-to-close') {
$attr{$name}{'drive-down-time-to-close'} = $aVal;
$attr{$name}{'drive-down-time-to-100'} = $aVal if(!defined($attr{$name}{'drive-down-time-to-100'}) || ($attr{$name}{'drive-down-time-to-100'} > $aVal));
} elsif($aName eq 'drive-up-time-to-100') {
$attr{$name}{'drive-up-time-to-100'} = $aVal;
$attr{$name}{'drive-up-time-to-open'} = $aVal if(!defined($attr{$name}{'drive-up-time-to-open'}) || ($attr{$name}{'drive-up-time-to-open'} < $aVal));
} elsif($aName eq 'drive-up-time-to-open') {
$attr{$name}{'drive-up-time-to-open'} = $aVal;
$attr{$name}{'drive-up-time-to-100'} = 0 if(!defined($attr{$name}{'drive-up-time-to-100'}) || ($attr{$name}{'drive-up-time-to-100'} > $aVal));
}
}
return undef;
}
##############################################################################
##############################################################################
##
## Parse a received command
##
##############################################################################
##############################################################################
#############################
sub SOMFY_DispatchRemoteCmd($$) {
my ($hash, $cmd) = @_;
my $name = $hash->{NAME};
if ($cmd eq "10") {
$cmd = "11"; # use "stop" instead of "go-my"
}
my $txtcmd = $somfy_codes{ $cmd };
return if ( ! $txtcmd );
my $rawdAttr = AttrVal($name,'rawDevice',undef);
# check if rdev is defined and exists
if( defined($rawdAttr) ) {
# normalize address in rawdev
$rawdAttr = uc( $rawdAttr );
my @rawdevs = split( /\s+/, $rawdAttr );
foreach my $rawdev ( @rawdevs ) {
my $slist = $modules{SOMFY}{defptr}{$rawdev};
if ( defined($slist)) {
foreach my $n ( keys %{ $slist } ) {
my $rawhash = $modules{SOMFY}{defptr}{$rawdev}{$n};
Log3 $hash, 4, "SOMFY_DispatchRemoteCmd " . $name . " found dispatch SOMFY device " . $rawhash->{NAME} . " sent command :$txtcmd:";
# add virtual as modifier to set command and directly call send
my $ret = SOMFY_InternalSet( $rawhash, $rawhash->{NAME}, "virtual", $txtcmd );
Log3 $hash, 1, "SOMFY_DispatchRemoteCmd " . $name . " Internal set :$txtcmd: to ".$rawhash->{NAME}." returned " . $ret if ( $ret );
}
} else {
Log3 $hash, 1, "SOMFY_DispatchRemoteCmd SOMFY rawDevice $rawdev not found from $name";
}
}
} else {
Log3 $hash, 1, "SOMFY_DispatchRemoteCmd No rawDevice set in remote $name";
}
}
#############################
sub SOMFY_Parse($$) {
my ($hash, $msg) = @_;
my $name = $hash->{NAME};
my $ret;
my $ioType = $hash->{TYPE};
# return "IODev unsupported" if ((my $ioType = $hash->{TYPE}) !~ m/^(CUL|SIGNALduino)$/);
# preprocessing if IODev is SIGNALduino
if ($ioType eq "SIGNALduino") {
my $encData = substr($msg, 2);
my $lengthEncData = length($encData);
$ret = "Somfy RTS message format error (length)! $encData (" . $lengthEncData ."), length should be 14 or 20" if ($lengthEncData != 14 && $lengthEncData != 20);
$ret = "Somfy RTS message format error! :".$encData.":" if ( ( ! $ret ) && ($encData !~ m/[0-9A-F]{14}/) );
my ( $decData, $check );
if ( ! $ret ) {
$decData = SOMFY_RTS_Crypt("d", $name, $encData);
$check = SOMFY_RTS_Check($name, $decData);
}
$ret = "Somfy RTS checksum error! :".$encData.":" if ( ( ! $ret ) && ($check ne substr($decData, 3, 1)) );
if ( $ret ) {
Log3 $name, 1, "$name: SOMFY_Parse : ".$ret;
return undef;
}
Log3 $name, 4, "$name: Somfy RTS preprocessing check: $check enc: $encData dec: $decData";
$msg = substr($msg, 0, 2) . $decData;
}
# Msg format:
# Ys AB 2C 004B 010010
# address needs bytes 1 and 3 swapped
if (substr($msg, 0, 2) eq "Yr" || substr($msg, 0, 2) eq "Yt") {
# changed time or repetition, just return the name
return "";
}
# Check for correct length
if ( length($msg) != 16 ) {
Log3 $name, 1, "$name: SOMFY_Parse : SOMFY incorrect length for command (".$msg.") / length should be 16";
return undef;
}
# get address
my $address = uc(substr($msg, 14, 2).substr($msg, 12, 2).substr($msg, 10, 2));
# get command and set new state
my $cmd = sprintf("%X", hex(substr($msg, 4, 2)) & 0xF0);
if ($cmd eq "10") {
$cmd = "11"; # use "stop" instead of "go-my"
}
my $newstate = $somfy_codes{ $cmd };
my $def = $modules{SOMFY}{defptr}{$address};
if ( ($def) && (keys %{ $def }) ) { # Check also for empty hash --> issue #5
my @list;
foreach my $name (keys %{ $def }) {
my $lh = $def->{$name};
$name = $lh->{NAME}; # It may be renamed
return "" if(IsIgnored($name));
return "" if(IsDisabled($name));
# update the state and log it
# Debug "SOMFY Parse: $name msg: $msg --> $cmd-$newstate";
Log3 $name, 4, "SOMFY Parse: $name msg: $msg --> $cmd-$newstate --> io is $ioType";
readingsSingleUpdate($lh, "received", $cmd, 1);
readingsSingleUpdate($lh, "parsestate", $newstate, 1);
SOMFY_DispatchRemoteCmd($lh, $cmd ) if ( SOMFY_isRemote( $lh ) );
push(@list, $name);
}
# return list of affected devices
return @list;
} else {
# rolling code and enckey
my $rolling = substr($msg, 6, 4);
my $encKey = substr($msg, 2, 2);
Log3 $hash, 1, "SOMFY Unknown device $address ($encKey $rolling), please define it";
return "UNDEFINED SOMFY_$address SOMFY $address $encKey $rolling";
}
}
##############################################################################
##############################################################################
##
## Central SET routine (internal and external)
##
##############################################################################
##############################################################################
##################################################
### New set (state) method (using internalset)
###
### Reimplemented calculations for position readings and state
### Allowed sets to be done without sending actually commands to the blinds
### syntax set <name> [ <virtual|send> ] <normal set parameter>
### position and state are also updated on stop or other commands based on remaining time
### position is handled between 0 and 100 blinds down but not completely closed and 200 completely closed
### if timings for 100 and close are equal no position above 100 is used (then 100 == closed)
### position is rounded to a value of 5 and state is rounded to a value of 10
#
### General assumption times are rather on the upper limit to reach desired state
# Readings
## state contains rounded (to 10) position and/or textField
## position contains rounded position (limited detail)
# STATE
## might contain position or textual form of the state (same as STATE reading)
###################################
# call with hash, name, [virtual/send], set-args (send is default if ommitted)
sub SOMFY_Set($@) {
my ( $hash, $name, @args ) = @_;
if ( lc($args[0]) =~m/(virtual|send)/ ) {
SOMFY_InternalSet( $hash, $name, @args );
} else {
SOMFY_InternalSet( $hash, $name, 'send', @args );
}
}
###################################
# call with hash, name, virtual/send, set-args
sub SOMFY_InternalSet($@) {
my ( $hash, $name, $mode, @args ) = @_;
return undef if ( IsIgnored($name) );
return undef if ( IsDisabled($name) );
### Check Args
return "SOMFY_InternalSet: mode must be virtual or send: $mode " if ( $mode !~m/(virtual|send)/ );
my $numberOfArgs = int(@args);
return "SOMFY_set: No set value specified" if ( $numberOfArgs < 1 );
my $cmd = lc($args[0]);
# just a number provided, assume "pos" command
if ($cmd =~ m/^\d{1,3}$/) {
# overwrite args if pos (only pos and num pos)
@args = ( "pos", $cmd );
$cmd = "pos";
$numberOfArgs = int(@args);
}
if( ! SOMFY_getTestSets( $hash, $cmd ) ) {
my $setist = SOMFY_getTestSets( $hash );
return "SOMFY_set: Unknown argument $cmd, choose one of " . $setist;
}
my $arg1 = "";
if ( $numberOfArgs >= 2 ) {
$arg1 = $args[1];
}
my $isSwitch = SOMFY_isSwitch( $hash );
return "SOMFY_set: Bad time spec" if($cmd =~m/(on|off)-for-timer/ && $numberOfArgs == 2 && $arg1 !~ m/^\d*\.?\d+$/);
return "SOMFY_set: Switch: only on/off supported" if($cmd !~ m/(on|off)/ && $isSwitch );
# read timing variables
my ($t1down100, $t1downclose, $t1upopen, $t1up100) = SOMFY_getTimingValues($hash);
#Log3($name,5,"SOMFY_set: $name -> timings -> td1:$t1down100: tdc :$t1downclose: tuo :$t1upopen: tu1 :$t1up100: ");
# get current infos
my $state = $hash->{STATE};
my $pos = ReadingsVal($name,'exact',undef);
if ( !defined($pos) ) {
$pos = ReadingsVal($name,'position',undef);
}
# do conversions
if ( AttrVal( $name, "positionInverse", 0 ) ) {
Log3($name,4,"SOMFY_set: $name Inverse before cmd:$cmd: arg1:$arg1: pos:$pos:");
$arg1 = SOMFY_ConvertFrom100To0( $arg1 ) if( ($cmd eq 'pos') || ($cmd eq 'manual') ) ;
$pos = SOMFY_ConvertFrom100To0( $pos );
Log3($name,4,"SOMFY_set: $name Inverse after cmd:$cmd: arg1:$arg1: pos:$pos:");
}
if($cmd eq 'manual') {
$mode = 'virtual'; # manual is virtual setting - no command to be sent
return "SOMFY_set: No manual position given" if(!defined($arg1));
return "SOMFY_set: $arg1 must be between 0 and 100 or on/off for manual " if($arg1 !~ /^(on|off|200|150|[1-9]?0)$/ );
$arg1 = 200 if ( $arg1 eq "on" );
$arg1 = 0 if ( $arg1 eq "off" );
} elsif ( ($cmd eq 'pos') || ($cmd eq 'position') ) {
return "SOMFY_set: No pos specification" if(!defined($arg1));
return "SOMFY_set: $arg1 must be between 0 and 100 for pos" if($arg1 < 0 || $arg1 > 200);
return "SOMFY_set: Please set attr drive-down-time-to-100, drive-down-time-to-close, etc"
if(!defined($t1downclose) || !defined($t1down100) || !defined($t1upopen) || !defined($t1up100));
$cmd = "pos";
# special cases for pos to avoid mypos being used since stop signal is sent after automatic stop
$cmd = "on" if ( $arg1 == 200 );
$cmd = "off" if ( $arg1 == 0 );
}
### initialize locals
my $drivetime = 0; # timings until halt command to be sent for on/off-for-timer and pos <value> -> move by time
my $updatetime = 0; # timing until update of pos to be done for any unlimited move move to endpos or go-my / stop
my $move = $cmd;
my $newState;
my $updateState;
# translate state info to numbers - closed = 200 , open = 0 (correct missing values)
if ( !defined($pos) ) {
if(exists($positions{$state})) {
$pos = $positions{$state};
} else {
$pos = ($state ne "???" ? $state : 0); # fix runtime error
}
$pos = sprintf( "%d", $pos );
}
Log3($name,4,"SOMFY_set: $name -> entering with mode :$mode: cmd :$cmd: arg1 :$arg1: pos :$pos: ");
# check timer running - stop timer if running and update detail pos
# recognize timer running if internal updateState is still set
if ( defined( $hash->{updateState} )) {
# timer is running so timer needs to be stopped and pos needs update
RemoveInternalTimer($hash);
$pos = SOMFY_CalcCurrentPos( $hash, $hash->{move}, $pos, SOMFY_UpdateStartTime($hash) );
delete $hash->{starttime};
delete $hash->{updateState};
delete $hash->{runningtime};
delete $hash->{runningcmd};
}
################ No error returns after this point to avoid stopped timer causing confusion...
# calc posRounded
my $posRounded = SOMFY_RoundInternal( $pos );
### handle commands
if ( $isSwitch ) {
if($cmd eq 'on') {
$newState = 'closed';
} elsif($cmd eq 'off') {
$newState = 'open';
} else {
}
} elsif(!defined($t1downclose) || !defined($t1down100) || !defined($t1upopen) || !defined($t1up100)) {
#if timings not set
if($cmd eq 'on') {
$newState = 'closed';
# $newState = 'moving';
# $updatetime = $somfy_maxRuntime;
# $updateState = 'closed';
} elsif($cmd eq 'off') {
$newState = 'open';
# $newState = 'moving';
# $updatetime = $somfy_maxRuntime;
# $updateState = 'open';
} elsif($cmd eq 'on-for-timer') {
# elsif cmd == on-for-timer - time x
$move = 'on';
$newState = 'moving';
$drivetime = $arg1;
if ( $drivetime == 0 ) {
$move = 'stop';
} else {
$updateState = 'moving';
}
} elsif($cmd eq 'off-for-timer') {
# elsif cmd == off-for-timer - time x
$move = 'off';
$newState = 'moving';
$drivetime = $arg1;
if ( $drivetime == 0 ) {
$move = 'stop';
} else {
$updateState = 'moving';
}
} elsif($cmd =~m/go-my/) {
$move = 'stop';
$newState = 'go-my';
} elsif($cmd =~m/stop/) {
$move = 'stop';
$newState = $state;
} elsif($cmd =~m/manual/) {
$newState = $arg1;
} else {
$newState = $state;
}
###else (here timing is set)
} else {
# default is roundedPos as new StatePos
$newState = $posRounded;
if($cmd eq 'on') {
if ( $posRounded == 200 ) {
# if pos == 200 - no state pos change / no timer
} elsif ( $posRounded >= 100 ) {
# elsif pos >= 100 - set timer for 100-to-closed --> update timer(newState 200)
my $remTime = ( $t1downclose - $t1down100 ) * ( (200-$pos) / 100 );
$updatetime = $remTime;
$updateState = 200;
} elsif ( $posRounded < 100 ) {
# elseif pos < 100 - set timer for remaining time to 100+time-to-close --> update timer( newState 200)
my $remTime = $t1down100 * ( (100 - $pos) / 100 );
$updatetime = ( $t1downclose - $t1down100 ) + $remTime;
$updateState = 200;
} else {
# else - unknown pos - assume pos 0 set timer for full time --> update timer( newState 200)
$newState = 0;
$updatetime = $t1downclose;
$updateState = 200;
}
} elsif($cmd eq 'off') {
if ( $posRounded == 0 ) {
# if pos == 0 - no state pos change / no timer
} elsif ( $posRounded <= 100 ) {
# elsif pos <= 100 - set timer for remaining time to 0 --> update timer( newState 0 )
my $remTime = ( $t1upopen - $t1up100 ) * ( $pos / 100 );
$updatetime = $remTime;
$updateState = 0;
} elsif ( $posRounded > 100 ) {
# elseif ( pos > 100 ) - set timer for remaining time to 100+time-to-open --> update timer( newState 0 )
my $remTime = $t1up100 * ( ($pos - 100 ) / 100 );
$updatetime = ( $t1upopen - $t1up100 ) + $remTime;
$updateState = 0;
} else {
# else - unknown pos assume pos 200 set time for full time --> update timer( newState 0 )
$newState = 200;
$updatetime = $t1upopen;
$updateState = 0;
}
} elsif($cmd eq 'pos') {
if ( $pos < $arg1 ) {
# if pos < x - set halt timer for remaining time to x / cmd close --> halt timer`( newState x )
$move = 'on';
my $remTime = $t1down100 * ( ( $arg1 - $pos ) / 100 );
$drivetime = $remTime;
$updateState = $arg1;
} elsif ( ( $pos >= $arg1 ) && ( $posRounded <= 100 ) ) {
# elsif pos <= 100 & pos > x - set halt timer for remaining time to x / cmd open --> halt timer ( newState x )
$move = 'off';
my $remTime = ( $t1upopen - $t1up100 ) * ( ( $pos - $arg1) / 100 );
$drivetime = $remTime;
if ( $drivetime == 0 ) {
# $move = 'stop'; # avoid sending stop to move to my-pos
$move = 'none';
} else {
$updateState = $arg1;
}
} elsif ( $pos > 100 ) {
# else if pos > 100 - set timer for remaining time to 100+time for 100-x / cmd open --> halt timer ( newState x )
$move = 'off';
my $remTime = ( $t1upopen - $t1up100 ) * ( ( 100 - $arg1) / 100 );
my $posTime = $t1up100 * ( ( $pos - 100) / 100 );
$drivetime = $remTime + $posTime;
$updateState = $arg1;
} else {
# else - send error (might be changed to first open completely then drive to pos x) / assume open
$newState = 0;
$move = 'on';
my $remTime = $t1down100 * ( ( $arg1 - 0 ) / 100 );
$drivetime = $remTime;
$updateState = $arg1;
### return "SOMFY_set: Pos not currently known please open or close first";
}
} elsif($cmd =~m/stop|go-my/) {
# update pos according to current detail pos
$move = 'stop';
} elsif($cmd eq 'off-for-timer') {
# calcPos at new time y / cmd close --> halt timer ( newState y )
$move = 'off';
$drivetime = $arg1;
if ( $drivetime == 0 ) {
$move = 'stop';
} else {
$updateState = SOMFY_CalcCurrentPos( $hash, $move, $pos, $arg1 );
}
} elsif($cmd eq 'on-for-timer') {
# calcPos at new time y / cmd open --> halt timer ( newState y )
$move = 'on';
$drivetime = $arg1;
if ( $drivetime == 0 ) {
$move = 'stop';
} else {
$updateState = SOMFY_CalcCurrentPos( $hash, $move, $pos, $arg1 );
}
} elsif($cmd =~m/manual/) {
$newState = $arg1;
}
## special case close is at 100 ("markisen")
if( ( $t1downclose == $t1down100) && ( $t1up100 == 0 ) ) {
if ( defined( $updateState )) {
$updateState = minNum( 100, $updateState );
}
$newState = minNum( 100, $posRounded );
}
}
### update hash / readings
Log3($name,4,"SOMFY_set: handled command $cmd --> move :$move: newState :$newState: ");
if ( defined($updateState)) {
Log3($name,5,"SOMFY_set: handled for drive/udpate: updateState :$updateState: drivet :$drivetime: updatet :$updatetime: ");
} else {
Log3($name,5,"SOMFY_set: handled for drive/udpate: updateState :: drivet :$drivetime: updatet :$updatetime: ");
}
# bulk update should do trigger if virtual mode
# SOMFY_UpdateState( $hash, $newState, $move, $updateState, ( $mode eq 'virtual' ) );
SOMFY_UpdateState( $hash, $newState, $move, $updateState, 1 );
### send command
if ( $mode ne 'virtual' ) {
if ( $move ne 'none' ) {
$args[0] = $somfy_sendCommands{$move};
$args[0] = $move if ( ! defined( $args[0] ) );
SOMFY_SendCommand($hash,@args);
} else {
# do nothing if commmand / move is set to none
}
} else {
# in virtual mode define drivetime as updatetime only, so no commands will be send
if ( $updatetime == 0 ) {
$updatetime = $drivetime;
}
$drivetime = 0;
}
### update time stamp
SOMFY_UpdateStartTime($hash);
$hash->{runningtime} = 0;
if($drivetime > 0) {
$hash->{runningcmd} = 'stop';
$hash->{runningtime} = $drivetime;
} elsif($updatetime > 0) {
$hash->{runningtime} = $updatetime;
}
### start timer
if($hash->{runningtime} > 0) {
# timer fuer stop starten
if ( defined( $hash->{runningcmd} )) {
Log3($name,4,"SOMFY_set: $name -> stopping in $hash->{runningtime} sec");
} else {
Log3($name,4,"SOMFY_set: $name -> update state in $hash->{runningtime} sec");
}
my $utime = $hash->{runningtime} ;
if($utime > $somfy_updateFreq) {
$utime = $somfy_updateFreq;
}
InternalTimer(gettimeofday()+$utime,"SOMFY_TimedUpdate",$hash,0);
} else {
delete $hash->{runningtime};
delete $hash->{starttime};
}
return undef;
} # end sub SOMFY_setFN
###############################
##############################################################################
##############################################################################
##
## Internal helper - not position related
##
##############################################################################
##############################################################################
#############################