-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
main.go
259 lines (223 loc) · 6.04 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
package main
import (
"bytes"
"flag"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/http/httptrace"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
"github.com/arduino/arduinoOTA/globals"
)
var compileInfo string
var (
version = flag.Bool("version", false, "Prints program version")
networkAddress = flag.String("address", "localhost", "The address of the board")
networkPort = flag.String("port", "80", "The board needs to be listening on this port")
username = flag.String("username", "", "Username for authentication")
password = flag.String("password", "", "Password for authentication")
sketchPath = flag.String("sketch", "", "Sketch path")
uploadEndpoint = flag.String("upload", "", "Upload endpoint")
resetEndpoint = flag.String("reset", "", "Upload endpoint")
syncEndpoint = flag.String("sync", "", "Upload endpoint")
binMode = flag.Bool("b", false, "Upload binary mode")
verbose = flag.Bool("v", true, "Verbose flag")
quiet = flag.Bool("q", false, "Quiet flag")
useSsl = flag.String("ssl", "", "SSL flag")
syncRet = flag.String("sync_exp", "", "sync expected return code in format code:string")
hasDownloadFile = flag.Bool("d", false, "set to true to take advantage of downloadFile API")
timeoutSeconds = flag.Int("t", 10, "Upload timeout")
)
func main() {
flag.Parse()
if *version {
fmt.Println(globals.VersionInfo.String() + compileInfo)
os.Exit(0)
}
var httpClient = &http.Client{
Timeout: time.Second * time.Duration(*timeoutSeconds),
}
httpheader := "http://"
if *useSsl != "" {
httpheader = "https://"
}
syncRetCode := 200
syncString := "SYNC"
if *syncRet != "" {
sliceStrRet := strings.Split(*syncRet, ":")
if len(sliceStrRet) == 2 {
syncRetCode, _ = strconv.Atoi(sliceStrRet[0])
syncString = sliceStrRet[1]
}
}
if *syncEndpoint != "" {
if *verbose {
fmt.Println("Resetting the board")
}
resp, err := httpClient.Post(httpheader+*networkAddress+":"+*networkPort+*syncEndpoint, "", nil)
if err != nil || resp.StatusCode != syncRetCode {
if *verbose {
fmt.Println("Failed to reset the board, upload failed")
}
os.Exit(1)
}
defer resp.Body.Close()
}
if *syncEndpoint != "" {
if *verbose {
fmt.Println("Waiting for the upload to start")
}
timeout := 0
for timeout < 10 {
resp, err := httpClient.Get(httpheader + *networkAddress + ":" + *networkPort + *syncEndpoint)
if err != nil {
if *verbose {
fmt.Println("Failed to reset the board, upload failed")
}
os.Exit(1)
}
defer resp.Body.Close()
statusString, err := ioutil.ReadAll(resp.Body)
if strings.Contains(string(statusString), syncString) {
fmt.Println(string(statusString))
break
}
time.Sleep(1 * time.Second)
timeout++
}
}
if *uploadEndpoint != "" {
f, err := os.Open(*sketchPath)
if err != nil {
if *verbose {
fmt.Println("Failed to open the sketch")
}
os.Exit(1)
}
defer f.Close()
var sketchData *bytes.Buffer
if *binMode {
sketchData = streamToBytes(f)
} else {
str := streamToString(f)
re := regexp.MustCompile(`\r?\n`)
str = re.ReplaceAllString(str, "")
sketchData = bytes.NewBufferString(str)
}
if *hasDownloadFile {
go http.ListenAndServe(":"+*networkPort, http.FileServer(http.Dir(filepath.Dir(*sketchPath))))
// find my IP if not specified
ip := getMyIP(net.ParseIP(*networkAddress))
url := "http://" + ip.String() + ":" + *networkPort + "/" + filepath.Base(*sketchPath)
sketchData = bytes.NewBufferString(url)
fmt.Println("Serving sketch on " + url)
}
req, err := http.NewRequest("POST", httpheader+*networkAddress+":"+*networkPort+*uploadEndpoint, sketchData)
if err != nil {
if *verbose {
fmt.Println("Error sending sketch file")
}
os.Exit(1)
}
if *binMode {
req.Header.Set("Content-Type", "application/octet-stream")
} else {
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
}
if len(*username) > 0 && len(*password) != 0 {
req.SetBasicAuth(*username, *password)
}
if *verbose {
trace := &httptrace.ClientTrace{
ConnectStart: func(network, addr string) {
fmt.Print("Connecting to board ... ")
},
ConnectDone: func(network, addr string, err error) {
if err != nil {
fmt.Println("failed!")
} else {
fmt.Println(" done")
}
},
WroteHeaders: func() {
fmt.Print("Uploading sketch ... ")
},
WroteRequest: func(wri httptrace.WroteRequestInfo) {
fmt.Println(" done")
fmt.Print("Flashing sketch ... ")
},
GotFirstResponseByte: func() {
fmt.Println(" done")
},
}
req = req.WithContext(httptrace.WithClientTrace(req.Context(), trace))
}
resp, err := httpClient.Do(req)
if err != nil {
if *verbose {
fmt.Println("Error flashing the sketch")
}
os.Exit(1)
}
defer resp.Body.Close()
respStr, _ := ioutil.ReadAll(resp.Body)
if resp.StatusCode != 200 {
if *verbose {
fmt.Println("Error flashing the sketch:" + string(respStr))
}
os.Exit(1)
}
if *verbose {
fmt.Println(string(respStr))
fmt.Println("Sketch uploaded successfully")
}
}
if *resetEndpoint != "" {
if *verbose {
fmt.Println("Resetting the board")
}
resp, err := httpClient.Post(httpheader+*networkAddress+":"+*networkPort+*resetEndpoint, "", nil)
if err != nil {
if *verbose {
fmt.Println("Failed to reset the board, please reset manually")
}
os.Exit(0)
}
defer resp.Body.Close()
}
}
func streamToBytes(stream io.Reader) *bytes.Buffer {
buf := new(bytes.Buffer)
buf.ReadFrom(stream)
return buf
}
func streamToString(stream io.Reader) string {
return streamToBytes(stream).String()
}
func getMyIP(otherip net.IP) net.IP {
ifaces, _ := net.Interfaces()
// handle err
var ips []net.IP
for _, i := range ifaces {
addrs, _ := i.Addrs()
// handle err
for _, addr := range addrs {
switch v := addr.(type) {
case *net.IPNet:
if v.Contains(otherip) {
return v.IP
}
case *net.IPAddr:
ips = append(ips, v.IP)
}
}
}
return nil
}