-
Notifications
You must be signed in to change notification settings - Fork 0
/
backend.go
399 lines (333 loc) · 7.71 KB
/
backend.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
package mcumgrsvc
import (
"errors"
"fmt"
"strings"
"sync"
"time"
"gopkg.in/cheggaaa/pb.v1"
"mynewt.apache.org/newt/util"
"mynewt.apache.org/newtmgr/newtmgr/config"
"mynewt.apache.org/newtmgr/nmxact/nmcoap"
"mynewt.apache.org/newtmgr/nmxact/nmp"
"mynewt.apache.org/newtmgr/nmxact/nmserial"
"mynewt.apache.org/newtmgr/nmxact/sesn"
"mynewt.apache.org/newtmgr/nmxact/xact"
"mynewt.apache.org/newtmgr/nmxact/xport"
amqp "github.com/rabbitmq/amqp091-go"
)
// http://www.dest-unreach.org/socat/doc/socat-ttyovertcp.txt
// server (host)
// socat tcp-l:port,reuseaddr,fork file:/dev/tty,nonblock,raw,echo=0,crnl,waitlock=/var/run/tty
// clinet (svc)
// docker run -ti --rm --add-host host.docker.internal:host-gateway alpine:latest
// > socat pty,link=/dev/vmodem0,raw,echo=0,waitslave tcp:host.docker.internal:port
var (
ErrBackendPortOpen = errors.New("Backend: port open error")
ErrBackendPortClose = errors.New("Backend: port close error")
ErrBackendPortFlush = errors.New("Backend: port flush error")
ErrBackendPort = errors.New("Backend: invalid port setting")
ErrBackendImage = errors.New("Backend: invalid image")
ErrBackendReset = errors.New("Backend: failed to reset")
)
var globalSesn sesn.Sesn
var globalXport xport.Xport
var globalP *config.ConnProfile
// This keeps track of whether the global interface has been assigned. This
// is necessary to accommodate golang's nil-interface semantics.
var globalXportSet bool
var globalTxFilter nmcoap.TxMsgFilter
var globalRxFilter nmcoap.RxMsgFilter
type Backend interface {
Handler(port string, baud int, url string) error
UploadImage(f []byte) error
Reset()
GetStatus() (exec, result string)
}
type mcumgrBackend struct {
upld chan bool
rst chan bool
ping chan bool
img []byte
mtx sync.Mutex
sta struct {
exec string
result string
mtx sync.Mutex
}
}
func NewMCUMgrBackend() Backend {
return &mcumgrBackend{
upld: make(chan bool),
rst: make(chan bool),
ping: make(chan bool),
}
}
func (b *mcumgrBackend) Handler(port string, baud int, url string) error {
b.setStatus("closed", "none")
args := make([]string, 3)
args[0] = "acm"
args[1] = "type=serial"
args[2] = fmt.Sprintf("connstring=dev=%s,baud=%d,mtu=512", port, baud)
err := connProfileAddCmd(args)
if err != nil {
return err
}
b.mtx.Lock()
go func() {
b.msgQueueReceive(url)
}()
for {
select {
case <-b.upld:
b.setStatus("proceeding", "none")
err = imageUploadCmd(b.img)
b.setStatus("downloaded", "success")
case <-b.rst:
err = resetRunCmd([]string{})
if err != nil {
}
// Close opening serial port
time.Sleep(3 * time.Second)
cleanup()
b.mtx.Unlock()
case <-b.ping:
// Establish serial connection as soon as pinged by SLCAN service
b.mtx.Unlock()
default:
}
}
}
func (b *mcumgrBackend) UploadImage(f []byte) error {
if f == nil {
return ErrBackendImage
}
if b.mtx.TryLock() {
b.setStatus("scheduled", "none")
b.img = f
b.upld <- true
}
return nil
}
func (b *mcumgrBackend) Reset() {
b.rst <- true
return
}
func (b *mcumgrBackend) setStatus(exec, result string) {
b.sta.mtx.Lock()
b.sta.exec = exec
b.sta.result = result
defer b.sta.mtx.Unlock()
}
func (b *mcumgrBackend) GetStatus() (exec, result string) {
b.sta.mtx.Lock()
defer b.sta.mtx.Unlock()
return b.sta.exec, b.sta.result
}
func (b *mcumgrBackend) msgQueueReceive(url string) error {
conn, err := amqp.Dial(url)
if err != nil {
}
defer conn.Close()
ch, err := conn.Channel()
if err != nil {
}
defer ch.Close()
q, err := ch.QueueDeclare(
"handover", // name
false, // durable
false, // delete when unused
false, // exclusive
false, // no-wait
nil, // arguments
)
if err != nil {
}
msgs, err := ch.Consume(
q.Name, // queue
"", // consumer
true, // auto-ack
false, // exclusive
false, // no-local
false, // no-wait
nil, // args
)
if err != nil {
}
for {
for d := range msgs {
if d.Body != nil {
b.ping <- true
}
}
}
}
func connProfileAddCmd(args []string) error {
// Connection Profile name required
if len(args) == 0 {
return ErrBackendPort
}
name := args[0]
cp := config.NewConnProfile()
cp.Name = name
cp.Type = config.CONN_TYPE_NONE
for _, vdef := range args[1:] {
s := strings.SplitN(vdef, "=", 2)
switch s[0] {
case "type":
var err error
cp.Type, err = config.ConnTypeFromString(s[1])
if err != nil {
return ErrBackendPort
}
case "connstring":
cp.ConnString = s[1]
default:
return ErrBackendPort
}
}
// Check that a type is specified.
if cp.Type == config.CONN_TYPE_NONE {
return ErrBackendPort
}
globalP = cp
return nil
}
func imageUploadCmd(img []byte) error {
noerase := false
imageNum := 0
upgrade := false
maxWinSz := xact.IMAGE_UPLOAD_DEF_MAX_WS
s, err := getSesn()
if err != nil {
return ErrBackendImage
}
c := xact.NewImageUpgradeCmd()
var opt = sesn.TxOptions{
Timeout: time.Duration(5 * float64(time.Second)),
Tries: 2,
}
c.SetTxOptions(opt)
c.Data = img
if noerase == true {
c.NoErase = true
}
if imageNum < 0 {
return ErrBackendImage
}
c.ImageNum = imageNum
c.Upgrade = upgrade
c.ProgressBar = pb.StartNew(len(img))
c.ProgressBar.SetUnits(pb.U_BYTES)
c.ProgressBar.ShowSpeed = true
c.LastOff = 0
c.MaxWinSz = maxWinSz
c.ProgressCb = func(cmd *xact.ImageUploadCmd, rsp *nmp.ImageUploadRsp) {
if rsp.Off > c.LastOff {
c.ProgressBar.Add(int(rsp.Off - c.LastOff))
c.LastOff = rsp.Off
}
}
res, err := c.Run(s)
if err != nil {
return err
}
if res.Status() != 0 {
return ErrBackendImage
}
c.ProgressBar.Finish()
return nil
}
func resetRunCmd(args []string) error {
s, err := getSesn()
if err != nil {
return ErrBackendReset
}
c := xact.NewResetCmd()
var opt = sesn.TxOptions{
Timeout: time.Duration(5 * float64(time.Second)),
Tries: 2,
}
c.SetTxOptions(opt)
if _, err := c.Run(s); err != nil {
return ErrBackendReset
}
return nil
}
func getSesn() (sesn.Sesn, error) {
if globalSesn != nil {
return globalSesn, nil
}
var s sesn.Sesn
sc, err := buildSesnCfg()
if err != nil {
return nil, err
}
sc.TxFilter = globalTxFilter
sc.RxFilter = globalRxFilter
x, err := getXport()
if err != nil {
return nil, err
}
s, err = x.BuildSesn(sc)
if err != nil {
return nil, util.ChildNewtError(err)
}
globalSesn = s
if err := globalSesn.Open(); err != nil {
return nil, util.ChildNewtError(err)
}
return globalSesn, nil
}
func getXport() (xport.Xport, error) {
if globalXport != nil {
return globalXport, nil
}
cp := globalP
switch cp.Type {
case config.CONN_TYPE_SERIAL_PLAIN, config.CONN_TYPE_SERIAL_OIC:
sc, err := config.ParseSerialConnString(cp.ConnString)
if err != nil {
return nil, err
}
globalXport = nmserial.NewSerialXport(sc)
default:
return nil, util.FmtNewtError("Unknown connection type: %s (%d)",
config.ConnTypeToString(cp.Type), int(cp.Type))
}
globalXportSet = true
if err := globalXport.Start(); err != nil {
return nil, util.ChildNewtError(err)
}
return globalXport, nil
}
func buildSesnCfg() (sesn.SesnCfg, error) {
sc := sesn.NewSesnCfg()
cp := globalP
switch cp.Type {
case config.CONN_TYPE_SERIAL_PLAIN:
sc.MgmtProto = sesn.MGMT_PROTO_NMP
return sc, nil
default:
return sc, util.FmtNewtError("Unknown connection type: %s (%d)",
config.ConnTypeToString(cp.Type), int(cp.Type))
}
}
func stopXport() {
if globalXportSet {
// Don't attempt to close a serial transport. Attempting to close
// the serial port while a read is in progress (in MacOS) just
// blocks until the read completes. Instead, let the OS close the
// port on termination.
globalXport.Stop()
}
}
func closeSesn() {
if globalSesn != nil {
globalSesn.Close()
}
}
func cleanup() {
closeSesn()
stopXport()
}