-
Notifications
You must be signed in to change notification settings - Fork 0
/
uart_chain.go
89 lines (74 loc) · 1.7 KB
/
uart_chain.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
package main
import (
"encoding/binary"
"errors"
"fmt"
"time"
)
func (channel *SerialChannel) PerformJob(chipId int, data []byte, timeoutDuration int) ([]byte, error) {
// Job ID
channel.queryIdLock.Lock()
queryId := (channel.queryId + 1) % 256
channel.queryId = queryId
channel.queryIdLock.Unlock()
statusCheck := []byte{0x9a}
// Preflight check
// res, err := channel.Request(chipId, 0x0, statusCheck)
// if err != nil {
// return nil, err
// }
// if len(res.Data) == 0 {
// return nil, errors.New("invalid frame")
// }
// Package
job := []byte{0x8c}
tmp := make([]byte, 4)
binary.BigEndian.PutUint32(tmp, queryId)
job = append(job, tmp...)
job = append(job, data...)
err := channel.Write(chipId, 0x00, job)
if err != nil {
return nil, err
}
// Check job
start := time.Now()
for {
// Job timeout
if time.Since(start).Seconds() >= float64(timeoutDuration) {
return nil, errors.New("job timeout")
}
// Retry every 200 ms
time.Sleep(100 * time.Millisecond)
// Do check
res, err := channel.Request(chipId, 0x0, statusCheck)
if err != nil {
return nil, err
}
if len(res.Data) == 0 {
return nil, errors.New("invalid frame")
}
// No job
jobState := res.Data[0]
data := res.Data[1:]
if jobState == 0 {
return nil, errors.New("no job found")
}
// Parse package
receivedJobId := binary.BigEndian.Uint32(data)
data = data[4:]
// Check job id
if receivedJobId != queryId {
return nil, fmt.Errorf("job mismatch. expected: %d, got: %d", queryId, receivedJobId)
}
// Job not ready
if jobState == 1 {
continue
}
// Job ready
if jobState == 2 {
return data, nil
}
// Invalid state
return nil, errors.New("invalid job state")
}
}