forked from arduino/arduino-create-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprogrammer.go
503 lines (414 loc) · 12.3 KB
/
programmer.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
package main
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"mime/multipart"
"net/http"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"sort"
"strconv"
"strings"
"time"
log "github.com/Sirupsen/logrus"
"github.com/facchinm/go-serial"
"github.com/mattn/go-shellwords"
"github.com/sfreiberg/simplessh"
"github.com/xrash/smetrics"
)
var compiling = false
var allowedSshBoards = []string{"arduino:avr:yun"}
func colonToUnderscore(input string) string {
output := strings.Replace(input, ":", "_", -1)
return output
}
func sshProgramAllowed(boardname string) bool {
sort.Strings(allowedSshBoards)
return sort.SearchStrings(allowedSshBoards, boardname) != len(allowedSshBoards)
}
type basicAuthData struct {
Username string `json:"username"`
Password string `json:"password"`
}
type boardExtraInfo struct {
Use1200bpsTouch bool `json:"use_1200bps_touch"`
WaitForUploadPort bool `json:"wait_for_upload_port"`
Network bool `json:"network"`
Auth basicAuthData `json:"auth"`
}
// Scp uploads sourceFile to remote machine like native scp console app.
func Scp(client *simplessh.Client, sourceFile, targetFile string) error {
session, err := client.SSHClient.NewSession()
if err != nil {
return err
}
defer session.Close()
src, srcErr := os.Open(sourceFile)
if srcErr != nil {
return srcErr
}
srcStat, statErr := src.Stat()
if statErr != nil {
return statErr
}
go func() {
w, _ := session.StdinPipe()
fmt.Fprintln(w, "C0644", srcStat.Size(), filepath.Base(targetFile))
if srcStat.Size() > 0 {
io.Copy(w, src)
fmt.Fprint(w, "\x00")
w.Close()
} else {
fmt.Fprint(w, "\x00")
w.Close()
}
}()
if err := session.Run("scp -t " + targetFile); err != nil {
return err
}
return nil
}
func spProgramSSHNetwork(portname string, boardname string, filePath string, commandline string, authdata basicAuthData) error {
log.Println("Starting network upload")
log.Println("Board Name: " + boardname)
if authdata.Username == "" {
authdata.Username = "root"
}
if authdata.Password == "" {
authdata.Password = "arduino"
}
ssh_client, err := simplessh.ConnectWithPassword(portname+":22", authdata.Username, authdata.Password)
if err != nil {
log.Println("Error connecting via ssh")
return err
}
defer ssh_client.Close()
err = Scp(ssh_client, filePath, "/tmp/sketch"+filepath.Ext(filePath))
if err != nil {
log.Printf("Upload: %s\n", err)
return err
}
if commandline == "" {
// very special case for Yun (remove once AVR boards.txt is fixed)
commandline = "merge-sketch-with-bootloader.lua /tmp/sketch.hex && /usr/bin/run-avrdude /tmp/sketch.hex"
}
fmt.Println(commandline)
ssh_output, err := ssh_client.Exec(commandline)
if err == nil {
log.Printf("Flash: %s\n", ssh_output)
mapD := map[string]string{"ProgrammerStatus": "Busy", "Msg": string(ssh_output)}
mapB, _ := json.Marshal(mapD)
h.broadcastSys <- mapB
}
return err
}
func spProgramNetwork(portname string, boardname string, filePath string, authdata basicAuthData) error {
log.Println("Starting network upload")
log.Println("Board Name: " + boardname)
if authdata.Username == "" {
authdata.Username = "root"
}
if authdata.Password == "" {
authdata.Password = "arduino"
}
// Prepare a form that you will submit to that URL.
_url := "http://" + portname + "/data/upload_sketch_silent"
var b bytes.Buffer
w := multipart.NewWriter(&b)
// Add your image file
filePath = strings.Trim(filePath, "\n")
f, err := os.Open(filePath)
if err != nil {
log.Println("Error opening file" + filePath + " err: " + err.Error())
return err
}
fw, err := w.CreateFormFile("sketch_hex", filePath)
if err != nil {
log.Println("Error creating form file")
return err
}
if _, err = io.Copy(fw, f); err != nil {
log.Println("Error copying form file")
return err
}
// Add the other fields
if fw, err = w.CreateFormField("board"); err != nil {
log.Println("Error creating form field")
return err
}
if _, err = fw.Write([]byte(colonToUnderscore(boardname))); err != nil {
log.Println("Error writing form field")
return err
}
// Don't forget to close the multipart writer.
// If you don't close it, your request will be missing the terminating boundary.
w.Close()
// Now that you have a form, you can submit it to your handler.
req, err := http.NewRequest("POST", _url, &b)
if err != nil {
log.Println("Error creating post request")
return err
}
// Don't forget to set the content type, this will contain the boundary.
req.Header.Set("Content-Type", w.FormDataContentType())
if authdata.Username != "" {
req.SetBasicAuth(authdata.Username, authdata.Password)
}
//h.broadcastSys <- []byte("Start flashing with command " + cmdString)
log.Printf("Network flashing on " + portname)
mapD := map[string]string{"ProgrammerStatus": "Starting", "Cmd": "POST"}
mapB, _ := json.Marshal(mapD)
h.broadcastSys <- mapB
// Submit the request
client := &http.Client{}
res, err := client.Do(req)
if err != nil {
log.Println("Error during post request")
return err
}
// Check the response
if res.StatusCode != http.StatusOK {
log.Errorf("bad status: %s", res.Status)
err = fmt.Errorf("bad status: %s", res.Status)
}
return err
}
func spProgramLocal(portname string, boardname string, filePath string, commandline string, extraInfo boardExtraInfo) error {
var err error
if extraInfo.Use1200bpsTouch {
portname, err = touch_port_1200bps(portname, extraInfo.WaitForUploadPort)
}
if err != nil {
log.Println("Could not touch the port")
return err
}
log.Printf("Received commandline (unresolved):" + commandline)
commandline = strings.Replace(commandline, "{build.path}", filepath.ToSlash(filepath.Dir(filePath)), 1)
commandline = strings.Replace(commandline, "{build.project_name}", strings.TrimSuffix(filepath.Base(filePath), filepath.Ext(filepath.Base(filePath))), 1)
commandline = strings.Replace(commandline, "{serial.port}", portname, 1)
commandline = strings.Replace(commandline, "{serial.port.file}", filepath.Base(portname), 1)
// search for runtime variables and replace with values from globalToolsMap
var runtimeRe = regexp.MustCompile("\\{(.*?)\\}")
runtimeVars := runtimeRe.FindAllString(commandline, -1)
fmt.Println(runtimeVars)
for _, element := range runtimeVars {
// use string similarity to resolve a runtime var with a "similar" map element
if globalToolsMap[element] == "" {
max_similarity := 0.0
for i, candidate := range globalToolsMap {
similarity := smetrics.Jaro(element, i)
if similarity > 0.8 && similarity > max_similarity {
max_similarity = similarity
globalToolsMap[element] = candidate
}
}
}
commandline = strings.Replace(commandline, element, globalToolsMap[element], 1)
}
z, _ := shellwords.Parse(commandline)
return spHandlerProgram(z[0], z[1:])
}
func spProgramRW(portname string, boardname string, filePath string, commandline string, extraInfo boardExtraInfo) {
compiling = true
defer func() {
time.Sleep(1500 * time.Millisecond)
compiling = false
}()
var err error
if extraInfo.Network {
err = spProgramNetwork(portname, boardname, filePath, extraInfo.Auth)
if err != nil && sshProgramAllowed(boardname) {
// http method failed, try ssh upload if allowed
err = spProgramSSHNetwork(portname, boardname, filePath, commandline, extraInfo.Auth)
}
} else {
err = spProgramLocal(portname, boardname, filePath, commandline, extraInfo)
}
if err != nil {
log.Printf("Command finished with error: %v", err)
mapD := map[string]string{"ProgrammerStatus": "Error", "Msg": "Could not program the board"}
mapB, _ := json.Marshal(mapD)
h.broadcastSys <- mapB
} else {
log.Printf("Finished without error. Good stuff")
mapD := map[string]string{"ProgrammerStatus": "Done", "Flash": "Ok"}
mapB, _ := json.Marshal(mapD)
h.broadcastSys <- mapB
// analyze stdin
}
}
var oscmd *exec.Cmd
func spHandlerProgram(flasher string, cmdString []string) error {
// if runtime.GOOS == "darwin" {
// sh, _ := exec.LookPath("sh")
// // prepend the flasher to run it via sh
// cmdString = append([]string{flasher}, cmdString...)
// oscmd = exec.Command(sh, cmdString...)
// } else {
// remove quotes form flasher command and cmdString
flasher = strings.Replace(flasher, "\"", "", -1)
for index, _ := range cmdString {
cmdString[index] = strings.Replace(cmdString[index], "\"", "", -1)
}
extension := ""
if runtime.GOOS == "windows" {
extension = ".exe"
}
oscmd = exec.Command(flasher, cmdString...)
tellCommandNotToSpawnShell(oscmd)
stdout, err := oscmd.StdoutPipe()
if err != nil {
return err
}
stderr, err := oscmd.StderrPipe()
if err != nil {
return err
}
multi := io.MultiReader(stderr, stdout)
// Stdout buffer
//var cmdOutput []byte
//h.broadcastSys <- []byte("Start flashing with command " + cmdString)
log.Printf("Flashing with command:" + flasher + extension + " " + strings.Join(cmdString, " "))
mapD := map[string]string{"ProgrammerStatus": "Starting", "Cmd": strings.Join(cmdString, " ")}
mapB, _ := json.Marshal(mapD)
h.broadcastSys <- mapB
err = oscmd.Start()
in := bufio.NewScanner(multi)
in.Split(bufio.ScanLines)
for in.Scan() {
log.Info(in.Text())
mapD := map[string]string{"ProgrammerStatus": "Busy", "Msg": in.Text()}
mapB, _ := json.Marshal(mapD)
h.broadcastSys <- mapB
}
err = oscmd.Wait()
return err
}
func spHandlerProgramKill() {
// Kill the process if there is one running
if oscmd != nil && oscmd.Process.Pid > 0 {
h.broadcastSys <- []byte("{\"ProgrammerStatus\": \"PreKilled\", \"Pid\": " + strconv.Itoa(oscmd.Process.Pid) + ", \"ProcessState\": \"" + oscmd.ProcessState.String() + "\"}")
oscmd.Process.Kill()
h.broadcastSys <- []byte("{\"ProgrammerStatus\": \"Killed\", \"Pid\": " + strconv.Itoa(oscmd.Process.Pid) + ", \"ProcessState\": \"" + oscmd.ProcessState.String() + "\"}")
} else {
if oscmd != nil {
h.broadcastSys <- []byte("{\"ProgrammerStatus\": \"KilledError\", \"Msg\": \"No current process\", \"Pid\": " + strconv.Itoa(oscmd.Process.Pid) + ", \"ProcessState\": \"" + oscmd.ProcessState.String() + "\"}")
} else {
h.broadcastSys <- []byte("{\"ProgrammerStatus\": \"KilledError\", \"Msg\": \"No current process\"}")
}
}
}
func formatCmdline(cmdline string, boardOptions map[string]string) (string, bool) {
list := strings.Split(cmdline, "{")
if len(list) == 1 {
return cmdline, false
}
cmdline = ""
for _, item := range list {
item_s := strings.Split(item, "}")
item = boardOptions[item_s[0]]
if len(item_s) == 2 {
cmdline += item + item_s[1]
} else {
if item != "" {
cmdline += item
} else {
cmdline += item_s[0]
}
}
}
log.Println(cmdline)
return cmdline, true
}
func containsStr(s []string, e string) bool {
for _, a := range s {
if a == e {
return true
}
}
return false
}
func findNewPortName(slice1 []string, slice2 []string) string {
m := map[string]int{}
for _, s1Val := range slice1 {
m[s1Val] = 1
}
for _, s2Val := range slice2 {
m[s2Val] = m[s2Val] + 1
}
for mKey, mVal := range m {
if mVal == 1 {
return mKey
}
}
return ""
}
func touch_port_1200bps(portname string, WaitForUploadPort bool) (string, error) {
initialPortName := portname
log.Println("Restarting in bootloader mode")
before_reset_ports, _ := serial.GetPortsList()
log.Println(before_reset_ports)
var ports []string
mode := &serial.Mode{
BaudRate: 1200,
Vmin: 0,
Vtimeout: 1,
}
port, err := serial.OpenPort(portname, mode)
if err != nil {
log.Println(err)
return "", err
}
err = port.SetDTR(false)
if err != nil {
log.Println(err)
}
port.Close()
timeout := false
go func() {
time.Sleep(10 * time.Second)
timeout = true
}()
// wait for port to disappear
if WaitForUploadPort {
for {
ports, _ = serial.GetPortsList()
log.Println(ports)
portname = findNewPortName(ports, before_reset_ports)
if portname != "" {
break
}
if timeout {
break
}
time.Sleep(time.Millisecond * 100)
}
}
// wait for port to reappear
if WaitForUploadPort {
after_reset_ports, _ := serial.GetPortsList()
log.Println(after_reset_ports)
for {
ports, _ = serial.GetPortsList()
log.Println(ports)
portname = findNewPortName(ports, after_reset_ports)
if portname != "" {
break
}
if timeout {
break
}
time.Sleep(time.Millisecond * 100)
}
}
if portname == "" {
portname = initialPortName
}
return portname, nil
}