/
BikeLightsView.mc
1934 lines (1668 loc) · 76.3 KB
/
BikeLightsView.mc
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
using Toybox.WatchUi;
using Toybox.AntPlus;
using Toybox.Math;
using Toybox.System;
using Toybox.Application;
using Toybox.Lang;
using Toybox.Time;
using Toybox.Time.Gregorian;
using Toybox.Application.Properties as Properties;
const lightModeCharacters = [
"S", /* High steady beam */
"M", /* Medium steady beam */
"s", /* Low steady beam */
"F", /* High flash */
"m", /* Medium flash */
"f" /* Low flash */
];
const controlModes = [
"S", /* SMART */
"N", /* NETWORK */
"M" /* MANUAL */
];
const networkModes = [
"INDV", /* LIGHT_NETWORK_MODE_INDIVIDUAL */
"AUTO", /* LIGHT_NETWORK_MODE_AUTO */
"HIVI", /* LIGHT_NETWORK_MODE_HIGH_VIS */
"TRAIL"
];
(:dataField)
class BaseView extends WatchUi.DataField {
function initialize() {
DataField.initialize();
}
}
(:widget)
class BaseView extends WatchUi.View {
function initialize() {
View.initialize();
}
}
class BikeLightsView extends BaseView {
// Fonts
protected var _lightsFont;
protected var _batteryFont;
protected var _controlModeFont;
// Fields related to lights and their network
protected var _lightNetwork;
protected var _lightNetworkListener;
protected var _networkMode;
protected var _networkState;
protected var _initializedLights = 0;
// Light data:
// 0. BikeLight instance
// 1. Light text (S>)
// 2. Light mode
// 3. An integer that represents light modes
// 4. Light control mode: 0 SMART, 1 NETWORK, 2 MANUAL
// 5. Title
// 6. Fit field
// 7. Next light mode
// 8. Next title
// 9. Compute setMode timeout
// 10. Minimum active filter group time in seconds
var headlightData = new [11]; // Can represent a taillight in case it is the only one
var taillightData = new [11];
protected var _errorCode;
// Settings
protected var _separatorWidth;
protected var _titleTopPadding;
protected var _titleFont;
protected var _activityColor;
(:touchScreen) private var _controlModeOnly = false;
// Pre-calculated positions
(:rectangle) protected var _isFullScreen;
(:rectangle) protected var _fieldWidth;
protected var _batteryWidth = 49;
protected var _batteryY;
protected var _lightY;
protected var _titleY;
protected var _offsetX;
// Parsed filters
protected var _globalFilters;
protected var _headlightFilters;
protected var _taillightFilters;
(:touchScreen) private var _headlightPanelSettings;
(:touchScreen) private var _taillightPanelSettings;
// Pre-calculated light panel values
(:touchScreen) private var _headlightPanel;
(:touchScreen) private var _taillightPanel;
(:touchScreen) private var _panelInitialized = false;
// Settings data
(:settings) var headlightSettings;
(:settings) var taillightSettings;
(:settings) private var _settingsInitialized;
(:highMemory) private var _individualNetwork;
// Fields used to evaluate filters
protected var _todayMoment;
protected var _sunsetTime;
protected var _sunriseTime;
(:dataField) private var _lastSpeed;
(:dataField) private var _acceleration;
(:highMemory) private var _bikeRadar;
private var _lastUpdateTime = 0;
private var _lastOnShowCallTime = 0;
// Used as an out parameter for getting the group filter title
private var _filterResult = [null /* Title */, 0 /* Filter timeout */];
function initialize() {
BaseView.initialize();
var fonts = Rez.Fonts;
_lightsFont = WatchUi.loadResource(fonts[:lightsFont]);
_batteryFont = WatchUi.loadResource(fonts[:batteryFont]);
_controlModeFont = WatchUi.loadResource(fonts[:controlModeFont]);
_lightNetworkListener = new BikeLightNetworkListener(self);
// In order to avoid calling Gregorian.utcInfo every second, calcualate Unix Timestamp of today
var now = Time.now();
var time = Gregorian.utcInfo(now, 0 /* FORMAT_SHORT */);
_todayMoment = now.value() - ((time.hour * 3600) + (time.min * 60) + time.sec);
onSettingsChanged();
}
// Called from SmartBikeLightsApp.onSettingsChanged()
function onSettingsChanged() {
//System.println("onSettingsChanged" + " timer=" + System.getTimer());
var errorCode = _errorCode;
if (errorCode != null && errorCode < 3) {
return;
}
errorCode = null;
_activityColor = getPropertyValue("AC");
try {
// Free memory before parsing to avoid out of memory exception
_globalFilters = null;
_headlightFilters = null;
_taillightFilters = null;
var configuration = parseConfiguration(getPropertyValue("LC"));
_globalFilters = configuration[0];
_headlightFilters = configuration[2];
_taillightFilters = configuration[4];
setupLightButtons(configuration);
var headlightModes = configuration[1]; // Headlight modes
if (validateLightModes(headlightData[0]) && validateLightModes(taillightData[0])) {
headlightData[3] = headlightModes;
var lightData = headlightModes == null ? headlightData : taillightData;
lightData[3] = configuration[3];
} else {
errorCode = 4;
}
} catch (e) {
errorCode = 3;
}
_errorCode = errorCode;
}
// Overrides DataField.onLayout
function onLayout(dc) {
// Due to getObsurityFlags returning incorrect results here, we have to postpone the calculation to onUpdate method
_lightY = null; // Force to pre-calculate again
}
(:lowMemory :deviceNetwork)
function onShow() {
//System.println("onShow=" + _lastUpdateTime + " timer=" + System.getTimer());
var timer = System.getTimer();
_lastOnShowCallTime = timer;
if (_initializedLights > 0 && timer - _lastUpdateTime < 1500) {
initializeLights(null, false);
return;
}
releaseLights();
_lightNetwork = null; // Release light network
_lightNetwork = new AntPlus.LightNetwork(_lightNetworkListener);
}
(:lowMemory :testNetwork)
function onShow() {
//System.println("onShow=" + _lastUpdateTime + " timer=" + System.getTimer());
var timer = System.getTimer();
_lastOnShowCallTime = timer;
if (_initializedLights > 0 && timer - _lastUpdateTime < 1500) {
initializeLights(null, false);
return;
}
releaseLights();
_lightNetwork = null; // Release light network
_lightNetwork = new TestNetwork.TestLightNetwork(_lightNetworkListener);
}
(:highMemory)
function onShow() {
//System.println("onShow=" + _lastUpdateTime + " timer=" + System.getTimer());
var timer = System.getTimer();
_lastOnShowCallTime = timer;
if (_lightNetwork instanceof AntLightNetwork.IndividualLightNetwork) {
// We don't need to recreate IndividualLightNetwork as the network mode does not change
return;
}
// When start button is pressed onShow is called, skip re-initialization in such case. This also prevents
// a re-initialization when switching between two data screens that both contain this data field.
if (_initializedLights > 0 && timer - _lastUpdateTime < 1500) {
initializeLights(null, false);
return;
}
// In case the user modifies the network mode outside the data field by using the built-in Garmin lights menu,
// the LightNetwork mode will not be updated (LightNetwork.getNetworkMode). The only way to update it is to
// create a new LightNetwork.
recreateLightNetwork();
}
(:highMemory)
function release() {
releaseLights();
if (_lightNetwork != null && _lightNetwork has :release) {
_lightNetwork.release();
}
_lightNetwork = null; // Release light network
}
// Overrides DataField.compute
(:dataField)
function compute(activityInfo) {
//System.println("usedMemory=" + System.getSystemStats().usedMemory);
// Needed for TestLightNetwork and IndividualLightNetwork
if (_errorCode == null && _lightNetwork != null && _lightNetwork has :update) {
_errorCode = _lightNetwork.update();
}
var initializedLights = _initializedLights;
if (initializedLights == 0 || _errorCode != null) {
return null;
}
var lastSpeed = _lastSpeed;
var currentSpeed = activityInfo.currentSpeed;
_acceleration = lastSpeed != null && currentSpeed != null && lastSpeed > 0 && currentSpeed > 0
? ((currentSpeed / lastSpeed) - 1) * 100
: null;
if (_sunsetTime == null && activityInfo.currentLocation != null) {
var position = activityInfo.currentLocation.toDegrees();
var time = Gregorian.utcInfo(Time.now(), 0 /* FORMAT_SHORT */);
_sunriseTime = getSunriseSet(true, time, position);
_sunsetTime = getSunriseSet(false, time, position);
}
var globalFilterResult = null;
var filterResult = _filterResult;
var globalFilterTitle = null;
for (var i = 0; i < initializedLights; i++) {
var lightData = getLightData(i, null);
if (lightData[7] != null) {
if (lightData[9] <= 0) {
lightData[7] = null;
} else {
lightData[9]--; /* Timeout */
continue;
}
}
if (lightData[4] != 0 /* SMART */ || lightData[2] < 0 /* Disconnected */) {
lightData[10] = null;
continue;
}
var filterTimer = lightData[10];
if (filterTimer != null && filterTimer > 1) {
lightData[10]--;
continue;
}
filterResult[0] = null;
// Calculate global filters only once and only when one of the lights is in smart mode
globalFilterResult = globalFilterResult == null
? checkFilters(activityInfo, _globalFilters, filterResult, null)
: globalFilterResult;
if (globalFilterResult == 0) {
setLightMode(lightData, 0, null, false);
continue;
}
if (globalFilterTitle == null) {
globalFilterTitle = filterResult[0];
}
var light = lightData[0];
var lightMode = checkFilters(
activityInfo,
getLightFilters(light),
filterResult,
lightData);
var title = filterResult[0] != null ? filterResult[0] : globalFilterTitle;
lightData[10] = filterResult[1];
setLightMode(lightData, lightMode, title, false);
}
_lastSpeed = activityInfo.currentSpeed;
return null;
}
// Overrides DataField.onUpdate
function onUpdate(dc) {
var timer = System.getTimer();
var lastUpdateTime = _lastUpdateTime;
// In case the device woke up from a sleep, set the control mode that was used before it went to sleep. When
// a device goes to sleep, it turns off the lights which triggers onExternalLightModeChange method in case
// the light are turned on and sets the control mode to manual. In such case, we store the control mode that
// was used before the external change so that we can restore it when the device wakes up. Idealy we would not
// change the control mode before a sleep, but as there is no way to detect when the device goes to sleep we
// cannot do that. We are able to detect only when the device woke up by checking whether onShow method was called
// prior calling onUpdate method. This will work only if the device went to sleep on the data screen were this
// data field is displayed, otherwise it will not work as onUpdate will not be called.
if (lastUpdateTime > 0 && (timer - lastUpdateTime) > 2000 && (timer - _lastOnShowCallTime) > 2000) {
//System.println("WAKE UP lastOnShowCallTime=" + _lastOnShowCallTime + " timer=" + System.getTimer());
for (var i = 0; i < 3; i += 2) {
var prevControlMode = getLightProperty("PCM", i, null);
if (prevControlMode != null) {
setLightProperty("CM", i, prevControlMode);
}
}
onShow();
}
_lastUpdateTime = timer;
var width = dc.getWidth();
var height = dc.getHeight();
var bgColor = getBackgroundColor();
var fgColor = 0x000000; /* COLOR_BLACK */
if (bgColor == 0x000000 /* COLOR_BLACK */) {
fgColor = 0xFFFFFF; /* COLOR_WHITE */
}
dc.setColor(fgColor, bgColor);
dc.clear();
if (_lightY == null) {
preCalculate(dc, width, height);
}
var text = _errorCode != null ? "Error " + _errorCode
: _initializedLights == 0 ? "No network"
: null;
if (text != null) {
drawCenterText(dc, text, fgColor, width, height);
return;
}
draw(dc, width, height, fgColor, bgColor);
}
function onNetworkStateUpdate(networkState) {
//System.println("onNetworkStateUpdate=" + networkState + " timer=" + System.getTimer());
_networkState = networkState;
if (_initializedLights > 0 && networkState != 2 /* LIGHT_NETWORK_STATE_FORMED */) {
// Set the mode to disconnected in order to be recorded in case lights recording is enabled
updateLightTextAndMode(headlightData, -1);
if (_initializedLights > 1) {
updateLightTextAndMode(taillightData, -1);
}
// We have to reinitialize in case the light network is dropped after its formation
releaseLights();
return;
}
if (_initializedLights > 0 || networkState != 2 /* LIGHT_NETWORK_STATE_FORMED */) {
//System.println("Skip=" + _initializedLights + " networkState=" + networkState +" timer=" + System.getTimer());
return;
}
var networkMode = _lightNetwork.getNetworkMode();
if (networkMode == null) {
networkMode = 3; // TRAIL
}
// In case the user changes the network mode outside the application, set the default to network control mode
var newNetworkMode = _networkMode != null && networkMode != _networkMode ? networkMode : null;
_networkMode = networkMode;
// Initialize lights
_initializedLights = initializeLights(newNetworkMode, true);
}
function updateLight(light, mode) {
var lightType = light.type;
if (_initializedLights == 0 || (lightType != 0 /* LIGHT_TYPE_HEADLIGHT */ && lightType != 2 /* LIGHT_TYPE_TAILLIGHT */)) {
//System.println("skip updateLight light=" + light.type + " mode=" + mode + " timer=" + System.getTimer());
return;
}
var lightData = getLightData(lightType, _initializedLights);
lightData[0] = light;
var nextMode = lightData[7];
if (mode == lightData[2] && nextMode == null) {
//System.println("skip updateLight light=" + light.type + " mode=" + mode + " currMode=" + lightData[2] + " nextMode=" + lightData[7] + " timer=" + System.getTimer());
return;
}
//System.println("updateLight light=" + light.type + " mode=" + mode + " currMode=" + lightData[2] + " nextMode=" + nextMode + " timer=" + System.getTimer());
var controlMode = lightData[4];
if (nextMode == mode) {
lightData[5] = lightData[8]; // Update title
lightData[7] = null;
lightData[8] = null;
} else if (controlMode != 1 /* NETWORK */) {
lightData[5] = null;
}
if (updateLightTextAndMode(lightData, mode) &&
nextMode != mode && controlMode != 1 /* NETWORK */ &&
// In the first few seconds during and after the network formation the lights may automatically switch to different
// light modes, which can change their control mode to manual. In order to avoid changing the control mode, we
// ignore initial light mode changes. This mostly helps when a device wakes up after only a few seconds of sleep.
(System.getTimer() - _lastOnShowCallTime) > 5000) {
// Change was done outside the data field.
onExternalLightModeChange(lightData, mode);
}
}
(:settings)
function getSettingsView() {
if (_errorCode != null || _initializedLights == 0 || !initializeSettings() || !(WatchUi has :Menu2)) {
return null;
}
var menu = _initializedLights > 1
? new Settings.LightsMenu(self)
: new Settings.LightMenu(headlightData[0].type, self);
return [menu, new Settings.MenuDelegate(menu)];
}
(:lightButtons)
function setLightAndControlMode(lightData, lightType, newMode, newControlMode) {
if (lightData[0] == null || _errorCode != null) {
return; // This can happen when in menu the network is dropped or an invalid configuration is set
}
var controlMode = lightData[4];
// In case the previous mode is Network we have to call setMode to override it
var forceSetMode = controlMode == 1 /* NETWORK */ && newControlMode != null;
if (newControlMode == 1 /* NETWORK */) {
setNetworkMode(lightData, _networkMode);
} else if ((controlMode == 2 /* MANUAL */ && newControlMode == null) || newControlMode == 2 /* MANUAL */) {
setLightProperty("MM", lightType, newMode);
setLightMode(lightData, newMode, null, forceSetMode);
} else if (newControlMode == 0 /* SMART */ && forceSetMode) {
setLightMode(lightData, lightData[2], null, true);
}
if (newControlMode != null) {
setLightProperty("CM", lightType, newControlMode);
lightData[4] = newControlMode;
}
}
(:touchScreen)
function onTap(location) {
if (_fieldWidth == null || _initializedLights == 0 || _errorCode != null) {
return false;
}
// Find which light was tapped
var lightData = getLightData((_fieldWidth / 2) > location[0] ? 0 : 2, _initializedLights);
if (getLightBatteryStatus(lightData) > 5) {
return false; // Battery is disconnected
}
var light = lightData[0];
var lightType = light.type;
var controlMode = lightData[4];
if (_isFullScreen) {
return onLightPanelTap(location, lightData, lightType, controlMode);
}
var modes = getLightModes(light);
var index = modes.indexOf(lightData[2]);
var newControlMode = null;
var newMode = null;
// Change to the next mode
if (_controlModeOnly && controlMode != 0 /* SMART */) {
newControlMode = 0; /* SMART */
} else if (controlMode == 0 /* SMART */) {
newControlMode = 1; /* NETWORK */
} else if (controlMode == 1 /* NETWORK */) {
newControlMode = 2; /* MANUAL */
index = -1;
}
if (!_controlModeOnly && (controlMode == 2 /* MANUAL */ || newControlMode == 2 /* MANUAL */)) {
index = (index + 1) % modes.size();
if (controlMode == 2 /* MANUAL */ && index == 0) {
newControlMode = 0; /* SMART */
// The mode will be calculated in compute method
} else {
newMode = modes[index];
}
}
setLightAndControlMode(lightData, lightType, newMode, newControlMode);
return true;
}
protected function getPropertyValue(key) {
return Properties.getValue(key);
}
(:widget)
protected function getBackgroundColor() {
}
(:rectangle)
protected function preCalculate(dc, width, height) {
var deviceSettings = System.getDeviceSettings();
var padding = height - 55 < 0 ? 0 : 3;
var settings = WatchUi.loadResource(Rez.JsonData.Settings);
_separatorWidth = settings[0];
_titleFont = settings[1];
_titleTopPadding = settings[2];
_offsetX = settings[3];
_fieldWidth = width;
_isFullScreen = width == deviceSettings.screenWidth && height == deviceSettings.screenHeight;
_batteryY = height - 19 - padding;
_lightY = _batteryY - padding - 32 /* Lights font size */;
_titleY = (_lightY - dc.getFontHeight(_titleFont) - _titleTopPadding) >= 0 ? _titleTopPadding : null;
}
(:round)
protected function preCalculate(dc, width, height) {
var flags = getObscurityFlags();
var settings = WatchUi.loadResource(Rez.JsonData.Settings);
_separatorWidth = settings[0];
_titleFont = settings[1];
_titleTopPadding = settings[2];
var titleHeight = dc.getFontHeight(_titleFont) + _titleTopPadding;
var lightHeight = height < 55 ? 35 : 55;
var totalHeight = lightHeight + titleHeight;
var includeTitle = height > 90 && width > 150;
totalHeight = includeTitle ? totalHeight : lightHeight;
var startY = (12800 >> flags) & 0x01 == 1 ? 2 /* From top */
: (200 >> flags) & 0x01 == 1 ? height - totalHeight /* From bottom */
: (height - totalHeight) / 2; /* From center */
_titleY = includeTitle ? startY : null;
_lightY = includeTitle ? _titleY + titleHeight : startY;
_batteryY = height < 55 ? null : _lightY + 35;
var offsetDirection = ((1415136409 >> (flags * 2)) & 0x03) - 1;
_offsetX = settings[3] * offsetDirection;
}
protected function initializeLights(newNetworkMode, firstTime) {
//System.println("initializeLights=" + newNetworkMode + " firstTime=" + firstTime + " timer=" + System.getTimer());
var errorCode = _errorCode;
if (errorCode == 1 || errorCode == 2) {
errorCode = null;
}
var lights = _lightNetwork.getBikeLights();
if (lights == null) {
_errorCode = errorCode;
return 0;
}
var recordLightModes = getPropertyValue("RL");
var totalLights = lights.size();
for (var i = 0; i < totalLights; i++) {
var light = lights[i];
var lightType = light != null ? light.type : 7;
if (lightType != 0 && lightType != 2) {
errorCode = 1;
break;
}
var capableModes = getLightModes(light);
var filters = getLightFilters(light);
if (newNetworkMode != null) {
setLightProperty("CM", lightType, 1 /* NETWORK */);
}
var controlMode = getLightProperty("CM", lightType, filters != null ? 0 /* SMART */ : 1 /* NETWORK */);
var lightMode = getInitialLightMode(light, controlMode);
var lightModeIndex = capableModes.indexOf(lightMode);
if (lightModeIndex < 0) {
lightModeIndex = 0;
lightMode = 0; /* LIGHT_MODE_OFF */
}
var lightData = getLightData(lightType, totalLights);
if (firstTime && lightData[0] != null) {
errorCode = 2;
break;
}
// Store fit field always on the correct light data in order avoid creating two taillight_mode fit fields
var fitData = getLightData(lightType, null);
if (recordLightModes && fitData[6] == null) {
fitData[6] = createField(
lightType == 0 /* LIGHT_TYPE_HEADLIGHT */ ? "headlight_mode" : "taillight_mode",
lightType, // Id
1 /*DATA_TYPE_SINT8 */,
{
:mesgType=> 20 /* Fit.MESG_TYPE_RECORD */
}
);
}
lightData[0] = light;
lightData[2] = null; // Force to update light text in case light modes were changed
updateLightTextAndMode(lightData, lightMode);
var oldControlMode = lightData[4];
lightData[4] = controlMode;
// In case of SMART or MANUAL control mode, we have to set the light mode in order to prevent the network mode
// from changing it.
if (firstTime || oldControlMode != controlMode) {
setInitialLightMode(lightData, lightMode, controlMode);
}
// Allow the initialization to complete even if the modes are invalid, so that the user
// is able to correct them by modifying the light configuration
if (!validateLightModes(light)) {
errorCode = 4;
}
}
_errorCode = errorCode;
return errorCode == null || errorCode == 4 ? totalLights : 0;
}
(:touchScreen)
protected function onLightPanelTap(location, lightData, lightType, controlMode) {
var panelData = lightType == 0 /* LIGHT_TYPE_HEADLIGHT */ ? _headlightPanel : _taillightPanel;
var totalButtonGroups = panelData[0];
var tapX = location[0];
var tapY = location[1];
var groupIndex = 6;
while (groupIndex < panelData.size()) {
var totalButtons = panelData[groupIndex];
// All buttons in the group have the same y and height, take the first one
var topY = panelData[groupIndex + 6];
var height = panelData[groupIndex + 8];
if (tapY >= topY && tapY < (topY + height)) {
for (var j = 0; j < totalButtons; j++) {
var buttonIndex = groupIndex + 1 + (j * 8);
var leftX = panelData[buttonIndex + 4];
var width = panelData[buttonIndex + 6];
if (tapX >= leftX && tapX < (leftX + width)) {
var newMode = panelData[buttonIndex];
onLightPanelModeChange(lightData, lightType, newMode, controlMode);
return true;
}
}
}
groupIndex += 1 + (totalButtons * 8);
}
return false;
}
(:touchScreen)
protected function onLightPanelModeChange(lightData, lightType, lightMode, controlMode) {
var newControlMode = lightMode < 0 ? controlMode != 0 /* SMART */ ? 0 : 1 /* NETWORK */
: controlMode != 2 /* MANUAL */ ? 2
: null;
setLightAndControlMode(lightData, lightType, lightMode, newControlMode);
}
protected function setInitialLightMode(lightData, lightMode, controlMode) {
if (controlMode != 1 /* NETWORK */) {
setLightMode(lightData, lightMode, null, true);
} else {
setNetworkMode(lightData, _networkMode);
}
}
protected function setLightMode(lightData, mode, title, force) {
if (lightData[2] == mode) {
lightData[5] = title; // updateLight may not be called when setting the same mode
if (!force) {
return;
}
}
//System.println("setLightMode=" + mode + " light=" + lightData[0].type + " force=" + force + " timer=" + System.getTimer());
lightData[7] = mode; // Next mode
lightData[8] = title; // Next title
// Do not set a timeout in case we force setting the same mode, as we won't get a light update
lightData[9] = lightData[2] == mode ? 0 : 5; // Timeout for compute method
lightData[0].setMode(mode);
}
protected function getLightBatteryStatus(lightData) {
var status = _lightNetwork.getBatteryStatus(lightData[0].identifier);
if (status == null) { /* Disconnected */
updateLightTextAndMode(lightData, -1);
return 6;
}
return status.batteryStatus;
}
protected function getLightModes(light) {
var modes = light.getCapableModes();
if (modes == null) {
return [0];
}
// LightNetwork supports up to five custom modes, any custom mode beyond the fifth one will be set to NULL.
// Cycliq lights FLY6 CE and Fly12 CE have the following modes: [0, 1, 2, 3, 6, 7, 63, 62, 61, 60, 59, null]
// In such case we need to remove the NULL values from the array.
if (modes.indexOf(null) > -1) {
modes = modes.slice(0, null);
modes.removeAll(null);
}
return modes;
}
protected function setLightProperty(id, lightType, value) {
Application.Storage.setValue(id + lightType, value);
}
(:lightButtons)
protected function onExternalLightModeChange(lightData, mode) {
//System.println("onExternalLightModeChange mode=" + mode + " lightType=" + lightData[0].type + " timer=" + System.getTimer());
var controlMode = lightData[4];
var lightType = lightData[0].type;
setLightProperty("PCM", lightType, controlMode);
setLightAndControlMode(lightData, lightType, mode, controlMode != 2 ? 2 /* MANUAL */ : null);
}
(:noLightButtons)
protected function onExternalLightModeChange(lightData, mode) {
var controlMode = lightData[4];
lightData[4] = 2; /* MANUAL */
lightData[5] = null;
// As onHide is never called, we use the last update time in order to determine whether the data field is currently
// displayed. In case that the data field is currently not displayed, we assume that the user used either Garmin
// lights menu or a CIQ application to change the light mode. In such case set the next control mode to manual so
// that when the data field will be again displayed the manual control mode will be active. In case when the light
// mode is changed while the data field is displayed (by pressing the button on the light), do not set the next mode
// so that the user will be able to reset back to smart by moving to a different data screen and then back to the one
// that contains this data field. In case when the network mode is changed when the data field is not displayed by
// using Garmin lights menu, network control mode will be active when the data field will be again displayed. As the
// network mode is not updated when changed until a new instance of the LightNetwork is created, the logic is done in
// onNetworkStateUpdate method.
if (System.getTimer() > _lastUpdateTime + 1500) {
var lightType = lightData[0].type;
setLightProperty("PCM", lightType, controlMode);
// Assume that the change was done either by Garmin lights menu or a CIQ application
setLightProperty("CM", lightType, 2 /* MANUAL */);
setLightProperty("MM", lightType, mode);
}
}
(:nonTouchScreen)
protected function releaseLights() {
_initializedLights = 0;
headlightData[0] = null;
taillightData[0] = null;
}
(:touchScreen)
protected function releaseLights() {
_initializedLights = 0;
headlightData[0] = null;
taillightData[0] = null;
_panelInitialized = false;
_headlightPanel = null;
_taillightPanel = null;
}
(:settings)
protected function initializeSettings() {
if (_settingsInitialized) {
return true;
}
if (!validateSettingsLightModes(headlightData[0]) || !validateSettingsLightModes(taillightData[0])) {
return false;
}
var lightType = headlightData[0].type;
if (headlightSettings == null && lightType == 0 /* LIGHT_TYPE_HEADLIGHT */) {
headlightSettings = getDefaultLightSettings(headlightData[0]);
}
if (taillightSettings == null) {
var lightData = _initializedLights > 1 ? taillightData
: lightType == 2 ? headlightData
: null;
taillightSettings = lightData != null ? getDefaultLightSettings(lightData[0]) : null;
}
_settingsInitialized = true;
return true;
}
(:rectangle)
protected function drawLight(lightData, position, dc, width, fgColor, bgColor) {
var justification = lightData[0].type;
var direction = justification == 0 ? 1 : -1;
var lightX = Math.round(width * 0.25f * position);
var batteryStatus = getLightBatteryStatus(lightData);
var title = lightData[5];
var lightXOffset = justification == 0 ? -4 : 2;
dc.setColor(fgColor, bgColor);
if (title != null && _titleY != null) {
dc.drawText(lightX, _titleY, _titleFont, title, 1 /* TEXT_JUSTIFY_CENTER */);
}
dc.drawText(lightX + (direction * (_batteryWidth / 2)) + lightXOffset, _lightY, _lightsFont, lightData[1], justification);
dc.drawText(lightX + (direction * 8), _lightY + 11, _controlModeFont, $.controlModes[lightData[4]], 1 /* TEXT_JUSTIFY_CENTER */);
drawBattery(dc, fgColor, lightX, _batteryY, batteryStatus);
}
(:round)
protected function drawLight(lightData, position, dc, width, fgColor, bgColor) {
var justification = lightData[0].type;
var direction = justification == 0 ? 1 : -1;
var lightX = Math.round(width * 0.25f * position) + _offsetX;
lightX += _initializedLights == 2 ? (direction * ((width / 4) - 25)) : 0;
var batteryStatus = getLightBatteryStatus(lightData);
var title = lightData[5];
var lightXOffset = justification == 0 ? -4 : 2;
dc.setColor(fgColor, bgColor);
if (title != null && _titleY != null) {
dc.drawText(lightX + (direction * 22), _titleY, _titleFont, title, justification);
}
dc.drawText(lightX + (direction * (_batteryWidth / 2)) + lightXOffset, _lightY, _lightsFont, lightData[1], justification);
dc.drawText(lightX + (direction * 8), _lightY + 11, _controlModeFont, $.controlModes[lightData[4]], 1 /* TEXT_JUSTIFY_CENTER */);
if (_batteryY != null) {
drawBattery(dc, fgColor, lightX, _batteryY, batteryStatus);
}
}
protected function drawBattery(dc, fgColor, x, y, batteryStatus) {
// Draw the battery shell
setTextColor(dc, fgColor);
dc.drawText(x, y, _batteryFont, "B", 1 /* TEXT_JUSTIFY_CENTER */);
// Do not draw the indicator in case the light is not connected anymore or an invalid status is given
// The only way to detect whether the light is still connected is to check whether the its battery status is not null
if (batteryStatus > 5) {
return;
}
// Draw the battery indicator
var color = batteryStatus == 5 /* BATT_STATUS_CRITICAL */ ? 0xFF0000 /* COLOR_RED */
: batteryStatus > 2 /* BATT_STATUS_GOOD */ ? 0xFF5500 /* COLOR_ORANGE */
: 0x00AA00; /* COLOR_DK_GREEN */
setTextColor(dc, color);
dc.drawText(x, y, _batteryFont, batteryStatus.toString(), 1 /* TEXT_JUSTIFY_CENTER */);
}
(:rectangle)
protected function drawCenterText(dc, text, color, width, height) {
setTextColor(dc, color);
dc.drawText(width / 2, height / 2, 2, text, 1 /* TEXT_JUSTIFY_CENTER */ | 4 /* TEXT_JUSTIFY_VCENTER */);
}
(:round)
protected function drawCenterText(dc, text, color, width, height) {
setTextColor(dc, color);
dc.drawText(width / 2, height / 2, 0, text, 1 /* TEXT_JUSTIFY_CENTER */ | 4 /* TEXT_JUSTIFY_VCENTER */);
}
protected function getSecondsOfDay(value) {
value = value.toNumber();
return value == null ? null : (value < 0 ? value + 86400 : value) % 86400;
}
// The below source code was ported from: https://www.esrl.noaa.gov/gmd/grad/solcalc/main.js
// which is used for the NOAA Solar Calculator: https://www.esrl.noaa.gov/gmd/grad/solcalc/
protected function getSunriseSet(rise, time, position) {
var month = time.month;
var year = time.year;
if (month <= 2) {
year -= 1;
month += 12;
}
var a = Math.floor(year / 100);
var b = 2 - a + Math.floor(a / 4);
var jd = Math.floor(365.25 * (year + 4716)) + Math.floor(30.6001 * (month + 1)) + time.day + b - 1524.5;
var t = (jd - 2451545.0) / 36525.0;
var omega = degToRad(125.04 - 1934.136 * t);
var l1 = 280.46646 + t * (36000.76983 + t * 0.0003032);
while (l1 > 360.0) {
l1 -= 360.0;
}
while (l1 < 0.0) {
l1 += 360.0;
}
var l0 = degToRad(l1);
var e = 0.016708634 - t * (0.000042037 + 0.0000001267 * t); // unitless
var mrad = degToRad(357.52911 + t * (35999.05029 - 0.0001537 * t));
var ec = degToRad((23.0 + (26.0 + ((21.448 - t * (46.8150 + t * (0.00059 - t * 0.001813))) / 60.0)) / 60.0) + 0.00256 * Math.cos(omega));
var y = Math.tan(ec/2.0);
y *= y;
var sinm = Math.sin(mrad);
var eqTime = (180.0 * (y * Math.sin(2.0 * l0) - 2.0 * e * sinm + 4.0 * e * y * sinm * Math.cos(2.0 * l0) - 0.5 * y * y * Math.sin(4.0 * l0) - 1.25 * e * e * Math.sin(2.0 * mrad)) / 3.141593) * 4.0; // in minutes of time
var sunEq = sinm * (1.914602 - t * (0.004817 + 0.000014 * t)) + Math.sin(mrad + mrad) * (0.019993 - 0.000101 * t) + Math.sin(mrad + mrad + mrad) * 0.000289; // in degrees
var latRad = degToRad(position[0].toFloat() /* latitude */);
var sdRad = degToRad(180.0 * (Math.asin(Math.sin(ec) * Math.sin(degToRad((l1 + sunEq) - 0.00569 - 0.00478 * Math.sin(omega))))) / 3.141593);
var hourAngle = Math.acos((Math.cos(degToRad(90.833)) / (Math.cos(latRad) * Math.cos(sdRad)) - Math.tan(latRad) * Math.tan(sdRad))); // in radians (for sunset, use -HA)
if (!rise) {
hourAngle = -hourAngle;
}
return getSecondsOfDay((720 - (4.0 * (position[1].toFloat() /* longitude */ + (180.0 * hourAngle / 3.141593))) - eqTime) * 60); // timeUTC in seconds
}
private function getLightFilters(light) {
return light.type == 0 /* LIGHT_TYPE_HEADLIGHT */ ? _headlightFilters : _taillightFilters;
}
private function updateLightTextAndMode(lightData, mode) {
if (lightData[2] == mode) {
return false;
}
var lightType = lightData[0].type;
lightData[1] = getLightText(lightType, mode, lightData[3]);
lightData[2] = mode;
var fitData = getLightData(lightType, null);
var fitField = fitData[6];
if (fitField != null) {
fitField.setData(mode);
}
return true;
}
(:settings)
private function getDefaultLightSettings(light) {
if (light == null) {
return null;
}
var modes = getLightModes(light);
var data = new [2 * modes.size() + 1];
var dataIndex = 1;
data[0] = light.type == 0 /* LIGHT_TYPE_HEADLIGHT */ ? "Headlight" : "Taillight";
for (var i = 0; i < modes.size(); i++) {
var mode = modes[i];
data[dataIndex] = mode == 0 ? "Off" : mode.toString();
data[dataIndex + 1] = mode;
dataIndex += 2;
}
return data;
}
(:noLightButtons :lowMemory)
private function setupLightButtons(configuration) {
}
(:noLightButtons :highMemory)
private function setupLightButtons(configuration) {
_individualNetwork = configuration[7];
if (_individualNetwork != null /* Is enabled */ || _lightNetwork instanceof AntLightNetwork.IndividualLightNetwork) {
recreateLightNetwork();
}