Repository navigation
Expand file tree
/
Copy pathHomekitRoot.java
More file actions
288 lines (268 loc) · 10.3 KB
/
Copy pathHomekitRoot.java
File metadata and controls
288 lines (268 loc) · 10.3 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
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
package io.github.hapjava.server.impl;
import io.github.hapjava.accessories.Bridge;
import io.github.hapjava.accessories.HomekitAccessory;
import io.github.hapjava.server.HomekitAccessoryCategories;
import io.github.hapjava.server.HomekitAuthInfo;
import io.github.hapjava.server.HomekitWebHandler;
import io.github.hapjava.server.impl.connections.HomekitClientConnectionFactoryImpl;
import io.github.hapjava.server.impl.connections.SubscriptionManager;
import io.github.hapjava.server.impl.jmdns.JmdnsHomekitAdvertiser;
import java.io.IOException;
import java.net.InetAddress;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import javax.jmdns.JmDNS;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Provides advertising and handling for HomeKit accessories. This class handles the advertising of
* HomeKit accessories and contains one or more accessories. When implementing a bridge accessory,
* you will interact with this class directly. Instantiate it via {@link
* HomekitServer#createBridge(HomekitAuthInfo, String, String, String, String, String, String)}. For
* single accessories, this is composed by {@link HomekitStandaloneAccessoryServer}.
*
* @author Andy Lintner
*/
public class HomekitRoot {
private static final Logger logger = LoggerFactory.getLogger(HomekitRoot.class);
private static final int DEFAULT_ACCESSORY_CATEGORY = HomekitAccessoryCategories.OTHER;
private final JmdnsHomekitAdvertiser advertiser;
private final HomekitWebHandler webHandler;
private final HomekitAuthInfo authInfo;
private final String label;
private final int category;
private final HomekitRegistry registry;
private final SubscriptionManager subscriptions = new SubscriptionManager();
private boolean started = false;
private int configurationIndex = 1;
private int nestedBatches = 0;
private boolean madeChanges = false;
HomekitRoot(
String label, HomekitWebHandler webHandler, InetAddress host, HomekitAuthInfo authInfo)
throws IOException {
this(label, DEFAULT_ACCESSORY_CATEGORY, webHandler, authInfo, new JmdnsHomekitAdvertiser(host));
}
HomekitRoot(
String label,
int category,
HomekitWebHandler webHandler,
InetAddress host,
HomekitAuthInfo authInfo)
throws IOException {
this(label, category, webHandler, authInfo, new JmdnsHomekitAdvertiser(host));
}
HomekitRoot(
String label,
int category,
HomekitWebHandler webHandler,
HomekitAuthInfo authInfo,
JmdnsHomekitAdvertiser advertiser)
throws IOException {
this.advertiser = advertiser;
this.webHandler = webHandler;
this.authInfo = authInfo;
this.label = label;
this.category = category;
this.registry = new HomekitRegistry(label, subscriptions);
}
HomekitRoot(
String label,
int category,
HomekitWebHandler webHandler,
JmDNS jmdns,
HomekitAuthInfo authInfo)
throws IOException {
this(label, category, webHandler, authInfo, new JmdnsHomekitAdvertiser(jmdns));
}
HomekitRoot(String label, HomekitWebHandler webHandler, JmDNS jmdns, HomekitAuthInfo authInfo)
throws IOException {
this(
label, DEFAULT_ACCESSORY_CATEGORY, webHandler, authInfo, new JmdnsHomekitAdvertiser(jmdns));
}
/**
* Begin a batch update of accessories.
*
* <p>After calling this, you can call addAccessory() and removeAccessory() multiple times without
* causing HAP-Java to re-publishing the metadata to HomeKit. You'll need to call
* completeUpdateBatch in order to publish all accumulated changes.
*/
public synchronized void batchUpdate() {
if (this.nestedBatches == 0) madeChanges = false;
++this.nestedBatches;
}
/** Publish accumulated accessory changes since batchUpdate() was called. */
public synchronized void completeUpdateBatch() {
if (--this.nestedBatches == 0 && madeChanges) registry.reset();
}
/**
* Add an accessory to be handled and advertised by this root. When using this for a bridge, the
* ID of the accessory must be greater than 1, as that ID is reserved for the Bridge itself.
*
* @param accessory to advertise and handle.
*/
public void addAccessory(HomekitAccessory accessory) {
if (accessory.getId() <= 1 && !(accessory instanceof Bridge)) {
throw new IndexOutOfBoundsException(
"The ID of an accessory used in a bridge must be greater than 1");
}
addAccessorySkipRangeCheck(accessory);
}
/**
* Skips the range check. Used by {@link HomekitStandaloneAccessoryServer} as well as {@link
* #addAccessory(HomekitAccessory)};
*
* @param accessory to advertise and handle.
*/
void addAccessorySkipRangeCheck(HomekitAccessory accessory) {
this.registry.add(accessory);
if (logger.isTraceEnabled()) {
accessory.getName().thenAccept(name -> logger.trace("Added accessory {}", name));
}
madeChanges = true;
if (started && nestedBatches == 0) {
registry.reset();
}
}
/**
* Removes an accessory from being handled or advertised by this root.
*
* @param accessory accessory to cease advertising and handling
*/
public void removeAccessory(HomekitAccessory accessory) {
if (this.registry.remove(accessory)) {
if (logger.isTraceEnabled()) {
accessory.getName().thenAccept(name -> logger.trace("Removed accessory {}", name));
}
madeChanges = true;
if (started && nestedBatches == 0) {
registry.reset();
}
} else {
accessory.getName().thenAccept(name -> logger.warn("Could not remove accessory {}", name));
}
}
/**
* Starts advertising and handling the previously added HomeKit accessories. You should try to
* call this after you have used the {@link #addAccessory(HomekitAccessory)} method to add all the
* initial accessories you plan on advertising, as any later additions will cause the HomeKit
* clients to reconnect.
*
* <p>Startup failures are logged. Use {@link #startAsync()} to handle them in the caller. An
* advertising failure also stops the HTTP listener. Recovery is not automatic and requires a new
* server and root.
*/
public void start() {
startAsync()
.whenComplete(
(ignored, error) -> {
if (error != null) {
logger.error("Could not start HomeKit root {}", label, error);
}
});
}
/**
* Starts handling and advertising the previously added HomeKit accessories.
*
* <p>Startup failures, including exceptions thrown before the HTTP handler returns a future,
* complete the returned future exceptionally after cleanup. If advertising fails after the HTTP
* listener has started, the listener is stopped as well. Recovery requires a new server and root;
* the default HTTP handler cannot be restarted.
*
* <p>A start requested while this root is starting or running fails without stopping the existing
* startup or listener.
*
* @return a future that completes after the HTTP listener has started and the advertiser has
* registered the service, or exceptionally after a failed start has been cleaned up
*/
public CompletableFuture<Void> startAsync() {
if (started) {
CompletableFuture<Void> failure = new CompletableFuture<>();
failure.completeExceptionally(new IllegalStateException("HomeKit root is already started"));
return failure;
}
started = true;
CompletableFuture<Integer> portFuture;
try {
madeChanges = false;
registry.reset();
portFuture =
webHandler.start(
new HomekitClientConnectionFactoryImpl(
authInfo, registry, subscriptions, advertiser));
} catch (RuntimeException e) {
portFuture = new CompletableFuture<>();
portFuture.completeExceptionally(e);
}
return portFuture
.thenAccept(
port -> {
try {
refreshAuthInfo();
advertiser.advertise(
label,
category,
authInfo.getMac(),
port,
configurationIndex,
authInfo.getSetupId());
} catch (Exception e) {
throw new CompletionException(e);
}
})
.whenComplete(
(ignored, error) -> {
if (error != null) {
started = false;
stop();
}
});
}
/** Stops advertising and handling the HomeKit accessories. */
public void stop() {
advertiser.stop();
webHandler.stop();
subscriptions.removeAll();
started = false;
}
/**
* Refreshes auth info after it has been changed outside this library
*
* @throws IOException if there is an error in the underlying protocol, such as a TCP error
*/
public void refreshAuthInfo() throws IOException {
advertiser.setMac(authInfo.getMac());
advertiser.setDiscoverable(!authInfo.hasUser());
}
/**
* By default, most homekit requests require that the client be paired. Allowing unauthenticated
* requests can be useful for debugging, but should not be used in production.
*
* @param allow whether to allow unauthenticated requests
*/
public void allowUnauthenticatedRequests(boolean allow) {
registry.setAllowUnauthenticatedRequests(allow);
}
/**
* By default, the bridge advertises itself at revision 1. If you make changes to the accessories
* you're including in the bridge after your first call to {@link start()}, you should increment
* this number. The behavior of the client if the configuration index were to decrement is
* undefined, so this implementation will not manage the configuration index by automatically
* incrementing - preserving this state across invocations should be handled externally.
*
* @param revision an integer, greater than or equal to one, indicating the revision of the
* accessory information
* @throws IOException if there is an error in the underlying protocol, such as a TCP error
*/
public void setConfigurationIndex(int revision) throws IOException {
if (revision < 1) {
throw new IllegalArgumentException("revision must be greater than or equal to 1");
}
this.configurationIndex = revision;
if (this.started) {
advertiser.setConfigurationIndex(revision);
}
}
HomekitRegistry getRegistry() {
return registry;
}
}