-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathconnection.go
More file actions
120 lines (102 loc) · 2.04 KB
/
connection.go
File metadata and controls
120 lines (102 loc) · 2.04 KB
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
package miio
import (
"encoding/json"
"net"
)
// Base connection.
type connection struct {
conn *net.UDPConn
closeRead chan bool
closeWrite chan bool
inMessages chan []byte
outMessages chan []byte
DeviceMessages chan []byte
}
// Creates a new connection.
func newConnection(ip string, port int) (*connection, error) {
addr := &net.UDPAddr{
IP: net.ParseIP(ip),
Port: port,
}
con, err := net.DialUDP("udp4", nil, addr)
if err != nil {
return nil, err
}
c := &connection{
conn: con,
closeWrite: make(chan bool),
closeRead: make(chan bool),
inMessages: make(chan []byte, 100),
outMessages: make(chan []byte, 100),
DeviceMessages: make(chan []byte, 100),
}
c.start()
return c, nil
}
// Close closes the connection.
func (c *connection) Close() {
if nil != c.conn {
c.conn.Close()
}
c.closeRead <- true
c.closeWrite <- true
close(c.inMessages)
close(c.outMessages)
close(c.closeRead)
close(c.closeWrite)
close(c.DeviceMessages)
}
// Send sends a new message.
func (c *connection) Send(cmd *command) error {
out, err := json.Marshal(cmd)
if err != nil {
return err
}
c.outMessages <- out
return nil
}
// Starts the listeners.
func (c *connection) start() {
go c.in()
go c.out()
}
// Processes incoming messages.
func (c *connection) in() {
buf := make([]byte, 2048)
for {
select {
case <-c.closeRead:
return
default:
size, _, err := c.conn.ReadFromUDP(buf)
if err != nil {
LOGGER.Error("Error reading from UDP: %s", err.Error())
continue
}
if size > 0 {
LOGGER.Debug("Received device message: %s", string(buf[0:size]))
msg := make([]byte, size)
copy(msg, buf[0:size])
c.DeviceMessages <- msg
}
}
}
}
// Processes outgoing messages.
func (c *connection) out() {
for {
select {
case <-c.closeWrite:
return
case msg, ok := <-c.outMessages:
if !ok {
return
}
LOGGER.Debug("Sending msg %s", string(msg))
_, err := c.conn.Write(msg)
if err != nil {
LOGGER.Error("Error reading to UDP: %s", err.Error())
}
}
}
}