-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserial.go
107 lines (102 loc) · 2.53 KB
/
serial.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
package main
import (
"encoding/binary"
"encoding/json"
"io"
"strconv"
"github.com/dictor/hamstrone_ground/hamstertongue"
"github.com/sirupsen/logrus"
)
func listenPort(stream io.ReadWriteCloser, bufferSize int, result chan *hamsterTongueMessage) {
buffer := make([]byte, bufferSize)
var (
markerFound bool
appendCount byte
message *hamsterTongueMessage = &hamsterTongueMessage{Payload: []byte{}}
)
for {
readCount, err := stream.Read(buffer)
if readCount > 0 {
for _, b := range buffer[0:readCount] {
if markerFound {
appendCount++
switch appendCount {
case 1:
message.Length = b
case 2:
message.Verb = b
case 3:
message.Noun = b
default:
if appendCount <= message.Length {
message.Payload = append(message.Payload, b)
} else {
message.CRC = b
result <- message
message = &hamsterTongueMessage{Payload: []byte{}}
markerFound = false
appendCount = 0
}
}
} else {
if b == hamstertongue.MessageConstant["Structure"]["Marker"] {
markerFound = true
} else {
globalLogger.Debugf("unknown packet recieved : %d\n", b)
}
}
}
}
if err != nil {
globalLogger.WithField("error", err).Errorln("encounter error while read serial port")
return
}
}
}
func decodeMessage(msgchan chan *hamsterTongueMessage, sendchan chan []byte) {
defer ValueMutex.Unlock()
for {
select {
case msg := <-msgchan:
globalLogger.WithFields(logrus.Fields{
"length": msg.Length,
"verb": msg.Verb,
"noun": msg.Noun,
"payload": msg.Payload,
}).Debugf("serial message income")
switch msg.Verb {
case hamstertongue.MessageConstant["Verb"]["Heartbeat"]:
case hamstertongue.MessageConstant["Verb"]["Value"]:
ValueMutex.Lock()
for i := 0; i < 16; i++ {
Value[strconv.Itoa(i)] = binary.LittleEndian.Uint32(addArrayPadding(msg.Payload[i*4:i*4+3], 4))
}
ValueMutex.Unlock()
case hamstertongue.MessageConstant["Verb"]["Signal"]:
data, err := json.Marshal(generalMessage{
Type: "signal",
Data: []interface{}{msg, string(msg.Payload)},
})
if err != nil {
globalLogger.WithField("error", err).Errorln("error caused while making message")
continue
}
sendchan <- data
}
}
}
}
func addArrayPadding(b []byte, minimumLength int) []byte {
if len(b) >= minimumLength {
return b
}
nb := make([]byte, minimumLength)
for i := 0; i < minimumLength; i++ {
if i < len(b) {
nb[i] = b[i]
} else {
nb[i] = 0
}
}
return nb
}