/
jswrap_bangle.c
2212 lines (2064 loc) · 74.5 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 "jsflash.h"
#ifndef EMSCRIPTEN
#include "jswrap_bluetooth.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"
#include "lcd_st7789_8bit.h"
#include "nmea.h"
#ifdef USE_TENSORFLOW
#include "jswrap_tensorflow.h"
#endif
/*JSON{
"type": "class",
"class" : "Bangle",
"ifdef" : "BANGLEJS"
}
Class containing utility functions for the [Bangle.js Smart Watch](http://www.espruino.com/Bangle.js)
*/
/*JSON{
"type" : "variable",
"name" : "VIBRATE",
"generate_full" : "VIBRATE_PIN",
"ifdef" : "BANGLEJS",
"return" : ["pin",""]
}
The Bangle.js's vibration motor.
*/
/*JSON{
"type" : "event",
"class" : "Bangle",
"name" : "accel",
"params" : [["xyz","JsVar",""]],
"ifdef" : "BANGLEJS"
}
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`
*/
/*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.
*/
/*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" : "charging",
"params" : [["charging","bool","`true` if charging"]],
"ifdef" : "BANGLEJS"
}
Is the battery charging or not?
*/
/*JSON{
"type" : "event",
"class" : "Bangle",
"name" : "mag",
"params" : [["xyz","JsVar",""]],
"ifdef" : "BANGLEJS"
}
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)
To get this event you must turn the compass on
with `Bangle.setCompassPower(1)`.
*/
/*JSON{
"type" : "event",
"class" : "Bangle",
"name" : "GPS-raw",
"params" : [["nmea","JsVar",""]],
"ifdef" : "BANGLEJS"
}
Raw NMEA GPS data lines received as a string
To get this event you must turn the GPS on
with `Bangle.setGPSPower(1)`.
*/
/*JSON{
"type" : "event",
"class" : "Bangle",
"name" : "GPS",
"params" : [["fix","JsVar","An object with fix info (see below)"]],
"ifdef" : "BANGLEJS"
}
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
"satellites": 7, // Number of satellites
"fix": 1 // NMEA Fix state - 0 is no fix
}
```
If a value such as `lat` is not known because there is no fix, it'll be `NaN`.
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"
}
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" : "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.
*/
/* This doesn't work, so remove for now - FIXMEJSON{
"type" : "event",
"class" : "Bangle",
"name" : "tap",
"params" : [["data","JsVar","`{dir, double, x, y, z}`"]],
"ifdef" : "BANGLEJS"
}
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"
}
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"
}
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.
*/
/*JSON{
"type" : "event",
"class" : "Bangle",
"name" : "swipe",
"params" : [["direction","int","`-1` for left, `1` for right"]],
"ifdef" : "BANGLEJS"
}
Emitted when a swipe on the touchscreen is detected (a movement from left->right, or right->left)
*/
/*JSON{
"type" : "event",
"class" : "Bangle",
"name" : "touch",
"params" : [["button","int","`1` for left, `2` for right"]],
"ifdef" : "BANGLEJS"
}
Emitted when the touchscreen is pressed, either on the left
or right hand side.
*/
#define GPS_UART EV_SERIAL1
#define IOEXP_GPS 0x01
#define IOEXP_LCD_BACKLIGHT 0x20
#define IOEXP_LCD_RESET 0x40
#define IOEXP_HRM 0x80
#define ACCEL_HISTORY_LEN 50 ///< Number of samples of accelerometer history
#define HRM_HISTORY_LEN 256
uint8_t nmeaCount = 0; // how many characters of NMEA data do we have?
char nmeaIn[NMEA_MAX_SIZE]; // 82 is the max for NMEA
char nmeaLine[NMEA_MAX_SIZE]; // A line of received NMEA data
NMEAFixInfo gpsFix;
typedef struct {
short x,y,z;
} Vector3;
#define DEFAULT_ACCEL_POLL_INTERVAL 80 // in msec - 12.5 to match accelerometer
#define DEFAULT_LCD_POWER_TIMEOUT 30000 // in msec - default for lcdPowerTimeout
#define HRM_POLL_INTERVAL 20 // in msec
#define ACCEL_POLL_INTERVAL_MAX 5000 // in msec - DEFAULT_ACCEL_POLL_INTERVAL_MAX+TIMER_MAX must be <65535
#define BTN_LOAD_TIMEOUT 1500 // in msec - how long does the button have to be pressed for before we restart
#define TIMER_MAX 60000 // 60 sec - enough to fit in uint16_t without overflow if we add ACCEL_POLL_INTERVAL
/// Internal I2C used for Accelerometer/Pressure
JshI2CInfo internalI2C;
/// 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
/// counter that counts up if watch has stayed face up or down
volatile unsigned char faceUpCounter;
/// Was the watch face-up? we use this when firing events
volatile bool wasFaceUp;
/// Was the watch charging? we use this when firing events
volatile bool wasCharging;
/// time since LCD contents were last modified
volatile uint16_t flipTimer; // in ms
/// How long has BTN1 been held down for
volatile uint16_t btn1Timer; // 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 the LCD on?
bool lcdPowerOn;
/// LCD Brightness - 255=full
uint8_t lcdBrightness;
/// Is the compass on?
bool compassPowerOn;
// compass data
Vector3 mag, magmin, magmax;
/// accelerometer data
Vector3 acc;
/// squared accelerometer magnitude
int accMagSquared;
/// accelerometer difference since last reading
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;
// Gesture settings
/// how big a difference before we consider a gesture started?
int accelGestureStartThresh = 800*800;
/// how small a difference before we consider a gesture ended?
int accelGestureEndThresh = 2000*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;
// Step data
/// How low must acceleration magnitude squared get before we consider the next rise a step?
int stepCounterThresholdLow = (8192-80)*(8192-80);
/// How high must acceleration magnitude squared get before we consider it a step?
int stepCounterThresholdHigh = (8192+80)*(8192+80);
/// Current steps since reset
uint32_t stepCounter;
/// has acceleration counter passed stepCounterThresholdLow?
bool stepWasLow;
/// 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*
int8_t hrmHistory[HRM_HISTORY_LEN];
volatile uint8_t hrmHistoryIdx;
/// Promise when beep is finished
JsVar *promiseBeep;
/// Promise when buzz is finished
JsVar *promiseBuzz;
typedef enum {
JSBT_NONE,
JSBT_LCD_ON = 1,
JSBT_LCD_OFF = 2,
JSBT_ACCEL_DATA = 4, ///< need to push xyz data to JS
JSBT_ACCEL_TAPPED = 8, ///< tap event detected
JSBT_GPS_DATA = 16, ///< we got a complete set of GPS data in 'gpsFix'
JSBT_GPS_DATA_LINE = 32, ///< we got a line of GPS data
JSBT_MAG_DATA = 64, ///< need to push magnetometer data to JS
JSBT_RESET = 128, ///< reset the watch and reload code from flash
JSBT_GESTURE_DATA = 256, ///< we have data from a gesture
JSBT_CHARGE_EVENT = 512, ///< we need to fire a charging event
JSBT_STEP_EVENT = 1024, ///< we've detected a step via the pedometer
JSBT_SWIPE_LEFT = 2048, ///< swiped left over touchscreen
JSBT_SWIPE_RIGHT = 4096, ///< swiped right over touchscreen
JSBT_SWIPE_MASK = JSBT_SWIPE_LEFT | JSBT_SWIPE_RIGHT,
JSBT_TOUCH_LEFT = 8192, ///< touch lhs of touchscreen
JSBT_TOUCH_RIGHT = 16384, ///< touch rhs of touchscreen
JSBT_TOUCH_MASK = JSBT_TOUCH_LEFT | JSBT_TOUCH_RIGHT,
JSBT_HRM_DATA = 32768, ///< Heart rate data is ready for analysis
} JsBangleTasks;
JsBangleTasks bangleTasks;
/// Flip buffer contents with the screen.
void lcd_flip(JsVar *parent) {
if (lcdPowerTimeout && !lcdPowerOn) {
// LCD was turned off, turn it back on
jswrap_banglejs_setLCDPower(1);
}
flipTimer = 0;
JsVar *graphics = jsvObjectGetChild(execInfo.hiddenRoot, JS_GRAPHICS_VAR, 0);
if (!graphics) return;
JsGraphics gfx;
if (!graphicsGetFromVar(&gfx, graphics)) return;
lcdST7789_flip(&gfx);
graphicsSetVar(&gfx);
jsvUnLock(graphics);
}
char clipi8(int x) {
if (x<-128) return -128;
if (x>127) return 127;
return (char)x;
}
#ifndef EMSCRIPTEN
/* Scan peripherals for any data that's needed
* Also, holding down both buttons will reboot */
void peripheralPollHandler() {
//jswrap_banglejs_ioWr(IOEXP_HRM,0); // debug using HRM LED
// Handle watchdog
if (!(jshPinGetValue(BTN1_PININDEX) && jshPinGetValue(BTN2_PININDEX)))
jshKickWatchDog();
// power on display if a button is pressed
if (flipTimer < TIMER_MAX)
flipTimer += pollInterval;
// If BTN3 is held down, trigger a soft reset so we go back to the clock
if (jshPinGetValue(BTN3_PININDEX)) {
if (btn1Timer < TIMER_MAX) {
btn1Timer += pollInterval;
if (btn1Timer >= BTN_LOAD_TIMEOUT) {
bangleTasks |= JSBT_RESET;
btn1Timer = TIMER_MAX;
// execInfo.execute |= EXEC_CTRL_C|EXEC_CTRL_C_WAIT; // set CTRLC
}
}
} else {
btn1Timer = 0;
}
if (lcdPowerTimeout && lcdPowerOn && flipTimer>=lcdPowerTimeout) {
// 10 seconds of inactivity, turn off display
bangleTasks |= JSBT_LCD_OFF;
}
// check charge status
bool isCharging = jswrap_banglejs_isCharging();
if (isCharging != wasCharging) {
wasCharging = isCharging;
bangleTasks |= JSBT_CHARGE_EVENT;
}
if (i2cBusy) return;
unsigned char buf[7];
// check the magnetometer if we had it on
if (compassPowerOn) {
buf[0]=0x10;
jsi2cWrite(&internalI2C, MAG_ADDR, 1, buf, true);
jsi2cRead(&internalI2C, MAG_ADDR, 7, buf, true);
if (buf[0]&1) { // then we have data (hopefully? No datasheet)
mag.y = buf[1] | (buf[2]<<8);
mag.x = buf[3] | (buf[4]<<8);
mag.z = buf[5] | (buf[6]<<8);
if (mag.x<magmin.x) magmin.x=mag.x;
if (mag.y<magmin.y) magmin.y=mag.y;
if (mag.z<magmin.z) magmin.z=mag.z;
if (mag.x>magmax.x) magmax.x=mag.x;
if (mag.y>magmax.y) magmax.y=mag.y;
if (mag.z>magmax.z) magmax.z=mag.z;
bangleTasks |= JSBT_MAG_DATA;
}
}
// poll KX023 accelerometer (no other way as IRQ line seems disconnected!)
// read interrupt source data
buf[0]=0x12; // INS1
jsi2cWrite(&internalI2C, ACCEL_ADDR, 1, buf, true);
jsi2cRead(&internalI2C, ACCEL_ADDR, 2, buf, true);
// 0 -> 0x12 INS1 - tap event
// 1 -> 0x13 INS2 - what kind of event
bool hasAccelData = (buf[1]&16)!=0; // DRDY
int tapType = (buf[1]>>2)&3; // TDTS0/1
if (tapType) {
// report tap
tapInfo = buf[0] | (tapType<<6);
bangleTasks |= JSBT_ACCEL_TAPPED;
// clear the IRQ flags
buf[0]=0x17;
jsi2cWrite(&internalI2C, ACCEL_ADDR, 1, buf, true);
jsi2cRead(&internalI2C, ACCEL_ADDR, 1, buf, true);
}
if (hasAccelData) {
buf[0]=6;
jsi2cWrite(&internalI2C, ACCEL_ADDR, 1, buf, true);
jsi2cRead(&internalI2C, ACCEL_ADDR, 6, buf, true);
// work out current reading in 16 bit
short newx = (buf[1]<<8)|buf[0];
short newy = (buf[3]<<8)|buf[2];
short newz = (buf[5]<<8)|buf[4];
int dx = newx-acc.x;
int dy = newy-acc.y;
int dz = newz-acc.z;
acc.x = newx;
acc.y = newy;
acc.z = newz;
accMagSquared = acc.x*acc.x + acc.y*acc.y + acc.z*acc.z;
accdiff = dx*dx + dy*dy + dz*dz;
// save history
accHistoryIdx = (accHistoryIdx+3) % sizeof(accHistory);
accHistory[accHistoryIdx ] = clipi8(newx>>7);
accHistory[accHistoryIdx+1] = clipi8(newy>>7);
accHistory[accHistoryIdx+2] = clipi8(newz>>7);
// trigger accelerometer data task
bangleTasks |= JSBT_ACCEL_DATA;
// check for step counter
if (accMagSquared < stepCounterThresholdLow)
stepWasLow = true;
else if ((accMagSquared > stepCounterThresholdHigh) && stepWasLow) {
stepWasLow = false;
stepCounter++;
bangleTasks |= JSBT_STEP_EVENT;
}
// checking for gestures
if (accGestureCount==0) { // no gesture yet
// if movement is eniugh, start one
if (accdiff > accelGestureStartThresh) {
accIdleCount = 0;
accGestureCount = 1;
}
} else { // we're recording a gesture
// keep incrementing gesture size
if (accGestureCount < 255)
accGestureCount++;
// if idle for long enough...
if (accdiff < accelGestureEndThresh) {
if (accIdleCount<255) accIdleCount++;
if (accIdleCount==accelGestureInactiveCount) {
// inactive for long enough for a gesture, but not too long
accGestureRecordedCount = accGestureCount;
if ((accGestureCount >= accelGestureMinLength) &&
(accGestureCount < ACCEL_HISTORY_LEN))
bangleTasks |= JSBT_GESTURE_DATA; // trigger a gesture task
accGestureCount = 0; // stop the gesture
}
} else if (accIdleCount < accelGestureInactiveCount)
accIdleCount = 0; // it was inactive but not long enough to trigger a gesture
}
}
//jswrap_banglejs_ioWr(IOEXP_HRM,1); // debug using HRM LED
}
void hrmPollHandler() {
//jswrap_banglejs_ioWr(IOEXP_HRM,0); // on
nrf_saadc_input_t ain = 1 + (pinInfo[HEARTRATE_PIN_ANALOG].analog & JSH_MASK_ANALOG_CH);
nrf_saadc_channel_config_t config;
config.acq_time = NRF_SAADC_ACQTIME_10US;
config.gain = NRF_SAADC_GAIN1;
config.mode = NRF_SAADC_MODE_SINGLE_ENDED;
config.pin_p = ain;
config.pin_n = ain;
config.reference = NRF_SAADC_REFERENCE_INTERNAL;
config.resistor_p = NRF_SAADC_RESISTOR_DISABLED;
config.resistor_n = NRF_SAADC_RESISTOR_DISABLED;
// make reading
nrf_saadc_enable();
nrf_saadc_resolution_set(NRF_SAADC_RESOLUTION_8BIT);
nrf_saadc_channel_init(0, &config);
extern nrf_saadc_value_t nrf_analog_read();
int v = nrf_analog_read();
if (v<-128) v=-128;
if (v>127) v=127;
hrmHistory[hrmHistoryIdx] = v;
hrmHistoryIdx = (hrmHistoryIdx+1) & (HRM_HISTORY_LEN-1);
if (hrmHistoryIdx==0)
bangleTasks |= JSBT_HRM_DATA;
//jswrap_banglejs_ioWr(IOEXP_HRM,1); // off
}
void backlightOnHandler() {
if (i2cBusy) return;
jswrap_banglejs_ioWr(IOEXP_LCD_BACKLIGHT, 0); // backlight on
}
void backlightOffHandler() {
if (i2cBusy) return;
jswrap_banglejs_ioWr(IOEXP_LCD_BACKLIGHT, 1); // backlight off
}
#endif // !EMSCRIPTEN
void btnHandlerCommon(int button, bool state, IOEventFlags flags) {
// wake up
if (lcdPowerTimeout) {
if (button<=3) {
// if a 'hard' button, turn LCD on
flipTimer = 0;
if (!lcdPowerOn) {
bangleTasks |= JSBT_LCD_ON;
return; // don't push button event if the LCD is off
}
} else {
// on touchscreen, keep LCD on if it was in previously
if (lcdPowerOn)
flipTimer = 0;
}
}
// Add to the event queue for normal processing for watches
jshPushIOEvent(flags | (state?EV_EXTI_IS_HIGH:0), jshGetSystemTime());
}
void btnTouchHandler() {
TouchState state =
(jshPinGetValue(BTN4_PININDEX)?TS_LEFT:0) |
(jshPinGetValue(BTN5_PININDEX)?TS_RIGHT:0);
touchStatus |= state;
if ((touchLastState2==TS_RIGHT && touchLastState==TS_BOTH && state==TS_LEFT) ||
(touchLastState==TS_RIGHT && state==1)) {
touchStatus |= TS_SWIPED;
bangleTasks |= JSBT_SWIPE_LEFT;
}
if ((touchLastState2==TS_LEFT && touchLastState==TS_BOTH && state==TS_RIGHT) ||
(touchLastState==TS_LEFT && state==TS_RIGHT)) {
touchStatus |= TS_SWIPED;
bangleTasks |= JSBT_SWIPE_RIGHT;
}
if (!state) {
if (touchLastState && !(touchStatus&TS_SWIPED)) {
if (touchStatus&TS_LEFT) bangleTasks |= JSBT_TOUCH_LEFT;
if (touchStatus&TS_RIGHT) bangleTasks |= JSBT_TOUCH_RIGHT;
}
touchStatus = TS_NONE;
}
touchLastState2 = touchLastState;
touchLastState = state;
}
void btn1Handler(bool state, IOEventFlags flags) {
btnHandlerCommon(1,state,flags);
}
void btn2Handler(bool state, IOEventFlags flags) {
btnHandlerCommon(2,state,flags);
}
void btn3Handler(bool state, IOEventFlags flags) {
btnHandlerCommon(3,state,flags);
}
void btn4Handler(bool state, IOEventFlags flags) {
btnTouchHandler();
btnHandlerCommon(4,state,flags);
}
void btn5Handler(bool state, IOEventFlags flags) {
btnTouchHandler();
btnHandlerCommon(5,state,flags);
}
/// Turn just the backlight on or off (or adjust brightness)
static void jswrap_banglejs_setLCDPowerBacklight(bool isOn) {
#ifndef EMSCRIPTEN
jstStopExecuteFn(backlightOnHandler, 0);
jstStopExecuteFn(backlightOffHandler, 0);
if (isOn) { // wake
if (lcdBrightness>0) {
jswrap_banglejs_ioWr(IOEXP_LCD_BACKLIGHT, 0); // backlight on
if (lcdBrightness < 255) { // only do PWM if brightness isn't full
JsSysTime now = jshGetSystemTime();
JsSysTime interval = jshGetTimeFromMilliseconds(10); // how often do we switch - 100Hz
JsSysTime ontime = interval*lcdBrightness/255; // how long to we stay on for?
jstExecuteFn(backlightOnHandler, NULL, now+interval, interval);
jstExecuteFn(backlightOffHandler, NULL, now+interval+ontime, interval);
}
} else { // lcdBrightness == 0
jswrap_banglejs_ioWr(IOEXP_LCD_BACKLIGHT, 1); // backlight off
}
} else { // sleep
jswrap_banglejs_ioWr(IOEXP_LCD_BACKLIGHT, 1); // backlight off
}
#endif
}
/*JSON{
"type" : "staticmethod",
"class" : "Bangle",
"name" : "setLCDPower",
"generate" : "jswrap_banglejs_setLCDPower",
"params" : [
["isOn","bool","True if the LCD should be on, false if not"]
],
"ifdef" : "BANGLEJS"
}
This function can be used to turn Bangle.js's LCD off or on.
**When on full, the LCD draws roughly 40mA.** You can adjust
When brightness using `Bange.setLCDBrightness`.
*/
void jswrap_banglejs_setLCDPower(bool isOn) {
if (isOn) { // wake
lcdST7789_cmd(0x11, 0, NULL); // SLPOUT
jshDelayMicroseconds(20);
lcdST7789_cmd(0x29, 0, NULL);
} else { // sleep
lcdST7789_cmd(0x28, 0, NULL);
jshDelayMicroseconds(20);
lcdST7789_cmd(0x10, 0, NULL); // SLPIN
}
jswrap_banglejs_setLCDPowerBacklight(isOn);
if (lcdPowerOn != isOn) {
JsVar *bangle =jsvObjectGetChild(execInfo.root, "Bangle", 0);
if (bangle) {
JsVar *v = jsvNewFromBool(isOn);
jsiQueueObjectCallbacks(bangle, JS_EVENT_PREFIX"lcdPower", &v, 1);
jsvUnLock(v);
}
jsvUnLock(bangle);
}
flipTimer = 0;
lcdPowerOn = isOn;
}
/*JSON{
"type" : "staticmethod",
"class" : "Bangle",
"name" : "setLCDBrightness",
"generate" : "jswrap_banglejs_setLCDBrightness",
"params" : [
["brightness","float","The brightness of Bangle.js's display - from 0(off) to 1(on full)"]
],
"ifdef" : "BANGLEJS"
}
This function can be used to adjust the brightness of Bangle.js's display, and
hence prolong its battery life.
Due to hardware design constraints, software PWM has to be used which
means that the display may flicker slightly when Bluetooth is active
and the display is not at full power.
**Power consumption**
* 0 = 7mA
* 0.1 = 12mA
* 0.2 = 18mA
* 0.5 = 28mA
* 0.9 = 40mA (switching overhead)
* 1 = 40mA
*/
void jswrap_banglejs_setLCDBrightness(JsVarFloat v) {
int b = (int)(v*256 + 0.5);
if (b<0) b=0;
if (b>255) b=255;
lcdBrightness = b;
if (lcdPowerOn) // need to re-run to adjust brightness
jswrap_banglejs_setLCDPowerBacklight(1);
}
/*JSON{
"type" : "staticmethod",
"class" : "Bangle",
"name" : "setLCDMode",
"generate" : "jswrap_banglejs_setLCDMode",
"params" : [
["mode","JsVar","The LCD mode (See below)"]
],
"ifdef" : "BANGLEJS"
}
This function can be used to change the way graphics is handled on Bangle.js.
Available options for `Bangle.setLCDMode` are:
* `Bangle.setLCDMode()` or `Bangle.setLCDMode("direct")` (the default) - The drawable area is 240x240 16 bit. Unbuffered, so draw calls take effect immediately. Terminal and vertical scrolling work (horizontal scrolling doesn't).
* `Bangle.setLCDMode("doublebuffered")` - The drawable area is 240x160 16 bit, terminal and scrolling will not work.
* `Bangle.setLCDMode("120x120")` - The drawable area is 120x120 8 bit, `g.getPixel`, terminal, and full scrolling work.
* `Bangle.setLCDMode("80x80")` - The drawable area is 80x80 8 bit, `g.getPixel`, terminal, and full scrolling work.
You can also call `Bangle.setLCDMode()` to return to normal, unbuffered `"direct"` mode.
*/
void jswrap_banglejs_setLCDMode(JsVar *mode) {
LCDST7789Mode lcdMode = LCDST7789_MODE_UNBUFFERED;
if (jsvIsUndefined(mode) || jsvIsStringEqual(mode,"direct"))
lcdMode = LCDST7789_MODE_UNBUFFERED;
else if (jsvIsStringEqual(mode,"null"))
lcdMode = LCDST7789_MODE_NULL;
else if (jsvIsStringEqual(mode,"doublebuffered"))
lcdMode = LCDST7789_MODE_DOUBLEBUFFERED;
else if (jsvIsStringEqual(mode,"120x120"))
lcdMode = LCDST7789_MODE_BUFFER_120x120;
else if (jsvIsStringEqual(mode,"80x80"))
lcdMode = LCDST7789_MODE_BUFFER_80x80;
else
jsExceptionHere(JSET_ERROR,"Unknown LCD Mode %j",mode);
JsVar *graphics = jsvObjectGetChild(execInfo.hiddenRoot, JS_GRAPHICS_VAR, 0);
if (!graphics) return;
JsGraphics gfx;
if (!graphicsGetFromVar(&gfx, graphics)) return;
// remove the buffer if it was defined
jsvObjectSetOrRemoveChild(gfx.graphicsVar, "buffer", 0);
switch (lcdMode) {
case LCDST7789_MODE_NULL:
case LCDST7789_MODE_UNBUFFERED:
gfx.data.width = LCD_WIDTH;
gfx.data.height = LCD_HEIGHT;
gfx.data.bpp = 16;
break;
case LCDST7789_MODE_DOUBLEBUFFERED:
gfx.data.width = LCD_WIDTH;
gfx.data.height = 160;
gfx.data.bpp = 16;
break;
case LCDST7789_MODE_BUFFER_120x120:
gfx.data.width = 120;
gfx.data.height = 120;
gfx.data.bpp = 8;
jsvObjectSetChildAndUnLock(gfx.graphicsVar, "buffer", jswrap_arraybuffer_constructor(120*120));
break;
case LCDST7789_MODE_BUFFER_80x80:
gfx.data.width = 80;
gfx.data.height = 80;
gfx.data.bpp = 8;
jsvObjectSetChildAndUnLock(gfx.graphicsVar, "buffer", jswrap_arraybuffer_constructor(80*80));
break;
}
graphicsStructResetState(&gfx); // reset colour, cliprect, etc
graphicsSetVar(&gfx);
jsvUnLock(graphics);
lcdST7789_setMode( lcdMode );
}
/*JSON{
"type" : "staticmethod",
"class" : "Bangle",
"name" : "getLCDMode",
"generate" : "jswrap_banglejs_getLCDMode",
"return" : ["JsVar","The LCD mode as a String"],
"ifdef" : "BANGLEJS"
}
The current LCD mode.
See `Bangle.setLCDMode` for examples.
*/
JsVar *jswrap_banglejs_getLCDMode() {
const char *name=0;
switch (lcdST7789_getMode()) {
case LCDST7789_MODE_NULL:
name = "null";
break;
case LCDST7789_MODE_UNBUFFERED:
name = "direct";
break;
case LCDST7789_MODE_DOUBLEBUFFERED:
name = "doublebuffered";
break;
case LCDST7789_MODE_BUFFER_120x120:
name = "120x120";
break;
case LCDST7789_MODE_BUFFER_80x80:
name = "80x80";
break;
}
if (!name) return 0;
return jsvNewFromString(name);
}
/*JSON{
"type" : "staticmethod",
"class" : "Bangle",
"name" : "setLCDOffset",
"generate" : "jswrap_banglejs_setLCDOffset",
"params" : [
["y","int","The amount of pixels to shift the LCD up or down"]
],
"ifdef" : "BANGLEJS"
}
This can be used to move the displayed memory area up or down temporarily. It's
used for displaying notifications while keeping the main display contents
intact.
*/
void jswrap_banglejs_setLCDOffset(int y) {
lcdST7789_setYOffset(y);
}
/*JSON{
"type" : "staticmethod",
"class" : "Bangle",
"name" : "setLCDTimeout",
"generate" : "jswrap_banglejs_setLCDTimeout",
"params" : [
["isOn","float","The timeout of the display in seconds, or `0`/`undefined` to turn power saving off. Default is 10 seconds."]
],
"ifdef" : "BANGLEJS"
}
This function can be used to turn Bangle.js's LCD power saving on or off.
With power saving off, the display will remain in the state you set it with `Bangle.setLCDPower`.
With power saving on, the display will turn on if a button is pressed, the watch is turned face up, or the screen is updated. It'll turn off automatically after the given timeout.
*/
void jswrap_banglejs_setLCDTimeout(JsVarFloat timeout) {
if (!isfinite(timeout)) lcdPowerTimeout=0;
else lcdPowerTimeout = timeout*1000;
if (lcdPowerTimeout<0) lcdPowerTimeout=0;
}
/*JSON{
"type" : "staticmethod",
"class" : "Bangle",
"name" : "setPollInterval",
"generate" : "jswrap_banglejs_setPollInterval",
"params" : [
["interval","float","Polling interval in milliseconds"]
],
"ifdef" : "BANGLEJS"
}
Set how often the watch should poll for new acceleration/gyro data
*/
void jswrap_banglejs_setPollInterval(JsVarFloat interval) {
if (!isfinite(interval) || interval<10 || interval>ACCEL_POLL_INTERVAL_MAX) {
jsExceptionHere(JSET_ERROR, "Invalid interval");
return;
}
pollInterval = (uint16_t)interval;
#ifndef EMSCRIPTEN
JsSysTime t = jshGetTimeFromMilliseconds(pollInterval);
jstStopExecuteFn(peripheralPollHandler, 0);
jstExecuteFn(peripheralPollHandler, NULL, jshGetSystemTime()+t, t);
#endif
}
/*JSON{
"type" : "staticmethod",
"class" : "Bangle",
"name" : "setOptions",
"generate" : "jswrap_banglejs_setOptions",
"params" : [
["options","JsVar",""]
],
"ifdef" : "BANGLEJS"
}
Set internal options used for gestures, step counting, etc...
* `gestureStartThresh` how big a difference before we consider a gesture started? default = `sqr(800)`
* `gestureEndThresh` how small a difference before we consider a gesture ended? default = `sqr(2000)`
* `gestureInactiveCount` how many samples do we keep after a gesture has ended? default = `4`
* `gestureMinLength` how many samples must a gesture have before we notify about it? default = `10`
* `stepCounterThresholdLow` How low must acceleration magnitude squared get before we consider the next rise a step? default = `sqr(8192-80)`
* `stepCounterThresholdHigh` How high must acceleration magnitude squared get before we consider it a step? default = `sqr(8192+80)`
*/
void jswrap_banglejs_setOptions(JsVar *options) {
jsvConfigObject configs[] = {
{"gestureStartThresh", JSV_INTEGER, &accelGestureStartThresh},
{"gestureEndThresh", JSV_INTEGER, &accelGestureEndThresh},
{"gestureInactiveCount", JSV_INTEGER, &accelGestureInactiveCount},
{"gestureMinLength", JSV_INTEGER, &accelGestureMinLength},
{"stepCounterThresholdLow", JSV_INTEGER, &stepCounterThresholdLow},
{"stepCounterThresholdHigh", JSV_INTEGER, &stepCounterThresholdHigh}
};
jsvReadConfigObject(options, configs, sizeof(configs) / sizeof(jsvConfigObject));
}
/*JSON{
"type" : "staticmethod",
"class" : "Bangle",
"name" : "isLCDOn",
"generate" : "jswrap_banglejs_isLCDOn",
"return" : ["bool","Is the display on or not?"],
"ifdef" : "BANGLEJS"
}
*/
// emscripten bug means we can't use 'bool' as return value here!
int jswrap_banglejs_isLCDOn() {
return lcdPowerOn;
}
/*JSON{
"type" : "staticmethod",
"class" : "Bangle",
"name" : "isCharging",
"generate" : "jswrap_banglejs_isCharging",
"return" : ["bool","Is the battery charging or not?"],
"ifdef" : "BANGLEJS"
}
*/
// emscripten bug means we can't use 'bool' as return value here!
int jswrap_banglejs_isCharging() {
return !jshPinGetValue(BAT_PIN_CHARGING);
}
/// get battery percentage
JsVarInt jswrap_banglejs_getBattery() {
JsVarFloat v = jshPinAnalog(BAT_PIN_VOLTAGE);
const JsVarFloat vlo = 0.51;
const JsVarFloat vhi = 0.62;
int pc = (v-vlo)*100/(vhi-vlo);
if (pc>100) pc=100;
if (pc<0) pc=0;
return pc;
}
/*JSON{
"type" : "staticmethod",
"class" : "Bangle",
"name" : "lcdWr",
"generate" : "jswrap_banglejs_lcdWr",
"params" : [
["cmd","int",""],
["data","JsVar",""]
],
"ifdef" : "BANGLEJS"
}
Writes a command directly to the ST7735 LCD controller
*/
void jswrap_banglejs_lcdWr(JsVarInt cmd, JsVar *data) {