-
Notifications
You must be signed in to change notification settings - Fork 12
/
board.go
executable file
·1319 lines (1066 loc) · 30.4 KB
/
board.go
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
/*
* Whitecat Blocky Environment, board abstraction
*
* Copyright (C) 2015 - 2016
* IBEROXARXA SERVICIOS INTEGRALES, S.L.
*
* Author: Jaume Olivé ([email protected] / [email protected])
*
* All rights reserved.
*
* Permission to use, copy, modify, and distribute this software
* and its documentation for any purpose and without fee is hereby
* granted, provided that the above copyright notice appear in all
* copies and that both that the copyright notice and this
* permission notice and warranty disclaimer appear in supporting
* documentation, and that the name of the author not be used in
* advertising or publicity pertaining to distribution of the
* software without specific, written prior permission.
*
* The author disclaim all warranties with regard to this
* software, including all implied warranties of merchantability
* and fitness. In no events shall the author be liable for any
* special, indirect or consequential damages or any damages
* whatsoever resulting from loss of use, data or profits, whether
* in an action of contract, negligence or other tortious action,
* arising out of or in connection with the use or performance of
* this software.
*/
package main
import (
"bytes"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"github.com/mikepb/go-serial"
"io/ioutil"
"log"
"math"
"net/http"
"os"
"os/exec"
"path"
"regexp"
"runtime"
"strconv"
"strings"
"sync"
"time"
)
type Source int
const (
NoSource Source = 0
CloudSource Source = 1
BoardSource Source = 2
DesktopSource Source = 3
FolderSource Source = 4
)
type SupportedBoard struct {
Id string
Description string
Manufacturer string
Brand string
Type string
Subtype string
}
type SupportedBoards []SupportedBoard
var Upgrading bool
type Board struct {
// Serial port
port *serial.Port
devInfo *serial.Info
// Device name
dev string
// Is there a new firmware build?
newBuild bool
// Board information
info string
// Board model
model string
subtype string
brand string
ota bool
firmware string
// Has board shell enable?
shell bool
// RXQueue
RXQueue chan byte
// Chunk size for send / receive files to / from board
chunkSize int
// If true disables notify board's boot events
disableInspectorBootNotify bool
consoleOut bool
consoleIn bool
quit chan bool
// Current timeout value, in milliseconds for read
timeoutVal int
// Firmware is valid?
validFirmware bool
// Prerequisites are valid?
validPrerequisites bool
// Max bauds for this board
maxBauds int
}
type BoardInfo struct {
Build string
Commit string
Board string
Subtype string
Brand string
Ota bool
Status struct {
Shell bool
History bool
}
}
func (board *Board) timeout(ms int) {
board.timeoutVal = ms
}
func (board *Board) noTimeout() {
board.timeoutVal = math.MaxInt32
}
// Inspects the serial data received for a board in order to find special
// special events, such as reset, core dumps, exceptions, etc ...
//
// Once inspected all bytes are send to RXQueue channel
func (board *Board) inspector() {
var re *regexp.Regexp
defer func() {
log.Println("stop inspector ...")
if err := recover(); err != nil {
}
}()
log.Println("start inspector ...")
buffer := make([]byte, 1)
line := ""
for {
if n, err := board.port.Read(buffer); err != nil {
panic(err)
} else {
if n > 0 {
if buffer[0] == '\n' {
if !board.disableInspectorBootNotify {
re = regexp.MustCompile(`^rst:.*\(POWERON_RESET\),boot:.*(.*)$`)
if re.MatchString(line) {
notify("boardPowerOnReset", "")
}
re = regexp.MustCompile(`^rst:.*(SW_CPU_RESET),boot:.*(.*)$`)
if re.MatchString(line) {
notify("boardSoftwareReset", "")
}
re = regexp.MustCompile(`^rst:.*(DEEPSLEEP_RESET),boot.*(.*)$`)
if re.MatchString(line) {
notify("boardDeepSleepReset", "")
}
re = regexp.MustCompile(`\<blockStart,(.*)\>`)
if re.MatchString(line) {
parts := re.FindStringSubmatch(line)
info := "\"block\": \"" + base64.StdEncoding.EncodeToString([]byte(parts[1])) + "\""
notify("blockStart", info)
}
re = regexp.MustCompile(`\<blockEnd,(.*)\>`)
if re.MatchString(line) {
parts := re.FindStringSubmatch(line)
info := "\"block\": \"" + base64.StdEncoding.EncodeToString([]byte(parts[1])) + "\""
notify("blockEnd", info)
}
re = regexp.MustCompile(`\<blockError,([0-9]*),(.*)\>`)
if re.MatchString(line) {
parts := re.FindStringSubmatch(line)
info := "\"block\": \"" + base64.StdEncoding.EncodeToString([]byte(parts[1])) + "\", " +
"\"error\": \"" + base64.StdEncoding.EncodeToString([]byte(parts[2])) + "\""
notify("blockError", info)
}
re = regexp.MustCompile(`\<blockErrorCatched,(.*)\>`)
if re.MatchString(line) {
parts := re.FindStringSubmatch(line)
info := "\"block\": \"" + base64.StdEncoding.EncodeToString([]byte(parts[1])) + "\""
notify("blockErrorCatched", info)
}
}
// Remove prompt from line
tmpLine := line
re = regexp.MustCompile(`^/.*>\s`)
tmpLine = string(re.ReplaceAll([]byte(tmpLine), []byte("")))
re = regexp.MustCompile(`^([\/\.\/\-_a-zA-Z]*):(\d*)\:\s(\d*)\:(.*)$`)
if re.MatchString(tmpLine) {
parts := re.FindStringSubmatch(tmpLine)
info := "\"where\": \"" + parts[1] + "\", " +
"\"line\": \"" + parts[2] + "\", " +
"\"exception\": \"" + parts[3] + "\", " +
"\"message\": \"" + base64.StdEncoding.EncodeToString([]byte(parts[4])) + "\""
log.Println(parts[4])
re = regexp.MustCompile(`^WARNING\s.*$`)
if re.MatchString(parts[4]) {
notify("boardRuntimeWarning", info)
} else {
notify("boardRuntimeError", info)
}
} else {
re = regexp.MustCompile(`^([\/\.\/\-_a-zA-Z]*)\:(\d*)\:\s*(.*)$`)
if re.MatchString(tmpLine) {
parts := re.FindStringSubmatch(tmpLine)
info := "\"where\": \"" + parts[1] + "\", " +
"\"line\": \"" + parts[2] + "\", " +
"\"exception\": \"0\", " +
"\"message\": \"" + base64.StdEncoding.EncodeToString([]byte(parts[3])) + "\""
re = regexp.MustCompile(`^WARNING\s.*$`)
if re.MatchString(parts[3]) {
notify("boardRuntimeWarning", info)
} else {
notify("boardRuntimeError", info)
}
}
}
line = ""
} else {
if buffer[0] != '\r' {
line = line + string(buffer[0])
}
}
if board.consoleOut {
ConsoleUp <- buffer[0]
}
if board.consoleIn {
board.RXQueue <- buffer[0]
}
}
}
}
}
func (board *Board) attach(info *serial.Info) {
defer func() {
if err := recover(); err != nil {
board.detach()
connectedBoard = board
connectedBoard.validFirmware = false
connectedBoard.validPrerequisites = false
connectedBoard.model = ""
connectedBoard.subtype = ""
connectedBoard.brand = ""
panic(err)
}
}()
log.Println("attaching board ...")
board.devInfo = info
// Configure options or serial port connection
options := serial.RawOptions
options.BitRate = 115200
options.Mode = serial.MODE_READ_WRITE
options.DTR = serial.DTR_OFF
options.RTS = serial.RTS_OFF
// Open port
port, openErr := options.Open(info.Name())
if openErr != nil {
panic(openErr)
}
// Create board struct
board.port = port
board.dev = info.Name()
board.RXQueue = make(chan byte, 10*1024)
board.chunkSize = 255
board.disableInspectorBootNotify = false
board.consoleOut = true
board.consoleIn = false
board.quit = make(chan bool)
board.timeoutVal = math.MaxInt32
board.validFirmware = true
board.validPrerequisites = true
Upgrading = false
go board.inspector()
// Reset the board
board.reset(true)
connectedBoard = board
if board.validFirmware && board.validPrerequisites {
notify("boardAttached", "")
log.Println("board attached")
}
}
func (board *Board) detach() {
log.Println("detaching board ...")
// Close board
if board != nil {
log.Println("closing serial port ...")
// Close serial port
board.port.Close()
time.Sleep(time.Millisecond * 1000)
}
connectedBoard = nil
}
/*
* Serial port primitives
*/
// Read one byte from RXQueue
func (board *Board) read() byte {
if board.timeoutVal != math.MaxInt32 {
for {
select {
case c := <-board.RXQueue:
return c
case <-time.After(time.Millisecond * time.Duration(board.timeoutVal)):
panic(errors.New("timeout"))
}
}
} else {
return <-board.RXQueue
}
}
// Read one line from RXQueue
func (board *Board) readLineCRLF() string {
var buffer bytes.Buffer
var b byte
for {
b = board.read()
if b == '\n' {
return buffer.String()
} else {
if b != '\r' {
buffer.WriteString(string(rune(b)))
}
}
}
return ""
}
func (board *Board) readLineCR() string {
var buffer bytes.Buffer
var b byte
for {
b = board.read()
if b == '\r' {
return buffer.String()
} else {
buffer.WriteString(string(rune(b)))
}
}
return ""
}
func (board *Board) consume() {
timeout := 0
for {
if len(board.RXQueue) > 0 {
break
} else {
time.Sleep(time.Millisecond * 10)
timeout = timeout + 10
if timeout > 200 {
break
}
}
}
for len(board.RXQueue) > 0 {
board.read()
}
}
// Wait until board is ready
func (board *Board) waitForReady() bool {
booting := false
whitecat := false
failingBack := 0
line := ""
vendorId, productId, _ := board.devInfo.USBVIDPID()
board.timeout(4000)
for {
select {
case <-time.After(time.Millisecond * time.Duration(board.timeoutVal)):
panic(errors.New("timeout"))
default:
line = board.readLineCRLF()
if regexp.MustCompile(`^.*formatting\s{0,1}\.\.\.$`).MatchString(line) {
log.Println("board is formatting the file system, setting time out to 120 seconds")
board.timeout(120000)
notify("boardUpdate", "Board is formatting the file system, please, wait ...")
}
if regexp.MustCompile(`^.*formating\s{0,1}\.\.\.$`).MatchString(line) {
log.Println("board is formatting the file system, setting time out to 80 seconds")
board.timeout(120000)
notify("boardUpdate", "Board is formatting the file system, please, wait ...")
}
if regexp.MustCompile(`^.*boot: Failed to verify app image.*$`).MatchString(line) {
board.validFirmware = false
board.validPrerequisites = false
notify("invalidFirmware", "")
return false
}
if regexp.MustCompile(`^.*boot: No bootable app partitions in the partition table.*$`).MatchString(line) {
board.validFirmware = false
board.validPrerequisites = false
notify("invalidFirmware", "")
return false
}
if regexp.MustCompile(`^Falling back to built-in command interpreter.$`).MatchString(line) {
failingBack = failingBack + 1
if failingBack > 4 {
board.validFirmware = false
board.validPrerequisites = false
notify("invalidFirmware", "")
return false
}
}
if regexp.MustCompile(`^flash read err,.*$`).MatchString(line) {
failingBack = failingBack + 1
if failingBack > 4 {
board.validFirmware = false
board.validPrerequisites = false
notify("invalidFirmware", "")
return false
}
}
if !booting {
if (vendorId == 0x1a86) && (productId == 0x7523) {
booting = regexp.MustCompile(`Booting Lua RTOS...`).MatchString(line)
} else {
booting = regexp.MustCompile(`^rst:.*\(POWERON_RESET\),boot:.*(.*)$`).MatchString(line)
if !booting {
booting = regexp.MustCompile(`^rst:.*\(RTCWDT_RTC_RESET\),boot:.*(.*)$`).MatchString(line)
}
}
} else {
if !whitecat {
if (vendorId != 0x1a86) || (productId != 0x7523) {
whitecat = regexp.MustCompile(`Booting Lua RTOS...`).MatchString(line)
} else {
whitecat = true
}
if whitecat {
// Send Ctrl-D
board.port.Write([]byte{4})
}
board.consoleOut = true
} else {
if regexp.MustCompile(`^Lua RTOS-boot-scripts-aborted-ESP32$`).MatchString(line) {
return true
}
}
}
}
}
}
// Test if line corresponds to Lua RTOS prompt
func isPrompt(line string) bool {
return regexp.MustCompile("^/.*>.*$").MatchString(line)
}
func (board *Board) getInfo() string {
board.consoleOut = false
board.consoleIn = true
board.timeout(2000)
info := board.sendCommand("dofile(\"/_info.lua\")")
board.noTimeout()
board.consoleOut = true
board.consoleIn = false
info = strings.Replace(info, ",}", "}", -1)
info = strings.Replace(info, ",]", "]", -1)
return info
}
// Send a command to the board
func (board *Board) sendCommand(command string) string {
var response string = ""
var prevShell string = "false"
if board.shell {
prevShell = "true"
}
// Disable shell
if board.info != "" {
board.port.Write([]byte("os.shell(false)\r\n"))
board.consume()
}
// Send command. We must append the \r\n chars at the end
board.port.Write([]byte(command + "\r\n"))
// Read response, that it must be the send command.
line := board.readLineCRLF()
if line == command {
// Read until prompt
for {
line = board.readLineCRLF()
if isPrompt(line) {
// Reenable shell
if board.info != "" {
board.port.Write([]byte("os.shell(" + prevShell + ")\r\n"))
board.consume()
}
return response
} else {
if response != "" {
response = response + "\r\n"
}
response = response + line
}
}
} else {
// Reenable shell
if board.info != "" {
board.port.Write([]byte("os.shell(" + prevShell + ")\r\n"))
board.consume()
}
return ""
}
// Reenable shell
if board.info != "" {
board.port.Write([]byte("os.shell(" + prevShell + ")\r\n"))
board.consume()
}
return ""
}
func (board *Board) reset(prerequisites bool) {
defer func() {
board.noTimeout()
board.consoleOut = true
board.consoleIn = false
if err := recover(); err != nil {
panic(err)
}
}()
board.consume()
board.shell = false
prevInfo := board.info
board.info = ""
board.consoleOut = false
board.consoleIn = true
// Reset board
options := serial.RawOptions
options.BitRate = 115200
options.Mode = serial.MODE_READ_WRITE
options.RTS = serial.RTS_OFF
board.port.Apply(&options)
time.Sleep(time.Millisecond * 10)
options.RTS = serial.RTS_ON
board.port.Apply(&options)
time.Sleep(time.Millisecond * 10)
options.RTS = serial.RTS_OFF
board.port.Apply(&options)
if !board.waitForReady() {
return
}
board.consume()
log.Println("board is ready ...")
if runtime.GOOS != "linux" {
if board.maxBauds != 115200 {
log.Println("changing baud rate to " + strconv.Itoa(board.maxBauds) + " ...")
board.consoleOut = false
board.consoleIn = true
board.port.Write([]byte("uart.attach(uart.UART0, " + strconv.Itoa(board.maxBauds) + ", 8, uart.PARNONE, uart.STOP1)\r\n"))
time.Sleep(time.Millisecond * 10)
options.BitRate = board.maxBauds
board.port.Apply(&options)
time.Sleep(time.Millisecond * 10)
board.consume()
board.consoleOut = false
board.consoleIn = true
}
}
if prerequisites {
notify("boardUpdate", "Downloading prerequisites")
// Clean
os.RemoveAll(path.Join(AppDataTmpFolder, "*"))
// Upgrade prerequisites
exists := ""
prerequisitesSource := NoSource
if PrerequisitesFolder != "" {
// Check if we can use prerrequisites n folder
if _, err := os.Stat(path.Join(PrerequisitesFolder, "lua", "board-info.lua")); !os.IsNotExist(err) {
if _, err := os.Stat(path.Join(PrerequisitesFolder, "lua", "lib", "block.lua")); !os.IsNotExist(err) {
prerequisitesSource = FolderSource
log.Println("using prerequisites in folder " + PrerequisitesFolder)
}
}
}
// HTTP client
timeout := time.Duration(20 * time.Second)
client := http.Client{
Timeout: timeout,
}
if prerequisitesSource == NoSource {
// Download
url := "https://ide.whitecatboard.org/boards/prerequisites.zip"
log.Println("Downloading prerequisites from " + url + " ...")
resp, err := client.Get(url)
if err == nil {
defer resp.Body.Close()
if resp.StatusCode == 200 {
log.Println("downloaded")
body, err := ioutil.ReadAll(resp.Body)
if err == nil {
err = ioutil.WriteFile(path.Join(AppDataTmpFolder, "prerequisites.zip"), body, 0777)
if err == nil {
unzip(path.Join(AppDataTmpFolder, "prerequisites.zip"), path.Join(AppDataTmpFolder, "prerequisites_files"))
prerequisitesSource = CloudSource
} else {
panic(err)
}
} else {
panic(err)
}
} else {
log.Println("download error (" + strconv.Itoa(resp.StatusCode) + ")")
}
} else {
log.Println("download error", err)
}
}
if prerequisitesSource == NoSource {
// Check if we can use prerrequisites installed on the board
exists = board.sendCommand("do local att = io.attributes(\"_info.lua\"); print(att ~= nil and att.type == \"file\"); end")
if exists == "true" {
exists = board.sendCommand("do local att = io.attributes(\"/lib/lua/block.lua\"); print(att ~= nil and att.type == \"file\"); end")
if exists == "true" {
prerequisitesSource = BoardSource
log.Println("using prerequisites installed on board")
}
}
}
if prerequisitesSource == NoSource {
// Check if we can use last downloaded prerrequisites
if _, err := os.Stat(path.Join(AppDataTmpFolder, "prerequisites_files", "lua", "board-info.lua")); !os.IsNotExist(err) {
if _, err := os.Stat(path.Join(AppDataTmpFolder, "prerequisites_files", "lua", "lib", "block.lua")); !os.IsNotExist(err) {
prerequisitesSource = DesktopSource
log.Println("using last downloaded prerequisites")
}
}
}
if prerequisitesSource == NoSource {
board.validPrerequisites = false
log.Println("alternative prerequisites don't found")
notify("invalidPrerequisites", "")
return
}
notify("boardUpdate", "Uploading framework")
board.consoleOut = false
board.consoleIn = true
// Test for lib/lua
if prerequisitesSource != BoardSource {
board.timeout(1000)
exists = board.sendCommand("do local att = io.attributes(\"/lib\"); print(att ~= nil and att.type == \"directory\"); end")
if exists != "true" {
log.Println("creating /lib folder")
board.sendCommand("os.mkdir(\"/lib\")")
} else {
log.Println("/lib folder, present")
}
exists = board.sendCommand("do local att = io.attributes(\"/lib/lua\"); print(att ~= nil and att.type == \"directory\"); end")
if exists != "true" {
log.Println("creating /lib/lua folder")
board.sendCommand("os.mkdir(\"/lib/lua\")")
} else {
log.Println("/lib/lua folder, present")
}
board.noTimeout()
}
if (prerequisitesSource == CloudSource) || (prerequisitesSource == DesktopSource) || (prerequisitesSource == FolderSource) {
useFolder := ""
if prerequisitesSource == FolderSource {
useFolder = path.Join(PrerequisitesFolder, "lua")
} else {
useFolder = path.Join(AppDataTmpFolder, "prerequisites_files", "lua")
}
buffer, err := ioutil.ReadFile(path.Join(useFolder, "board-info.lua"))
if err == nil {
resp := board.writeFile("/_info.lua", buffer)
if resp == "" {
panic(errors.New("timeout"))
}
} else {
panic(err)
}
files, err := ioutil.ReadDir(path.Join(useFolder, "lib"))
if err == nil {
for _, finfo := range files {
if regexp.MustCompile(`.*\.lua`).MatchString(finfo.Name()) {
file, _ := ioutil.ReadFile(path.Join(useFolder, "lib", finfo.Name()))
log.Println("Sending ", "/lib/lua/"+finfo.Name(), " ...")
resp := board.writeFile("/lib/lua/"+finfo.Name(), file)
if resp == "" {
panic(errors.New("timeout"))
}
board.consume()
}
}
} else {
panic(err)
}
}
board.consoleOut = true
// Get board info
info := board.getInfo()
// Parse some board info
var boardInfo BoardInfo
json.Unmarshal([]byte(info), &boardInfo)
// Test for a newer software build
board.newBuild = false
board.info = info
board.model = boardInfo.Board
board.subtype = boardInfo.Subtype
board.brand = boardInfo.Brand
board.ota = boardInfo.Ota
board.shell = boardInfo.Status.Shell
firmware := ""
if board.brand != "" {
firmware = board.brand + "-"
}
firmware = firmware + board.model
if board.subtype != "" {
firmware = firmware + "-" + board.subtype
}
board.firmware = firmware
log.Println("Check for new firmware at ", LastBuildURL+"?firmware="+board.firmware)
resp, err := client.Get(LastBuildURL + "?firmware=" + board.firmware)
if err == nil {
body, err := ioutil.ReadAll(resp.Body)
if err == nil {
lastCommit := string(body)
if (boardInfo.Commit != lastCommit) && (lastCommit != "") {
board.newBuild = true
log.Println("new firmware available: ", lastCommit)
}
} else {
panic(err)
}
} else {
log.Println("error checking firmware", err)
}
board.consume()
} else {
board.info = prevInfo
board.newBuild = false
}
}
func (board *Board) getDirContent(path string) string {
var content string
defer func() {
board.noTimeout()
board.consoleOut = true
board.consoleIn = false
if err := recover(); err != nil {
}
}()
content = ""
board.consoleOut = false
board.consoleIn = true
board.timeout(1000)
response := board.sendCommand("os.ls(\"" + path + "\")")
for _, line := range strings.Split(response, "\n") {
element := strings.Split(strings.Replace(line, "\r", "", -1), "\t")
if len(element) == 4 {
if content != "" {
content = content + ","
}
content = content + "{" +
"\"type\": \"" + element[0] + "\"," +
"\"size\": \"" + element[1] + "\"," +
"\"date\": \"" + element[2] + "\"," +
"\"name\": \"" + element[3] + "\"" +
"}"
}
}
board.consoleOut = true
return "[" + content + "]"
}
func (board *Board) removeFile(path string) {
board.consoleOut = false
board.consoleIn = true
board.timeout(2000)
board.sendCommand("os.remove(\"" + path + "\")")
board.noTimeout()
board.consoleOut = true
board.consoleIn = false
}
func (board *Board) writeFile(path string, buffer []byte) string {
defer func() {
board.noTimeout()
board.consoleOut = true
board.consoleIn = false
if err := recover(); err != nil {
}
}()
board.timeout(2000)
board.consoleOut = false
board.consoleIn = true
writeCommand := "io.receive(\"" + path + "\")"
outLen := 0
outIndex := 0
board.consume()
// Send command and test for echo
board.port.Write([]byte(writeCommand + "\r"))
if board.readLineCR() == writeCommand {
for {
// Wait for chunk
if board.readLineCRLF() == "C" {
// Get chunk length
if outIndex < len(buffer) {
if outIndex+board.chunkSize < len(buffer) {
outLen = board.chunkSize
} else {
outLen = len(buffer) - outIndex
}
} else {
outLen = 0
}
// Send chunk length
board.port.Write([]byte{byte(outLen)})
if outLen > 0 {
// Send chunk
board.port.Write(buffer[outIndex : outIndex+outLen])
} else {
break
}
outIndex = outIndex + outLen
}
}
if board.readLineCRLF() == "true" {
board.consume()
return "ok"
}
}
return ""
}
func (board *Board) runCode(buffer []byte) {