/
jswrap_bangle.c
6268 lines (5869 loc) · 221 KB
/
jswrap_bangle.c
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
/*
* This file is part of Espruino, a JavaScript interpreter for Microcontrollers
*
* Copyright (C) 2019 Gordon Williams <gw@pur3.co.uk>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* ----------------------------------------------------------------------------
* This file is designed to be parsed during the build process
*
* Contains JavaScript interface for Bangle.js (http://www.espruino.com/Bangle.js)
* ----------------------------------------------------------------------------
*/
#include <jswrap_bangle.h>
#include "jsinteractive.h"
#include "jsdevices.h"
#include "jsnative.h"
#include "jshardware.h"
#include "jsdevices.h"
#include "jspin.h"
#include "jstimer.h"
#include "jswrap_promise.h"
#include "jswrap_date.h"
#include "jswrap_math.h"
#include "jswrap_storage.h"
#include "jswrap_array.h"
#include "jswrap_arraybuffer.h"
#include "jswrap_heatshrink.h"
#include "jswrap_espruino.h"
#include "jswrap_terminal.h"
#include "jswrap_error.h"
#include "jsflash.h"
#include "graphics.h"
#include "bitmap_font_6x8.h"
#ifndef EMULATED
#include "jswrap_bluetooth.h"
#include "app_timer.h"
#include "nrf_gpio.h"
#include "nrf_delay.h"
#include "nrf_soc.h"
#include "nrf_saadc.h"
#include "nrf5x_utils.h"
#include "bluetooth.h" // for self-test
#include "jsi2c.h" // accelerometer/etc
#endif
#include "jswrap_graphics.h"
#ifdef LCD_CONTROLLER_LPM013M126
#include "lcd_memlcd.h"
#endif
#ifdef LCD_CONTROLLER_ST7789_8BIT
#include "lcd_st7789_8bit.h"
#endif
#if defined(LCD_CONTROLLER_ST7789V) || defined(LCD_CONTROLLER_ST7735) || defined(LCD_CONTROLLER_GC9A01)
#include "lcd_spilcd.h"
#endif
#ifdef ACCEL_DEVICE_KX126
#include "kx126_registers.h"
#endif
#include "stepcount.h"
#ifdef GPS_PIN_RX
#include "nmea.h"
#endif
#ifdef USE_TENSORFLOW
#include "jswrap_tensorflow.h"
#endif
#if ESPR_BANGLE_UNISTROKE
#include "unistroke.h"
#endif
#ifdef HEARTRATE_DEVICE_VC31
#include "hrm_vc31.h" // for Bangle.setOptions
#endif
/*TYPESCRIPT
declare const BTN1: Pin;
declare const BTN2: Pin;
declare const BTN3: Pin;
declare const BTN4: Pin;
declare const BTN5: Pin;
declare const g: Graphics<false>;
type WidgetArea = "tl" | "tr" | "bl" | "br";
type Widget = {
area: WidgetArea;
width: number;
sortorder?: number;
draw: (this: Widget, w: Widget) => void;
x?: number;
y?: number;
};
declare const WIDGETS: { [key: string]: Widget };
*/
/*JSON{
"type": "class",
"class" : "Bangle",
"ifdef" : "BANGLEJS"
}
Class containing utility functions for the [Bangle.js Smart
Watch](http://www.espruino.com/Bangle.js)
*/
/*TYPESCRIPT{
"class" : "Bangle"
}
static CLOCK: ShortBoolean;
static strokes: undefined | { [key: string]: Unistroke };
*/
/*TYPESCRIPT
type ShortBoolean = boolean | 0 | 1;
*/
/*JSON{
"type" : "variable",
"name" : "VIBRATE",
"generate_full" : "VIBRATE_PIN",
"ifdef" : "BANGLEJS",
"return" : ["pin",""]
}
The Bangle.js's vibration motor.
*/
/*TYPESCRIPT
type AccelData = {
x: number;
y: number;
z: number;
diff: number;
mag: number;
};
*/
/*JSON{
"type" : "event",
"class" : "Bangle",
"name" : "accel",
"params" : [["xyz","JsVar",""]],
"ifdef" : "BANGLEJS",
"typescript": "on(event: \"accel\", callback: (xyz: AccelData) => void): void;"
}
Accelerometer data available with `{x,y,z,diff,mag}` object as a parameter.
* `x` is X axis (left-right) in `g`
* `y` is Y axis (up-down) in `g`
* `z` is Z axis (in-out) in `g`
* `diff` is difference between this and the last reading in `g`
* `mag` is the magnitude of the acceleration in `g`
You can also retrieve the most recent reading with `Bangle.getAccel()`.
*/
/*JSON{
"type" : "event",
"class" : "Bangle",
"name" : "step",
"params" : [["up","int","The number of steps since Bangle.js was last reset"]],
"ifdef" : "BANGLEJS"
}
Called whenever a step is detected by Bangle.js's pedometer.
*/
/*TYPESCRIPT
type HealthStatus = {
movement: number;
steps: number;
bpm: number;
bpmConfidence: number;
};
*/
/*JSON{
"type" : "event",
"class" : "Bangle",
"name" : "health",
"params" : [["info","JsVar","An object containing the last 10 minutes health data"]],
"ifdef" : "BANGLEJS",
"typescript" : "on(event: \"health\", callback: (info: HealthStatus) => void): void;"
}
See `Bangle.getHealthStatus()` for more information. This is used for health
tracking to allow Bangle.js to record historical exercise data.
*/
/*JSON{
"type" : "event",
"class" : "Bangle",
"name" : "faceUp",
"params" : [["up","bool","`true` if face-up"]],
"ifdef" : "BANGLEJS"
}
Has the watch been moved so that it is face-up, or not face up?
*/
/*JSON{
"type" : "event",
"class" : "Bangle",
"name" : "twist",
"ifdef" : "BANGLEJS"
}
This event happens when the watch has been twisted around it's axis - for
instance as if it was rotated so someone could look at the time.
To tweak when this happens, see the `twist*` options in `Bangle.setOptions()`
*/
/*JSON{
"type" : "event",
"class" : "Bangle",
"name" : "charging",
"params" : [["charging","bool","`true` if charging"]],
"ifdef" : "BANGLEJS"
}
Is the battery charging or not?
*/
/*TYPESCRIPT
type CompassData = {
x: number;
y: number;
z: number;
dx: number;
dy: number;
dz: number;
heading: number;
};
*/
/*JSON{
"type" : "event",
"class" : "Bangle",
"name" : "mag",
"params" : [["xyz","JsVar",""]],
"ifdef" : "BANGLEJS",
"typescript" : "on(event: \"mag\", callback: (xyz: CompassData) => void): void;"
}
Magnetometer/Compass data available with `{x,y,z,dx,dy,dz,heading}` object as a
parameter
* `x/y/z` raw x,y,z magnetometer readings
* `dx/dy/dz` readings based on calibration since magnetometer turned on
* `heading` in degrees based on calibrated readings (will be NaN if magnetometer
hasn't been rotated around 360 degrees).
**Note:** In 2v15 firmware and earlier the heading is inverted (360-heading). There's
a fix in the bootloader which will apply a fix for those headings, but old apps may
still expect an inverted value.
To get this event you must turn the compass on with `Bangle.setCompassPower(1)`.
You can also retrieve the most recent reading with `Bangle.getCompass()`.
*/
/*JSON{
"type" : "event",
"class" : "Bangle",
"name" : "GPS-raw",
"params" : [
["nmea","JsVar","A string containing the raw NMEA data from the GPS"],
["dataLoss","bool","This is set to true if some lines of GPS data have previously been lost (eg because system was too busy to queue up a GPS-raw event)"]
],
"ifdef" : "BANGLEJS",
"typescript" : "on(event: \"GPS-raw\", callback: (nmea: string, dataLoss: boolean) => void): void;"
}
Raw NMEA GPS / u-blox data messages received as a string
To get this event you must turn the GPS on with `Bangle.setGPSPower(1)`.
*/
/*TYPESCRIPT
type GPSFix = {
lat: number;
lon: number;
alt: number;
speed: number;
course: number;
time: Date;
satellites: number;
fix: number;
hdop: number
};
*/
/*JSON{
"type" : "event",
"class" : "Bangle",
"name" : "GPS",
"params" : [["fix","JsVar","An object with fix info (see below)"]],
"ifdef" : "BANGLEJS",
"typescript" : "on(event: \"GPS\", callback: (fix: GPSFix) => void): void;"
}
GPS data, as an object. Contains:
```
{ "lat": number, // Latitude in degrees
"lon": number, // Longitude in degrees
"alt": number, // altitude in M
"speed": number, // Speed in kph
"course": number, // Course in degrees
"time": Date, // Current Time (or undefined if not known)
"satellites": 7, // Number of satellites
"fix": 1 // NMEA Fix state - 0 is no fix
"hdop": number, // Horizontal Dilution of Precision
}
```
If a value such as `lat` is not known because there is no fix, it'll be `NaN`.
`hdop` is a value from the GPS receiver that gives a rough idea of accuracy of
lat/lon based on the geometry of the satellites in range. Multiply by 5 to get a
value in meters. This is just a ballpark estimation and should not be considered
remotely accurate.
To get this event you must turn the GPS on with `Bangle.setGPSPower(1)`.
*/
/*JSON{
"type" : "event",
"class" : "Bangle",
"name" : "HRM",
"params" : [["hrm","JsVar","An object with heart rate info (see below)"]],
"ifdef" : "BANGLEJS",
"typescript" : "on(event: \"HRM\", callback: (hrm: { bpm: number, confidence: number, raw: Uint8Array }) => void): void;"
}
Heat rate data, as an object. Contains:
```
{ "bpm": number, // Beats per minute
"confidence": number, // 0-100 percentage confidence in the heart rate
"raw": Uint8Array, // raw samples from heart rate monitor
}
```
To get this event you must turn the heart rate monitor on with
`Bangle.setHRMPower(1)`.
*/
/*JSON{
"type" : "event",
"class" : "Bangle",
"name" : "HRM-raw",
"params" : [["hrm","JsVar","A object containing instant readings from the heart rate sensor"]],
"ifdef" : "BANGLEJS",
"typescript" : "on(event: \"HRM-raw\", callback: (hrm: { raw: number, filt: number, bpm: number, confidence: number }) => void): void;"
}
Called when heart rate sensor data is available - see `Bangle.setHRMPower(1)`.
`hrm` is of the form:
```
{ "raw": -1, // raw value from sensor
"filt": -1, // bandpass-filtered raw value from sensor
"bpm": 88.9, // last BPM value measured
"confidence": 0 // confidence in the BPM value
}
```
*/
/*JSON{
"type" : "event",
"class" : "Bangle",
"name" : "HRM-env",
"params" : [["env","JsVar","An integer containing current environment reading (light level)"]],
"ifdef" : "BANGLEJS2"
}
Called when an environment sample heart rate sensor data is available (this is the amount of light received by the HRM sensor from the environment when its LED is off). On the newest VC31B based watches this is only 4 bit (0..15).
To get it you need to turn the HRM on with `Bangle.setHRMPower(1)` and also set `Bangle.setOptions({hrmPushEnv:true})`.
It is also possible to poke registers with `Bangle.hrmWr` to increase the poll rate if needed. See https://banglejs.com/apps/?id=flashcount for an example of this.
*/
/*TYPESCRIPT
type PressureData = {
temperature: number;
pressure: number;
altitude: number;
}
*/
/*JSON{
"type" : "event",
"class" : "Bangle",
"name" : "pressure",
"params" : [["e","JsVar","An object containing `{temperature,pressure,altitude}`"]],
"ifdef" : "BANGLEJS",
"typescript" : "on(event: \"pressure\", callback: (e: PressureData) => void): void;"
}
When `Bangle.setBarometerPower(true)` is called, this event is fired containing
barometer readings.
Same format as `Bangle.getPressure()`
*/
/*JSON{
"type" : "event",
"class" : "Bangle",
"name" : "lcdPower",
"params" : [["on","bool","`true` if screen is on"]],
"ifdef" : "BANGLEJS"
}
Has the screen been turned on or off? Can be used to stop tasks that are no
longer useful if nothing is displayed. Also see `Bangle.isLCDOn()`
*/
/*JSON{
"type" : "event",
"class" : "Bangle",
"name" : "backlight",
"params" : [["on","bool","`true` if backlight is on"]],
"ifdef" : "BANGLEJS"
}
Has the backlight been turned on or off? Can be used to stop tasks that are no
longer useful if want to see in sun screen only. Also see `Bangle.isBacklightOn()`
*/
/*JSON{
"type" : "event",
"class" : "Bangle",
"name" : "lock",
"params" : [
["on","bool","`true` if screen is locked, `false` if it is unlocked and touchscreen/buttons will work"],
["reason","string","(2v20 onwards) If known, the reason for locking/unlocking - 'button','js','tap','doubleTap','faceUp','twist','timeout'"]
],
"ifdef" : "BANGLEJS"
}
Has the screen been locked? Also see `Bangle.isLocked()`
*/
/*TYPESCRIPT
type TapAxis = -2 | -1 | 0 | 1 | 2;
*/
/*JSON{
"type" : "event",
"class" : "Bangle",
"name" : "tap",
"params" : [["data","JsVar","`{dir, double, x, y, z}`"]],
"ifdef" : "BANGLEJS",
"typescript" : "on(event: \"tap\", callback: (data: { dir: \"left\" | \"right\" | \"top\" | \"bottom\" | \"front\" | \"back\", double: boolean, x: TapAxis, y: TapAxis, z: TapAxis }) => void): void;"
}
If the watch is tapped, this event contains information on the way it was
tapped.
`dir` reports the side of the watch that was tapped (not the direction it was
tapped in).
```
{
dir : "left/right/top/bottom/front/back",
double : true/false // was this a double-tap?
x : -2 .. 2, // the axis of the tap
y : -2 .. 2, // the axis of the tap
z : -2 .. 2 // the axis of the tap
```
*/
/*JSON{
"type" : "event",
"class" : "Bangle",
"name" : "gesture",
"params" : [["xyz","JsVar","An Int8Array of XYZXYZXYZ data"]],
"ifdef" : "BANGLEJS",
"typescript" : "on(event: \"gesture\", callback: (xyz: Int8Array) => void): void;"
}
Emitted when a 'gesture' (fast movement) is detected
*/
/*JSON{
"type" : "event",
"class" : "Bangle",
"name" : "aiGesture",
"params" : [["gesture","JsVar","The name of the gesture (if '.tfnames' exists, or the index. 'undefined' if not matching"],
["weights","JsVar","An array of floating point values output by the model"]],
"ifdef" : "BANGLEJS",
"typescript" : "on(event: \"aiGesture\", callback: (gesture: string | undefined, weights: number[]) => void): void;"
}
Emitted when a 'gesture' (fast movement) is detected, and a Tensorflow model is
in storage in the `".tfmodel"` file.
If a `".tfnames"` file is specified as a comma-separated list of names, it will
be used to decode `gesture` from a number into a string.
*/
/*TYPESCRIPT
type SwipeCallback = (directionLR: -1 | 0 | 1, directionUD?: -1 | 0 | 1) => void;
*/
/*JSON{
"type" : "event",
"class" : "Bangle",
"name" : "swipe",
"params" : [["directionLR","int","`-1` for left, `1` for right, `0` for up/down"],
["directionUD","int","`-1` for up, `1` for down, `0` for left/right (Bangle.js 2 only)"]],
"ifdef" : "BANGLEJS",
"typescript" : "on(event: \"swipe\", callback: SwipeCallback): void;"
}
Emitted when a swipe on the touchscreen is detected (a movement from
left->right, right->left, down->up or up->down)
Bangle.js 1 is only capable of detecting left/right swipes as it only contains a
2 zone touchscreen.
*/
/*TYPESCRIPT
type TouchCallback = (button: number, xy?: { x: number, y: number }) => void;
*/
/*JSON{
"type" : "event",
"class" : "Bangle",
"name" : "touch",
"params" : [
["button","int","`1` for left, `2` for right"],
["xy","JsVar","Object of form `{x,y,type}` containing touch coordinates (if the device supports full touch). Clipped to 0..175 (LCD pixel coordinates) on firmware 2v13 and later.`type` is only available on Bangle.js 2 and is an integer, either 0 for swift touches or 2 for longer ones."]
],
"ifdef" : "BANGLEJS",
"typescript" : "on(event: \"touch\", callback: TouchCallback): void;"
}
Emitted when the touchscreen is pressed
*/
/*TYPESCRIPT
type DragCallback = (event: {
x: number;
y: number;
dx: number;
dy: number;
b: 1 | 0;
}) => void;
*/
/*JSON{
"type" : "event",
"class" : "Bangle",
"name" : "drag",
"params" : [["event","JsVar","Object of form `{x,y,dx,dy,b}` containing touch coordinates, difference in touch coordinates, and an integer `b` containing number of touch points (currently 1 or 0)"]],
"ifdef" : "BANGLEJS",
"typescript" : "on(event: \"drag\", callback: DragCallback): void;"
}
Emitted when the touchscreen is dragged or released
The touchscreen extends past the edge of the screen and while `x` and `y`
coordinates are arranged such that they align with the LCD's pixels, if your
finger goes towards the edge of the screen, `x` and `y` could end up larger than
175 (the screen's maximum pixel coordinates) or smaller than 0. Coordinates from
the `touch` event are clipped.
*/
/*JSON{
"type" : "event",
"class" : "Bangle",
"name" : "stroke",
"params" : [["event","JsVar","Object of form `{xy:Uint8Array([x1,y1,x2,y2...])}` containing touch coordinates"]],
"ifdef" : "BANGLEJS_Q3",
"typescript" : "on(event: \"stroke\", callback: (event: { xy: Uint8Array, stroke?: string }) => void): void;"
}
Emitted when the touchscreen is dragged for a large enough distance to count as
a gesture.
If Bangle.strokes is defined and populated with data from `Unistroke.new`, the
`event` argument will also contain a `stroke` field containing the most closely
matching stroke name.
For example:
```
Bangle.strokes = {
up : Unistroke.new(new Uint8Array([57, 151, ... 158, 137])),
alpha : Unistroke.new(new Uint8Array([161, 55, ... 159, 161])),
};
Bangle.on('stroke',o=>{
print(o.stroke);
g.clear(1).drawPoly(o.xy);
});
// Might print something like
{
"xy": new Uint8Array([149, 50, ... 107, 136]),
"stroke": "alpha"
}
```
*/
/*JSON{
"type" : "event",
"class" : "Bangle",
"name" : "midnight",
"ifdef" : "BANGLEJS"
}
Emitted at midnight (at the point the `day` health info is reset to 0).
Can be used for housekeeping tasks that don't want to be run during the day.
*/
#define ACCEL_HISTORY_LEN 50 ///< Number of samples of accelerometer history
// =========================================================================
// DEVICE SPECIFIC CONFIG
#ifdef BANGLEJS_Q3
#ifndef EMULATED
JshI2CInfo i2cAccel;
JshI2CInfo i2cMag;
JshI2CInfo i2cTouch;
JshI2CInfo i2cPressure;
JshI2CInfo i2cHRM;
#define ACCEL_I2C &i2cAccel
#define MAG_I2C &i2cMag
#define TOUCH_I2C &i2cTouch
#define PRESSURE_I2C &i2cPressure
#define HRM_I2C &i2cHRM
#define GPS_UART EV_SERIAL1
#define HEARTRATE 1
bool pressureBMP280Enabled = false;
bool pressureSPL06Enabled = false;
#define PRESSURE_DEVICE_SPL06_007 1 // BMP280 already defined
#define PRESSURE_DEVICE_BMP280_EN pressureBMP280Enabled
#define PRESSURE_DEVICE_SPL06_007_EN pressureSPL06Enabled // hardware v2.1 is SPL06_001 - we need this as well
#endif // EMULATED
#define HOME_BTN 1
#define DEFAULT_LCD_POWER_TIMEOUT 0 // don't turn LCD off
#define DEFAULT_BACKLIGHT_TIMEOUT 3000
#define DEFAULT_LOCK_TIMEOUT 5000
#endif
#ifdef BANGLEJS_F18
#ifndef EMULATED
/// Internal I2C used for Accelerometer/Pressure
JshI2CInfo i2cInternal;
#define ACCEL_I2C &i2cInternal
#define MAG_I2C &i2cInternal
// Nordic app timer to handle backlight PWM
APP_TIMER_DEF(m_backlight_on_timer_id);
APP_TIMER_DEF(m_backlight_off_timer_id);
#define BACKLIGHT_PWM_INTERVAL 15 // in msec - 67Hz PWM
#define HEARTRATE 1
#define GPS_UART EV_SERIAL1
#define GPS_UBLOX 1 // handle decoding of 'UBX' packets from the GPS
#endif // !EMULATED
#define IOEXP_GPS 0x01
#define IOEXP_LCD_BACKLIGHT 0x20
#define IOEXP_LCD_RESET 0x40
#define IOEXP_HRM 0x80
#define HOME_BTN 3
#endif
#ifdef DTNO1_F5
/// Internal I2C used for Accelerometer/Pressure
JshI2CInfo i2cInternal;
#define ACCEL_I2C &i2cInternal
#define PRESSURE_I2C &i2cInternal
#define HOME_BTN 3
#endif
#ifdef DICKENS
JshI2CInfo i2cInternal;
#define ACCEL_I2C &i2cInternal
#define PRESSURE_I2C &i2cInternal
#define MAG_I2C &i2cInternal
#define HOME_BTN 2
#define DEFAULT_BTN_LOAD_TIMEOUT 4000
#define DEFAULT_LCD_POWER_TIMEOUT 20000
#define DEFAULT_TWIST_THRESHOLD 600
#define DEFAULT_TWIST_MAXY 0
#define WAKE_FROM_OFF_TIME 1000
#define MAG_MAX_RANGE 400 // maximum range of readings allowed between magmin/magmax. In the UK at ~20uT 250 is ok, and the max field strength us ~40uT
#endif
#ifdef ID205
#define HOME_BTN 1
#endif
// =========================================================================
#if HOME_BTN==1
#define HOME_BTN_PININDEX BTN1_PININDEX
#endif
#if HOME_BTN==2
#define HOME_BTN_PININDEX BTN2_PININDEX
#endif
#if HOME_BTN==3
#define HOME_BTN_PININDEX BTN3_PININDEX
#endif
#if HOME_BTN==4
#define HOME_BTN_PININDEX BTN4_PININDEX
#endif
#if HOME_BTN==5
#define HOME_BTN_PININDEX BTN5_PININDEX
#endif
// =========================================================================
#define DEFAULT_ACCEL_POLL_INTERVAL 80 // in msec - 12.5 hz to match accelerometer
#define POWER_SAVE_ACCEL_POLL_INTERVAL 800 // in msec
#define POWER_SAVE_MIN_ACCEL 1638 // min acceleration before we exit power save... (8192*0.2)
#define POWER_SAVE_TIMEOUT 60000 // 60 seconds of inactivity
#define ACCEL_POLL_INTERVAL_MAX 4000 // in msec - DEFAULT_ACCEL_POLL_INTERVAL_MAX+TIMER_MAX must be <65535
#ifndef DEFAULT_BTN_LOAD_TIMEOUT
#define DEFAULT_BTN_LOAD_TIMEOUT 1500 // in msec - how long does the button have to be pressed for before we restart
#endif
#define TIMER_MAX 60000 // 60 sec - enough to fit in uint16_t without overflow if we add ACCEL_POLL_INTERVAL
#ifndef DEFAULT_LCD_POWER_TIMEOUT
#define DEFAULT_LCD_POWER_TIMEOUT 30000 // in msec - default for lcdPowerTimeout
#endif
#ifndef DEFAULT_BACKLIGHT_TIMEOUT
#define DEFAULT_BACKLIGHT_TIMEOUT DEFAULT_LCD_POWER_TIMEOUT
#endif
#ifndef DEFAULT_LOCK_TIMEOUT
#define DEFAULT_LOCK_TIMEOUT 30000 // in msec - default for lockTimeout
#endif
#ifndef DEFAULT_TWIST_THRESHOLD
#define DEFAULT_TWIST_THRESHOLD 800
#endif
#ifndef DEFAULT_TWIST_MAXY
#define DEFAULT_TWIST_MAXY -800
#endif
#ifndef WAKE_FROM_OFF_TIME
#define WAKE_FROM_OFF_TIME 200
#endif
#ifdef TOUCH_DEVICE
short touchX, touchY; ///< current touch event coordinates
short lastTouchX, lastTouchY; ///< last touch event coordinates - updated when JSBT_DRAG is fired
bool touchPts, lastTouchPts; ///< whether a fnger is currently touching or not
unsigned char touchType; ///< variable to differentiate press, long press, double press
short touchMinX = 0, touchMinY = 0, touchMaxX = 160, touchMaxY = 160; ///< touchscreen calibration values (what we expect from hardware, then we map this to LCD_WIDTH/HEIGHT)
#endif
#ifdef PRESSURE_DEVICE
#ifdef PRESSURE_DEVICE_SPL06_007
#ifndef PRESSURE_DEVICE_SPL06_007_EN
#define PRESSURE_DEVICE_SPL06_007_EN 1
#endif
#define SPL06_PRSB2 0x00 ///< Pressure/temp data start
#define SPL06_PRSCFG 0x06 ///< Pressure config
#define SPL06_TMPCFG 0x07 ///< Temperature config
#define SPL06_MEASCFG 0x08 ///< Sensor status and config
#define SPL06_CFGREG 0x09 ///< FIFO config
#define SPL06_RESET 0x0C ///< reset
#define SPL06_COEF_START 0x10 ///< Start of calibration coefficients
#define SPL06_COEF_NUM 18 ///< Number of calibration coefficient registers
#define SPL06_8SAMPLES 3
/// Calibration coefficients
short barometer_c0, barometer_c1, barometer_c01, barometer_c11, barometer_c20, barometer_c21, barometer_c30;
int barometer_c00, barometer_c10;
#endif
#ifdef PRESSURE_DEVICE_BMP280
#ifndef PRESSURE_DEVICE_BMP280_007_EN
#define PRESSURE_DEVICE_BMP280_007_EN 1
#endif
int barometerDT[3]; // temp calibration
int barometerDP[9]; // pressure calibration
#endif
#ifdef PRESSURE_DEVICE_HP203
#ifndef PRESSURE_DEVICE_HP203_EN
#define PRESSURE_DEVICE_HP203_EN 1
#endif
#endif
/// Promise when pressure is requested
JsVar *promisePressure; // return promise of getPressure() - when set, the next pressure reading will complete this promise
volatile uint16_t barometerOnTimer; // how long has the barometer been on?
double barometerPressure;
double barometerTemperature;
double barometerAltitude;
double barometerSeaLevelPressure = 1013.25; // Standard atmospheric pressure (millibars)
bool jswrap_banglejs_barometerPoll();
JsVar *jswrap_banglejs_getBarometerObject();
#endif // PRESSURE_DEVICE
#ifdef HEARTRATE
#include "hrm.h"
#include "heartrate.h"
#ifdef HEARTRATE_VC31_BINARY
#include "vc31_binary/algo.h"
/// The sport mode we're giving to the HRM algorithm. -1 = auto, >=0 = forced
int8_t hrmSportMode;
/// Running average of acceleration difference - if this goes above a certain level we assive we're doing sports
unsigned int hrmSportActivity;
#define HRM_SPORT_ACTIVITY_THRESHOLD 2000 ///< value in hrmSportActivity before we assume we're in sport mode
#define HRM_SPORT_ACTIVITY_TIMEOUT 20000 ///< millisecs after sport activity detected to stay in sport mode
/// milliseconds since last sporty activity detected - if less than some threshold we put HRM into sport mode
volatile uint16_t hrmSportTimer;
#endif
#endif
#ifdef GPS_PIN_RX
#ifdef GPS_UBLOX
/// Handling data coming from UBlox GPS
typedef enum {
UBLOX_PROTOCOL_NOT_DETECTED = 0,
UBLOX_PROTOCOL_NMEA = 1,
UBLOX_PROTOCOL_UBX = 2
} UBloxProtocol;
/// What protocol is the current packet??
UBloxProtocol inComingUbloxProtocol = UBLOX_PROTOCOL_NOT_DETECTED;
/// UBlox UBX message expected length
uint16_t ubxMsgPayloadEnd = 0;
#endif // GPS_UBLOX
// ------------------------- Current data as it comes from GPS
/// how many characters of NMEA/UBX data do we have in gpsLine
uint16_t gpsLineLength = 0;
/// Data received from GPS UART via IRQ, 82 is the max for NMEA
uint8_t gpsLine[NMEA_MAX_SIZE];
// ------------------------- Last line of data from GPS
/// length of data to be handled in jswrap_banglejs_idle
uint8_t gpsLastLineLength = 0;
/// GPS data line to be handled in jswrap_banglejs_idle
char gpsLastLine[NMEA_MAX_SIZE];
/// GPS fix data converted from GPS
NMEAFixInfo gpsFix;
#endif // GPS_PIN_RX
#ifdef ESPR_BATTERY_FULL_VOLTAGE
float batteryFullVoltage = ESPR_BATTERY_FULL_VOLTAGE;
#endif // ESPR_BATTERY_FULL_VOLTAGE
#ifndef EMULATED
/// Nordic app timer to handle call of peripheralPollHandler
APP_TIMER_DEF(m_peripheral_poll_timer_id);
#endif
/// Is I2C busy? if so we'll skip one reading in our interrupt so we don't overlap
bool i2cBusy;
/// How often should be poll for accelerometer/compass data?
volatile uint16_t pollInterval; // in ms
/// Timer used for power save (lowering the poll interval)
volatile uint16_t powerSaveTimer;
/// counter that counts up if watch has stayed face up or down
volatile uint16_t faceUpTimer;
/// Was the watch face-up? we use this when firing events
volatile bool wasFaceUp, faceUp;
/// Was the FACE_UP event sent yet?
bool faceUpSent;
/// Was the watch charging? we use this when firing events
volatile bool wasCharging;
/// time since a button/touchscreen/etc was last pressed
volatile uint16_t inactivityTimer; // in ms
/// time since the Bangle's charge state was changed
volatile uint16_t chargeTimer; // in ms
/// How long has BTN1 been held down for (or TIMER_MAX is a reset has already happened)
volatile uint16_t homeBtnTimer; // in ms
/// How long has BTN1 been held down and watch hasn't reset (used to queue an interrupt)
volatile uint16_t homeBtnInterruptTimer; // in ms
/// How long does the home button have to be pressed before the default app is reloaded?
int btnLoadTimeout; // in ms
/// Is LCD power automatic? If true this is the number of ms for the timeout, if false it's 0
int lcdPowerTimeout; // in ms
/// Is LCD backlight automatic? If true this is the number of ms for the timeout, if false it's 0
int backlightTimeout; // in ms
/// Is locking automatic? If true this is the number of ms for the timeout, if false it's 0
int lockTimeout; // in ms
/// If a button was pressed to wake the LCD up, which one was it?
char lcdWakeButton;
/// If a button was pressed to wake the LCD up, when should we start accepting events for it?
JsSysTime lcdWakeButtonTime;
/// LCD Brightness - 255=full
uint8_t lcdBrightness;
#ifdef ESPR_BACKLIGHT_FADE
/// Actual LCD brightness (if we fade to a new brightness level)
uint8_t realLcdBrightness;
bool lcdFadeHandlerActive;
#endif
#ifdef MAG_I2C
// compass data
Vector3 mag, magmin, magmax;
bool magOnWhenCharging;
#define MAG_CHARGE_TIMEOUT 3000 // time after charging when magnetometer value gets automatically reset
#ifndef MAG_MAX_RANGE
#define MAG_MAX_RANGE 500 // maximum range of readings allowed between magmin/magmax. In the UK at ~20uT 250 is ok, and the max field strength us ~40uT
#endif
#endif // MAG_I2C
#ifdef MAG_DEVICE_GMC303
uint8_t magCalib[3]; // Magnetic Coefficient Registers - used to rescale the magnetometer values
#endif
/// accelerometer data. 8192 = 1G
Vector3 acc;
/// squared accelerometer magnitude
int accMagSquared;
/// magnitude of difference in accelerometer vectors since last reading
unsigned int accDiff;
/// History of accelerometer readings
int8_t accHistory[ACCEL_HISTORY_LEN*3];
/// Index in accelerometer history of the last sample
volatile uint8_t accHistoryIdx;
/// How many samples have we been recording a gesture for? If 0, we're not recoding a gesture
volatile uint8_t accGestureCount;
/// How many samples have been recorded? Used when putting data into an array
volatile uint8_t accGestureRecordedCount;
/// How many samples has the accelerometer movement been less than accelGestureEndThresh for?
volatile uint8_t accIdleCount;
/// data on how watch was tapped
unsigned char tapInfo;
/// time since watch was last twisted enough past twistThreshold
volatile uint16_t twistTimer; // in ms
// Gesture settings
/// how big a difference before we consider a gesture started?
unsigned short accelGestureStartThresh = 800;
/// how small a difference before we consider a gesture ended?
unsigned short accelGestureEndThresh = 2000;
/// how many samples do we keep after a gesture has ended
int accelGestureInactiveCount = 4;
/// how many samples must a gesture have before we notify about it?
int accelGestureMinLength = 10;
/// How much acceleration to register a twist of the watch strap?
int twistThreshold = DEFAULT_TWIST_THRESHOLD;
/// Maximum acceleration in Y to trigger a twist (low Y means watch is facing the right way up)
int twistMaxY = DEFAULT_TWIST_MAXY;
/// How little time (in ms) must a twist take from low->high acceleration?
int twistTimeout = 1000;
/// Current steps since reset
uint32_t stepCounter;
/// What state was the touchscreen last in
typedef enum {
TS_NONE = 0,
TS_LEFT = 1,
TS_RIGHT = 2,
TS_BOTH = 3,
TS_SWIPED = 4
} TouchState;
TouchState touchLastState; /// What happened in the last event?
TouchState touchLastState2; /// What happened in the event before last?
TouchState touchStatus; ///< What has happened *while the current touch is in progress
typedef enum {
TG_SWIPE_NONE,
TG_SWIPE_LEFT,
TG_SWIPE_RIGHT,
TG_SWIPE_UP,
TG_SWIPE_DOWN,
} TouchGestureType;
TouchGestureType touchGesture; /// is JSBT_SWIPE is set, what happened?
/// How often should we fire 'health' events?
#define HEALTH_INTERVAL 600000 // 10 minutes (600 seconds)
/// Struct with currently tracked health info
typedef struct {
uint8_t index; ///< time_in_ms / HEALTH_INTERVAL - we fire a new Health event when this changes
uint32_t movement; ///< total accelerometer difference. Used for activity tracking.
uint16_t movementSamples; ///< Number of samples added to movement
uint16_t stepCount; ///< steps during current period
uint16_t bpm10; ///< beats per minute (x10)
uint8_t bpmConfidence; ///< confidence of current BPM figure
} HealthState;
/// Currently tracked health info during this period
HealthState healthCurrent;
/// Health info during the last period, used when firing a health event
HealthState healthLast;
/// Health data so far this day
HealthState healthDaily;
/// Promise when beep is finished
JsVar *promiseBeep;
/// Promise when buzz is finished
JsVar *promiseBuzz;
//
unsigned short beepFreq;
unsigned char buzzAmt;
typedef enum {
JSBF_NONE,
JSBF_WAKEON_FACEUP = 1<<0,
JSBF_WAKEON_BTN1 = 1<<1,
JSBF_WAKEON_BTN2 = 1<<2,
JSBF_WAKEON_BTN3 = 1<<3,
JSBF_WAKEON_TOUCH = 1<<4,
JSBF_WAKEON_DBLTAP = 1<<5,
JSBF_WAKEON_TWIST = 1<<6,
JSBF_BEEP_VIBRATE = 1<<7, // use vibration motor for beep
JSBF_ENABLE_BEEP = 1<<8,
JSBF_ENABLE_BUZZ = 1<<9,
JSBF_ACCEL_LISTENER = 1<<10, ///< we have a listener for accelerometer data
JSBF_POWER_SAVE = 1<<11, ///< if no movement detected for a while, lower the accelerometer poll interval
JSBF_HRM_ON = 1<<12,
JSBF_GPS_ON = 1<<13,
JSBF_COMPASS_ON = 1<<14,
JSBF_BAROMETER_ON = 1<<15,
JSBF_LCD_ON = 1<<16,
JSBF_LCD_BL_ON = 1<<17,
JSBF_LOCKED = 1<<18,
JSBF_HRM_INSTANT_LISTENER = 1<<19,
JSBF_LCD_DBL_REFRESH = 1<<20, ///< On Bangle.js 2, toggle extcomin twice for each poll interval (avoids screen 'flashing' behaviour off axis)
JSBF_DEFAULT = ///< default at power-on
JSBF_WAKEON_TWIST|
JSBF_WAKEON_BTN1|JSBF_WAKEON_BTN2|JSBF_WAKEON_BTN3
} JsBangleFlags;
volatile JsBangleFlags bangleFlags = JSBF_NONE;
typedef enum {
JSBT_NONE,
JSBT_RESET = 1<<0, ///< reset the watch and reload code from flash
JSBT_LCD_ON = 1<<1, ///< LCD controller (can turn this on without the backlight)
JSBT_LCD_OFF = 1<<2,
JSBT_LCD_BL_ON = 1<<3, ///< LCD backlight
JSBT_LCD_BL_OFF = 1<<4,
JSBT_LOCK = 1<<5, ///< watch is locked
JSBT_UNLOCK = 1<<6, ///< watch is unlocked
JSBT_ACCEL_DATA = 1<<7, ///< need to push xyz data to JS
JSBT_ACCEL_TAPPED = 1<<8, ///< tap event detected
#ifdef GPS_PIN_RX
JSBT_GPS_DATA = 1<<9, ///< we got a complete set of GPS data in 'gpsFix'
JSBT_GPS_DATA_LINE = 1<<10, ///< we got a line of GPS data
JSBT_GPS_DATA_PARTIAL = 1<<11, ///< we got some GPS data but it needs storing for later because it was too big to go in our buffer
JSBT_GPS_DATA_OVERFLOW = 1<<12, ///< we got more GPS data than we could handle and had to drop some
#endif
#ifdef PRESSURE_DEVICE
JSBT_PRESSURE_DATA = 1<<13,
#endif
JSBT_MAG_DATA = 1<<14, ///< need to push magnetometer data to JS
JSBT_GESTURE_DATA = 1<<15, ///< we have data from a gesture
JSBT_HRM_DATA = 1<<16, ///< Heart rate data is ready for analysis
JSBT_CHARGE_EVENT = 1<<17, ///< we need to fire a charging event
JSBT_STEP_EVENT = 1<<18, ///< we've detected a step via the pedometer
JSBT_SWIPE = 1<<19, ///< swiped over touchscreen, info in touchGesture