-
Notifications
You must be signed in to change notification settings - Fork 0
/
uart.go
375 lines (337 loc) · 8.38 KB
/
uart.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
package main
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"io"
"sync"
"time"
"github.com/jacobsa/go-serial/serial"
"github.com/sigurn/crc16"
)
type SerialChannel struct {
Tag string
queryIdLock sync.Mutex
queryId uint32
Closed bool
RW io.ReadWriteCloser
requestLock sync.Mutex
writeLock sync.Mutex
readLock sync.Mutex
callbacks map[uint32]chan []byte
}
type SerialFrame struct {
ChipID uint8
Data []byte
}
func SerialOpen(path string, speed uint) (*SerialChannel, error) {
res, err := serial.Open(serial.OpenOptions{
PortName: path,
BaudRate: speed,
DataBits: 8,
StopBits: 1,
InterCharacterTimeout: 100,
MinimumReadSize: 0,
RTSCTSFlowControl: false,
})
if err != nil {
return nil, err
} else {
return &SerialChannel{RW: res, Closed: false, queryId: 0, callbacks: make(map[uint32]chan []byte), Tag: path}, nil
}
}
func (channel *SerialChannel) Write(chipId int, reqType uint8, data []byte) error {
channel.writeLock.Lock()
defer channel.writeLock.Unlock()
return channel.doWrite(chipId, reqType, data)
}
func (channel *SerialChannel) Read() (*SerialFrame, error) {
timer := time.NewTimer(1000 * time.Millisecond)
doneError := make(chan error, 1)
doneFrame := make(chan *SerialFrame, 1)
go func() {
channel.readLock.Lock()
defer channel.readLock.Unlock()
r, err := channel.doRead()
if err != nil {
doneError <- err
} else {
doneFrame <- r
}
}()
select {
case err := <-doneError:
return nil, err
case p := <-doneFrame:
return p, nil
case <-timer.C:
return nil, errors.New("Request timeout")
}
}
func (channel *SerialChannel) Request(chipId int, reqType uint8, data []byte) (*SerialFrame, error) {
channel.requestLock.Lock()
defer channel.requestLock.Unlock()
// log.Printf("Request")
err := channel.Write(chipId, reqType, data)
if err != nil {
return nil, err
}
// log.Printf("Request read")
res, err := channel.Read()
// log.Printf("Request end")
return res, err
}
func (channel *SerialChannel) Close() {
// Write lock
channel.writeLock.Lock()
defer channel.writeLock.Unlock()
// Closing
channel.Closed = true
channel.RW.Close()
}
//////////////////////////////////////////////////////////////////////////////////////////
// SYSMON
//////////////////////////////////////////////////////////////////////////////////////////
func (channel *SerialChannel) GetTemperature(chipId int) (float32, error) {
resp, err := channel.Request(chipId, 0x00, []byte{0x7c, 0x0e, 0x00, 0x00, 0x00})
if err != nil {
return 0, err
}
x := float32(binary.BigEndian.Uint16(resp.Data[1:]))
temp := x*502.9098/65536 - 273.819
return temp, nil
}
//////////////////////////////////////////////////////////////////////////////////////////
// PLL
//////////////////////////////////////////////////////////////////////////////////////////
const (
PllWrite = 0x0A
PllRead = 0x0B
PllLock = 0x0C
)
func (channel *SerialChannel) PllGet(chipId int, addr uint8) (uint16, error) {
resp, err := channel.Request(chipId, 0xA2, []byte{PllRead, addr})
if err != nil {
return 0, err
}
value := binary.BigEndian.Uint16(resp.Data)
return value, nil
}
func (channel *SerialChannel) PllSet(chipId int, addr uint8, value uint16) error {
req := []byte{PllWrite, addr, 0, 0}
binary.BigEndian.PutUint16(req[2:], value)
_, err := channel.Request(chipId, 0xA2, req)
if err != nil {
return err
}
return nil
}
func (channel *SerialChannel) PllSetMask(chipId int, cv PllConstValue) error {
oldValue, err := channel.PllGet(chipId, cv.Const.Addr)
if err != nil {
return err
}
newValue := (oldValue & cv.Const.Mask) | (cv.Value & ^cv.Const.Mask)
if err = channel.PllSet(chipId, cv.Const.Addr, newValue); err != nil {
return err
}
return nil
}
func (channel *SerialChannel) PllApply(chipId int, cvs []PllConstValue, prop *XilinxProperty) error {
power, err := channel.PllGet(chipId, prop.PLLPowerAddr)
if err != nil {
return err
}
if err = channel.PllSet(chipId, prop.PLLPowerAddr, 0xFFFF); err != nil {
return err
}
for _, cv := range cvs {
if err = channel.PllSetMask(chipId, cv); err != nil {
return err
}
}
if err = channel.PllSet(chipId, prop.PLLPowerAddr, power); err != nil {
return err
}
return nil
}
func (channel *SerialChannel) SetFrequency(chipId int, frequency int) error {
setup, found := Xilinx7Series.PLLFreq[frequency]
if !found {
return nil
}
if err := channel.PllApply(chipId, setup, &Xilinx7Series); err != nil {
return err
}
return nil
}
//////////////////////////////////////////////////////////////////////////////////////////
// Implementation
//////////////////////////////////////////////////////////////////////////////////////////
func (channel *SerialChannel) doWrite(chipId int, reqType uint8, data []byte) error {
packed := pack(uint8(chipId), reqType, data)
// log.Printf("[%v] Write: %x: %d|%d|%x", channel.Tag, packed, chipId, reqType, data)
n, err := channel.RW.Write(packed)
if err != nil {
return err
}
if n != len(packed) {
return errors.New("UART wirte issue")
}
return nil
}
func (channel *SerialChannel) doRead() (*SerialFrame, error) {
var buffer bytes.Buffer
var buffer2 bytes.Buffer
b := make([]byte, 1)
for {
n, err := channel.RW.Read(b)
switch err {
case io.EOF:
continue
case nil:
default:
return nil, err
}
if n != 1 {
continue
}
// log.Printf("Received: %02x", b[0])
buffer2.WriteByte(b[0])
switch b[0] {
case STX:
buffer.Reset()
case ETX:
// log.Printf("Frame (0): %02x", buffer.Bytes())
// log.Printf("Frame (r): %02x", buffer2.Bytes())
frm, err := unserialize(buffer.Bytes())
if err != nil {
return nil, err
}
// log.Printf("Frame: %02x", frm.Data)
return frm, nil
case ESC:
for {
n, err := channel.RW.Read(b)
switch err {
case io.EOF:
continue
case nil:
default:
return nil, err
}
if n != 1 {
continue
}
buffer2.WriteByte(b[0])
break
}
// log.Printf("Received: %02x", b[0])
fallthrough
default:
buffer.WriteByte(b[0])
}
}
}
const (
STX byte = 0x02
ETX byte = 0x03
ESC byte = 0x1B
PacketHeaderLength = 5
PacketChecksumLength = 2
)
func escape(data []byte) []byte {
var buf bytes.Buffer
for _, b := range data {
switch b {
case STX:
fallthrough
case ESC:
fallthrough
case ETX:
buf.WriteByte(ESC)
fallthrough
default:
buf.WriteByte(b)
}
}
return buf.Bytes()
}
func calcChecksum(data []byte) []byte {
arr := make([]byte, 2)
table := crc16.MakeTable(crc16.CRC16_ARC)
checksum := crc16.Checksum(data, table)
binary.BigEndian.PutUint16(arr, checksum)
return arr
}
type packetHeader struct {
Version uint8
Type uint8
ID uint8
Length uint16
}
func pack(id uint8, requestType uint8, data []byte) []byte {
// Frame
header := packetHeader{
Version: 0,
Type: requestType,
ID: id,
Length: uint16(len(data)),
}
var payload bytes.Buffer
binary.Write(&payload, binary.BigEndian, &header)
payload.Write(data)
payload.Write(calcChecksum(payload.Bytes()))
body := payload.Bytes()
body = escape(body)
// Transfer package
var res bytes.Buffer
res.WriteByte(STX)
res.Write(body)
res.WriteByte(ETX)
return res.Bytes()
}
func parsePacket(p []byte) (*SerialFrame, error) {
// check length
if len(p) < PacketHeaderLength {
return nil, fmt.Errorf("invalid parsing: %x", p)
}
// parse header
hdr := packetHeader{}
headerBuf := bytes.NewBuffer(p[:PacketHeaderLength])
binary.Read(headerBuf, binary.BigEndian, &hdr)
data := p[PacketHeaderLength:]
if len(data) != int(hdr.Length) {
return nil, fmt.Errorf("invalid parsing: %x", p)
}
res := SerialFrame{ChipID: hdr.ID, Data: data}
return &res, nil
}
func unserialize(p []byte) (*SerialFrame, error) {
// check crc first
payload, err := popCRC(p)
if err != nil {
return nil, err
}
// parse header + check data
res, err := parsePacket(payload)
if err != nil {
return nil, err
}
return res, nil
}
func popCRC(p []byte) ([]byte, error) {
// check length
if len(p) < PacketChecksumLength {
return nil, fmt.Errorf("invalid packet: %x", p)
}
pcrc := len(p) - PacketChecksumLength
payload := p[:pcrc]
checksum := p[pcrc:]
// checksum
if !bytes.Equal(checksum, calcChecksum(payload)) {
return nil, fmt.Errorf("checksum failed expected %x, got %x. data: %x", calcChecksum(payload), checksum, p)
}
return payload, nil
}