-
Notifications
You must be signed in to change notification settings - Fork 6
/
connector_http.go
246 lines (220 loc) · 5.04 KB
/
connector_http.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
package main
import (
"fmt"
"io"
"log"
"os"
"time"
"github.com/gosuri/uilive"
"github.com/imroc/req/v3"
)
const (
HTTPPort = "8080"
HTTPTimeout = 5
)
const (
AuthStatusApproved = 1 + iota
AuthStatusDenied
AuthStatusWaiting
)
type HTTPConnector struct {
client *req.Client
printer *Printer
}
func (hc *HTTPConnector) Ping(p *Printer) bool {
if p.Sacp {
return false
}
if ping(p.IP, HTTPPort, 3) {
hc.printer = p
return true
}
return false
}
func (hc *HTTPConnector) Connect() error {
result := struct {
Token string `json:"token"`
}{}
req := hc.request().
SetResult(&result).
SetRetryCount(3).
SetRetryFixedInterval(1 * time.Second).
SetRetryCondition(func(r *req.Response, err error) bool {
if Debug {
log.Printf("-- retrying %s -> %d, token %s", r.Request.URL, r.StatusCode, hc.printer.Token)
}
// token expired
if r.StatusCode == 403 && hc.printer.Token != "" {
hc.printer.Token = ""
// reconnect with no token to get new one
return true
}
return false
})
resp, err := req.Post(hc.URL("/connect"))
if err != nil {
return err
}
if resp.StatusCode == 200 {
if hc.printer.Token != result.Token {
hc.printer.Token = result.Token
}
tip := false
for {
switch hc.checkStatus() {
case AuthStatusApproved:
return nil
case AuthStatusWaiting:
if !tip {
tip = true
log.Println(">>> Please tap Yes on Snapmaker touchscreen to continue <<<")
}
// wait for auth on HMI
<-time.After(2 * time.Second)
case AuthStatusDenied:
return fmt.Errorf("access denied")
}
}
/*
} else if resp.StatusCode == 403 && hc.printer.Token != "" {
// token expired
hc.printer.Token = ""
// reconnect with no token to get new one
return hc.Connect()
*/
}
return fmt.Errorf("connect error %d", resp.StatusCode)
}
func (hc *HTTPConnector) Disconnect() (err error) {
if hc.client != nil && hc.printer.Token != "" {
_, err = hc.request().Post(hc.URL("/disconnect"))
}
return
}
func (hc *HTTPConnector) SetToolTemperature(tool int, temperature int) (err error) {
// *** NOT IMPLEMENTED ***
err = fmt.Errorf("not implemented")
return
}
func (hc *HTTPConnector) SetBedTemperature(tool int, temperature int) (err error) {
// *** NOT IMPLEMENTED ***
err = fmt.Errorf("not implemented")
return
}
func (hc *HTTPConnector) Home() (err error) {
// *** NOT IMPLEMENTED ***
err = fmt.Errorf("not implemented")
return
}
func (hc *HTTPConnector) Upload(payload *Payload) (err error) {
finished := make(chan empty, 1)
defer func() {
finished <- empty{}
}()
go func() {
ticker := time.NewTicker(2 * time.Second)
for {
select {
case <-ticker.C:
hc.checkStatus()
case <-finished:
if Debug {
log.Printf("-- heartbeat stopped")
}
ticker.Stop()
return
}
}
}()
w := uilive.New()
w.Start()
log.SetOutput(w)
defer func() {
w.Stop()
log.SetOutput(os.Stderr)
}()
file := req.FileUpload{
ParamName: "file",
FileName: payload.Name,
GetFileContent: func() (io.ReadCloser, error) {
pr, pw := io.Pipe()
go func() {
defer pw.Close()
content, err := payload.GetContent(NoFix)
if !NoFix {
log.SetOutput(os.Stderr)
if err != nil {
log.Printf("G-Code fix error(ignored): %s", err)
} else if payload.ShouldBeFix() {
log.Printf("G-Code fixed")
}
log.SetOutput(w)
}
pw.Write(content)
}()
return pr, nil
},
FileSize: payload.Size,
// ContentType: "application/octet-stream",
}
r := hc.request(0)
r.SetFileUpload(file)
r.SetUploadCallbackWithInterval(func(info req.UploadInfo) {
if info.FileSize > 0 {
perc := float64(info.UploadedSize) / float64(info.FileSize) * 100.0
log.Printf(" - HTTP sending %.1f%%", perc)
} else {
log.Printf(" - HTTP sending %s...", humanReadableSize(info.UploadedSize))
}
}, 35*time.Millisecond)
_, err = r.Post(hc.URL("/upload"))
return
}
func (hc *HTTPConnector) request(timeout ...int) *req.Request {
to := HTTPTimeout
if len(timeout) > 0 {
to = timeout[0]
}
if hc.client == nil {
hc.client = req.C()
hc.client.DisableAllowGetMethodPayload()
if Debug {
hc.client.EnableDumpAllWithoutRequestBody()
}
}
req := hc.client.SetTimeout(time.Second * time.Duration(to)).R()
// for GET
req.SetQueryParam("token", hc.printer.Token)
// for POST
req.SetFormData(map[string]string{"token": hc.printer.Token})
return req
}
func (hc *HTTPConnector) checkStatus() (status int) {
r, err := hc.request().Get(hc.URL("/status"))
if Debug {
log.Printf("-- heartbeat: %d, err(%s)", r.StatusCode, err)
}
if err == nil {
switch r.StatusCode {
case 200:
return AuthStatusApproved
case 204:
return AuthStatusWaiting
// case 401:
// return AuthStatusDenied
// case 403:
// if hc.printer.Token != "" { hc.printer.Token = ""}
// return AuthStatusExpired
}
}
return AuthStatusDenied
}
/*
URL to make url with path
*/
func (hc *HTTPConnector) URL(path string) string {
return fmt.Sprintf("http://%s:%s/api/v1%s", hc.printer.IP, HTTPPort, path)
}
func init() {
Connector.RegisterHandler(&HTTPConnector{})
}