-
-
Notifications
You must be signed in to change notification settings - Fork 150
/
Copy pathprogrammer.go
343 lines (296 loc) · 9.67 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
package main
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"github.com/facchinm/go-serial"
"github.com/kardianos/osext"
"io"
"log"
"mime/multipart"
"net/http"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"time"
)
// Download the file from URL first, store in tmp folder, then pass to spProgram
func spProgramFromUrl(portname string, boardname string, url string) {
mapB, _ := json.Marshal(map[string]string{"ProgrammerStatus": "DownloadStart", "Url": url})
h.broadcastSys <- mapB
filename, err := downloadFromUrl(url)
mapB, _ = json.Marshal(map[string]string{"ProgrammerStatus": "DownloadDone", "Filename": filename, "Url": url})
h.broadcastSys <- mapB
if err != nil {
spErr(err.Error())
} else {
spProgram(portname, boardname, filename)
}
// delete file
}
func colonToUnderscore(input string) string {
output := strings.Replace(input, ":", "_", -1)
return output
}
func spProgramNetwork(portname string, boardname string, filePath string) {
// Prepare a form that you will submit to that URL.
_url := "http://root:arduino@" + portname + "/data/upload_sketch_silent"
var b bytes.Buffer
w := multipart.NewWriter(&b)
// Add your image file
f, err := os.Open(filePath)
if err != nil {
return
}
fw, err := w.CreateFormFile("sketch_hex", filePath)
if err != nil {
return
}
if _, err = io.Copy(fw, f); err != nil {
return
}
// Add the other fields
if fw, err = w.CreateFormField("board"); err != nil {
return
}
if _, err = fw.Write([]byte(colonToUnderscore(boardname))); err != nil {
return
}
// 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 {
return
}
// Don't forget to set the content type, this will contain the boundary.
req.Header.Set("Content-Type", w.FormDataContentType())
// Submit the request
client := &http.Client{}
res, err := client.Do(req)
if err != nil {
return
}
// Check the response
if res.StatusCode != http.StatusOK {
err = fmt.Errorf("bad status: %s", res.Status)
}
return
}
func spProgramLocal(portname string, boardname string, filePath string) {
isFound, flasher, mycmd := assembleCompilerCommand(boardname, portname, filePath)
mapD := map[string]string{"ProgrammerStatus": "CommandReady", "IsFound": strconv.FormatBool(isFound), "Flasher": flasher, "Cmd": strings.Join(mycmd, " ")}
mapB, _ := json.Marshal(mapD)
h.broadcastSys <- mapB
if isFound {
spHandlerProgram(flasher, mycmd)
} else {
spErr("We could not find the board " + boardname + " that you were trying to program.")
}
}
func spProgram(portname string, boardname string, filePath string) {
// check if the port is phisical or network
var networkPort bool
myport, exist := findPortByNameRerun(portname)
if !exist {
spErr("We could not find the port " + portname + " that you were trying to open.")
} else {
networkPort = myport.NetworkPort
}
if networkPort {
spProgramNetwork(portname, boardname, filePath)
} else {
spProgramLocal(portname, boardname, filePath)
}
}
func spHandlerProgram(flasher string, cmdString []string) {
var oscmd *exec.Cmd
// 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 {
oscmd = exec.Command(flasher, cmdString...)
// }
// Stdout buffer
//var cmdOutput []byte
//h.broadcastSys <- []byte("Start flashing with command " + cmdString)
log.Printf("Flashing with command:" + strings.Join(cmdString, " "))
mapD := map[string]string{"ProgrammerStatus": "Starting", "Cmd": strings.Join(cmdString, " ")}
mapB, _ := json.Marshal(mapD)
h.broadcastSys <- mapB
cmdOutput, err := oscmd.CombinedOutput()
if err != nil {
log.Printf("Command finished with error: %v "+string(cmdOutput), err)
h.broadcastSys <- []byte("Could not program the board")
mapD := map[string]string{"ProgrammerStatus": "Error", "Msg": "Could not program the board", "Output": string(cmdOutput)}
mapB, _ := json.Marshal(mapD)
h.broadcastSys <- mapB
} else {
log.Printf("Finished without error. Good stuff. stdout: " + string(cmdOutput))
h.broadcastSys <- []byte("Flash OK!")
mapD := map[string]string{"ProgrammerStatus": "Done", "Flash": "Ok", "Output": string(cmdOutput)}
mapB, _ := json.Marshal(mapD)
h.broadcastSys <- mapB
// analyze stdin
}
}
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 assembleCompilerCommand(boardname string, portname string, filePath string) (bool, string, []string) {
// get executable (self)path and use it as base for all other paths
execPath, _ := osext.Executable()
boardFields := strings.Split(boardname, ":")
if len(boardFields) != 3 {
h.broadcastSys <- []byte("Board need to be specified in core:architecture:name format")
return false, "", nil
}
tempPath := (filepath.Dir(execPath) + "/" + boardFields[0] + "/hardware/" + boardFields[1] + "/boards.txt")
file, err := os.Open(tempPath)
if err != nil {
h.broadcastSys <- []byte("Could not find board: " + boardname)
log.Println("Error:", err)
return false, "", nil
}
scanner := bufio.NewScanner(file)
boardOptions := make(map[string]string)
uploadOptions := make(map[string]string)
for scanner.Scan() {
// map everything matching with boardname
if strings.Contains(scanner.Text(), boardFields[2]) {
arr := strings.Split(scanner.Text(), "=")
arr[0] = strings.Replace(arr[0], boardFields[2]+".", "", 1)
boardOptions[arr[0]] = arr[1]
}
}
boardOptions["serial.port"] = portname
boardOptions["serial.port.file"] = filepath.Base(portname)
// filepath need special care; the project_name var is the filename minus its extension (hex or bin)
// if we are going to modify standard IDE files we also could pass ALL filename
filePath = strings.Trim(filePath, "\n")
boardOptions["build.path"] = filepath.Dir(filePath)
boardOptions["build.project_name"] = strings.TrimSuffix(filepath.Base(filePath), filepath.Ext(filepath.Base(filePath)))
file.Close()
// get infos about the programmer
tempPath = (filepath.Dir(execPath) + "/" + boardFields[0] + "/hardware/" + boardFields[1] + "/platform.txt")
file, err = os.Open(tempPath)
if err != nil {
h.broadcastSys <- []byte("Could not find board: " + boardname)
log.Println("Error:", err)
return false, "", nil
}
scanner = bufio.NewScanner(file)
tool := boardOptions["upload.tool"]
for scanner.Scan() {
// map everything matching with upload
if strings.Contains(scanner.Text(), tool) {
arr := strings.Split(scanner.Text(), "=")
uploadOptions[arr[0]] = arr[1]
arr[0] = strings.Replace(arr[0], "tools."+tool+".", "", 1)
boardOptions[arr[0]] = arr[1]
// we have a "=" in command line
if len(arr) > 2 {
boardOptions[arr[0]] = arr[1] + "=" + arr[2]
}
}
}
file.Close()
// multiple verisons of the same programmer can be handled if "version" is specified
version := uploadOptions["runtime.tools."+tool+".version"]
path := (filepath.Dir(execPath) + "/" + boardFields[0] + "/tools/" + tool + "/" + version)
if err != nil {
h.broadcastSys <- []byte("Could not find board: " + boardname)
log.Println("Error:", err)
return false, "", nil
}
boardOptions["runtime.tools."+tool+".path"] = path
cmdline := boardOptions["upload.pattern"]
// remove cmd.path as it is handled differently
cmdline = strings.Replace(cmdline, "\"{cmd.path}\"", " ", 1)
cmdline = strings.Replace(cmdline, "\"{path}/{cmd}\"", " ", 1)
cmdline = strings.Replace(cmdline, "\"", "", -1)
// split the commandline in substrings and recursively replace mapped strings
cmdlineSlice := strings.Split(cmdline, " ")
var winded = true
for index, _ := range cmdlineSlice {
winded = true
for winded != false {
cmdlineSlice[index], winded = formatCmdline(cmdlineSlice[index], boardOptions)
}
}
// some boards (eg. Leonardo, Yun) need a special procedure to enter bootloader
if boardOptions["upload.use_1200bps_touch"] == "true" {
// triggers bootloader mode
// the portname could change in this occasion, so fail gently
log.Println("Restarting in bootloader mode")
mode := &serial.Mode{
BaudRate: 1200,
Vmin: 1,
Vtimeout: 0,
}
port, err := serial.OpenPort(portname, mode)
if err != nil {
log.Println(err)
return false, "", nil
}
//port.SetDTR(false)
port.Close()
time.Sleep(time.Second / 2)
// time.Sleep(time.Second / 4)
// wait for port to reappear
if boardOptions["upload.wait_for_upload_port"] == "true" {
ports, _ := serial.GetPortsList()
for !(containsStr(ports, portname)) {
ports, _ = serial.GetPortsList()
}
}
}
tool = (filepath.Dir(execPath) + "/" + boardFields[0] + "/tools/" + tool + "/bin/" + tool)
// the file doesn't exist, we are on windows
if _, err := os.Stat(tool); err != nil {
tool = tool + ".exe"
// convert all "/" to "\"
tool = strings.Replace(tool, "/", "\\", -1)
}
// remove blanks from cmdlineSlice
var cmdlineSliceOut []string
for _, element := range cmdlineSlice {
if element != "" {
cmdlineSliceOut = append(cmdlineSliceOut, element)
}
}
return (tool != ""), tool, cmdlineSliceOut
}