-
Notifications
You must be signed in to change notification settings - Fork 0
/
osdp_messenger.go
80 lines (69 loc) · 2.27 KB
/
osdp_messenger.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
package osdp
import (
"io"
"time"
)
type OSDPMessengerEvent int
// TODO: propagate event with error codes
const (
OSDPDisconnected OSDPMessengerEvent = 0
OSDPConnected OSDPMessengerEvent = 1
OSDPReceiveTimeout OSDPMessengerEvent = 2
OSDPReceiveError OSDPMessengerEvent = 3
OSDPTransmitError OSDPMessengerEvent = 4
)
type OSDPMessenger struct {
connected bool
transceiver OSDPTransceiver
}
func NewOSDPMessenger(transceiver OSDPTransceiver, secure bool) *OSDPMessenger {
return &OSDPMessenger{connected: false, transceiver: transceiver}
}
func (osdpMessenger *OSDPMessenger) SendOSDPCommand(osdpMessage *OSDPMessage, timeout time.Duration) error {
// TODO Implement write timeout
osdpPacket, err := osdpMessage.PacketFromMessage()
if err != nil {
return err
}
return osdpMessenger.transceiver.Transmit(osdpPacket.ToBytes())
}
func (osdpMessenger *OSDPMessenger) ReceiveResponse(timeout time.Duration) (*OSDPMessage, error) {
payload := []byte{}
timeStart := time.Now()
for {
responseData, err := osdpMessenger.transceiver.Receive()
if err != nil {
if time.Since(timeStart) > timeout {
return nil, OSDPReceiveTimeoutError
}
}
payload = append(payload, responseData...)
osdpPacket, err := NewPacketFromBytes(payload)
if err == nil {
sequenceNumber := osdpPacket.msgCtrlInfo & 0x03
return &OSDPMessage{
MessageCode: OSDPCode(osdpPacket.msgCode),
PeripheralAddress: osdpPacket.peripheralAddress, MessageData: osdpPacket.msgData,
SequenceNumber: sequenceNumber,
MAC: osdpPacket.msgAuthenticationCode,
SecureBlockData: osdpPacket.securityBlockData,
SecureBlockType: osdpPacket.securityBlockType,
Secure: osdpPacket.secure,
}, nil
}
// Keep Receiving until we get a valid packet, timeout or error
if err != PacketIncompleteError && err != InvalidSOMError && err != io.EOF {
return nil, err
}
if time.Since(timeStart) > timeout {
return nil, OSDPReceiveTimeoutError
}
}
}
func (osdpMessenger *OSDPMessenger) SendAndReceive(osdpMessage *OSDPMessage, writeTimeout time.Duration, readTimeout time.Duration) (*OSDPMessage, error) {
err := osdpMessenger.SendOSDPCommand(osdpMessage, writeTimeout)
if err != nil {
return nil, err
}
return osdpMessenger.ReceiveResponse(readTimeout)
}