/
jsinteractive.c
2277 lines (2098 loc) · 80.3 KB
/
jsinteractive.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/.
*
* ----------------------------------------------------------------------------
* Interactive Shell implementation
* ----------------------------------------------------------------------------
*/
#include "jsutils.h"
#include "jsinteractive.h"
#include "jshardware.h"
#include "jstimer.h"
#include "jswrapper.h"
#include "jswrap_json.h"
#include "jswrap_io.h"
#include "jswrap_stream.h"
#include "jswrap_flash.h" // load and save to flash
#include "jswrap_object.h" // jswrap_object_keys_or_property_names
#include "jsnative.h" // jsnSanityTest
#ifdef ARM
#define CHAR_DELETE_SEND 0x08
#else
#define CHAR_DELETE_SEND '\b'
#endif
#define CTRL_C_TIME_FOR_BREAK jshGetTimeFromMilliseconds(100)
#ifdef ESP8266
extern void jshPrintBanner(void); // prints a debugging banner while we're in beta
#endif
#ifdef FLASH_STR
// debugging...
#define os_printf os_printf_plus
extern void os_printf_plus(char *fmt, ...);
#endif
// ----------------------------------------------------------------------------
typedef enum {
IS_NONE,
IS_HAD_R,
IS_HAD_27,
IS_HAD_27_79,
IS_HAD_27_91,
IS_HAD_27_91_NUMBER, ///< Esc [ then 0-9
} PACKED_FLAGS InputState;
JsVar *events = 0; // Array of events to execute
JsVarRef timerArray = 0; // Linked List of timers to check and run
JsVarRef watchArray = 0; // Linked List of input watches to check and run
// ----------------------------------------------------------------------------
IOEventFlags consoleDevice = DEFAULT_CONSOLE_DEVICE; ///< The console device for user interaction
Pin pinBusyIndicator = DEFAULT_BUSY_PIN_INDICATOR;
Pin pinSleepIndicator = DEFAULT_SLEEP_PIN_INDICATOR;
JsiStatus jsiStatus;
JsSysTime jsiLastIdleTime; ///< The last time we went around the idle loop - use this for timers
uint32_t jsiTimeSinceCtrlC;
// ----------------------------------------------------------------------------
JsVar *inputLine = 0; ///< The current input line
JsvStringIterator inputLineIterator; ///< Iterator that points to the end of the input line
int inputLineLength = -1;
bool inputLineRemoved = false;
size_t inputCursorPos = 0; ///< The position of the cursor in the input line
InputState inputState = 0; ///< state for dealing with cursor keys
uint16_t inputStateNumber; ///< Number from when `Esc [ 1234` is sent - for storing line number
uint16_t jsiLineNumberOffset; ///< When we execute code, this is the 'offset' we apply to line numbers in error/debug
bool hasUsedHistory = false; ///< Used to speed up - if we were cycling through history and then edit, we need to copy the string
unsigned char loopsIdling; ///< How many times around the loop have we been entirely idle?
bool interruptedDuringEvent; ///< Were we interrupted while executing an event? If so may want to clear timers
// ----------------------------------------------------------------------------
#ifdef USE_DEBUGGER
void jsiDebuggerLine(JsVar *line);
#endif
// ----------------------------------------------------------------------------
/**
* Get the device from the class variable.
*/
IOEventFlags jsiGetDeviceFromClass(JsVar *class) {
// Devices have their Object data set up to something special
// See jspNewObject
if (class->varData.str[0]=='D' &&
class->varData.str[1]=='E' &&
class->varData.str[2]=='V')
return (IOEventFlags)class->varData.str[3];
return EV_NONE;
}
JsVar *jsiGetClassNameFromDevice(IOEventFlags device) {
const char *deviceName = jshGetDeviceString(device);
return jsvFindChildFromString(execInfo.root, deviceName, false);
}
NO_INLINE bool jsiEcho() {
return ((jsiStatus&JSIS_ECHO_OFF_MASK)==0);
}
static bool jsiShowInputLine() {
return jsiEcho() && !inputLineRemoved;
}
/** Called when the input line/cursor is modified *and its iterator should be reset
* Because JsvStringIterator doesn't lock the string, it's REALLY IMPORTANT
* that we call this BEFORE we do jsvUnLock(inputLine) */
static NO_INLINE void jsiInputLineCursorMoved() {
// free string iterator
if (inputLineIterator.var) {
jsvStringIteratorFree(&inputLineIterator);
inputLineIterator.var = 0;
}
inputLineLength = -1;
}
/// Called to append to the input line
static NO_INLINE void jsiAppendToInputLine(const char *str) {
// recreate string iterator if needed
if (!inputLineIterator.var) {
jsvStringIteratorNew(&inputLineIterator, inputLine, 0);
jsvStringIteratorGotoEnd(&inputLineIterator);
}
while (*str) {
jsvStringIteratorAppend(&inputLineIterator, *(str++));
inputLineLength++;
}
}
/**
* Change the console to a new location.
*/
void jsiSetConsoleDevice(
IOEventFlags device //!< The device to use as a console.
) {
// The `consoleDevice` is the global used to indicate which device we are using as the
// the console.
if (device == consoleDevice) return;
if (!jshIsDeviceInitialised(device)) {
JshUSARTInfo inf;
jshUSARTInitInfo(&inf);
jshUSARTSetup(device, &inf);
}
// Log to the old console that we are moving consoles and then, once we have moved
// the console, log to the new console that we have moved consoles.
jsiConsoleRemoveInputLine();
if (jsiEcho()) { // intentionally not using jsiShowInputLine()
jsiConsolePrintf("-> %s\n", jshGetDeviceString(device));
}
IOEventFlags oldDevice = consoleDevice;
consoleDevice = device;
if (jsiEcho()) { // intentionally not using jsiShowInputLine()
jsiConsolePrintf("<- %s\n", jshGetDeviceString(oldDevice));
}
}
/**
* Retrieve the device being used as the console.
*/
IOEventFlags jsiGetConsoleDevice() {
// The `consoleDevice` is the global used to hold the current console. This function
// encapsulates access.
return consoleDevice;
}
/**
* Send a character to the console.
*/
NO_INLINE void jsiConsolePrintChar(char data) {
jshTransmit(consoleDevice, (unsigned char)data);
}
/**
* \breif Send a NULL terminated string to the console.
*/
NO_INLINE void jsiConsolePrintString(const char *str) {
while (*str) {
if (*str == '\n') jsiConsolePrintChar('\r');
jsiConsolePrintChar(*(str++));
}
}
#ifdef FLASH_STR
// internal version that copies str from flash to an internal buffer
NO_INLINE void jsiConsolePrintString_int(const char *str) {
size_t len = flash_strlen(str);
char buff[len+1];
flash_strncpy(buff, str, len+1);
jsiConsolePrintString(buff);
}
#endif
/**
* Perform a printf to the console.
* Execute a printf command to the current JS console.
*/
#ifndef FLASH_STR
void jsiConsolePrintf(const char *fmt, ...) {
va_list argp;
va_start(argp, fmt);
vcbprintf((vcbprintf_callback)jsiConsolePrint,0, fmt, argp);
va_end(argp);
}
#else
void jsiConsolePrintf_int(const char *fmt, ...) {
// fmt is in flash and requires special aligned accesses
size_t len = flash_strlen(fmt);
char buff[len+1];
flash_strncpy(buff, fmt, len+1);
va_list argp;
va_start(argp, fmt);
vcbprintf((vcbprintf_callback)jsiConsolePrintString, 0, buff, argp);
va_end(argp);
}
#endif
/// Print the contents of a string var from a character position until end of line (adding an extra ' ' to delete a character if there was one)
void jsiConsolePrintStringVarUntilEOL(JsVar *v, size_t fromCharacter, size_t maxChars, bool andBackup) {
size_t chars = 0;
JsvStringIterator it;
jsvStringIteratorNew(&it, v, fromCharacter);
while (jsvStringIteratorHasChar(&it) && chars<maxChars) {
char ch = jsvStringIteratorGetChar(&it);
if (ch == '\n') break;
jsiConsolePrintChar(ch);
chars++;
jsvStringIteratorNext(&it);
}
jsvStringIteratorFree(&it);
if (andBackup) {
jsiConsolePrintChar(' ');chars++;
while (chars--) jsiConsolePrintChar(0x08); //delete
}
}
/** Print the contents of a string var - directly - starting from the given character, and
* using newLineCh to prefix new lines (if it is not 0). */
void jsiConsolePrintStringVarWithNewLineChar(JsVar *v, size_t fromCharacter, char newLineCh) {
JsvStringIterator it;
jsvStringIteratorNew(&it, v, fromCharacter);
while (jsvStringIteratorHasChar(&it)) {
char ch = jsvStringIteratorGetChar(&it);
if (ch == '\n') jsiConsolePrintChar('\r');
jsiConsolePrintChar(ch);
if (ch == '\n' && newLineCh) jsiConsolePrintChar(newLineCh);
jsvStringIteratorNext(&it);
}
jsvStringIteratorFree(&it);
}
/**
* Print the contents of a string var - directly.
*/
void jsiConsolePrintStringVar(JsVar *v) {
jsiConsolePrintStringVarWithNewLineChar(v,0,0);
}
/** Assuming that we are at the end of the string, this backs up
* and deletes it */
void jsiConsoleEraseStringVarBackwards(JsVar *v) {
assert(jsvHasCharacterData(v));
size_t line, lines = jsvGetLinesInString(v);
for (line=lines;line>0;line--) {
size_t i,chars = jsvGetCharsOnLine(v, line);
if (line==lines) {
for (i=0;i<chars;i++) jsiConsolePrintChar(0x08); // move cursor back
}
for (i=0;i<chars;i++) jsiConsolePrintChar(' '); // move cursor forwards and wipe out
for (i=0;i<chars;i++) jsiConsolePrintChar(0x08); // move cursor back
if (line>1) {
// clear the character before - this would have had a colon
jsiConsolePrint("\x08 ");
// move cursor up
jsiConsolePrint("\x1B[A"); // 27,91,65 - up
}
}
}
/** Assuming that we are at fromCharacter position in the string var,
* erase everything that comes AFTER and return the cursor to 'fromCharacter'
* On newlines, if erasePrevCharacter, we remove the character before too. */
void jsiConsoleEraseStringVarFrom(JsVar *v, size_t fromCharacter, bool erasePrevCharacter) {
assert(jsvHasCharacterData(v));
size_t cursorLine, cursorCol;
jsvGetLineAndCol(v, fromCharacter, &cursorLine, &cursorCol);
// delete contents of current line
size_t i, chars = jsvGetCharsOnLine(v, cursorLine);
for (i=cursorCol;i<=chars;i++) jsiConsolePrintChar(' ');
for (i=0;i<chars;i++) jsiConsolePrintChar(0x08); // move cursor back
size_t line, lines = jsvGetLinesInString(v);
for (line=cursorLine+1;line<=lines;line++) {
jsiConsolePrint("\x1B[B"); // move down
chars = jsvGetCharsOnLine(v, line);
for (i=0;i<chars;i++) jsiConsolePrintChar(' '); // move cursor forwards and wipe out
for (i=0;i<chars;i++) jsiConsolePrintChar(0x08); // move cursor back
if (erasePrevCharacter) {
jsiConsolePrint("\x08 "); // move cursor back and insert space
}
}
// move the cursor back up
for (line=cursorLine+1;line<=lines;line++)
jsiConsolePrint("\x1B[A"); // 27,91,65 - up
// move the cursor forwards
for (i=1;i<cursorCol;i++)
jsiConsolePrint("\x1B[C"); // 27,91,67 - right
}
void jsiMoveCursor(size_t oldX, size_t oldY, size_t newX, size_t newY) {
// see http://www.termsys.demon.co.uk/vtansi.htm - we could do this better
// move cursor
while (oldX < newX) {
jsiConsolePrint("\x1B[C"); // 27,91,67 - right
oldX++;
}
while (oldX > newX) {
jsiConsolePrint("\x1B[D"); // 27,91,68 - left
oldX--;
}
while (oldY < newY) {
jsiConsolePrint("\x1B[B"); // 27,91,66 - down
oldY++;
}
while (oldY > newY) {
jsiConsolePrint("\x1B[A"); // 27,91,65 - up
oldY--;
}
}
void jsiMoveCursorChar(JsVar *v, size_t fromCharacter, size_t toCharacter) {
if (fromCharacter==toCharacter) return;
size_t oldX, oldY;
jsvGetLineAndCol(v, fromCharacter, &oldY, &oldX);
size_t newX, newY;
jsvGetLineAndCol(v, toCharacter, &newY, &newX);
jsiMoveCursor(oldX, oldY, newX, newY);
}
/// If the input line was shown in the console, remove it
void jsiConsoleRemoveInputLine() {
if (!inputLineRemoved) {
inputLineRemoved = true;
if (jsiEcho() && inputLine) { // intentionally not using jsiShowInputLine()
jsiMoveCursorChar(inputLine, inputCursorPos, 0);
jsiConsoleEraseStringVarFrom(inputLine, 0, true);
jsiConsolePrintChar(0x08); // go back to start of line
#ifdef USE_DEBUGGER
if (jsiStatus & JSIS_IN_DEBUGGER) {
jsiConsolePrintChar(0x08); // d
jsiConsolePrintChar(0x08); // e
jsiConsolePrintChar(0x08); // b
jsiConsolePrintChar(0x08); // u
jsiConsolePrintChar(0x08); // g
}
#endif
}
}
}
/// If the input line has been removed, return it
void jsiConsoleReturnInputLine() {
if (inputLineRemoved) {
inputLineRemoved = false;
if (jsiEcho()) { // intentionally not using jsiShowInputLine()
#ifdef USE_DEBUGGER
if (jsiStatus & JSIS_IN_DEBUGGER)
jsiConsolePrint("debug");
#endif
jsiConsolePrintChar('>'); // show the prompt
jsiConsolePrintStringVarWithNewLineChar(inputLine, 0, ':');
jsiMoveCursorChar(inputLine, jsvGetStringLength(inputLine), inputCursorPos);
}
}
}
void jsiConsolePrintPosition(struct JsLex *lex, size_t tokenPos) {
jslPrintPosition((vcbprintf_callback)jsiConsolePrintString, 0, lex, tokenPos);
}
/**
* Clear the input line of data.
*/
void jsiClearInputLine() {
jsiConsoleRemoveInputLine();
// clear input line
jsiInputLineCursorMoved();
jsvUnLock(inputLine);
inputLine = jsvNewFromEmptyString();
}
/**
* ??? What does this do ???.
*/
void jsiSetBusy(
JsiBusyDevice device, //!< ???
bool isBusy //!< ???
) {
static JsiBusyDevice business = 0;
if (isBusy)
business |= device;
else
business &= (JsiBusyDevice)~device;
if (pinBusyIndicator != PIN_UNDEFINED)
jshPinOutput(pinBusyIndicator, business!=0);
}
/**
* Set the status of a pin as a function of whether we are asleep.
* When called, if a pin is set for a sleep indicator, we set the pin to be true
* if the sleep type is awake and false otherwise.
*/
void jsiSetSleep(JsiSleepType isSleep) {
if (pinSleepIndicator != PIN_UNDEFINED)
jshPinOutput(pinSleepIndicator, isSleep == JSI_SLEEP_AWAKE);
}
static JsVarRef _jsiInitNamedArray(const char *name) {
JsVar *array = jsvObjectGetChild(execInfo.hiddenRoot, name, JSV_ARRAY);
JsVarRef arrayRef = 0;
if (array) arrayRef = jsvGetRef(jsvRef(array));
jsvUnLock(array);
return arrayRef;
}
// Used when recovering after being flashed
// 'claim' anything we are using
void jsiSoftInit() {
jswInit();
jsErrorFlags = 0;
events = jsvNewWithFlags(JSV_ARRAY);
inputLine = jsvNewFromEmptyString();
inputCursorPos = 0;
jsiLineNumberOffset = 0;
jsiInputLineCursorMoved();
inputLineIterator.var = 0;
jsiStatus &= ~JSIS_ALLOW_DEEP_SLEEP;
// Load timer/watch arrays
timerArray = _jsiInitNamedArray(JSI_TIMERS_NAME);
watchArray = _jsiInitNamedArray(JSI_WATCHES_NAME);
// Now run initialisation code
JsVar *initCode = jsvObjectGetChild(execInfo.hiddenRoot, JSI_INIT_CODE_NAME, 0);
if (initCode) {
jsvUnLock2(jspEvaluateVar(initCode, 0, 0), initCode);
jsvRemoveNamedChild(execInfo.hiddenRoot, JSI_INIT_CODE_NAME);
}
// Check any existing watches and set up interrupts for them
if (watchArray) {
JsVar *watchArrayPtr = jsvLock(watchArray);
JsvObjectIterator it;
jsvObjectIteratorNew(&it, watchArrayPtr);
while (jsvObjectIteratorHasValue(&it)) {
JsVar *watch = jsvObjectIteratorGetValue(&it);
JsVar *watchPin = jsvObjectGetChild(watch, "pin", 0);
jshPinWatch(jshGetPinFromVar(watchPin), true);
jsvUnLock2(watchPin, watch);
jsvObjectIteratorNext(&it);
}
jsvObjectIteratorFree(&it);
jsvUnLock(watchArrayPtr);
}
// Timers are stored by time in the future now, so no need
// to fiddle with them.
// Make sure we set up lastIdleTime, as this could be used
// when adding an interval from onInit (called below)
jsiLastIdleTime = jshGetSystemTime();
jsiTimeSinceCtrlC = 0xFFFFFFFF;
// And look for onInit function
JsVar *onInit = jsvObjectGetChild(execInfo.root, JSI_ONINIT_NAME, 0);
if (onInit) {
if (jsiEcho()) jsiConsolePrint("Running onInit()...\n");
jsiExecuteEventCallback(0, onInit, 0, 0);
jsvUnLock(onInit);
}
// Now look for `init` events on `E`
JsVar *E = jsvObjectGetChild(execInfo.root, "E", 0);
if (E) {
JsVar *callback = jsvObjectGetChild(E, INIT_CALLBACK_NAME, 0);
if (callback) {
jsiExecuteEventCallback(0, callback, 0, 0);
jsvUnLock(callback);
}
jsvUnLock(E);
}
}
/** Output the given variable as JSON, or if it exists
* in the root scope (and it's not 'existing') then just
* the name is dumped. */
void jsiDumpJSON(vcbprintf_callback user_callback, void *user_data, JsVar *data, JsVar *existing) {
// Check if it exists in the root scope
JsVar *name = jsvGetArrayIndexOf(execInfo.root, data, true);
if (name && jsvIsString(name) && name!=existing) {
// if it does, print the name
cbprintf(user_callback, user_data, "%v", name);
} else {
// if it doesn't, print JSON
jsfGetJSONWithCallback(data, JSON_NEWLINES | JSON_PRETTY | JSON_SHOW_DEVICES, user_callback, user_data);
}
}
NO_INLINE static void jsiDumpEvent(vcbprintf_callback user_callback, void *user_data, JsVar *parentName, JsVar *eventKeyName, JsVar *eventFn) {
JsVar *eventName = jsvNewFromStringVar(eventKeyName, strlen(JS_EVENT_PREFIX), JSVAPPENDSTRINGVAR_MAXLENGTH);
cbprintf(user_callback, user_data, "%v.on(%q, ", parentName, eventName);
jsvUnLock(eventName);
jsiDumpJSON(user_callback, user_data, eventFn, 0);
user_callback(");\n", user_data);
}
/** Output extra functions defined in an object such that they can be copied to a new device */
NO_INLINE void jsiDumpObjectState(vcbprintf_callback user_callback, void *user_data, JsVar *parentName, JsVar *parent) {
JsvIsInternalChecker checker = jsvGetInternalFunctionCheckerFor(parent);
JsvObjectIterator it;
jsvObjectIteratorNew(&it, parent);
while (jsvObjectIteratorHasValue(&it)) {
JsVar *child = jsvObjectIteratorGetKey(&it);
JsVar *data = jsvObjectIteratorGetValue(&it);
if (!checker || !checker(child)) {
if (jsvIsStringEqual(child, JSPARSE_PROTOTYPE_VAR)) {
// recurse to print prototypes
JsVar *name = jsvNewFromStringVar(parentName,0,JSVAPPENDSTRINGVAR_MAXLENGTH);
if (name) {
jsvAppendString(name, ".prototype");
jsiDumpObjectState(user_callback, user_data, name, data);
jsvUnLock(name);
}
} else if (jsvIsStringEqualOrStartsWith(child, JS_EVENT_PREFIX, true)) {
// Handle the case that this is an event
if (jsvIsArray(data)) {
JsvObjectIterator ait;
jsvObjectIteratorNew(&ait, data);
while (jsvObjectIteratorHasValue(&ait)) {
JsVar *v = jsvObjectIteratorGetValue(&ait);
jsiDumpEvent(user_callback, user_data, parentName, child, v);
jsvUnLock(v);
jsvObjectIteratorNext(&ait);
}
jsvObjectIteratorFree(&ait);
} else {
jsiDumpEvent(user_callback, user_data, parentName, child, data);
}
} else {
// It's a normal function
if (!jsvIsNative(data)) {
cbprintf(user_callback, user_data, "%v.%v = ", parentName, child);
jsiDumpJSON(user_callback, user_data, data, 0);
user_callback(";\n", user_data);
}
}
}
jsvUnLock2(data, child);
jsvObjectIteratorNext(&it);
}
jsvObjectIteratorFree(&it);
}
/** Dump the code required to initialise a serial port to this string */
void jsiDumpSerialInitialisation(vcbprintf_callback user_callback, void *user_data, const char *serialName, bool addObjectProperties) {
JsVar *serialVarName = jsvFindChildFromString(execInfo.root, serialName, false);
JsVar *serialVar = jsvSkipName(serialVarName);
if (serialVar) {
if (addObjectProperties)
jsiDumpObjectState(user_callback, user_data, serialVarName, serialVar);
JsVar *baud = jsvObjectGetChild(serialVar, USART_BAUDRATE_NAME, 0);
JsVar *options = jsvObjectGetChild(serialVar, DEVICE_OPTIONS_NAME, 0);
if (baud || options) {
int baudrate = (int)jsvGetInteger(baud);
if (baudrate <= 0) baudrate = DEFAULT_BAUD_RATE;
cbprintf(user_callback, user_data, "%s.setup(%d", serialName, baudrate);
if (jsvIsObject(options)) {
user_callback(", ", user_data);
jsfGetJSONWithCallback(options, JSON_SHOW_DEVICES, user_callback, user_data);
}
user_callback(");\n", user_data);
}
jsvUnLock3(baud, options, serialVar);
}
jsvUnLock(serialVarName);
}
/** Dump the code required to initialise a SPI port to this string */
void jsiDumpDeviceInitialisation(vcbprintf_callback user_callback, void *user_data, const char *deviceName) {
JsVar *deviceVar = jsvObjectGetChild(execInfo.root, deviceName, 0);
if (deviceVar) {
JsVar *options = jsvObjectGetChild(deviceVar, DEVICE_OPTIONS_NAME, 0);
if (options) {
cbprintf(user_callback, user_data, "%s.setup(", deviceName);
if (jsvIsObject(options))
jsfGetJSONWithCallback(options, JSON_SHOW_DEVICES, user_callback, user_data);
user_callback(");\n", user_data);
}
jsvUnLock2(options, deviceVar);
}
}
/** Dump all the code required to initialise hardware to this string */
void jsiDumpHardwareInitialisation(vcbprintf_callback user_callback, void *user_data, bool addObjectProperties) {
if (jsiStatus&JSIS_ECHO_OFF) user_callback("echo(0);", user_data);
if (pinBusyIndicator != DEFAULT_BUSY_PIN_INDICATOR) {
cbprintf(user_callback, user_data, "setBusyIndicator(%p);\n", pinBusyIndicator);
}
if (pinSleepIndicator != DEFAULT_SLEEP_PIN_INDICATOR) {
cbprintf(user_callback, user_data, "setSleepIndicator(%p);\n", pinSleepIndicator);
}
if (jsiStatus&JSIS_ALLOW_DEEP_SLEEP) {
user_callback("setDeepSleep(1);\n", user_data);
}
jsiDumpSerialInitialisation(user_callback, user_data, "USB", addObjectProperties);
int i;
for (i=0;i<USART_COUNT;i++)
jsiDumpSerialInitialisation(user_callback, user_data, jshGetDeviceString(EV_SERIAL1+i), addObjectProperties);
for (i=0;i<SPI_COUNT;i++)
jsiDumpDeviceInitialisation(user_callback, user_data, jshGetDeviceString(EV_SPI1+i));
for (i=0;i<I2C_COUNT;i++)
jsiDumpDeviceInitialisation(user_callback, user_data, jshGetDeviceString(EV_I2C1+i));
// pins
Pin pin;
for (pin=0;jshIsPinValid(pin) && pin<255;pin++) {
if (IS_PIN_USED_INTERNALLY(pin)) continue;
JshPinState state = jshPinGetState(pin);
JshPinState statem = state&JSHPINSTATE_MASK;
if (statem == JSHPINSTATE_GPIO_OUT || statem == JSHPINSTATE_GPIO_OUT_OPENDRAIN) {
bool isOn = (state&JSHPINSTATE_PIN_IS_ON)!=0;
if (!isOn && IS_PIN_A_LED(pin)) continue;
cbprintf(user_callback, user_data, "digitalWrite(%p,%d);\n",pin,isOn?1:0);
} else if (/*statem == JSHPINSTATE_GPIO_IN ||*/statem == JSHPINSTATE_GPIO_IN_PULLUP || statem == JSHPINSTATE_GPIO_IN_PULLDOWN) {
#ifdef DEFAULT_CONSOLE_RX_PIN
// the console input pin is always a pullup now - which is expected
if (pin == DEFAULT_CONSOLE_RX_PIN &&
statem == JSHPINSTATE_GPIO_IN_PULLUP) continue;
#endif
// don't bother with normal inputs, as they come up in this state (ish) anyway
const char *s = "";
if (statem == JSHPINSTATE_GPIO_IN_PULLUP) s="_pullup";
if (statem == JSHPINSTATE_GPIO_IN_PULLDOWN) s="_pulldown";
cbprintf(user_callback, user_data, "pinMode(%p,\"input%s\");\n",pin,s);
}
if (statem == JSHPINSTATE_GPIO_OUT_OPENDRAIN)
cbprintf(user_callback, user_data, "pinMode(%p,\"opendrain\");\n",pin);
}
}
// Used when shutting down before flashing
// 'release' anything we are using, but ensure that it doesn't get freed
void jsiSoftKill() {
inputCursorPos = 0;
jsiInputLineCursorMoved();
jsvUnLock(inputLine);
inputLine=0;
// kill any wrapped stuff
jswKill();
// Stop all active timer tasks
jstReset();
// Unref Watches/etc
if (events) {
jsvUnLock(events);
events=0;
}
if (timerArray) {
jsvUnRefRef(timerArray);
timerArray=0;
}
if (watchArray) {
// Check any existing watches and disable interrupts for them
JsVar *watchArrayPtr = jsvLock(watchArray);
JsvObjectIterator it;
jsvObjectIteratorNew(&it, watchArrayPtr);
while (jsvObjectIteratorHasValue(&it)) {
JsVar *watchPtr = jsvObjectIteratorGetValue(&it);
JsVar *watchPin = jsvObjectGetChild(watchPtr, "pin", 0);
jshPinWatch(jshGetPinFromVar(watchPin), false);
jsvUnLock2(watchPin, watchPtr);
jsvObjectIteratorNext(&it);
}
jsvObjectIteratorFree(&it);
jsvUnRef(watchArrayPtr);
jsvUnLock(watchArrayPtr);
watchArray=0;
}
// Save initialisation information
JsVar *initCode = jsvNewFromEmptyString();
if (initCode) { // out of memory
JsvStringIterator it;
jsvStringIteratorNew(&it, initCode, 0);
jsiDumpHardwareInitialisation((vcbprintf_callback)&jsvStringIteratorPrintfCallback, &it, false);
jsvStringIteratorFree(&it);
jsvObjectSetChild(execInfo.hiddenRoot, JSI_INIT_CODE_NAME, initCode);
jsvUnLock(initCode);
}
}
void jsiSemiInit(bool autoLoad) {
jspInit();
// Set state
interruptedDuringEvent = false;
// Set defaults
jsiStatus = JSIS_NONE;
pinBusyIndicator = DEFAULT_BUSY_PIN_INDICATOR;
/* If flash contains any code, then we should
Try and load from it... */
bool loadFlash = autoLoad && jsfFlashContainsCode();
if (loadFlash) {
jspSoftKill();
jsvSoftKill();
jsfLoadFromFlash();
jsvSoftInit();
jspSoftInit();
}
// Softinit may run initialisation code that will overwrite defaults
jsiSoftInit();
if (jsiEcho()) { // intentionally not using jsiShowInputLine()
if (!loadFlash) {
jsiConsolePrint(
#ifndef LINUX
// set up terminal to avoid word wrap
"\e[?7l"
#endif
// rectangles @ http://www.network-science.de/ascii/
"\n"
" _____ _ \n"
"| __|___ ___ ___ _ _|_|___ ___ \n"
"| __|_ -| . | _| | | | | . |\n"
"|_____|___| _|_| |___|_|_|_|___|\n"
" |_| http://espruino.com\n"
" "JS_VERSION" Copyright 2015 G.Williams\n");
#ifdef ESP8266
jshPrintBanner();
#endif
}
jsiConsolePrint("\n"); // output new line
inputLineRemoved = true; // we need to put the input line back...
}
}
// The 'proper' init function - this should be called only once at bootup
void jsiInit(bool autoLoad) {
#if defined(LINUX) || !defined(USB)
consoleDevice = DEFAULT_CONSOLE_DEVICE;
#else
consoleDevice = EV_LIMBO;
#endif
#ifndef RELEASE
jsnSanityTest();
#endif
jsiSemiInit(autoLoad);
}
#ifndef LINUX
// This should get jsiOneSecondAfterStartupcalled from jshardware.c one second after startup,
// it does initialisation tasks like setting the right console device
void jsiOneSecondAfterStartup() {
/* When we start up, we put all console output into 'Limbo' (EV_LIMBO),
because we want to get started immediately, but we don't know where
to send any console output (USB takes a while to initialise). Not only
that but if we start transmitting on Serial right away, the first
char or two can get corrupted.
*/
#ifdef USB
if (consoleDevice == EV_LIMBO) {
consoleDevice = DEFAULT_CONSOLE_DEVICE;
if (jshIsUSBSERIALConnected())
consoleDevice = EV_USBSERIAL;
// now move any output that was made to Limbo to the given device
jshTransmitMove(EV_LIMBO, consoleDevice);
// finally, kick output - just in case
jshUSARTKick(consoleDevice);
} else {
// the console has already been moved
jshTransmitClearDevice(EV_LIMBO);
}
#endif
}
#endif
void jsiKill() {
jsiSoftKill();
jspKill();
}
int jsiCountBracketsInInput() {
int brackets = 0;
JsLex lex;
jslInit(&lex, inputLine);
while (lex.tk!=LEX_EOF && lex.tk!=LEX_UNFINISHED_COMMENT) {
if (lex.tk=='{' || lex.tk=='[' || lex.tk=='(') brackets++;
if (lex.tk=='}' || lex.tk==']' || lex.tk==')') brackets--;
if (brackets<0) break; // closing bracket before opening!
jslGetNextToken(&lex);
}
if (lex.tk==LEX_UNFINISHED_COMMENT)
brackets=1000; // if there's an unfinished comment, we're in the middle of something
jslKill(&lex);
return brackets;
}
/// Tries to get rid of some memory (by clearing command history). Returns true if it got rid of something, false if it didn't.
bool jsiFreeMoreMemory() {
JsVar *history = jsvObjectGetChild(execInfo.hiddenRoot, JSI_HISTORY_NAME, 0);
if (!history) return 0;
JsVar *item = jsvArrayPopFirst(history);
bool freed = item!=0;
jsvUnLock2(item, history);
// TODO: could also free the array structure?
// TODO: could look at all streams (Serial1/HTTP/etc) and see if their buffers contain data that could be removed
return freed;
}
// Add a new line to the command history
void jsiHistoryAddLine(JsVar *newLine) {
if (!newLine || jsvGetStringLength(newLine)==0) return;
JsVar *history = jsvObjectGetChild(execInfo.hiddenRoot, JSI_HISTORY_NAME, JSV_ARRAY);
if (!history) return; // out of memory
// if it was already in history, remove it - we'll put it back in front
JsVar *alreadyInHistory = jsvGetArrayIndexOf(history, newLine, false/*not exact*/);
if (alreadyInHistory) {
jsvRemoveChild(history, alreadyInHistory);
jsvUnLock(alreadyInHistory);
}
// put it back in front
jsvArrayPush(history, newLine);
jsvUnLock(history);
}
JsVar *jsiGetHistoryLine(bool previous /* next if false */) {
JsVar *history = jsvObjectGetChild(execInfo.hiddenRoot, JSI_HISTORY_NAME, 0);
JsVar *historyLine = 0;
if (history) {
JsVar *idx = jsvGetArrayIndexOf(history, inputLine, true/*exact*/); // get index of current line
if (idx) {
if (previous && jsvGetPrevSibling(idx)) {
historyLine = jsvSkipNameAndUnLock(jsvLock(jsvGetPrevSibling(idx)));
} else if (!previous && jsvGetNextSibling(idx)) {
historyLine = jsvSkipNameAndUnLock(jsvLock(jsvGetNextSibling(idx)));
}
jsvUnLock(idx);
} else {
if (previous) historyLine = jsvSkipNameAndUnLock(jsvGetArrayItem(history, jsvGetArrayLength(history)-1));
// if next, we weren't using history so couldn't go forwards
}
jsvUnLock(history);
}
return historyLine;
}
bool jsiIsInHistory(JsVar *line) {
JsVar *history = jsvObjectGetChild(execInfo.hiddenRoot, JSI_HISTORY_NAME, 0);
if (!history) return false;
JsVar *historyFound = jsvGetArrayIndexOf(history, line, true/*exact*/);
bool inHistory = historyFound!=0;
jsvUnLock2(historyFound, history);
return inHistory;
}
void jsiReplaceInputLine(JsVar *newLine) {
if (jsiShowInputLine()) {
size_t oldLen = jsvGetStringLength(inputLine);
jsiMoveCursorChar(inputLine, inputCursorPos, oldLen); // move cursor to end
jsiConsoleEraseStringVarBackwards(inputLine);
jsiConsolePrintStringVarWithNewLineChar(newLine,0,':');
}
jsiInputLineCursorMoved();
jsvUnLock(inputLine);
inputLine = jsvLockAgain(newLine);
inputCursorPos = jsvGetStringLength(inputLine);
}
void jsiChangeToHistory(bool previous) {
#ifdef USE_DEBUGGER
if (jsiStatus & JSIS_IN_DEBUGGER) return;
#endif
JsVar *nextHistory = jsiGetHistoryLine(previous);
if (nextHistory) {
jsiReplaceInputLine(nextHistory);
jsvUnLock(nextHistory);
hasUsedHistory = true;
} else if (!previous) { // if next, but we have something, just clear the line
if (jsiShowInputLine()) {
jsiConsoleEraseStringVarBackwards(inputLine);
}
jsiInputLineCursorMoved();
jsvUnLock(inputLine);
inputLine = jsvNewFromEmptyString();
inputCursorPos = 0;
}
}
void jsiIsAboutToEditInputLine() {
// we probably plan to do something with the line now - check it wasn't in history
// and if it was, duplicate it
if (hasUsedHistory) {
hasUsedHistory = false;
if (jsiIsInHistory(inputLine)) {
JsVar *newLine = jsvCopy(inputLine);
if (newLine) { // could have been out of memory!
jsiInputLineCursorMoved();
jsvUnLock(inputLine);
inputLine = newLine;
}
}
}
}
void jsiHandleDelete(bool isBackspace) {
size_t l = jsvGetStringLength(inputLine);
if (isBackspace && inputCursorPos==0) return; // at beginning of line
if (!isBackspace && inputCursorPos>=l) return; // at end of line
// work out if we are deleting a newline
bool deleteNewline = (isBackspace && jsvGetCharInString(inputLine,inputCursorPos-1)=='\n') ||
(!isBackspace && jsvGetCharInString(inputLine,inputCursorPos)=='\n');
// If we mod this to keep the string, use jsiIsAboutToEditInputLine
if (deleteNewline && jsiShowInputLine()) {
jsiConsoleEraseStringVarFrom(inputLine, inputCursorPos, true/*before newline*/); // erase all in front
if (isBackspace) {
// delete newline char
jsiConsolePrint("\x08 "); // delete and then send space
jsiMoveCursorChar(inputLine, inputCursorPos, inputCursorPos-1); // move cursor back
jsiInputLineCursorMoved();
}
}
JsVar *v = jsvNewFromEmptyString();
size_t p = inputCursorPos;
if (isBackspace) p--;
if (p>0) jsvAppendStringVar(v, inputLine, 0, p); // add before cursor (delete)
if (p+1<l) jsvAppendStringVar(v, inputLine, p+1, JSVAPPENDSTRINGVAR_MAXLENGTH); // add the rest
jsiInputLineCursorMoved();
jsvUnLock(inputLine);
inputLine=v;
if (isBackspace)
inputCursorPos--; // move cursor back
// update the console
if (jsiShowInputLine()) {
if (deleteNewline) {
// we already removed everything, so just put it back
jsiConsolePrintStringVarWithNewLineChar(inputLine, inputCursorPos, ':');
jsiMoveCursorChar(inputLine, jsvGetStringLength(inputLine), inputCursorPos); // move cursor back
} else {
// clear the character and move line back
if (isBackspace) jsiConsolePrintChar(0x08);
jsiConsolePrintStringVarUntilEOL(inputLine, inputCursorPos, 0xFFFFFFFF, true/*and backup*/);
}
}
}
void jsiHandleHome() {
while (inputCursorPos>0 && jsvGetCharInString(inputLine,inputCursorPos-1)!='\n') {
if (jsiShowInputLine()) jsiConsolePrintChar(0x08);
inputCursorPos--;
}
}
void jsiHandleEnd() {
size_t l = jsvGetStringLength(inputLine);
while (inputCursorPos<l && jsvGetCharInString(inputLine,inputCursorPos)!='\n') {
if (jsiShowInputLine())
jsiConsolePrintChar(jsvGetCharInString(inputLine,inputCursorPos));
inputCursorPos++;
}
}
/** Page up/down move cursor to beginnint or end */
void jsiHandlePageUpDown(bool isDown) {