forked from apple/HomeKitADK
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Main.c
324 lines (266 loc) · 11.4 KB
/
Main.c
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
// Copyright (c) 2015-2019 The HomeKit ADK Contributors
//
// Licensed under the Apache License, Version 2.0 (the “License”);
// you may not use this file except in compliance with the License.
// See [CONTRIBUTORS.md] for the list of HomeKit ADK project authors.
#include "App.h"
#include "DB.h"
#include "HAP.h"
#include "HAPPlatform+Init.h"
#include "HAPPlatformAccessorySetup+Init.h"
#include "HAPPlatformBLEPeripheralManager+Init.h"
#include "HAPPlatformKeyValueStore+Init.h"
#include "HAPPlatformMFiHWAuth+Init.h"
#include "HAPPlatformMFiTokenAuth+Init.h"
#include "HAPPlatformRunLoop+Init.h"
#if IP
#include "HAPPlatformServiceDiscovery+Init.h"
#include "HAPPlatformTCPStreamManager+Init.h"
#endif
#include <signal.h>
static bool requestedFactoryReset = false;
static bool clearPairings = false;
#define PREFERRED_ADVERTISING_INTERVAL (HAPBLEAdvertisingIntervalCreateFromMilliseconds(417.5f))
/**
* Global platform objects.
* Only tracks objects that will be released in DeinitializePlatform.
*/
static struct {
HAPPlatformKeyValueStore keyValueStore;
HAPAccessoryServerOptions hapAccessoryServerOptions;
HAPPlatform hapPlatform;
HAPAccessoryServerCallbacks hapAccessoryServerCallbacks;
#if HAVE_NFC
HAPPlatformAccessorySetupNFC setupNFC;
#endif
#if IP
HAPPlatformTCPStreamManager tcpStreamManager;
#endif
HAPPlatformMFiHWAuth mfiHWAuth;
HAPPlatformMFiTokenAuth mfiTokenAuth;
} platform;
/**
* HomeKit accessory server that hosts the accessory.
*/
static HAPAccessoryServerRef accessoryServer;
void HandleUpdatedState(HAPAccessoryServerRef* _Nonnull server, void* _Nullable context);
/**
* Functions provided by App.c for each accessory application.
*/
extern void AppRelease(void);
extern void AppCreate(HAPAccessoryServerRef* server, HAPPlatformKeyValueStoreRef keyValueStore);
extern void AppInitialize(
HAPAccessoryServerOptions* hapAccessoryServerOptions,
HAPPlatform* hapPlatform,
HAPAccessoryServerCallbacks* hapAccessoryServerCallbacks);
extern void AppDeinitialize();
extern void AppAccessoryServerStart(void);
extern void AccessoryServerHandleUpdatedState(HAPAccessoryServerRef* server, void* _Nullable context);
extern const HAPAccessory* AppGetAccessoryInfo();
/**
* Initialize global platform objects.
*/
static void InitializePlatform() {
// Key-value store.
HAPPlatformKeyValueStoreCreate(
&platform.keyValueStore, &(const HAPPlatformKeyValueStoreOptions) { .rootDirectory = ".HomeKitStore" });
platform.hapPlatform.keyValueStore = &platform.keyValueStore;
// Accessory setup manager. Depends on key-value store.
static HAPPlatformAccessorySetup accessorySetup;
HAPPlatformAccessorySetupCreate(
&accessorySetup, &(const HAPPlatformAccessorySetupOptions) { .keyValueStore = &platform.keyValueStore });
platform.hapPlatform.accessorySetup = &accessorySetup;
#if IP
// TCP stream manager.
HAPPlatformTCPStreamManagerCreate(
&platform.tcpStreamManager,
&(const HAPPlatformTCPStreamManagerOptions) {
.interfaceName = NULL, // Listen on all available network interfaces.
.port = kHAPNetworkPort_Any, // Listen on unused port number from the ephemeral port range.
.maxConcurrentTCPStreams = kHAPIPSessionStorage_DefaultNumElements });
// Service discovery.
static HAPPlatformServiceDiscovery serviceDiscovery;
HAPPlatformServiceDiscoveryCreate(
&serviceDiscovery,
&(const HAPPlatformServiceDiscoveryOptions) {
0 /* Register services on all available network interfaces. */
});
platform.hapPlatform.ip.serviceDiscovery = &serviceDiscovery;
#endif
#if (BLE)
// BLE peripheral manager. Depends on key-value store.
static HAPPlatformBLEPeripheralManagerOptions blePMOptions = { 0 };
blePMOptions.keyValueStore = &platform.keyValueStore;
static HAPPlatformBLEPeripheralManager blePeripheralManager;
HAPPlatformBLEPeripheralManagerCreate(&blePeripheralManager, &blePMOptions);
platform.hapPlatform.ble.blePeripheralManager = &blePeripheralManager;
#endif
#if HAVE_MFI_HW_AUTH
// Apple Authentication Coprocessor provider.
HAPPlatformMFiHWAuthCreate(&platform.mfiHWAuth);
#endif
#if HAVE_MFI_HW_AUTH
platform.hapPlatform.authentication.mfiHWAuth = &platform.mfiHWAuth;
#endif
// Software Token provider. Depends on key-value store.
HAPPlatformMFiTokenAuthCreate(
&platform.mfiTokenAuth,
&(const HAPPlatformMFiTokenAuthOptions) { .keyValueStore = &platform.keyValueStore });
// Run loop.
HAPPlatformRunLoopCreate(&(const HAPPlatformRunLoopOptions) { .keyValueStore = &platform.keyValueStore });
platform.hapAccessoryServerOptions.maxPairings = kHAPPairingStorage_MinElements;
platform.hapPlatform.authentication.mfiTokenAuth =
HAPPlatformMFiTokenAuthIsProvisioned(&platform.mfiTokenAuth) ? &platform.mfiTokenAuth : NULL;
platform.hapAccessoryServerCallbacks.handleUpdatedState = HandleUpdatedState;
}
/**
* Deinitialize global platform objects.
*/
static void DeinitializePlatform() {
#if HAVE_MFI_HW_AUTH
// Apple Authentication Coprocessor provider.
HAPPlatformMFiHWAuthRelease(&platform.mfiHWAuth);
#endif
#if IP
// TCP stream manager.
HAPPlatformTCPStreamManagerRelease(&platform.tcpStreamManager);
#endif
AppDeinitialize();
// Run loop.
HAPPlatformRunLoopRelease();
}
/**
* Restore platform specific factory settings.
*/
void RestorePlatformFactorySettings(void) {
}
/**
* Either simply passes State handling to app, or processes Factory Reset
*/
void HandleUpdatedState(HAPAccessoryServerRef* _Nonnull server, void* _Nullable context) {
if (HAPAccessoryServerGetState(server) == kHAPAccessoryServerState_Idle && requestedFactoryReset) {
HAPPrecondition(server);
HAPError err;
HAPLogInfo(&kHAPLog_Default, "A factory reset has been requested.");
// Purge app state.
err = HAPPlatformKeyValueStorePurgeDomain(&platform.keyValueStore, ((HAPPlatformKeyValueStoreDomain) 0x00));
if (err) {
HAPAssert(err == kHAPError_Unknown);
HAPFatalError();
}
// Reset HomeKit state.
err = HAPRestoreFactorySettings(&platform.keyValueStore);
if (err) {
HAPAssert(err == kHAPError_Unknown);
HAPFatalError();
}
// Restore platform specific factory settings.
RestorePlatformFactorySettings();
// De-initialize App.
AppRelease();
requestedFactoryReset = false;
// Re-initialize App.
AppCreate(server, &platform.keyValueStore);
// Restart accessory server.
AppAccessoryServerStart();
return;
} else if (HAPAccessoryServerGetState(server) == kHAPAccessoryServerState_Idle && clearPairings) {
HAPError err;
err = HAPRemoveAllPairings(&platform.keyValueStore);
if (err) {
HAPAssert(err == kHAPError_Unknown);
HAPFatalError();
}
AppAccessoryServerStart();
} else {
AccessoryServerHandleUpdatedState(server, context);
}
}
#if IP
static void InitializeIP() {
// Prepare accessory server storage.
static HAPIPSession ipSessions[kHAPIPSessionStorage_DefaultNumElements];
static uint8_t ipInboundBuffers[HAPArrayCount(ipSessions)][kHAPIPSession_DefaultInboundBufferSize];
static uint8_t ipOutboundBuffers[HAPArrayCount(ipSessions)][kHAPIPSession_DefaultOutboundBufferSize];
static HAPIPEventNotificationRef ipEventNotifications[HAPArrayCount(ipSessions)][kAttributeCount];
for (size_t i = 0; i < HAPArrayCount(ipSessions); i++) {
ipSessions[i].inboundBuffer.bytes = ipInboundBuffers[i];
ipSessions[i].inboundBuffer.numBytes = sizeof ipInboundBuffers[i];
ipSessions[i].outboundBuffer.bytes = ipOutboundBuffers[i];
ipSessions[i].outboundBuffer.numBytes = sizeof ipOutboundBuffers[i];
ipSessions[i].eventNotifications = ipEventNotifications[i];
ipSessions[i].numEventNotifications = HAPArrayCount(ipEventNotifications[i]);
}
static HAPIPReadContextRef ipReadContexts[kAttributeCount];
static HAPIPWriteContextRef ipWriteContexts[kAttributeCount];
static uint8_t ipScratchBuffer[kHAPIPSession_DefaultScratchBufferSize];
static HAPIPAccessoryServerStorage ipAccessoryServerStorage = {
.sessions = ipSessions,
.numSessions = HAPArrayCount(ipSessions),
.readContexts = ipReadContexts,
.numReadContexts = HAPArrayCount(ipReadContexts),
.writeContexts = ipWriteContexts,
.numWriteContexts = HAPArrayCount(ipWriteContexts),
.scratchBuffer = { .bytes = ipScratchBuffer, .numBytes = sizeof ipScratchBuffer }
};
platform.hapAccessoryServerOptions.ip.transport = &kHAPAccessoryServerTransport_IP;
platform.hapAccessoryServerOptions.ip.accessoryServerStorage = &ipAccessoryServerStorage;
platform.hapPlatform.ip.tcpStreamManager = &platform.tcpStreamManager;
}
#endif
#if BLE
static void InitializeBLE() {
static HAPBLEGATTTableElementRef gattTableElements[kAttributeCount];
static HAPBLESessionCacheElementRef sessionCacheElements[kHAPBLESessionCache_MinElements];
static HAPSessionRef session;
static uint8_t procedureBytes[2048];
static HAPBLEProcedureRef procedures[1];
static HAPBLEAccessoryServerStorage bleAccessoryServerStorage = {
.gattTableElements = gattTableElements,
.numGATTTableElements = HAPArrayCount(gattTableElements),
.sessionCacheElements = sessionCacheElements,
.numSessionCacheElements = HAPArrayCount(sessionCacheElements),
.session = &session,
.procedures = procedures,
.numProcedures = HAPArrayCount(procedures),
.procedureBuffer = { .bytes = procedureBytes, .numBytes = sizeof procedureBytes }
};
platform.hapAccessoryServerOptions.ble.transport = &kHAPAccessoryServerTransport_BLE;
platform.hapAccessoryServerOptions.ble.accessoryServerStorage = &bleAccessoryServerStorage;
platform.hapAccessoryServerOptions.ble.preferredAdvertisingInterval = PREFERRED_ADVERTISING_INTERVAL;
platform.hapAccessoryServerOptions.ble.preferredNotificationDuration = kHAPBLENotification_MinDuration;
}
#endif
int main(int argc HAP_UNUSED, char* _Nullable argv[_Nullable] HAP_UNUSED) {
HAPAssert(HAPGetCompatibilityVersion() == HAP_COMPATIBILITY_VERSION);
// Initialize global platform objects.
InitializePlatform();
#if IP
InitializeIP();
#endif
#if BLE
InitializeBLE();
#endif
// Perform Application-specific initalizations such as setting up callbacks
// and configure any additional unique platform dependencies
AppInitialize(&platform.hapAccessoryServerOptions, &platform.hapPlatform, &platform.hapAccessoryServerCallbacks);
// Initialize accessory server.
HAPAccessoryServerCreate(
&accessoryServer,
&platform.hapAccessoryServerOptions,
&platform.hapPlatform,
&platform.hapAccessoryServerCallbacks,
/* context: */ NULL);
// Create app object.
AppCreate(&accessoryServer, &platform.keyValueStore);
// Start accessory server for App.
AppAccessoryServerStart();
// Run main loop until explicitly stopped.
HAPPlatformRunLoopRun();
// Run loop stopped explicitly by calling function HAPPlatformRunLoopStop.
// Cleanup.
AppRelease();
HAPAccessoryServerRelease(&accessoryServer);
DeinitializePlatform();
return 0;
}