-
Notifications
You must be signed in to change notification settings - Fork 13
/
connection.go
366 lines (299 loc) · 7.76 KB
/
connection.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
package gozwave
import (
"io"
"sync"
"time"
"github.com/pborman/uuid"
"github.com/sirupsen/logrus"
"github.com/stampzilla/gozwave/commands/reports"
"github.com/stampzilla/gozwave/interfaces"
"github.com/stampzilla/gozwave/serialapi"
)
type Connection struct {
readWriteCloser io.ReadWriteCloser
portOpener PortOpener
Connected bool
// Keep track of requests wating a response
inFlight map[string]*sendPackage
send chan *sendPackage
lastCommand string // Uuid of last sent command
lastResult chan byte
reportCallback func(byte, reports.Report)
sync.RWMutex
}
type sendPackage struct {
message []byte
uuid string
result byte // ACK, NAC, CAN
function byte
commandclass byte
expectedReport byte
node byte
timeout time.Duration
returnChan chan *serialapi.Message
sync.RWMutex
}
func (sp *sendPackage) Close() {
sp.RLock()
if sp.returnChan == nil {
sp.RUnlock()
return
}
sp.RUnlock()
sp.Lock()
close(sp.returnChan)
sp.returnChan = nil
sp.Unlock()
}
func (sp *sendPackage) IsOpen() bool {
sp.RLock()
defer sp.RUnlock()
return sp.returnChan != nil
}
func NewConnection() *Connection {
z := &Connection{
inFlight: make(map[string]*sendPackage),
send: make(chan *sendPackage),
lastResult: make(chan byte),
reportCallback: func(byte, reports.Report) {},
}
return z
}
func (conn *Connection) Write(msg interfaces.Encodable) error {
pkg := newSendPackage(msg.Encode())
conn.send <- pkg
return nil
}
func (conn *Connection) WriteWithTimeout(msg interfaces.Encodable, t time.Duration) (<-chan *serialapi.Message, error) {
pkg := newSendPackage(msg.Encode())
pkg.returnChan = make(chan *serialapi.Message)
pkg.timeout = t
conn.send <- pkg
return pkg.returnChan, nil
}
func (conn *Connection) WriteAndWaitForReport(msg interfaces.Encodable, t time.Duration, er byte) (<-chan reports.Report, error) {
pkg := newSendPackage(msg.Encode())
returnChan := make(chan reports.Report)
pkg.returnChan = make(chan *serialapi.Message)
pkg.timeout = t
pkg.expectedReport = er
conn.send <- pkg
go func() {
defer close(returnChan)
for msg := range pkg.returnChan {
if f, ok := msg.Data.(*serialapi.FuncApplicationCommandHandler); ok {
returnChan <- f.Report
return
}
logrus.Errorf("WriteAndWaitForReport: Received wrong type: %T", msg)
}
}()
return returnChan, nil
}
func (conn *Connection) Connect(connectChan chan error) (err error) {
defer func() {
logrus.Error("Disonnected")
conn.Connected = false
}()
conn.readWriteCloser, err = conn.portOpener.Open()
if err != nil {
select {
case connectChan <- err:
default:
}
return
}
go func() {
<-time.After(time.Millisecond * 200)
logrus.Debug("Connected")
select {
case connectChan <- nil:
default:
}
conn.Connected = true
}()
go conn.Writer()
return conn.Reader()
}
func (conn *Connection) Writer() {
for {
<-time.After(time.Millisecond * 50)
select {
case pkg := <-conn.send:
conn.Lock()
conn.lastCommand = ""
conn.inFlight[pkg.uuid] = pkg
conn.lastCommand = pkg.uuid
if pkg.timeout != 0 { // Only add the message to the inflight list if someone is waiting for an response
go conn.timeoutWorker(pkg)
}
abort := make(chan struct{})
go func() {
select {
case result := <-conn.lastResult:
pkg.result = result
case <-time.After(time.Second):
logrus.Warn("Send timeout")
// SEND TIMEOUT
}
close(abort)
}()
logrus.Debugf("Write: %x", pkg.message)
conn.readWriteCloser.Write(pkg.message)
conn.Unlock()
<-abort
conn.lastCommand = ""
}
}
}
func (conn *Connection) Reader() error {
incomming := make([]byte, 0)
age := time.Now()
for {
buf := make([]byte, 128)
n, err := conn.readWriteCloser.Read(buf)
if err != nil {
logrus.Error("Serial read failed: ", err)
conn.readWriteCloser.Close()
return err
}
//fmt.Println(hex.Dump(buf[:n]))
// If data in buffer is older than 40ms, clear buffer before appending data
if time.Now().Sub(age) > (time.Millisecond * 40) {
incomming = make([]byte, 0)
}
incomming = append(incomming, buf[:n]...)
age = time.Now()
for len(incomming) > 0 {
l, msg, err := serialapi.Decode(incomming)
if err != nil {
logrus.Errorf("%s - %d", err.Error(), l)
}
if l == 1 {
for index, c := range conn.inFlight {
conn.RLock()
if c.uuid == conn.lastCommand {
select {
case conn.lastResult <- incomming[0]:
case <-time.After(time.Millisecond * 50):
}
if msg.IsNAK() {
logrus.Warnf("Command failed: %s - %#v", c.uuid, c)
delete(conn.inFlight, index)
c.Close()
}
if msg.IsCAN() {
go func() {
<-time.After(time.Millisecond * 100)
conn.send <- c
}()
}
}
conn.RUnlock()
}
}
// The message is not compleatly read yet, wait for some more data
if l > len(incomming) {
break
}
if l == -1 { // Invalid checksum
incomming = incomming[1:] // Remove first char and try again
logrus.Debugf("Removing first byte, buffer len=%d", len(incomming))
continue
}
if l > 1 { // A message was received
conn.Lock()
for index, c := range conn.inFlight {
if !c.Match(incomming) {
logrus.Infof("Check match %#v", c)
continue
}
if c.IsOpen() {
select {
case c.returnChan <- msg: // Try to deliver message
case <-time.After(time.Second):
logrus.Warnf("Timeout writing response to requester: %#v", msg)
}
c.Close()
}
delete(conn.inFlight, index)
}
conn.Unlock()
}
if msg != nil {
if cmd, ok := msg.Data.(*serialapi.FuncApplicationCommandHandler); ok {
// Deliver the update to the parent
go conn.reportCallback(msg.NodeID, cmd.Report)
}
}
//logrus.Infof("Recived: %s", strings.TrimSpace(hex.Dump(incomming)))
logrus.Debugf("Recived: %x", incomming)
incomming = incomming[l:]
if l > 1 {
conn.readWriteCloser.Write([]byte{0x06}) // Send ACK to stick
}
}
}
}
func newSendPackage(data []byte) *sendPackage {
pkg := &sendPackage{
message: serialapi.CompileMessage(data),
uuid: uuid.New(),
}
if len(data) > 0 {
pkg.function = data[0]
}
if len(data) > 1 {
pkg.node = data[1]
}
if len(data) > 4 {
pkg.commandclass = data[3]
}
return pkg
}
func (c *sendPackage) Match(incomming []byte) bool {
//if len(incomming) > 3 && c.function != 0 && c.function != incomming[3] && !(c.function == serialapi.SendData && incomming[3] == 0x04) {
// SerialAPI specific
if !MatchByteAt(incomming, c.function, 3) && !(c.function == serialapi.SendData && MatchByteAt(incomming, serialapi.ApplicationCommandHandler, 3)) {
logrus.Warnf("Skipping pkg %s, function %x != %x", c.uuid, c.function, incomming[3])
return false
}
if c.function == serialapi.GetNodeProtocolInfo {
return true
}
// Z-wave specific
if !MatchByteAt(incomming, c.node, 5) {
logrus.Warnf("Skipping pkg %s, node %x != %x", c.uuid, c.node, incomming[5])
return false
}
if !MatchByteAt(incomming, c.commandclass, 7) {
logrus.Warnf("Skipping pkg %s, commandclass %x is not %x", c.uuid, c.commandclass, incomming[7])
return false
}
if !MatchByteAt(incomming, c.expectedReport, 8) {
logrus.Errorf("Skipping pkg %s, expectedReport %x is not %x", c.uuid, c.expectedReport, incomming[8])
return false
}
return true
}
func (conn *Connection) timeoutWorker(sp *sendPackage) {
<-time.After(sp.timeout)
conn.Lock()
for index, c := range conn.inFlight {
if index == sp.uuid {
logrus.Warnf("TIMEOUT: %s", sp.uuid)
delete(conn.inFlight, sp.uuid)
c.Close()
}
}
conn.Unlock()
}
func MatchByteAt(message []byte, b byte, position int) bool {
if b == 0 {
return true
}
if len(message) < position {
return false
}
return message[position] == b
}