forked from brutella/hc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathip_transport.go
231 lines (192 loc) · 5.85 KB
/
ip_transport.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
package hc
import (
"bytes"
"io/ioutil"
"net"
"sync"
"github.com/brutella/hc/accessory"
"github.com/brutella/hc/characteristic"
"github.com/brutella/hc/db"
"github.com/brutella/hc/event"
"github.com/brutella/hc/hap"
"github.com/brutella/hc/hap/http"
"github.com/brutella/hc/util"
"github.com/brutella/log"
"github.com/gosexy/to"
)
type ipTransport struct {
config *Config
context hap.Context
server http.Server
mutex *sync.Mutex
mdns *MDNSService
storage util.Storage
database db.Database
device hap.SecuredDevice
container *accessory.Container
// Used to communicate between different parts of the program (e.g. successful pairing with HomeKit)
emitter event.Emitter
}
// NewIPTransport creates a transport to provide accessories over IP.
//
// The IP transports stores the crypto keys inside a database, which
// is by default inside a folder at the current working directory.
// The folder is named exactly as the accessory name.
//
// The transports can contain more than one accessory. If this is the
// case, the first accessory acts as the HomeKit bridge.
//
// *Important:* Changing the name of the accessory, or letting multiple
// transports store the data inside the same database lead to
// unexpected behavior – don't do that.
//
// The transport is secured with an 8-digit pin, which must be entered
// by an iOS client to successfully pair with the accessory. If the
// provided transport config does not specify any pin, 00102003 is used.
func NewIPTransport(config Config, a *accessory.Accessory, as ...*accessory.Accessory) (Transport, error) {
// Find transport name which is visible in mDNS
name := a.Info.Name.GetValue()
if len(name) == 0 {
log.Fatal("Invalid empty name for first accessory")
}
cfg := defaultConfig(name)
cfg.merge(config)
storage, err := util.NewFileStorage(cfg.StoragePath)
if err != nil {
return nil, err
}
database := db.NewDatabaseWithStorage(storage)
hap_pin, err := NewPin(cfg.Pin)
if err != nil {
return nil, err
}
cfg.load(storage)
device, err := hap.NewSecuredDevice(cfg.id, hap_pin, database)
t := &ipTransport{
storage: storage,
database: database,
device: device,
config: cfg,
container: accessory.NewContainer(),
mutex: &sync.Mutex{},
context: hap.NewContextForSecuredDevice(device),
emitter: event.NewEmitter(),
}
t.addAccessory(a)
for _, a := range as {
t.addAccessory(a)
}
// Users can only pair discoverable accessories
if t.isPaired() {
cfg.discoverable = false
}
cfg.categoryId = int(t.container.AccessoryType())
cfg.updateConfigHash(t.container.ContentHash())
cfg.save(storage)
// Listen for events to update mDNS txt records
t.emitter.AddListener(t)
return t, err
}
func (t *ipTransport) Start() {
// Create server which handles incoming tcp connections
config := http.Config{
Port: t.config.Port,
Context: t.context,
Database: t.database,
Container: t.container,
Device: t.device,
Mutex: t.mutex,
Emitter: t.emitter,
}
s := http.NewServer(config)
t.server = s
// Publish server port which might be different then `t.config.Port`
t.config.servePort = int(to.Int64(s.Port()))
mdns := NewMDNSService(t.config)
t.mdns = mdns
mdns.Publish()
// Publish accessory ip
log.Println("[INFO] Accessory IP is", t.config.IP)
// Listen until server.Stop() is called
s.ListenAndServe()
}
// Stop stops the ip transport by unpublishing the mDNS service.
func (t *ipTransport) Stop() {
if t.mdns != nil {
t.mdns.Stop()
}
if t.server != nil {
t.server.Stop()
}
}
// isPaired returns true when the transport is already paired
func (t *ipTransport) isPaired() bool {
// If more than one entity is stored in the database, we are paired with a device.
// The transport itself is a device and is stored in the database, therefore
// we have to check for more than one entity.
if es, err := t.database.Entities(); err == nil && len(es) > 1 {
return true
}
return false
}
func (t *ipTransport) updateMDNSReachability() {
if mdns := t.mdns; mdns != nil {
t.config.discoverable = t.isPaired() == false
mdns.Update()
}
}
func (t *ipTransport) addAccessory(a *accessory.Accessory) {
t.container.AddAccessory(a)
for _, s := range a.Services {
for _, c := range s.Characteristics {
// When a characteristic value changes and events are enabled for this characteristic
// all listeners are notified. Since we don't track which client is interested in
// which characteristic change event, we send them to all active connections.
onConnChange := func(conn net.Conn, c *characteristic.Characteristic, new, old interface{}) {
if c.Events == true {
t.notifyListener(a, c, conn)
}
}
c.OnValueUpdateFromConn(onConnChange)
onChange := func(c *characteristic.Characteristic, new, old interface{}) {
if c.Events == true {
t.notifyListener(a, c, nil)
}
}
c.OnValueUpdate(onChange)
}
}
}
func (t *ipTransport) notifyListener(a *accessory.Accessory, c *characteristic.Characteristic, except net.Conn) {
conns := t.context.ActiveConnections()
for _, conn := range conns {
if conn == except {
continue
}
resp, err := hap.NewNotification(a, c)
if err != nil {
log.Fatal(err)
}
// Write response into buffer to replace HTTP protocol
// specifier with EVENT as required by HAP
var buffer = new(bytes.Buffer)
resp.Write(buffer)
bytes, err := ioutil.ReadAll(buffer)
bytes = hap.FixProtocolSpecifier(bytes)
log.Printf("[VERB] %s <- %s", conn.RemoteAddr(), string(bytes))
conn.Write(bytes)
}
}
// Handles event which are sent when pairing with a device is added or removed
func (t *ipTransport) Handle(ev interface{}) {
switch ev.(type) {
case event.DevicePaired:
log.Printf("[INFO] Event: paired with device")
t.updateMDNSReachability()
case event.DeviceUnpaired:
log.Printf("[INFO] Event: unpaired with device")
t.updateMDNSReachability()
default:
break
}
}