-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
main.go
418 lines (341 loc) · 10.4 KB
/
main.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
package main
import (
"bufio"
"flag"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"time"
"github.com/arduino/arduino101load/globals"
shellwords "github.com/mattn/go-shellwords"
)
var (
verbose = flag.Bool("v", false, "Show verbose logging")
quiet = flag.Bool("q", true, "Show quiet logging")
force = flag.Bool("f", false, "Force firmware update")
copier = flag.Bool("c", false, "Copy bin_file to bin_save")
core = flag.String("core", "", "Firmware location")
from = flag.String("from", "", "Original file location")
to = flag.String("to", "", "Save file location")
dfu_path = flag.String("dfu", "", "Location of dfu-util binaries")
bin_file_name = flag.String("bin", "", "Location of sketch binary")
com_port = flag.String("port", "", "Upload serial port")
ble_compliance_string = flag.String("ble_fw_str", "", "BLE FW ID string")
ble_compliance_offset = flag.Int("ble_fw_pos", 0, "BLE FW ID offset")
rtos_compliance_string = flag.String("rtos_fw_str", "", "RTOS FW ID string")
rtos_compliance_offset = flag.Int("rtos_fw_pos", 0, "RTOS FW ID offset")
)
const dfu_flags = "-d,8087:0ABA"
const rtos_firmware = "quark.bin"
const ble_firmware = "ble_core.bin"
func PrintlnVerbose(a ...interface{}) {
if *verbose {
fmt.Println(a...)
}
}
func PrintVerbose(a ...interface{}) {
if *verbose {
fmt.Print(a...)
}
}
func main_load() {
if *dfu_path == "" {
fmt.Println("Need to specify dfu-util location")
os.Exit(1)
}
if *bin_file_name == "" && *force == false {
fmt.Println("Need to specify a binary location or force FW update")
os.Exit(1)
}
// Remove ""s from the strings
*dfu_path = strings.Replace(*dfu_path, "\"", "", -1)
*bin_file_name = strings.Replace(*bin_file_name, "\"", "", -1)
*ble_compliance_string = strings.Replace(*ble_compliance_string, "\"", "", -1)
*rtos_compliance_string = strings.Replace(*rtos_compliance_string, "\"", "", -1)
dfu := filepath.Join(*dfu_path, "dfu-util")
dfu = filepath.ToSlash(dfu)
PrintlnVerbose("Serial Port: " + *com_port)
PrintlnVerbose("BIN FILE " + *bin_file_name)
counter := 0
board_found := false
if runtime.GOOS == "darwin" {
library_path := os.Getenv("DYLD_LIBRARY_PATH")
if !strings.Contains(library_path, *dfu_path) {
os.Setenv("DYLD_LIBRARY_PATH", *dfu_path+":"+library_path)
}
}
dfu_search_command := []string{dfu, dfu_flags, "-l"}
var err error
for counter < 100 && board_found == false {
if counter%10 == 0 {
PrintlnVerbose("Waiting for device...")
}
err, found, _ := launchCommandAndWaitForOutput(dfu_search_command, "sensor_core", false, false)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
if counter == 40 {
fmt.Println("Flashing is taking longer than expected")
fmt.Println("Try pressing MASTER_RESET button")
}
if found == true {
board_found = true
PrintlnVerbose("Device found!")
break
}
time.Sleep(100 * time.Millisecond)
counter++
}
if board_found == false {
fmt.Println("ERROR: Timed out waiting for Arduino 101 on " + *com_port)
os.Exit(1)
}
needUpdateRTOS := false
needUpdateBLE := false
if *ble_compliance_string != "" {
// obtain a temporary filename
tmpfile, _ := ioutil.TempFile(os.TempDir(), "dfu")
tmpfile.Close()
os.Remove(tmpfile.Name())
// reset DFU interface counter
dfu_reset_command := []string{dfu, dfu_flags, "-U", tmpfile.Name(), "--alt", "8", "-K", "1"}
err, _, _ := launchCommandAndWaitForOutput(dfu_reset_command, "", false, false)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
os.Remove(tmpfile.Name())
// download a piece of BLE firmware
dfu_ble_dump_command := []string{dfu, dfu_flags, "-U", tmpfile.Name(), "--alt", "8", "-K", strconv.Itoa(*ble_compliance_offset)}
err, _, _ = launchCommandAndWaitForOutput(dfu_ble_dump_command, "", false, false)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// check for BLE library compliance
PrintlnVerbose("Verifying BLE version:", *ble_compliance_string)
found := searchVersionInDFU(tmpfile.Name(), *ble_compliance_string)
// remove the temporary file
os.Remove(tmpfile.Name())
if !found {
needUpdateBLE = true
} else {
PrintlnVerbose("BLE version: verified")
}
}
if *rtos_compliance_string != "" {
// obtain a temporary filename
tmpfile, _ := ioutil.TempFile(os.TempDir(), "dfu")
tmpfile.Close()
os.Remove(tmpfile.Name())
// reset DFU interface counter
dfu_reset_command := []string{dfu, dfu_flags, "-U", tmpfile.Name(), "--alt", "2", "-K", "1"}
err, _, _ := launchCommandAndWaitForOutput(dfu_reset_command, "", false, false)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
os.Remove(tmpfile.Name())
// download a piece of RTOS firmware
dfu_rtos_dump_command := []string{dfu, dfu_flags, "-U", tmpfile.Name(), "--alt", "2", "-K", strconv.Itoa(*rtos_compliance_offset)}
err, _, _ = launchCommandAndWaitForOutput(dfu_rtos_dump_command, "", false, false)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// check for BLE library compliance
PrintlnVerbose("Verifying RTOS version:", *rtos_compliance_string)
found := searchVersionInDFU(tmpfile.Name(), *rtos_compliance_string)
// remove the temporary file
os.Remove(tmpfile.Name())
if !found {
needUpdateRTOS = true
} else {
PrintlnVerbose("RTOS version: verified")
}
}
firmwarePath, _ := os.Executable()
firmwarePath = filepath.Join(filepath.Dir(firmwarePath), "firmwares")
if stat, err := os.Stat(*core); err == nil && stat.IsDir() {
firmwarePath = *core
} else {
firmwarePath = filepath.Join(firmwarePath, *core)
}
if needUpdateBLE || *force == true {
// flash current BLE firmware to partition 8
dfu_ble_flash_command := []string{dfu, dfu_flags, "-D", filepath.Join(firmwarePath, ble_firmware), "--alt", "8"}
fmt.Println("ATTENTION: BLE firmware is being flashed")
fmt.Println("DO NOT DISCONNECT THE BOARD")
err, _, _ = launchCommandAndWaitForOutput(dfu_ble_flash_command, "", true, true)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
}
if needUpdateRTOS || *force == true {
// flash current RTOS firmware to partition 2
dfu_rtos_flash_command := []string{dfu, dfu_flags, "-D", filepath.Join(firmwarePath, rtos_firmware), "--alt", "2"}
fmt.Println("ATTENTION: RTOS firmware is being flashed")
fmt.Println("DO NOT DISCONNECT THE BOARD")
err, _, _ = launchCommandAndWaitForOutput(dfu_rtos_flash_command, "", true, true)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
}
// Finally flash the sketch
if *bin_file_name == "" {
fmt.Println("SUCCESS: Upload completed")
os.Exit(0)
}
dfu_download := []string{dfu, dfu_flags, "-D", *bin_file_name, "-v", "--alt", "7", "-R"}
err, _, _ = launchCommandAndWaitForOutput(dfu_download, "", true, false)
if err == nil {
fmt.Println("SUCCESS: Sketch will execute in about 5 seconds.")
os.Exit(0)
} else {
fmt.Println("ERROR: Upload failed on " + *com_port)
os.Exit(1)
}
}
func main_debug(args []string) {
if len(args) < 1 {
fmt.Println("Not enough arguments")
os.Exit(1)
}
*verbose = true
type Command struct {
command string
background bool
}
var commands []Command
fullcmdline := strings.Join(args[:], "")
temp_commands := strings.Split(fullcmdline, ";")
for _, command := range temp_commands {
background_commands := strings.Split(command, "&")
for i, command := range background_commands {
var cmd Command
cmd.background = (i < len(background_commands)-1)
cmd.command = command
commands = append(commands, cmd)
}
}
var err error
for _, command := range commands {
fmt.Println("command: " + command.command)
cmd, _ := shellwords.Parse(command.command)
fmt.Println(cmd)
if command.background == false {
err, _, _ = launchCommandAndWaitForOutput(cmd, "", true, false)
} else {
err, _ = launchCommandBackground(cmd, "", true)
}
if err != nil {
fmt.Println("ERROR: Command \" " + command.command + " \" failed")
os.Exit(1)
}
}
os.Exit(0)
}
func main() {
name := filepath.Base(os.Args[0])
flag.Parse()
PrintlnVerbose(globals.VersionInfo)
if *copier {
if *from == "" || *to == "" {
fmt.Println("ERROR: need -from and -to arguments")
os.Exit(1)
}
*from = strings.Replace(*from, "\"", "", -1)
*to = strings.Replace(*to, "\"", "", -1)
copy(*from, *to)
os.Exit(0)
}
if strings.Contains(name, "load") {
fmt.Println("Starting download script...")
main_load()
}
if strings.Contains(name, "debug") {
fmt.Println("Starting debug script...")
main_debug(os.Args[1:])
}
fmt.Println("Wrong executable name")
os.Exit(1)
}
// Copy a file
func copy(source, destination string) {
// Open original file
originalFile, err := os.Open(source)
if err != nil {
os.Exit(1)
}
defer originalFile.Close()
// Create new file
newFile, err := os.Create(destination)
if err != nil {
os.Exit(1)
}
defer newFile.Close()
// Copy the bytes to destination from source
_, err = io.Copy(newFile, originalFile)
if err != nil {
os.Exit(1)
}
// Commit the file contents
// Flushes memory to disk
err = newFile.Sync()
if err != nil {
os.Exit(1)
}
}
func searchVersionInDFU(file string, string_to_search string) bool {
read, _ := ioutil.ReadFile(file)
return strings.Contains(string(read), string_to_search)
}
func launchCommandAndWaitForOutput(command []string, stringToSearch string, print_output bool, show_spinner bool) (error, bool, string) {
oscmd := exec.Command(command[0], command[1:]...)
tellCommandNotToSpawnShell(oscmd)
stdout, _ := oscmd.StdoutPipe()
stderr, _ := oscmd.StderrPipe()
multi := io.MultiReader(stdout, stderr)
if print_output && *verbose {
oscmd.Stdout = os.Stdout
oscmd.Stderr = os.Stderr
}
err := oscmd.Start()
in := bufio.NewScanner(multi)
in.Split(bufio.ScanRunes)
found := false
out := ""
lastPrint := time.Now()
for in.Scan() {
if show_spinner && time.Since(lastPrint) > time.Second {
fmt.Printf(". ")
lastPrint = time.Now()
}
out += in.Text()
if stringToSearch != "" {
if strings.Contains(out, stringToSearch) {
found = true
}
}
}
err = oscmd.Wait()
if show_spinner {
fmt.Println("")
}
return err, found, out
}
func launchCommandBackground(command []string, stringToSearch string, print_output bool) (error, bool) {
oscmd := exec.Command(command[0], command[1:]...)
tellCommandNotToSpawnShell(oscmd)
err := oscmd.Start()
return err, false
}