/
jswrap_espruino.c
2618 lines (2341 loc) · 83.7 KB
/
jswrap_espruino.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) 2013 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
*
* JavaScript methods for Espruino utility functions
* ----------------------------------------------------------------------------
*/
#include "jswrap_espruino.h"
#include "jswrap_math.h"
#include "jswrap_arraybuffer.h"
#include "jswrap_json.h"
#include "jsflash.h"
#include "jswrapper.h"
#include "jsinteractive.h"
#include "jswrap_interactive.h"
#include "jstimer.h"
#ifdef PUCKJS
#include "jswrap_puck.h" // jswrap_puck_getTemperature
#endif
/*JSON{
"type" : "variable",
"name" : "__FILE__",
"generate" : false,
"return" : ["JsVar","The filename of the JavaScript that is currently executing"]
}
The filename of the JavaScript that is currently executing.
If `load` has been called with a filename (eg `load("myfile.js")`) then
`__FILE__` is set to that filename. Otherwise (eg `load()`) or immediately
after booting, `__FILE__` is not set.
*//*Documentation only*/
/*JSON{
"type" : "class",
"class" : "E"
}
This is the built-in JavaScript class for Espruino utility functions.
*/
/*JSON{
"type" : "event",
"class" : "E",
"name" : "init"
}
This event is called right after the board starts up, and has a similar effect
to creating a function called `onInit`.
For example to write `"Hello World"` every time Espruino starts, use:
```
E.on('init', function() {
console.log("Hello World!");
});
```
**Note:** that subsequent calls to `E.on('init', ` will **add** a new handler,
rather than replacing the last one. This allows you to write modular code -
something that was not possible with `onInit`.
*/
/*JSON{
"type" : "event",
"class" : "E",
"name" : "kill"
}
This event is called just before the device shuts down for commands such as
`reset()`, `load()`, `save()`, `E.reboot()` or `Bangle.off()`
For example to write `"Bye!"` just before shutting down use:
```
E.on('kill', function() {
console.log("Bye!");
});
```
**NOTE:** This event is not called when the device is 'hard reset' - for example
by removing power, hitting an actual reset button, or via a Watchdog timer
reset.
*/
/*JSON{
"type" : "event",
"class" : "E",
"name" : "errorFlag",
"params" : [
["errorFlags","JsVar","An array of new error flags, as would be returned by `E.getErrorFlags()`. Error flags that were present before won't be reported."]
],
"typescript" : "on(event: \"errorFlag\", callback: (errorFlags: ErrorFlag[]) => void): void;"
}
This event is called when an error is created by Espruino itself (rather than JS
code) which changes the state of the error flags reported by `E.getErrorFlags()`
This could be low memory, full buffers, UART overflow, etc. `E.getErrorFlags()`
has a full description of each type of error.
This event will only be emitted when error flag is set. If the error flag was
already set nothing will be emitted. To clear error flags so that you do get a
callback each time a flag is set, call `E.getErrorFlags()`.
*/
/*JSON{
"type" : "event",
"class" : "E",
"name" : "touch",
"params" : [
["x","int","X coordinate in display coordinates"],
["y","int","Y coordinate in display coordinates"],
["b","int","Touch count - 0 for released, 1 for pressed"]
]
}
This event is called when a full touchscreen device on an Espruino is interacted
with.
**Note:** This event is not implemented on Bangle.js because it only has a two
area touchscreen.
To use the touchscreen to draw lines, you could do:
```
var last;
E.on('touch',t=>{
if (last) g.lineTo(t.x, t.y);
else g.moveTo(t.x, t.y);
last = t.b;
});
```
*/
/*JSON{
"type" : "staticmethod",
"class" : "E",
"name" : "getTemperature",
"generate" : "jswrap_espruino_getTemperature",
"return" : ["float","The temperature in degrees C"]
}
Use the microcontroller's internal thermistor to work out the temperature.
On Puck.js v2.0 this will use the on-board PCT2075TP temperature sensor, but on
other devices it may not be desperately well calibrated.
While this is implemented on Espruino boards, it may not be implemented on other
devices. If so it'll return NaN.
**Note:** This is not entirely accurate and varies by a few degrees from chip
to chip. It measures the **die temperature**, so when connected to USB it could
be reading 10 over degrees C above ambient temperature. When running from
battery with `setDeepSleep(true)` it is much more accurate though.
*/
JsVarFloat jswrap_espruino_getTemperature() {
#ifdef PUCKJS
return jswrap_puck_getTemperature();
#else
return jshReadTemperature();
#endif
}
/*JSON{
"type" : "staticmethod",
"ifndef" : "SAVE_ON_FLASH",
"class" : "E",
"name" : "getAnalogVRef",
"generate_full" : "jshReadVRef()",
"return" : ["float","The voltage (in Volts) that a reading of 1 from `analogRead` actually represents - usually around 3.3v"]
}
Check the internal voltage reference. To work out an actual voltage of an input
pin, you can use `analogRead(pin)*E.getAnalogVRef()`
**Note:** This value is calculated by reading the voltage on an internal
voltage reference with the ADC. It will be slightly noisy, so if you need this
for accurate measurements we'd recommend that you call this function several
times and average the results.
While this is implemented on Espruino boards, it may not be implemented on other
devices. If so it'll return NaN.
*/
int nativeCallGetCType() {
if (lex->tk == LEX_R_VOID) {
jslMatch(LEX_R_VOID);
return JSWAT_VOID;
}
if (lex->tk == LEX_ID) {
int t = -1;
char *name = jslGetTokenValueAsString();
if (strcmp(name,"int")==0) t=JSWAT_INT32;
if (strcmp(name,"double")==0) t=JSWAT_JSVARFLOAT;
if (strcmp(name,"bool")==0) t=JSWAT_BOOL;
if (strcmp(name,"Pin")==0) t=JSWAT_PIN;
if (strcmp(name,"JsVar")==0) t=JSWAT_JSVAR;
if (strcmp(name,"float")==0) t=JSWAT_FLOAT32;
jslMatch(LEX_ID);
return t;
}
return -1; // unknown
}
/*JSON{
"type" : "staticmethod",
"ifndef" : "SAVE_ON_FLASH",
"class" : "E",
"name" : "nativeCall",
"generate" : "jswrap_espruino_nativeCall",
"params" : [
["addr","int","The address in memory of the function (or offset in `data` if it was supplied"],
["sig","JsVar","The signature of the call, `returnType (arg1,arg2,...)`. Allowed types are `void`,`bool`,`int`,`double`,`float`,`Pin`,`JsVar`"],
["data","JsVar","(Optional) A string containing the function itself. If not supplied then 'addr' is used as an absolute address."]
],
"return" : ["JsVar","The native function"],
"typescript" : "nativeCall(addr: number, sig: string, data?: string): any;"
}
ADVANCED: It's very easy to crash Espruino using this function if
you get the code/arguments you supply wrong!
Create a native function that executes the code at the given address, e.g.
`E.nativeCall(0x08012345,'double (double,double)')(1.1, 2.2)`
If you're executing a thumb function, you'll almost certainly need to set the
bottom bit of the address to 1.
Note it's not guaranteed that the call signature you provide can be used - there
are limits on the number of arguments allowed (5).
When supplying `data`, if it is a 'flat string' then it will be used directly,
otherwise it'll be converted to a flat string and used.
The argument types in `sig` are:
* `void` - returns nothing
* `bool` - boolean value
* `int` - 32 bit integer
* `double` - 64 bit floating point
* `float` - 32 bit floating point (2v21 and later)
* `Pin` - Espruino 'pin' value (8 bit integer)
* `JsVar` - Pointer to an Espruino JsVar structure
*/
JsVar *jswrap_espruino_nativeCall(JsVarInt addr, JsVar *signature, JsVar *data) {
unsigned int argTypes = 0;
if (jsvIsUndefined(signature)) {
// Nothing to do
} else if (jsvIsString(signature)) {
JsLex lex;
JsLex *oldLex = jslSetLex(&lex);
jslInit(signature);
int argType;
bool ok = true;
int argNumber = 0;
argType = nativeCallGetCType();
if (argType>=0) argTypes |= (unsigned)argType << (JSWAT_BITS * argNumber++);
else ok = false;
if (ok) ok = jslMatch('(');
while (ok && lex.tk!=LEX_EOF && lex.tk!=')') {
argType = nativeCallGetCType();
if (argType>=0) {
argTypes |= (unsigned)argType << (JSWAT_BITS * argNumber++);
if (lex.tk!=')') ok = jslMatch(',');
} else ok = false;
}
if (ok) ok = jslMatch(')');
jslKill();
jslSetLex(oldLex);
if (argTypes & (unsigned int)~0xFFFF)
ok = false;
if (!ok) {
jsExceptionHere(JSET_ERROR, "Error Parsing signature at argument number %d", argNumber);
return 0;
}
} else {
jsExceptionHere(JSET_ERROR, "Invalid Signature");
return 0;
}
JsVar *fn = jsvNewNativeFunction((void *)(size_t)addr, (unsigned short)argTypes);
if (data) {
JsVar *flat = jsvAsFlatString(data);
jsvAddNamedChildAndUnLock(fn, flat, JSPARSE_FUNCTION_CODE_NAME);
}
return fn;
}
/*JSON{
"type" : "staticmethod",
"ifndef" : "SAVE_ON_FLASH",
"class" : "E",
"name" : "clip",
"generate" : "jswrap_espruino_clip",
"params" : [
["x","float","A floating point value to clip"],
["min","float","The smallest the value should be"],
["max","float","The largest the value should be"]
],
"return" : ["float","The value of x, clipped so as not to be below min or above max."]
}
Clip a number to be between min and max (inclusive)
*/
JsVarFloat jswrap_espruino_clip(JsVarFloat x, JsVarFloat min, JsVarFloat max) {
if (x<min) x=min;
if (x>max) x=max;
return x;
}
/*JSON{
"type" : "staticmethod",
"ifndef" : "SAVE_ON_FLASH",
"class" : "E",
"name" : "sum",
"generate" : "jswrap_espruino_sum",
"params" : [
["arr","JsVar","The array to sum"]
],
"return" : ["float","The sum of the given buffer"],
"typescript" : "sum(arr: string | number[] | ArrayBuffer): number;"
}
Sum the contents of the given Array, String or ArrayBuffer and return the result
*/
JsVarFloat jswrap_espruino_sum(JsVar *arr) {
if (!(jsvIsString(arr) || jsvIsArray(arr) || jsvIsArrayBuffer(arr))) {
jsExceptionHere(JSET_ERROR, "First argument must be Array, not %t", arr);
return NAN;
}
JsVarFloat sum = 0;
JsvIterator itsrc;
jsvIteratorNew(&itsrc, arr, JSIF_DEFINED_ARRAY_ElEMENTS);
while (jsvIteratorHasElement(&itsrc)) {
sum += jsvIteratorGetFloatValue(&itsrc);
jsvIteratorNext(&itsrc);
}
jsvIteratorFree(&itsrc);
return sum;
}
/*JSON{
"type" : "staticmethod",
"ifndef" : "SAVE_ON_FLASH",
"class" : "E",
"name" : "variance",
"generate" : "jswrap_espruino_variance",
"params" : [
["arr","JsVar","The array to work out the variance for"],
["mean","float","The mean value of the array"]
],
"return" : ["float","The variance of the given buffer"],
"typescript" : "variance(arr: string | number[] | ArrayBuffer, mean: number): number;"
}
Work out the variance of the contents of the given Array, String or ArrayBuffer
and return the result. This is equivalent to `v=0;for (i in arr)
v+=Math.pow(mean-arr[i],2)`
*/
JsVarFloat jswrap_espruino_variance(JsVar *arr, JsVarFloat mean) {
if (!(jsvIsIterable(arr))) {
jsExceptionHere(JSET_ERROR, "First argument must iterable, not %t", arr);
return NAN;
}
JsVarFloat variance = 0;
JsvIterator itsrc;
jsvIteratorNew(&itsrc, arr, JSIF_EVERY_ARRAY_ELEMENT);
while (jsvIteratorHasElement(&itsrc)) {
JsVarFloat val = jsvIteratorGetFloatValue(&itsrc);
val -= mean;
variance += val*val;
jsvIteratorNext(&itsrc);
}
jsvIteratorFree(&itsrc);
return variance;
}
/*JSON{
"type" : "staticmethod",
"ifndef" : "SAVE_ON_FLASH",
"class" : "E",
"name" : "convolve",
"generate" : "jswrap_espruino_convolve",
"params" : [
["arr1","JsVar","An array to convolve"],
["arr2","JsVar","An array to convolve"],
["offset","int32","The mean value of the array"]
],
"return" : ["float","The variance of the given buffer"],
"typescript" : "convolve(arr1: string | number[] | ArrayBuffer, arr2: string | number[] | ArrayBuffer, offset: number): number;"
}
Convolve arr1 with arr2. This is equivalent to `v=0;for (i in arr1) v+=arr1[i] *
arr2[(i+offset) % arr2.length]`
*/
JsVarFloat jswrap_espruino_convolve(JsVar *arr1, JsVar *arr2, int offset) {
if (!(jsvIsIterable(arr1)) ||
!(jsvIsIterable(arr2))) {
jsExceptionHere(JSET_ERROR, "Expecting first 2 arguments to be iterable, not %t and %t", arr1, arr2);
return NAN;
}
JsVarFloat conv = 0;
JsvIterator it1;
jsvIteratorNew(&it1, arr1, JSIF_EVERY_ARRAY_ELEMENT);
JsvIterator it2;
jsvIteratorNew(&it2, arr2, JSIF_EVERY_ARRAY_ELEMENT);
// get iterator2 at the correct offset
int l = (int)jsvGetLength(arr2);
offset = offset % l;
if (offset<0) offset += l;
while (offset-->0)
jsvIteratorNext(&it2);
while (jsvIteratorHasElement(&it1)) {
conv += jsvIteratorGetFloatValue(&it1) * jsvIteratorGetFloatValue(&it2);
jsvIteratorNext(&it1);
jsvIteratorNext(&it2);
// restart iterator if it hit the end
if (!jsvIteratorHasElement(&it2)) {
jsvIteratorFree(&it2);
jsvIteratorNew(&it2, arr2, JSIF_EVERY_ARRAY_ELEMENT);
}
}
jsvIteratorFree(&it1);
jsvIteratorFree(&it2);
return conv;
}
#if defined(SAVE_ON_FLASH_MATH) || defined(BANGLEJS)
#define FFTDATATYPE double
#else
#define FFTDATATYPE float
#endif
// http://paulbourke.net/miscellaneous/dft/
/*
This computes an in-place complex-to-complex FFT
x and y are the real and imaginary arrays of 2^m points.
dir = 1 gives forward transform
dir = -1 gives reverse transform
*/
short FFT(short int dir,long m,FFTDATATYPE *x,FFTDATATYPE *y)
{
long n,i,i1,j,k,i2,l,l1,l2;
FFTDATATYPE c1,c2,tx,ty,t1,t2,u1,u2,z;
/* Calculate the number of points */
n = 1;
for (i=0;i<m;i++)
n *= 2;
/* Do the bit reversal */
i2 = n >> 1;
j = 0;
for (i=0;i<n-1;i++) {
if (i < j) {
tx = x[i];
ty = y[i];
x[i] = x[j];
y[i] = y[j];
x[j] = tx;
y[j] = ty;
}
k = i2;
while (k <= j) {
j -= k;
k >>= 1;
}
j += k;
}
/* Compute the FFT */
c1 = -1.0;
c2 = 0.0;
l2 = 1;
for (l=0;l<m;l++) {
l1 = l2;
l2 <<= 1;
u1 = 1.0;
u2 = 0.0;
for (j=0;j<l1;j++) {
for (i=j;i<n;i+=l2) {
i1 = i + l1;
t1 = u1 * x[i1] - u2 * y[i1];
t2 = u1 * y[i1] + u2 * x[i1];
x[i1] = x[i] - t1;
y[i1] = y[i] - t2;
x[i] += t1;
y[i] += t2;
}
z = u1 * c1 - u2 * c2;
u2 = u1 * c2 + u2 * c1;
u1 = z;
}
c2 = (FFTDATATYPE)jswrap_math_sqrt((1.0 - c1) / 2.0);
if (dir == 1)
c2 = -c2;
c1 = (FFTDATATYPE)jswrap_math_sqrt((1.0 + c1) / 2.0);
}
/* Scaling for forward transform */
if (dir == 1) {
for (i=0;i<n;i++) {
x[i] /= (FFTDATATYPE)n;
y[i] /= (FFTDATATYPE)n;
}
}
return(TRUE);
}
/*JSON{
"type" : "staticmethod",
"ifndef" : "SAVE_ON_FLASH",
"class" : "E",
"name" : "FFT",
"generate" : "jswrap_espruino_FFT",
"params" : [
["arrReal","JsVar","An array of real values"],
["arrImage","JsVar","An array of imaginary values (or if undefined, all values will be taken to be 0)"],
["inverse","bool","Set this to true if you want an inverse FFT - otherwise leave as 0"]
],
"typescript" : "FFT(arrReal: string | number[] | ArrayBuffer, arrImage?: string | number[] | ArrayBuffer, inverse?: boolean): any;"
}
Performs a Fast Fourier Transform (FFT) in 32 bit floats on the supplied data
and writes it back into the original arrays. Note that if only one array is
supplied, the data written back is the modulus of the complex result
`sqrt(r*r+i*i)`.
In order to perform the FFT, there has to be enough room on the stack to
allocate two arrays of 32 bit floating point numbers - this will limit the
maximum size of FFT possible to around 1024 items on most platforms.
**Note:** on the Original Espruino board, FFTs are performed in 64bit arithmetic
as there isn't space to include the 32 bit maths routines (2x more RAM is
required).
*/
void _jswrap_espruino_FFT_getData(FFTDATATYPE *dst, JsVar *src, size_t length) {
JsvIterator it;
size_t i=0;
if (jsvIsIterable(src)) {
jsvIteratorNew(&it, src, JSIF_EVERY_ARRAY_ELEMENT);
while (i<length && jsvIteratorHasElement(&it)) {
dst[i++] = (FFTDATATYPE)jsvIteratorGetFloatValue(&it);
jsvIteratorNext(&it);
}
jsvIteratorFree(&it);
}
while (i<length)
dst[i++]=0;
}
void _jswrap_espruino_FFT_setData(JsVar *dst, FFTDATATYPE *src, FFTDATATYPE *srcModulus, size_t length) {
JsvIterator it;
jsvIteratorNew(&it, dst, JSIF_EVERY_ARRAY_ELEMENT);
size_t i=0;
while (i<length && jsvIteratorHasElement(&it)) {
JsVarFloat f;
if (srcModulus)
f = jswrap_math_sqrt(src[i]*src[i] + srcModulus[i]*srcModulus[i]);
else
f = src[i];
jsvUnLock(jsvIteratorSetValue(&it, jsvNewFromFloat(f)));
i++;
jsvIteratorNext(&it);
}
jsvIteratorFree(&it);
}
void jswrap_espruino_FFT(JsVar *arrReal, JsVar *arrImag, bool inverse) {
if (!(jsvIsIterable(arrReal)) ||
!(jsvIsUndefined(arrImag) || jsvIsIterable(arrImag))) {
jsExceptionHere(JSET_ERROR, "Expecting first 2 arguments to be iterable or undefined, not %t and %t", arrReal, arrImag);
return;
}
// get length and work out power of 2
size_t l = (size_t)jsvGetLength(arrReal);
size_t pow2 = 1;
int order = 0;
while (pow2 < l) {
pow2 <<= 1;
order++;
}
if (jsuGetFreeStack() < 256+sizeof(FFTDATATYPE)*pow2*2) {
jsExceptionHere(JSET_ERROR, "Insufficient stack for computing FFT");
return;
}
FFTDATATYPE *vReal = (FFTDATATYPE*)alloca(sizeof(FFTDATATYPE)*pow2*2);
FFTDATATYPE *vImag = &vReal[pow2];
// load data
_jswrap_espruino_FFT_getData(vReal, arrReal, pow2);
_jswrap_espruino_FFT_getData(vImag, arrImag, pow2);
// do FFT
FFT(inverse ? -1 : 1, order, vReal, vImag);
// Put the results back
// If we had imaginary data then DON'T modulus the result
bool hasImagResult = jsvIsIterable(arrImag);
_jswrap_espruino_FFT_setData(arrReal, vReal, hasImagResult?0:vImag, pow2);
if (hasImagResult)
_jswrap_espruino_FFT_setData(arrImag, vImag, 0, pow2);
}
/*JSON{
"type" : "staticmethod",
"ifndef" : "SAVE_ON_FLASH",
"class" : "E",
"name" : "enableWatchdog",
"generate" : "jswrap_espruino_enableWatchdog",
"params" : [
["timeout","float","The timeout in seconds before a watchdog reset"],
["isAuto","JsVar","If undefined or true, the watchdog is kicked automatically. If not, you must call `E.kickWatchdog()` yourself"]
],
"typescript" : "enableWatchdog(timeout: number, isAuto?: boolean): void;"
}
Enable the watchdog timer. This will reset Espruino if it isn't able to return
to the idle loop within the timeout.
If `isAuto` is false, you must call `E.kickWatchdog()` yourself every so often
or the chip will reset.
```
E.enableWatchdog(0.5); // automatic mode
while(1); // Espruino will reboot because it has not been idle for 0.5 sec
```
```
E.enableWatchdog(1, false);
setInterval(function() {
if (everything_ok)
E.kickWatchdog();
}, 500);
// Espruino will now reset if everything_ok is false,
// or if the interval fails to be called
```
**NOTE:** This is only implemented on STM32, nRF5x and ESP32 devices (all official
Espruino boards).
**NOTE:** On STM32 (Pico, WiFi, Original) with `setDeepSleep(1)` you need to
explicitly wake Espruino up with an interval of less than the watchdog timeout
or the watchdog will fire and the board will reboot. You can do this with
`setInterval("", time_in_milliseconds)`.
**NOTE:** On ESP32, the timeout will be rounded to the nearest second.
*/
void jswrap_espruino_enableWatchdog(JsVarFloat time, JsVar *isAuto) {
if (time<0 || isnan(time)) time=1;
if (jsvIsUndefined(isAuto) || jsvGetBool(isAuto))
jsiStatus |= JSIS_WATCHDOG_AUTO;
else
jsiStatus &= ~JSIS_WATCHDOG_AUTO;
jshEnableWatchDog(time);
}
/*JSON{
"type" : "staticmethod",
"ifndef" : "SAVE_ON_FLASH",
"class" : "E",
"name" : "kickWatchdog",
"generate" : "jswrap_espruino_kickWatchdog"
}
Kicks a Watchdog timer set up with `E.enableWatchdog(..., false)`. See
`E.enableWatchdog` for more information.
**NOTE:** This is only implemented on STM32 and nRF5x devices (all official
Espruino boards).
*/
void jswrap_espruino_kickWatchdog() {
jshKickWatchDog();
}
/// Return an array of errors based on the current flags
JsVar *jswrap_espruino_getErrorFlagArray(JsErrorFlags flags) {
JsVar *arr = jsvNewEmptyArray();
if (!arr) return 0;
if (flags&JSERR_RX_FIFO_FULL) jsvArrayPushString(arr, "FIFO_FULL");
if (flags&JSERR_BUFFER_FULL) jsvArrayPushString(arr, "BUFFER_FULL");
if (flags&JSERR_CALLBACK) jsvArrayPushString(arr, "CALLBACK");
if (flags&JSERR_LOW_MEMORY) jsvArrayPushString(arr, "LOW_MEMORY");
if (flags&JSERR_MEMORY) jsvArrayPushString(arr, "MEMORY");
if (flags&JSERR_MEMORY_BUSY) jsvArrayPushString(arr, "MEMORY_BUSY");
if (flags&JSERR_UART_OVERFLOW) jsvArrayPushString(arr, "UART_OVERFLOW");
return arr;
}
/*TYPESCRIPT
type ErrorFlag =
| "FIFO_FULL"
| "BUFFER_FULL"
| "CALLBACK"
| "LOW_MEMORY"
| "MEMORY"
| "UART_OVERFLOW";
*/
/*JSON{
"type" : "staticmethod",
"ifndef" : "SAVE_ON_FLASH",
"class" : "E",
"name" : "getErrorFlags",
"generate" : "jswrap_espruino_getErrorFlags",
"return" : ["JsVar","An array of error flags"],
"typescript" : "getErrorFlags(): ErrorFlag[]"
}
Get and reset the error flags. Returns an array that can contain:
`'FIFO_FULL'`: The receive FIFO filled up and data was lost. This could be state
transitions for setWatch, or received characters.
`'BUFFER_FULL'`: A buffer for a stream filled up and characters were lost. This
can happen to any stream - Serial,HTTP,etc.
`'CALLBACK'`: A callback (`setWatch`, `setInterval`, `on('data',...)`) caused an
error and so was removed.
`'LOW_MEMORY'`: Memory is running low - Espruino had to run a garbage collection
pass or remove some of the command history
`'MEMORY'`: Espruino ran out of memory and was unable to allocate some data that
it needed.
`'UART_OVERFLOW'` : A UART received data but it was not read in time and was
lost
*/
JsVar *jswrap_espruino_getErrorFlags() {
JsErrorFlags flags = jsErrorFlags;
jsErrorFlags = JSERR_NONE;
return jswrap_espruino_getErrorFlagArray(flags);
}
/*TYPESCRIPT
type Flag =
| "deepSleep"
| "pretokenise"
| "unsafeFlash"
| "unsyncFiles";
*/
/*JSON{
"type" : "staticmethod",
"class" : "E",
"name" : "getFlags",
"generate" : "jsfGetFlags",
"return" : ["JsVar","An object containing flag names and their values"],
"typescript" : "getFlags(): { [key in Flag]: boolean }"
}
Get Espruino's interpreter flags that control the way it handles your JavaScript
code.
* `deepSleep` - Allow deep sleep modes (also set by setDeepSleep)
* `pretokenise` - When adding functions, pre-minify them and tokenise reserved
words
* `unsafeFlash` - Some platforms stop writes/erases to interpreter memory to
stop you bricking the device accidentally - this removes that protection
* `unsyncFiles` - When writing files, *don't* flush all data to the SD card
after each command (the default is *to* flush). This is much faster, but can
cause filesystem damage if power is lost without the filesystem unmounted.
*/
/*JSON{
"type" : "staticmethod",
"class" : "E",
"name" : "setFlags",
"generate" : "jsfSetFlags",
"params" : [
["flags","JsVar","An object containing flag names and boolean values. You need only specify the flags that you want to change."]
],
"typescript" : "setFlags(flags: { [key in Flag]?: boolean }): void"
}
Set the Espruino interpreter flags that control the way it handles your
JavaScript code.
Run `E.getFlags()` and check its description for a list of available flags and
their values.
*/
// TODO Improve TypeScript declaration
/*JSON{
"type" : "staticmethod",
"class" : "E",
"name" : "pipe",
"ifndef" : "SAVE_ON_FLASH",
"generate" : "jswrap_pipe",
"params" : [
["source","JsVar","The source file/stream that will send content. As of 2v19 this can also be a `String`"],
["destination","JsVar","The destination file/stream that will receive content from the source."],
["options","JsVar",["[optional] An object `{ chunkSize : int=64, end : bool=true, complete : function }`","chunkSize : The amount of data to pipe from source to destination at a time","complete : a function to call when the pipe activity is complete","end : call the 'end' function on the destination when the source is finished"]]
],
"typescript" : "pipe(source: any, destination: any, options?: PipeOptions): void"
}
Pipe one stream to another.
This can be given any object with a `read` method as a source, and any object with a `.write(data)` method as a destination.
Data will be piped from `source` to `destination` in the idle loop until `source.read(...)` returns `undefined`.
For instance:
```
// Print a really big string to the console, 1 character at a time and write 'Finished!' at the end
E.pipe("This is a really big String",
{write: print},
{chunkSize:1, complete:()=>print("Finished!")});
// Pipe the numbers 1 to 100 to a StorageFile in Storage
E.pipe({ n:0, read : function() { if (this.n<100) return (this.n++)+"\n"; }},
require("Storage").open("testfile","w"));
// Pipe a StorageFile straight to the Bluetooth UART
E.pipe(require("Storage").open("testfile","r"), Bluetooth);
// Pipe a normal file in Storage (not StorageFile) straight to the Bluetooth UART
E.pipe(require("Storage").read("blob.txt"), Bluetooth);
// Pipe a normal file in Storage as a response to an HTTP request
function onPageRequest(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
E.pipe(require("Storage").read("webpage.txt"), res);
}
require("http").createServer(onPageRequest).listen(80);
```
*/
/*JSON{
"type" : "staticmethod",
"class" : "E",
"name" : "toArrayBuffer",
"generate" : "jswrap_espruino_toArrayBuffer",
"params" : [
["str","JsVar","The string to convert to an ArrayBuffer"]
],
"return" : ["JsVar","An ArrayBuffer that uses the given string"],
"return_object" : "ArrayBufferView",
"typescript" : "toArrayBuffer(str: string): ArrayBuffer;"
}
Create an ArrayBuffer from the given string. This is done via a reference, not a
copy - so it is very fast and memory efficient.
Note that this is an ArrayBuffer, not a Uint8Array. To get one of those, do:
`new Uint8Array(E.toArrayBuffer('....'))`.
*/
JsVar *jswrap_espruino_toArrayBuffer(JsVar *str) {
if (!jsvIsString(str)) return 0;
return jsvNewArrayBufferFromString(str, 0);
}
void (_jswrap_espruino_toString_char)(int ch, JsvStringIterator *it) {
jsvStringIteratorSetCharAndNext(it, (char)ch);
}
JsVar *jswrap_espruino_toStringX(JsVar *args, bool forceFlat) {
// One argument
if (jsvGetArrayLength(args)==1) {
JsVar *arg = jsvGetArrayItem(args,0);
// Is it a flat string? If so we're there already - just return it
if ((jsvIsString(arg) && !forceFlat) || jsvIsFlatString(arg))
return arg;
// In the case where we have a Uint8Array,etc, return it directly
if (jsvIsArrayBuffer(arg) &&
JSV_ARRAYBUFFER_GET_SIZE(arg->varData.arraybuffer.type)==1 &&
arg->varData.arraybuffer.byteOffset==0) {
JsVar *backing = jsvGetArrayBufferBackingString(arg, NULL);
if (((backing && !forceFlat) || jsvIsFlatString(backing)) &&
jsvGetLength(backing) == arg->varData.arraybuffer.length) {
jsvUnLock(arg);
return backing;
}
jsvUnLock(backing);
}
jsvUnLock(arg);
}
// Allocate data
unsigned int len = (unsigned int)jsvIterateCallbackCount(args);
JsVar *str = forceFlat ? jsvNewFlatStringOfLength(len) : jsvNewStringOfLength(len, NULL);
if (forceFlat && !str) {
// if we couldn't do it, try again after garbage collecting/defrag
#ifdef SAVE_ON_FLASH
jsvGarbageCollect();
#else
jsvDefragment();
#endif
str = jsvNewFlatStringOfLength(len);
}
if (!str) return 0;
// Now use jsvIterateCallback to add in data
JsvStringIterator it;
jsvStringIteratorNew(&it, str, 0);
jsvIterateCallback(args, (void (*)(int, void *))_jswrap_espruino_toString_char, &it);
jsvStringIteratorFree(&it);
return str;
}
/*JSON{
"type" : "staticmethod",
"class" : "E",
"name" : "toString",
"generate" : "jswrap_espruino_toString",
"params" : [
["args","JsVarArray","The arguments to convert to a String"]
],
"return" : ["JsVar","A String"],
"return_object" : "String",
"typescript" : "toString(...args: any[]): string;"
}
Returns a `String` representing the data in the arguments.
This creates a string from the given arguments in the same way as `E.toUint8Array`. If each argument is:
* A String or an Array, each element is traversed and added as an 8 bit character
* `{data : ..., count : N}` causes `data` to be repeated `count` times
* `{callback : fn}` calls the function and adds the result
* Anything else is converted to a character directly.
In the case where there's one argument which is an 8 bit typed array backed by a
flat string of the same length, the backing string will be returned without
doing a copy or other allocation. The same applies if there's a single argument
which is itself a flat string.
```JS
E.toString(0,1,2,"Hi",3)
"\0\1\2Hi\3"
E.toString(1,2,{data:[3,4], count:4},5,6)
"\1\2\3\4\3\4\3\4\3\4\5\6"
>E.toString(1,2,{callback : () => "Hello World"},5,6)
="\1\2Hello World\5\6"
```
**Note:** Prior to Espruino 2v18 `E.toString` would always return a flat string,
or would return `undefined` if one couldn't be allocated. Now, it will return
a normal (fragmented) String if a contiguous chunk of memory cannot be allocated.
You can still check if the returned value is a Flat string using `E.getAddressOf(str, true)!=0`,
or can use `E.toFlatString` instead.
*/
JsVar *jswrap_espruino_toString(JsVar *args) {
return jswrap_espruino_toStringX(args, false);
}
/*JSON{
"type" : "staticmethod",
"class" : "E",
"name" : "toFlatString",
"generate" : "jswrap_espruino_toFlatString",
"params" : [
["args","JsVarArray","The arguments to convert to a Flat String"]
],
"return" : ["JsVar","A Flat String (or undefined)"],
"return_object" : "String",
"typescript" : "toFlatString(...args: any[]): string | undefined;"
}
Returns a Flat `String` representing the data in the arguments, or `undefined` if one can't be allocated.
This provides the same behaviour that `E.toString` had in Espruino before 2v18 - see `E.toString` for
more information.
*/
JsVar *jswrap_espruino_toFlatString(JsVar *args) {
return jswrap_espruino_toStringX(args, true);
}
/*JSON{
"type" : "staticmethod",
"ifndef" : "SAVE_ON_FLASH",
"class" : "E",
"name" : "asUTF8",
"generate" : "jswrap_espruino_asUTF8",
"params" : [
["str","JsVar","The string to turn into a UTF8 Unicode String"]
],
"return" : ["JsVar","A String"],
"return_object" : "String"
}
By default, strings in Espruino are standard 8 bit binary strings
unless they contain Unicode chars or a `\u####` escape code
that doesn't map to the range 0..255.
However calling E.asUTF8 will convert one of those strings to
UTF8.
```
var s = String.fromCharCode(0xF0,0x9F,0x8D,0x94);
var u = E.asUTF8(s);
s.length // 4
s[0] // "\xF0"
u.length // 1
u[0] // hamburger emoji
```
**NOTE:** UTF8 is currently only available on Bangle.js devices
*/
JsVar *jswrap_espruino_asUTF8(JsVar *str) {
#ifdef ESPR_UNICODE_SUPPORT
return jsvNewUTF8StringAndUnLock(jsvAsString(str));
#else
jsExceptionHere(JSET_ERROR, "Unicode not supported on this build");