forked from project-chip/connectedhomeip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMTRDeviceOverXPC.mm
494 lines (440 loc) · 24.9 KB
/
MTRDeviceOverXPC.mm
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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
/**
*
* Copyright (c) 2022 Project CHIP Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#import "MTRDeviceOverXPC.h"
#import "MTRCluster.h"
#import "MTRClusterStateCacheContainer+XPC.h"
#import "MTRDeviceController+XPC.h"
#import "MTRDeviceControllerOverXPC_Internal.h"
#import "MTRDeviceControllerXPCConnection.h"
#import "MTRError.h"
#import "MTRLogging_Internal.h"
NS_ASSUME_NONNULL_BEGIN
typedef void (^MTRFetchProxyHandleCompletion)(MTRDeviceControllerXPCProxyHandle * _Nullable handle, NSError * _Nullable error);
@interface MTRDeviceOverXPC ()
@property (nonatomic, strong, readonly, nullable) id<NSCopying> controllerID;
@property (nonatomic, strong, readonly) MTRDeviceControllerOverXPC * controller;
@property (nonatomic, readonly) NSNumber * nodeID;
@property (nonatomic, strong, readonly) MTRDeviceControllerXPCConnection * xpcConnection;
- (void)fetchProxyHandleWithQueue:(dispatch_queue_t)queue completion:(MTRFetchProxyHandleCompletion)completion;
@end
@implementation MTRDeviceOverXPC
- (instancetype)initWithControllerOverXPC:(MTRDeviceControllerOverXPC *)controllerOverXPC
deviceID:(NSNumber *)deviceID
xpcConnection:(MTRDeviceControllerXPCConnection *)xpcConnection
{
_controllerID = controllerOverXPC.controllerXPCID;
_controller = controllerOverXPC;
_nodeID = deviceID;
_xpcConnection = xpcConnection;
return self;
}
- (void)subscribeWithQueue:(dispatch_queue_t)queue
params:(MTRSubscribeParams *)params
clusterStateCacheContainer:(MTRClusterStateCacheContainer * _Nullable)clusterStateCacheContainer
attributeReportHandler:(void (^_Nullable)(NSArray * value))attributeReportHandler
eventReportHandler:(void (^_Nullable)(NSArray * value))eventReportHandler
errorHandler:(void (^)(NSError * error))errorHandler
subscriptionEstablished:(void (^_Nullable)(void))subscriptionEstablishedHandler
resubscriptionScheduled:(MTRDeviceResubscriptionScheduledHandler _Nullable)resubscriptionScheduledHandler
{
MTR_LOG_DEBUG("Subscribing all attributes... Note that attributeReportHandler, eventReportHandler, and resubscriptionScheduled "
"are not supported.");
__auto_type workBlock = ^(MTRDeviceControllerXPCProxyHandle * _Nullable handle, NSError * _Nullable error) {
if (error != nil) {
errorHandler(error);
return;
}
if (clusterStateCacheContainer) {
[clusterStateCacheContainer setXPCConnection:self->_xpcConnection controllerID:self.controllerID deviceID:self.nodeID];
}
[handle.proxy subscribeWithController:self.controllerID
nodeId:self.nodeID.unsignedLongLongValue
minInterval:params.minInterval
maxInterval:params.maxInterval
params:[MTRDeviceController encodeXPCSubscribeParams:params]
shouldCache:(clusterStateCacheContainer != nil)
completion:^(NSError * _Nullable error) {
dispatch_async(queue, ^{
if (error) {
errorHandler(error);
} else {
subscriptionEstablishedHandler();
}
});
__auto_type handleRetainer = handle;
(void) handleRetainer;
}];
};
[self fetchProxyHandleWithQueue:queue completion:workBlock];
}
- (void)readAttributesWithEndpointID:(NSNumber * _Nullable)endpointID
clusterID:(NSNumber * _Nullable)clusterID
attributeID:(NSNumber * _Nullable)attributeID
params:(MTRReadParams * _Nullable)params
queue:(dispatch_queue_t)queue
completion:(MTRDeviceResponseHandler)completion
{
MTR_LOG_DEBUG("Reading attribute ...");
__auto_type workBlock = ^(MTRDeviceControllerXPCProxyHandle * _Nullable handle, NSError * _Nullable error) {
if (error != nil) {
completion(nil, error);
return;
}
[handle.proxy readAttributeWithController:self.controllerID
nodeId:self.nodeID.unsignedLongLongValue
endpointId:endpointID
clusterId:clusterID
attributeId:attributeID
params:[MTRDeviceController encodeXPCReadParams:params]
completion:^(id _Nullable values, NSError * _Nullable error) {
dispatch_async(queue, ^{
MTR_LOG_DEBUG("Attribute read");
completion([MTRDeviceController decodeXPCResponseValues:values], error);
// The following captures the proxy handle in the closure so that the
// handle won't be released prior to block call.
__auto_type handleRetainer = handle;
(void) handleRetainer;
});
}];
};
[self fetchProxyHandleWithQueue:queue completion:workBlock];
}
- (void)readAttributePaths:(NSArray<MTRAttributeRequestPath *> * _Nullable)attributePaths
eventPaths:(NSArray<MTREventRequestPath *> * _Nullable)eventPaths
params:(MTRReadParams * _Nullable)params
queue:(dispatch_queue_t)queue
completion:(MTRDeviceResponseHandler)completion
{
[self readAttributePaths:attributePaths eventPaths:eventPaths params:params includeDataVersion:NO queue:queue completion:completion];
}
- (void)readAttributePaths:(NSArray<MTRAttributeRequestPath *> * _Nullable)attributePaths
eventPaths:(NSArray<MTREventRequestPath *> * _Nullable)eventPaths
params:(MTRReadParams * _Nullable)params
includeDataVersion:(BOOL)includeDataVersion
queue:(dispatch_queue_t)queue
completion:(MTRDeviceResponseHandler)completion
{
if (attributePaths == nil || eventPaths != nil) {
MTR_LOG_ERROR("MTRBaseDevice doesn't support reading event paths over XPC");
dispatch_async(queue, ^{
completion(nil, [NSError errorWithDomain:MTRErrorDomain code:MTRErrorCodeInvalidState userInfo:nil]);
});
return;
}
// TODO: Have a better XPC setup for the multiple-paths case, instead of
// just converting it into a bunch of separate reads.
auto expectedResponses = attributePaths.count;
__block decltype(expectedResponses) responses = 0;
NSMutableArray<NSDictionary<NSString *, id> *> * seenValues = [[NSMutableArray alloc] init];
__block BOOL dispatched = NO;
for (MTRAttributeRequestPath * path in attributePaths) {
__auto_type singleAttributeResponseHandler = ^(NSArray<NSDictionary<NSString *, id> *> * _Nullable values, NSError * _Nullable error) {
if (dispatched) {
// We hit an error earlier or something.
return;
}
if (error != nil) {
dispatched = YES;
completion(nil, error);
return;
}
[seenValues addObjectsFromArray:values];
++responses;
if (responses == expectedResponses) {
dispatched = YES;
completion([seenValues copy], nil);
};
};
[self readAttributesWithEndpointID:path.endpoint
clusterID:path.cluster
attributeID:path.attribute
params:params
queue:queue
completion:singleAttributeResponseHandler];
}
}
- (void)_writeAttributeWithEndpointID:(NSNumber *)endpointID
clusterID:(NSNumber *)clusterID
attributeID:(NSNumber *)attributeID
value:(id)value
timedWriteTimeout:(NSNumber * _Nullable)timeoutMs
queue:(dispatch_queue_t)queue
completion:(MTRDeviceResponseHandler)completion
{
MTR_LOG_DEBUG("Writing attribute ...");
__auto_type workBlock = ^(MTRDeviceControllerXPCProxyHandle * _Nullable handle, NSError * _Nullable error) {
if (error != nil) {
completion(nil, error);
return;
}
[handle.proxy writeAttributeWithController:self.controllerID
nodeId:self.nodeID.unsignedLongLongValue
endpointId:endpointID
clusterId:clusterID
attributeId:attributeID
value:value
timedWriteTimeout:timeoutMs
completion:^(id _Nullable values, NSError * _Nullable error) {
dispatch_async(queue, ^{
MTR_LOG_DEBUG("Attribute written");
completion([MTRDeviceController decodeXPCResponseValues:values], error);
// The following captures the proxy handle in the closure so that the
// handle won't be released prior to block call.
__auto_type handleRetainer = handle;
(void) handleRetainer;
});
}];
};
[self fetchProxyHandleWithQueue:queue completion:workBlock];
}
- (void)invokeCommandWithEndpointID:(NSNumber *)endpointID
clusterID:(NSNumber *)clusterID
commandID:(NSNumber *)commandID
commandFields:(id)commandFields
timedInvokeTimeout:(NSNumber * _Nullable)timeoutMs
queue:(dispatch_queue_t)queue
completion:(MTRDeviceResponseHandler)completion
{
MTR_LOG_DEBUG("Invoking command ...");
__auto_type workBlock = ^(MTRDeviceControllerXPCProxyHandle * _Nullable handle, NSError * _Nullable error) {
if (error != nil) {
completion(nil, error);
return;
}
[handle.proxy invokeCommandWithController:self.controllerID
nodeId:self.nodeID.unsignedLongLongValue
endpointId:endpointID
clusterId:clusterID
commandId:commandID
fields:commandFields
timedInvokeTimeout:timeoutMs
completion:^(id _Nullable values, NSError * _Nullable error) {
dispatch_async(queue, ^{
MTR_LOG_DEBUG("Command invoked");
completion([MTRDeviceController decodeXPCResponseValues:values], error);
// The following captures the proxy handle in the closure so that the
// handle won't be released prior to block call.
__auto_type handleRetainer = handle;
(void) handleRetainer;
});
}];
};
[self fetchProxyHandleWithQueue:queue completion:workBlock];
}
- (void)_invokeCommandWithEndpointID:(NSNumber *)endpointID
clusterID:(NSNumber *)clusterID
commandID:(NSNumber *)commandID
commandFields:(id)commandFields
timedInvokeTimeout:(NSNumber * _Nullable)timeoutMs
serverSideProcessingTimeout:(NSNumber * _Nullable)serverSideProcessingTimeout
logCall:(BOOL)logCall
queue:(dispatch_queue_t)queue
completion:(MTRDeviceResponseHandler)completion
{
if (serverSideProcessingTimeout != nil) {
MTR_LOG_ERROR("MTRBaseDevice doesn't support invokes with a server-side processing timeout over XPC");
dispatch_async(queue, ^{
completion(nil, [NSError errorWithDomain:MTRErrorDomain code:MTRErrorCodeInvalidState userInfo:nil]);
});
return;
}
[self invokeCommandWithEndpointID:endpointID
clusterID:clusterID
commandID:commandID
commandFields:commandFields
timedInvokeTimeout:timeoutMs
queue:queue
completion:completion];
}
- (void)subscribeToAttributesWithEndpointID:(NSNumber * _Nullable)endpointID
clusterID:(NSNumber * _Nullable)clusterID
attributeID:(NSNumber * _Nullable)attributeID
params:(MTRSubscribeParams * _Nullable)params
queue:(dispatch_queue_t)queue
reportHandler:(MTRDeviceResponseHandler)reportHandler
subscriptionEstablished:(void (^_Nullable)(void))subscriptionEstablishedHandler
{
MTR_LOG_DEBUG("Subscribing attribute ...");
__auto_type workBlock = ^(MTRDeviceControllerXPCProxyHandle * _Nullable handle, NSError * _Nullable error) {
MTR_LOG_DEBUG("Setup report handler");
if (error != nil) {
subscriptionEstablishedHandler();
reportHandler(nil, error);
return;
}
[self.xpcConnection
registerReportHandlerWithController:self.controllerID
nodeID:self.nodeID
handler:^(id _Nullable values, NSError * _Nullable error) {
if (values && ![values isKindOfClass:[NSArray class]]) {
MTR_LOG_ERROR("Unsupported report format");
return;
}
if (!values) {
MTR_LOG_DEBUG("Error report received");
dispatch_async(queue, ^{
reportHandler(values, error);
});
return;
}
__auto_type decodedValues = [MTRDeviceController decodeXPCResponseValues:values];
NSMutableArray<NSDictionary<NSString *, id> *> * filteredValues =
[NSMutableArray arrayWithCapacity:[decodedValues count]];
for (NSDictionary<NSString *, id> * decodedValue in decodedValues) {
MTRAttributePath * attributePath = decodedValue[MTRAttributePathKey];
if ((endpointID == nil || [attributePath.endpoint isEqualToNumber:endpointID])
&& (clusterID == nil || [attributePath.cluster isEqualToNumber:clusterID])
&& (attributeID == nil ||
[attributePath.attribute isEqualToNumber:attributeID])) {
[filteredValues addObject:decodedValue];
}
}
if ([filteredValues count] > 0) {
MTR_LOG_DEBUG("Report received");
dispatch_async(queue, ^{
reportHandler(filteredValues, error);
});
}
}];
[handle.proxy subscribeAttributeWithController:self.controllerID
nodeId:self.nodeID.unsignedLongLongValue
endpointId:endpointID
clusterId:clusterID
attributeId:attributeID
minInterval:params.minInterval
maxInterval:params.maxInterval
params:[MTRDeviceController encodeXPCSubscribeParams:params]
establishedHandler:^{
[self.xpcConnection callSubscriptionEstablishedHandler:^{
dispatch_async(queue, ^{
MTR_LOG_DEBUG("Subscription established");
subscriptionEstablishedHandler();
// The following captures the proxy handle in the closure so that the handle
// won't be released prior to block call.
__auto_type handleRetainer = handle;
(void) handleRetainer;
});
}];
}];
};
[self fetchProxyHandleWithQueue:queue completion:workBlock];
}
- (void)deregisterReportHandlersWithQueue:(dispatch_queue_t)queue completion:(void (^)(void))completion
{
MTR_LOG_DEBUG("Deregistering report handlers");
__auto_type workBlock = ^{
[self->_xpcConnection deregisterReportHandlersWithController:self.controllerID
nodeID:self.nodeID
completion:^{
dispatch_async(queue, completion);
}];
};
if (self.controllerID != nil) {
workBlock();
} else {
[self.controller fetchControllerIdWithQueue:queue
completion:^(id _Nullable controllerID,
MTRDeviceControllerXPCProxyHandle * _Nullable handle, NSError * _Nullable error) {
if (error != nil) {
// We're already running on the right queue.
completion();
return;
}
self->_controllerID = controllerID;
workBlock();
}];
}
}
- (void)openCommissioningWindowWithSetupPasscode:(NSNumber *)setupPasscode
discriminator:(NSNumber *)discriminator
duration:(NSNumber *)duration
queue:(dispatch_queue_t)queue
completion:(MTRDeviceOpenCommissioningWindowHandler)completion
{
MTR_LOG_ERROR("MTRBaseDevice doesn't support openCommissioningWindowWithSetupPasscode over XPC");
dispatch_async(queue, ^{
completion(nil, [NSError errorWithDomain:MTRErrorDomain code:MTRErrorCodeInvalidState userInfo:nil]);
});
}
- (void)openCommissioningWindowWithDiscriminator:(NSNumber *)discriminator
duration:(NSNumber *)duration
queue:(dispatch_queue_t)queue
completion:(MTRDeviceOpenCommissioningWindowHandler)completion
{
MTR_LOG_ERROR("MTRBaseDevice doesn't support openCommissioningWindowWithDiscriminator over XPC");
dispatch_async(queue, ^{
completion(nil, [NSError errorWithDomain:MTRErrorDomain code:MTRErrorCodeInvalidState userInfo:nil]);
});
}
- (void)downloadLogOfType:(MTRDiagnosticLogType)type
timeout:(NSTimeInterval)timeout
queue:(dispatch_queue_t)queue
completion:(void (^)(NSURL * _Nullable url, NSError * _Nullable error))completion
{
MTR_LOG_DEBUG("Downloading log ...");
__auto_type workBlock = ^(MTRDeviceControllerXPCProxyHandle * _Nullable handle, NSError * _Nullable error) {
if (error != nil) {
completion(nil, error);
return;
}
[handle.proxy downloadLogWithController:self.controllerID
nodeId:self.nodeID
type:type
timeout:timeout
completion:^(NSString * _Nullable url, NSError * _Nullable error) {
dispatch_async(queue, ^{
MTR_LOG_DEBUG("Download log");
completion([NSURL URLWithString:url], error);
// The following captures the proxy handle in the closure so that the
// handle won't be released prior to block call.
__auto_type handleRetainer = handle;
(void) handleRetainer;
});
}];
};
[self fetchProxyHandleWithQueue:queue completion:workBlock];
}
- (void)fetchProxyHandleWithQueue:(dispatch_queue_t)queue completion:(MTRFetchProxyHandleCompletion)completion
{
if (self.controllerID != nil) {
[self->_xpcConnection getProxyHandleWithCompletion:^(
dispatch_queue_t _Nonnull proxyQueue, MTRDeviceControllerXPCProxyHandle * _Nullable handle) {
dispatch_async(queue, ^{
if (handle == nil) {
MTR_LOG_ERROR("Failed to obtain XPC connection");
completion(nil, [NSError errorWithDomain:MTRErrorDomain code:MTRErrorCodeGeneralError userInfo:nil]);
} else {
completion(handle, nil);
}
});
}];
} else {
[self.controller fetchControllerIdWithQueue:queue
completion:^(id _Nullable controllerID,
MTRDeviceControllerXPCProxyHandle * _Nullable handle, NSError * _Nullable error) {
// We're already running on the right queue.
if (error != nil) {
completion(nil, error);
} else {
self->_controllerID = controllerID;
completion(handle, nil);
}
}];
}
}
@end
NS_ASSUME_NONNULL_END