diff --git a/src/darwin/Framework/CHIP/MTRAttributeCacheContainer.mm b/src/darwin/Framework/CHIP/MTRAttributeCacheContainer.mm index 4a9e80b02fa903..e0ee3e77e43a4b 100644 --- a/src/darwin/Framework/CHIP/MTRAttributeCacheContainer.mm +++ b/src/darwin/Framework/CHIP/MTRAttributeCacheContainer.mm @@ -43,8 +43,8 @@ - (instancetype)init } - (void)setXPCConnection:(MTRDeviceControllerXPCConnection *)xpcConnection - controllerId:(id)controllerId - deviceId:(uint64_t)deviceId + controllerId:(id)controllerId + deviceId:(uint64_t)deviceId { self.xpcConnection = xpcConnection; self.xpcControllerId = controllerId; @@ -65,28 +65,28 @@ static CHIP_ERROR AppendAttibuteValueToArray( } MTR_LOG_ERROR("Error: Cached value could not be converted to generic NSObject"); [array addObject:@ { - MTRAttributePathKey : [[MTRAttributePath alloc] initWithPath:path], - MTRErrorKey : [MTRError errorForCHIPErrorCode:CHIP_ERROR_DECODE_FAILED] - }]; + MTRAttributePathKey : [[MTRAttributePath alloc] initWithPath:path], + MTRErrorKey : [MTRError errorForCHIPErrorCode:CHIP_ERROR_DECODE_FAILED] + }]; return CHIP_ERROR_DECODE_FAILED; } MTR_LOG_ERROR("Error: Failed to read from attribute cache: %s", err.AsString()); [array addObject:@ { - MTRAttributePathKey : [[MTRAttributePath alloc] initWithPath:path], - MTRErrorKey : [MTRError errorForCHIPErrorCode:err] - }]; + MTRAttributePathKey : [[MTRAttributePath alloc] initWithPath:path], + MTRErrorKey : [MTRError errorForCHIPErrorCode:err] + }]; return err; } - (void)readAttributeWithEndpointId:(NSNumber * _Nullable)endpointId - clusterId:(NSNumber * _Nullable)clusterId - attributeId:(NSNumber * _Nullable)attributeId - clientQueue:(dispatch_queue_t)clientQueue - completion:(void (^)(NSArray *> * _Nullable values, - NSError * _Nullable error))completion + clusterId:(NSNumber * _Nullable)clusterId + attributeId:(NSNumber * _Nullable)attributeId + clientQueue:(dispatch_queue_t)clientQueue + completion:(void (^)(NSArray *> * _Nullable values, + NSError * _Nullable error))completion { __auto_type completionHandler = ^(NSArray *> * _Nullable values, NSError * _Nullable error) { - dispatch_async(clientQueue, ^ { + dispatch_async(clientQueue, ^{ completion(values, error); }); }; @@ -101,27 +101,27 @@ - (void)readAttributeWithEndpointId:(NSNumber * _Nullable)endpointId __auto_type controllerId = self.xpcControllerId; uint64_t nodeId = self.deviceId; [xpcConnection - getProxyHandleWithCompletion:^(dispatch_queue_t _Nonnull queue, MTRDeviceControllerXPCProxyHandle * _Nullable handle) { - if (handle) { - [handle.proxy readAttributeCacheWithController:controllerId - nodeId:nodeId - endpointId:endpointId - clusterId:clusterId - attributeId:attributeId - completion:^(id _Nullable values, NSError * _Nullable error) { - completion([MTRDeviceController decodeXPCResponseValues:values], error); - __auto_type handleRetainer = handle; - (void) handleRetainer; - }]; - } else { - MTR_LOG_ERROR("Attribute cache read failed due to XPC connection failure"); - completion(nil, [NSError errorWithDomain:MTRErrorDomain code:MTRErrorCodeGeneralError userInfo:nil]); - } - }]; + getProxyHandleWithCompletion:^(dispatch_queue_t _Nonnull queue, MTRDeviceControllerXPCProxyHandle * _Nullable handle) { + if (handle) { + [handle.proxy readAttributeCacheWithController:controllerId + nodeId:nodeId + endpointId:endpointId + clusterId:clusterId + attributeId:attributeId + completion:^(id _Nullable values, NSError * _Nullable error) { + completion([MTRDeviceController decodeXPCResponseValues:values], error); + __auto_type handleRetainer = handle; + (void) handleRetainer; + }]; + } else { + MTR_LOG_ERROR("Attribute cache read failed due to XPC connection failure"); + completion(nil, [NSError errorWithDomain:MTRErrorDomain code:MTRErrorCodeGeneralError userInfo:nil]); + } + }]; return; } - dispatch_async(DeviceLayer::PlatformMgrImpl().GetWorkQueue(), ^ { + dispatch_async(DeviceLayer::PlatformMgrImpl().GetWorkQueue(), ^{ if (endpointId == nil && clusterId == nil) { MTR_LOG_ERROR("Error: currently read from attribute cache does not support wildcards for both endpoint and cluster"); completionHandler(nil, [NSError errorWithDomain:MTRErrorDomain code:MTRErrorCodeInvalidArgument userInfo:nil]); @@ -138,32 +138,32 @@ - (void)readAttributeWithEndpointId:(NSNumber * _Nullable)endpointId CHIP_ERROR err = CHIP_NO_ERROR; if (endpointId == nil) { err = self.cppAttributeCache->ForEachAttribute( - static_cast([clusterId unsignedLongValue]), [&](const app::ConcreteAttributePath & path) { - if (attributeId == nil - || static_cast([attributeId unsignedLongValue]) == path.mAttributeId) { - (void) AppendAttibuteValueToArray(path, self.cppAttributeCache, result); - } - return CHIP_NO_ERROR; - }); - } else if (clusterId == nil) { - err = self.cppAttributeCache->ForEachCluster( - static_cast([endpointId unsignedShortValue]), [&](chip::ClusterId enumeratedClusterId) { - (void) self.cppAttributeCache->ForEachAttribute(static_cast([endpointId unsignedShortValue]), - enumeratedClusterId, [&](const app::ConcreteAttributePath & path) { + static_cast([clusterId unsignedLongValue]), [&](const app::ConcreteAttributePath & path) { if (attributeId == nil - || static_cast([attributeId unsignedLongValue]) == path.mAttributeId) { + || static_cast([attributeId unsignedLongValue]) == path.mAttributeId) { (void) AppendAttibuteValueToArray(path, self.cppAttributeCache, result); } return CHIP_NO_ERROR; }); - return CHIP_NO_ERROR; - }); + } else if (clusterId == nil) { + err = self.cppAttributeCache->ForEachCluster( + static_cast([endpointId unsignedShortValue]), [&](chip::ClusterId enumeratedClusterId) { + (void) self.cppAttributeCache->ForEachAttribute(static_cast([endpointId unsignedShortValue]), + enumeratedClusterId, [&](const app::ConcreteAttributePath & path) { + if (attributeId == nil + || static_cast([attributeId unsignedLongValue]) == path.mAttributeId) { + (void) AppendAttibuteValueToArray(path, self.cppAttributeCache, result); + } + return CHIP_NO_ERROR; + }); + return CHIP_NO_ERROR; + }); } else if (attributeId == nil) { err = self.cppAttributeCache->ForEachAttribute(static_cast([endpointId unsignedShortValue]), - static_cast([clusterId unsignedLongValue]), [&](const app::ConcreteAttributePath & path) { - (void) AppendAttibuteValueToArray(path, self.cppAttributeCache, result); - return CHIP_NO_ERROR; - }); + static_cast([clusterId unsignedLongValue]), [&](const app::ConcreteAttributePath & path) { + (void) AppendAttibuteValueToArray(path, self.cppAttributeCache, result); + return CHIP_NO_ERROR; + }); } else { app::ConcreteAttributePath path; path.mEndpointId = static_cast([endpointId unsignedShortValue]); diff --git a/src/darwin/Framework/CHIP/MTRBaseDevice.mm b/src/darwin/Framework/CHIP/MTRBaseDevice.mm index d9c8d0829b4b7e..c1a54ac7b6983d 100644 --- a/src/darwin/Framework/CHIP/MTRBaseDevice.mm +++ b/src/darwin/Framework/CHIP/MTRBaseDevice.mm @@ -79,11 +79,11 @@ - (instancetype)initWithPath:(const ConcreteDataAttributePath &)path value:(null @interface MTREventReport () - (instancetype)initWithPath:(const ConcreteEventPath &)path - eventNumber:(NSNumber *)eventNumber - priority:(NSNumber *)priority - timestamp:(NSNumber *)timestamp - value:(nullable id)value - error:(nullable NSError *)error; + eventNumber:(NSNumber *)eventNumber + priority:(NSNumber *)priority + timestamp:(NSNumber *)timestamp + value:(nullable id)value + error:(nullable NSError *)error; @end @interface MTRReadClientContainer : NSObject @@ -99,7 +99,7 @@ - (void)onDone; static void InitializeReadClientContainers() { static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^ { + dispatch_once(&onceToken, ^{ readClientContainers = [NSMutableDictionary dictionary]; readClientContainersLock = [[NSLock alloc] init]; }); @@ -130,7 +130,7 @@ static void PurgeReadClientContainers(uint64_t deviceId, dispatch_queue_t queue, [readClientContainersLock unlock]; // Destroy read clients in the work queue - dispatch_async(DeviceLayer::PlatformMgrImpl().GetWorkQueue(), ^ { + dispatch_async(DeviceLayer::PlatformMgrImpl().GetWorkQueue(), ^{ for (MTRReadClientContainer * container in listToDelete) { if (container.readClientPtr) { Platform::Delete(container.readClientPtr); @@ -179,7 +179,7 @@ static void CauseReadClientFailure(uint64_t deviceId, dispatch_queue_t queue, vo [readClientContainers removeObjectForKey:key]; [readClientContainersLock unlock]; - dispatch_async(DeviceLayer::PlatformMgrImpl().GetWorkQueue(), ^ { + dispatch_async(DeviceLayer::PlatformMgrImpl().GetWorkQueue(), ^{ for (MTRReadClientContainer * container in listToFail) { // Send auto resubscribe request again by read clients, which must fail. chip::app::ReadPrepareParams readParams; @@ -246,7 +246,7 @@ - (instancetype)initWithDevice:(chip::DeviceProxy *)device - (void)invalidateCASESession { - dispatch_sync(DeviceLayer::PlatformMgrImpl().GetWorkQueue(), ^ { + dispatch_sync(DeviceLayer::PlatformMgrImpl().GetWorkQueue(), ^{ DeviceProxy * device = [self internalDevice]; if (device != nullptr) { device->Disconnect(); @@ -263,7 +263,7 @@ - (void)invalidateCASESession class SubscriptionCallback final : public ClusterStateCache::Callback { public: SubscriptionCallback(dispatch_queue_t queue, DataReportCallback attributeReportCallback, DataReportCallback eventReportCallback, - ErrorCallback errorCallback, SubscriptionEstablishedHandler _Nullable subscriptionEstablishedHandler) + ErrorCallback errorCallback, SubscriptionEstablishedHandler _Nullable subscriptionEstablishedHandler) : mQueue(queue) , mAttributeReportCallback(attributeReportCallback) , mEventReportCallback(eventReportCallback) @@ -274,8 +274,8 @@ - (void)invalidateCASESession } SubscriptionCallback(dispatch_queue_t queue, DataReportCallback attributeReportCallback, DataReportCallback eventReportCallback, - ErrorCallback errorCallback, SubscriptionEstablishedHandler _Nullable subscriptionEstablishedHandler, - void (^onDoneHandler)(void)) + ErrorCallback errorCallback, SubscriptionEstablishedHandler _Nullable subscriptionEstablishedHandler, + void (^onDoneHandler)(void)) : mQueue(queue) , mAttributeReportCallback(attributeReportCallback) , mEventReportCallback(eventReportCallback) @@ -286,17 +286,11 @@ - (void)invalidateCASESession { } - BufferedReadCallback & GetBufferedCallback() { - return mBufferedReadAdapter; - } + BufferedReadCallback & GetBufferedCallback() { return mBufferedReadAdapter; } // We need to exist to get a ReadClient, so can't take this as a constructor argument. - void AdoptReadClient(std::unique_ptr aReadClient) { - mReadClient = std::move(aReadClient); - } - void AdoptAttributeCache(std::unique_ptr aAttributeCache) { - mAttributeCache = std::move(aAttributeCache); - } + void AdoptReadClient(std::unique_ptr aReadClient) { mReadClient = std::move(aReadClient); } + void AdoptAttributeCache(std::unique_ptr aAttributeCache) { mAttributeCache = std::move(aAttributeCache); } private: void OnReportBegin() override; @@ -353,19 +347,19 @@ void AdoptAttributeCache(std::unique_ptr aAttributeCache) { } // anonymous namespace - (void)subscribeWithQueue:(dispatch_queue_t)queue - minInterval:(uint16_t)minInterval - maxInterval:(uint16_t)maxInterval - params:(nullable MTRSubscribeParams *)params - cacheContainer:(MTRAttributeCacheContainer * _Nullable)attributeCacheContainer - attributeReportHandler:(nullable void (^)(NSArray * value))attributeReportHandler - eventReportHandler:(nullable void (^)(NSArray * value))eventReportHandler - errorHandler:(void (^)(NSError * error))errorHandler + minInterval:(uint16_t)minInterval + maxInterval:(uint16_t)maxInterval + params:(nullable MTRSubscribeParams *)params + cacheContainer:(MTRAttributeCacheContainer * _Nullable)attributeCacheContainer + attributeReportHandler:(nullable void (^)(NSArray * value))attributeReportHandler + eventReportHandler:(nullable void (^)(NSArray * value))eventReportHandler + errorHandler:(void (^)(NSError * error))errorHandler subscriptionEstablished:(nullable void (^)(void))subscriptionEstablishedHandler { - dispatch_async(DeviceLayer::PlatformMgrImpl().GetWorkQueue(), ^ { + dispatch_async(DeviceLayer::PlatformMgrImpl().GetWorkQueue(), ^{ DeviceProxy * device = [self internalDevice]; if (!device) { - dispatch_async(queue, ^ { + dispatch_async(queue, ^{ errorHandler([MTRError errorForCHIPErrorCode:CHIP_ERROR_INCORRECT_STATE]); }); return; @@ -390,20 +384,20 @@ - (void)subscribeWithQueue:(dispatch_queue_t)queue if (attributeCacheContainer) { __weak MTRAttributeCacheContainer * weakPtr = attributeCacheContainer; callback = std::make_unique( - queue, attributeReportHandler, eventReportHandler, errorHandler, subscriptionEstablishedHandler, ^ { - MTRAttributeCacheContainer * container = weakPtr; - if (container) { - container.cppAttributeCache = nullptr; - } - }); + queue, attributeReportHandler, eventReportHandler, errorHandler, subscriptionEstablishedHandler, ^{ + MTRAttributeCacheContainer * container = weakPtr; + if (container) { + container.cppAttributeCache = nullptr; + } + }); attributeCache = std::make_unique(*callback.get()); readClient = std::make_unique(InteractionModelEngine::GetInstance(), device->GetExchangeManager(), - attributeCache->GetBufferedCallback(), ReadClient::InteractionType::Subscribe); + attributeCache->GetBufferedCallback(), ReadClient::InteractionType::Subscribe); } else { callback = std::make_unique( - queue, attributeReportHandler, eventReportHandler, errorHandler, subscriptionEstablishedHandler); + queue, attributeReportHandler, eventReportHandler, errorHandler, subscriptionEstablishedHandler); readClient = std::make_unique(InteractionModelEngine::GetInstance(), device->GetExchangeManager(), - callback->GetBufferedCallback(), ReadClient::InteractionType::Subscribe); + callback->GetBufferedCallback(), ReadClient::InteractionType::Subscribe); } CHIP_ERROR err; @@ -417,7 +411,7 @@ - (void)subscribeWithQueue:(dispatch_queue_t)queue } if (err != CHIP_NO_ERROR) { - dispatch_async(queue, ^ { + dispatch_async(queue, ^{ errorHandler([MTRError errorForCHIPErrorCode:err]); }); @@ -469,7 +463,7 @@ id _Nullable NSObjectFromCHIPTLV(chip::TLV::TLVReader * data) return nil; } return [NSDictionary - dictionaryWithObjectsAndKeys:MTRBooleanValueType, MTRTypeKey, [NSNumber numberWithBool:val], MTRValueKey, nil]; + dictionaryWithObjectsAndKeys:MTRBooleanValueType, MTRTypeKey, [NSNumber numberWithBool:val], MTRValueKey, nil]; } case chip::TLV::kTLVType_FloatingPointNumber: { // Try float first @@ -485,7 +479,7 @@ id _Nullable NSObjectFromCHIPTLV(chip::TLV::TLVReader * data) return nil; } return [NSDictionary - dictionaryWithObjectsAndKeys:MTRDoubleValueType, MTRTypeKey, [NSNumber numberWithDouble:val], MTRValueKey, nil]; + dictionaryWithObjectsAndKeys:MTRDoubleValueType, MTRTypeKey, [NSNumber numberWithDouble:val], MTRValueKey, nil]; } case chip::TLV::kTLVType_UTF8String: { uint32_t len = data->GetLength(); @@ -709,13 +703,9 @@ CHIP_ERROR Encode(chip::TLV::TLVWriter & writer, chip::TLV::Tag tag) const static constexpr bool kIsFabricScoped = false; - static bool MustUseTimedInvoke() { - return false; - } + static bool MustUseTimedInvoke() { return false; } - id _Nullable GetDecodedObject() const { - return decodedObj; - } + id _Nullable GetDecodedObject() const { return decodedObj; } private: id _Nullable decodedObj; @@ -728,9 +718,7 @@ id _Nullable GetDecodedObject() const { dispatch_queue_t queue, MTRDeviceResponseHandler handler, MTRActionBlock action, bool keepAlive = false) : MTRCallbackBridge(queue, handler, action, OnSuccessFn, keepAlive) {}; - static void OnSuccessFn(void * context, id value) { - DispatchSuccess(context, value); - } + static void OnSuccessFn(void * context, id value) { DispatchSuccess(context, value); } }; template class BufferedReadAttributeCallback final : public app::ReadClient::Callback { @@ -742,8 +730,8 @@ static void OnSuccessFn(void * context, id value) { using OnSubscriptionEstablishedCallbackType = std::function; BufferedReadAttributeCallback(ClusterId aClusterId, AttributeId aAttributeId, OnSuccessCallbackType aOnSuccess, - OnErrorCallbackType aOnError, OnDoneCallbackType aOnDone, - OnSubscriptionEstablishedCallbackType aOnSubscriptionEstablished = nullptr) + OnErrorCallbackType aOnError, OnDoneCallbackType aOnDone, + OnSubscriptionEstablishedCallbackType aOnSubscriptionEstablished = nullptr) : mClusterId(aClusterId) , mAttributeId(aAttributeId) , mOnSuccess(aOnSuccess) @@ -754,13 +742,9 @@ static void OnSuccessFn(void * context, id value) { { } - app::BufferedReadCallback & GetBufferedCallback() { - return mBufferedReadAdapter; - } + app::BufferedReadCallback & GetBufferedCallback() { return mBufferedReadAdapter; } - void AdoptReadClient(Platform::UniquePtr aReadClient) { - mReadClient = std::move(aReadClient); - } + void AdoptReadClient(Platform::UniquePtr aReadClient) { mReadClient = std::move(aReadClient); } private: void OnAttributeData( @@ -777,27 +761,23 @@ void OnAttributeData( VerifyOrExit(aStatus.IsSuccess(), err = aStatus.ToChipError()); VerifyOrExit((aPath.mClusterId == mClusterId || mClusterId == kInvalidClusterId) - && (aPath.mAttributeId == mAttributeId || mAttributeId == kInvalidAttributeId), - err = CHIP_ERROR_SCHEMA_MISMATCH); + && (aPath.mAttributeId == mAttributeId || mAttributeId == kInvalidAttributeId), + err = CHIP_ERROR_SCHEMA_MISMATCH); VerifyOrExit(apData != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT); SuccessOrExit(err = app::DataModel::Decode(*apData, value)); mOnSuccess(aPath, value); -exit: + exit: if (err != CHIP_NO_ERROR) { mOnError(&aPath, err); } } - void OnError(CHIP_ERROR aError) override { - mOnError(nullptr, aError); - } + void OnError(CHIP_ERROR aError) override { mOnError(nullptr, aError); } - void OnDone(ReadClient *) override { - mOnDone(this); - } + void OnDone(ReadClient *) override { mOnDone(this); } void OnSubscriptionEstablished(SubscriptionId aSubscriptionId) override { @@ -819,174 +799,174 @@ void OnDeallocatePaths(chip::app::ReadPrepareParams && aReadPrepareParams) overr }; - (void)readAttributeWithEndpointId:(NSNumber *)endpointId - clusterId:(NSNumber *)clusterId - attributeId:(NSNumber *)attributeId - params:(MTRReadParams * _Nullable)params - clientQueue:(dispatch_queue_t)clientQueue - completion:(MTRDeviceResponseHandler)completion + clusterId:(NSNumber *)clusterId + attributeId:(NSNumber *)attributeId + params:(MTRReadParams * _Nullable)params + clientQueue:(dispatch_queue_t)clientQueue + completion:(MTRDeviceResponseHandler)completion { new NSObjectDataValueCallbackBridge( - clientQueue, completion, ^(chip::Callback::Cancelable * success, chip::Callback::Cancelable * failure) { - auto successFn = chip::Callback::Callback::FromCancelable(success); - auto failureFn = chip::Callback::Callback::FromCancelable(failure); - auto context = successFn->mContext; - auto successCb = successFn->mCall; - auto failureCb = failureFn->mCall; - auto resultArray = [[NSMutableArray alloc] init]; - auto resultSuccess = [[NSMutableArray alloc] init]; - auto resultFailure = [[NSMutableArray alloc] init]; - auto onSuccessCb - = [resultArray, resultSuccess](const app::ConcreteAttributePath & attribPath, const NSObjectData & aData) { - [resultArray addObject:@ { - MTRAttributePathKey : [[MTRAttributePath alloc] initWithPath:attribPath], - MTRDataKey : aData.GetDecodedObject() - }]; - if ([resultSuccess count] == 0) { - [resultSuccess addObject:[NSNumber numberWithBool:YES]]; - } - }; + clientQueue, completion, ^(chip::Callback::Cancelable * success, chip::Callback::Cancelable * failure) { + auto successFn = chip::Callback::Callback::FromCancelable(success); + auto failureFn = chip::Callback::Callback::FromCancelable(failure); + auto context = successFn->mContext; + auto successCb = successFn->mCall; + auto failureCb = failureFn->mCall; + auto resultArray = [[NSMutableArray alloc] init]; + auto resultSuccess = [[NSMutableArray alloc] init]; + auto resultFailure = [[NSMutableArray alloc] init]; + auto onSuccessCb + = [resultArray, resultSuccess](const app::ConcreteAttributePath & attribPath, const NSObjectData & aData) { + [resultArray addObject:@ { + MTRAttributePathKey : [[MTRAttributePath alloc] initWithPath:attribPath], + MTRDataKey : aData.GetDecodedObject() + }]; + if ([resultSuccess count] == 0) { + [resultSuccess addObject:[NSNumber numberWithBool:YES]]; + } + }; + + auto onFailureCb = [resultArray, resultFailure](const app::ConcreteAttributePath * attribPath, CHIP_ERROR aError) { + if (attribPath) { + [resultArray addObject:@ { + MTRAttributePathKey : [[MTRAttributePath alloc] initWithPath:*attribPath], + MTRErrorKey : [MTRError errorForCHIPErrorCode:aError] + }]; + } else if ([resultFailure count] == 0) { + [resultFailure addObject:[MTRError errorForCHIPErrorCode:aError]]; + } + }; - auto onFailureCb = [resultArray, resultFailure](const app::ConcreteAttributePath * attribPath, CHIP_ERROR aError) { - if (attribPath) { - [resultArray addObject:@ { - MTRAttributePathKey : [[MTRAttributePath alloc] initWithPath:*attribPath], - MTRErrorKey : [MTRError errorForCHIPErrorCode:aError] - }]; - } else if ([resultFailure count] == 0) { - [resultFailure addObject:[MTRError errorForCHIPErrorCode:aError]]; + app::AttributePathParams attributePath; + if (endpointId) { + attributePath.mEndpointId = static_cast([endpointId unsignedShortValue]); } - }; - - app::AttributePathParams attributePath; - if (endpointId) { - attributePath.mEndpointId = static_cast([endpointId unsignedShortValue]); - } - if (clusterId) { - attributePath.mClusterId = static_cast([clusterId unsignedLongValue]); - } - if (attributeId) { - attributePath.mAttributeId = static_cast([attributeId unsignedLongValue]); - } - app::InteractionModelEngine * engine = app::InteractionModelEngine::GetInstance(); - CHIP_ERROR err = CHIP_NO_ERROR; - - chip::app::ReadPrepareParams readParams([self internalDevice]->GetSecureSession().Value()); - readParams.mpAttributePathParamsList = &attributePath; - readParams.mAttributePathParamsListSize = 1; - readParams.mIsFabricFiltered = params == nil || params.fabricFiltered == nil || [params.fabricFiltered boolValue]; - - auto onDone = [resultArray, resultSuccess, resultFailure, context, successCb, failureCb]( - BufferedReadAttributeCallback * callback) { - if ([resultFailure count] > 0 || [resultSuccess count] == 0) { - // Failure - if (failureCb) { - if ([resultFailure count] > 0) { - failureCb(context, [MTRError errorToCHIPErrorCode:resultFailure[0]]); - } else if ([resultArray count] > 0) { - failureCb(context, [MTRError errorToCHIPErrorCode:resultArray[0][MTRErrorKey]]); - } else { - failureCb(context, CHIP_ERROR_READ_FAILED); + if (clusterId) { + attributePath.mClusterId = static_cast([clusterId unsignedLongValue]); + } + if (attributeId) { + attributePath.mAttributeId = static_cast([attributeId unsignedLongValue]); + } + app::InteractionModelEngine * engine = app::InteractionModelEngine::GetInstance(); + CHIP_ERROR err = CHIP_NO_ERROR; + + chip::app::ReadPrepareParams readParams([self internalDevice]->GetSecureSession().Value()); + readParams.mpAttributePathParamsList = &attributePath; + readParams.mAttributePathParamsListSize = 1; + readParams.mIsFabricFiltered = params == nil || params.fabricFiltered == nil || [params.fabricFiltered boolValue]; + + auto onDone = [resultArray, resultSuccess, resultFailure, context, successCb, failureCb]( + BufferedReadAttributeCallback * callback) { + if ([resultFailure count] > 0 || [resultSuccess count] == 0) { + // Failure + if (failureCb) { + if ([resultFailure count] > 0) { + failureCb(context, [MTRError errorToCHIPErrorCode:resultFailure[0]]); + } else if ([resultArray count] > 0) { + failureCb(context, [MTRError errorToCHIPErrorCode:resultArray[0][MTRErrorKey]]); + } else { + failureCb(context, CHIP_ERROR_READ_FAILED); + } + } + } else { + // Success + if (successCb) { + successCb(context, resultArray); } } - } else { - // Success - if (successCb) { - successCb(context, resultArray); - } - } - chip::Platform::Delete(callback); - }; + chip::Platform::Delete(callback); + }; - auto callback = chip::Platform::MakeUnique>( - attributePath.mClusterId, attributePath.mAttributeId, onSuccessCb, onFailureCb, onDone, nullptr); - VerifyOrReturnError(callback != nullptr, CHIP_ERROR_NO_MEMORY); + auto callback = chip::Platform::MakeUnique>( + attributePath.mClusterId, attributePath.mAttributeId, onSuccessCb, onFailureCb, onDone, nullptr); + VerifyOrReturnError(callback != nullptr, CHIP_ERROR_NO_MEMORY); - auto readClient = chip::Platform::MakeUnique(engine, [self internalDevice]->GetExchangeManager(), - callback -> GetBufferedCallback(), chip::app::ReadClient::InteractionType::Read); - VerifyOrReturnError(readClient != nullptr, CHIP_ERROR_NO_MEMORY); + auto readClient = chip::Platform::MakeUnique(engine, [self internalDevice]->GetExchangeManager(), + callback -> GetBufferedCallback(), chip::app::ReadClient::InteractionType::Read); + VerifyOrReturnError(readClient != nullptr, CHIP_ERROR_NO_MEMORY); - err = readClient->SendRequest(readParams); + err = readClient->SendRequest(readParams); - if (err != CHIP_NO_ERROR) { - return err; - } + if (err != CHIP_NO_ERROR) { + return err; + } - // - // At this point, we'll get a callback through the OnDone callback above regardless of success or failure - // of the read operation to permit us to free up the callback object. So, release ownership of the callback - // object now to prevent it from being reclaimed at the end of this scoped block. - // - callback->AdoptReadClient(std::move(readClient)); - callback.release(); - return err; - }); + // + // At this point, we'll get a callback through the OnDone callback above regardless of success or failure + // of the read operation to permit us to free up the callback object. So, release ownership of the callback + // object now to prevent it from being reclaimed at the end of this scoped block. + // + callback->AdoptReadClient(std::move(readClient)); + callback.release(); + return err; + }); } - (void)writeAttributeWithEndpointId:(NSNumber *)endpointId - clusterId:(NSNumber *)clusterId - attributeId:(NSNumber *)attributeId - value:(id)value - timedWriteTimeout:(NSNumber * _Nullable)timeoutMs - clientQueue:(dispatch_queue_t)clientQueue - completion:(MTRDeviceResponseHandler)completion + clusterId:(NSNumber *)clusterId + attributeId:(NSNumber *)attributeId + value:(id)value + timedWriteTimeout:(NSNumber * _Nullable)timeoutMs + clientQueue:(dispatch_queue_t)clientQueue + completion:(MTRDeviceResponseHandler)completion { new NSObjectDataValueCallbackBridge( - clientQueue, completion, ^(chip::Callback::Cancelable * success, chip::Callback::Cancelable * failure) { - auto successFn = chip::Callback::Callback::FromCancelable(success); - auto failureFn = chip::Callback::Callback::FromCancelable(failure); - auto context = successFn->mContext; - auto successCb = successFn->mCall; - auto failureCb = failureFn->mCall; - auto resultArray = [[NSMutableArray alloc] init]; - auto resultSuccess = [[NSMutableArray alloc] init]; - auto resultFailure = [[NSMutableArray alloc] init]; - auto onSuccessCb = [resultArray, resultSuccess](const app::ConcreteAttributePath & attribPath) { - [resultArray addObject:@ { MTRAttributePathKey : [[MTRAttributePath alloc] initWithPath:attribPath] }]; - if ([resultSuccess count] == 0) { - [resultSuccess addObject:[NSNumber numberWithBool:YES]]; - } - }; - - auto onFailureCb = [resultArray, resultFailure](const app::ConcreteAttributePath * attribPath, CHIP_ERROR aError) { - if (attribPath) { - [resultArray addObject:@ { - MTRAttributePathKey : [[MTRAttributePath alloc] initWithPath:*attribPath], - MTRErrorKey : [MTRError errorForCHIPErrorCode:aError], - }]; - } else { - if ([resultFailure count] == 0) { - [resultFailure addObject:[MTRError errorForCHIPErrorCode:aError]]; + clientQueue, completion, ^(chip::Callback::Cancelable * success, chip::Callback::Cancelable * failure) { + auto successFn = chip::Callback::Callback::FromCancelable(success); + auto failureFn = chip::Callback::Callback::FromCancelable(failure); + auto context = successFn->mContext; + auto successCb = successFn->mCall; + auto failureCb = failureFn->mCall; + auto resultArray = [[NSMutableArray alloc] init]; + auto resultSuccess = [[NSMutableArray alloc] init]; + auto resultFailure = [[NSMutableArray alloc] init]; + auto onSuccessCb = [resultArray, resultSuccess](const app::ConcreteAttributePath & attribPath) { + [resultArray addObject:@ { MTRAttributePathKey : [[MTRAttributePath alloc] initWithPath:attribPath] }]; + if ([resultSuccess count] == 0) { + [resultSuccess addObject:[NSNumber numberWithBool:YES]]; } - } - }; - - auto onDoneCb - = [context, successCb, failureCb, resultArray, resultSuccess, resultFailure](app::WriteClient * pWriteClient) { - if ([resultFailure count] > 0 || [resultSuccess count] == 0) { - // Failure - if (failureCb) { - if ([resultFailure count] > 0) { - failureCb(context, [MTRError errorToCHIPErrorCode:resultFailure[0]]); - } else if ([resultArray count] > 0) { - failureCb(context, [MTRError errorToCHIPErrorCode:resultArray[0][MTRErrorKey]]); - } else { - failureCb(context, CHIP_ERROR_WRITE_FAILED); + }; + + auto onFailureCb = [resultArray, resultFailure](const app::ConcreteAttributePath * attribPath, CHIP_ERROR aError) { + if (attribPath) { + [resultArray addObject:@ { + MTRAttributePathKey : [[MTRAttributePath alloc] initWithPath:*attribPath], + MTRErrorKey : [MTRError errorForCHIPErrorCode:aError], + }]; + } else { + if ([resultFailure count] == 0) { + [resultFailure addObject:[MTRError errorForCHIPErrorCode:aError]]; } } - } else { - // Success - if (successCb) { - successCb(context, resultArray); - } - } - }; - - return chip::Controller::WriteAttribute([self internalDevice]->GetSecureSession().Value(), + }; + + auto onDoneCb + = [context, successCb, failureCb, resultArray, resultSuccess, resultFailure](app::WriteClient * pWriteClient) { + if ([resultFailure count] > 0 || [resultSuccess count] == 0) { + // Failure + if (failureCb) { + if ([resultFailure count] > 0) { + failureCb(context, [MTRError errorToCHIPErrorCode:resultFailure[0]]); + } else if ([resultArray count] > 0) { + failureCb(context, [MTRError errorToCHIPErrorCode:resultArray[0][MTRErrorKey]]); + } else { + failureCb(context, CHIP_ERROR_WRITE_FAILED); + } + } + } else { + // Success + if (successCb) { + successCb(context, resultArray); + } + } + }; + + return chip::Controller::WriteAttribute([self internalDevice]->GetSecureSession().Value(), static_cast([endpointId unsignedShortValue]), static_cast([clusterId unsignedLongValue]), static_cast([attributeId unsignedLongValue]), NSObjectData(value), onSuccessCb, onFailureCb, (timeoutMs == nil) ? NullOptional : Optional([timeoutMs unsignedShortValue]), onDoneCb, NullOptional); - }); + }); } class NSObjectCommandCallback final : public app::CommandSender::Callback { @@ -1004,7 +984,7 @@ new NSObjectDataValueCallbackBridge( * into a hypothetical OnDoneCallback function. */ NSObjectCommandCallback(chip::ClusterId clusterId, chip::CommandId commandId, OnSuccessCallbackType aOnSuccess, - OnErrorCallbackType aOnError, OnDoneCallbackType aOnDone = {}) + OnErrorCallbackType aOnError, OnDoneCallbackType aOnDone = {}) : mOnSuccess(aOnSuccess) , mOnError(aOnError) , mOnDone(aOnDone) @@ -1013,21 +993,15 @@ new NSObjectDataValueCallbackBridge( { } - void SetOnDoneCallback(OnDoneCallbackType callback) { - mOnDone = callback; - } + void SetOnDoneCallback(OnDoneCallbackType callback) { mOnDone = callback; } private: void OnResponse(app::CommandSender * apCommandSender, const app::ConcreteCommandPath & aCommandPath, - const app::StatusIB & aStatus, TLV::TLVReader * aReader) override; + const app::StatusIB & aStatus, TLV::TLVReader * aReader) override; - void OnError(const app::CommandSender * apCommandSender, CHIP_ERROR aError) override { - mOnError(aError); - } + void OnError(const app::CommandSender * apCommandSender, CHIP_ERROR aError) override { mOnError(aError); } - void OnDone(app::CommandSender * apCommandSender) override { - mOnDone(apCommandSender); - } + void OnDone(app::CommandSender * apCommandSender) override { mOnDone(apCommandSender); } OnSuccessCallbackType mOnSuccess; OnErrorCallbackType mOnError; @@ -1037,7 +1011,7 @@ void OnDone(app::CommandSender * apCommandSender) override { }; void NSObjectCommandCallback::OnResponse(app::CommandSender * apCommandSender, const app::ConcreteCommandPath & aCommandPath, - const app::StatusIB & aStatus, TLV::TLVReader * aReader) + const app::StatusIB & aStatus, TLV::TLVReader * aReader) { NSObjectData response; CHIP_ERROR err = CHIP_NO_ERROR; @@ -1061,115 +1035,114 @@ void OnDone(app::CommandSender * apCommandSender) override { } - (void)invokeCommandWithEndpointId:(NSNumber *)endpointId - clusterId:(NSNumber *)clusterId - commandId:(NSNumber *)commandId - commandFields:(id)commandFields - timedInvokeTimeout:(NSNumber * _Nullable)timeoutMs - clientQueue:(dispatch_queue_t)clientQueue - completion:(MTRDeviceResponseHandler)completion + clusterId:(NSNumber *)clusterId + commandId:(NSNumber *)commandId + commandFields:(id)commandFields + timedInvokeTimeout:(NSNumber * _Nullable)timeoutMs + clientQueue:(dispatch_queue_t)clientQueue + completion:(MTRDeviceResponseHandler)completion { new NSObjectDataValueCallbackBridge( - clientQueue, completion, ^(chip::Callback::Cancelable * success, chip::Callback::Cancelable * failure) { - auto successFn = chip::Callback::Callback::FromCancelable(success); - auto failureFn = chip::Callback::Callback::FromCancelable(failure); - auto context = successFn->mContext; - auto successCb = successFn->mCall; - auto failureCb = failureFn->mCall; - auto resultArray = [[NSMutableArray alloc] init]; - auto resultSuccess = [[NSMutableArray alloc] init]; - auto resultFailure = [[NSMutableArray alloc] init]; - auto onSuccessCb = [resultArray, resultSuccess](const app::ConcreteCommandPath & commandPath, - const app::StatusIB & status, const NSObjectData & responseData) { - if (responseData.GetDecodedObject()) { - [resultArray addObject:@ { - MTRCommandPathKey : [[MTRCommandPath alloc] initWithPath:commandPath], - MTRDataKey : responseData.GetDecodedObject() - }]; - } else { - [resultArray addObject:@ { MTRCommandPathKey : [[MTRCommandPath alloc] initWithPath:commandPath] }]; - } - if ([resultSuccess count] == 0) { - [resultSuccess addObject:[NSNumber numberWithBool:YES]]; - } - }; + clientQueue, completion, ^(chip::Callback::Cancelable * success, chip::Callback::Cancelable * failure) { + auto successFn = chip::Callback::Callback::FromCancelable(success); + auto failureFn = chip::Callback::Callback::FromCancelable(failure); + auto context = successFn->mContext; + auto successCb = successFn->mCall; + auto failureCb = failureFn->mCall; + auto resultArray = [[NSMutableArray alloc] init]; + auto resultSuccess = [[NSMutableArray alloc] init]; + auto resultFailure = [[NSMutableArray alloc] init]; + auto onSuccessCb = [resultArray, resultSuccess](const app::ConcreteCommandPath & commandPath, + const app::StatusIB & status, const NSObjectData & responseData) { + if (responseData.GetDecodedObject()) { + [resultArray addObject:@ { + MTRCommandPathKey : [[MTRCommandPath alloc] initWithPath:commandPath], + MTRDataKey : responseData.GetDecodedObject() + }]; + } else { + [resultArray addObject:@ { MTRCommandPathKey : [[MTRCommandPath alloc] initWithPath:commandPath] }]; + } + if ([resultSuccess count] == 0) { + [resultSuccess addObject:[NSNumber numberWithBool:YES]]; + } + }; - auto onFailureCb = [resultFailure](CHIP_ERROR aError) { - if ([resultFailure count] == 0) { - [resultFailure addObject:[MTRError errorForCHIPErrorCode:aError]]; - } - }; + auto onFailureCb = [resultFailure](CHIP_ERROR aError) { + if ([resultFailure count] == 0) { + [resultFailure addObject:[MTRError errorForCHIPErrorCode:aError]]; + } + }; - app::CommandPathParams commandPath = { static_cast([endpointId unsignedShortValue]), 0, - static_cast([clusterId unsignedLongValue]), - static_cast([commandId unsignedLongValue]), (app::CommandPathFlags::kEndpointIdValid) - }; - - auto decoder = chip::Platform::MakeUnique( - commandPath.mClusterId, commandPath.mCommandId, onSuccessCb, onFailureCb); - VerifyOrReturnError(decoder != nullptr, CHIP_ERROR_NO_MEMORY); - - auto rawDecoderPtr = decoder.get(); - auto onDoneCb = [rawDecoderPtr, context, successCb, failureCb, resultArray, resultSuccess, resultFailure]( - app::CommandSender * commandSender) { - if ([resultFailure count] > 0 || [resultSuccess count] == 0) { - // Failure - if (failureCb) { - if ([resultFailure count] > 0) { - failureCb(context, [MTRError errorToCHIPErrorCode:resultFailure[0]]); - } else { - failureCb(context, CHIP_ERROR_WRITE_FAILED); + app::CommandPathParams commandPath = { static_cast([endpointId unsignedShortValue]), 0, + static_cast([clusterId unsignedLongValue]), + static_cast([commandId unsignedLongValue]), (app::CommandPathFlags::kEndpointIdValid) }; + + auto decoder = chip::Platform::MakeUnique( + commandPath.mClusterId, commandPath.mCommandId, onSuccessCb, onFailureCb); + VerifyOrReturnError(decoder != nullptr, CHIP_ERROR_NO_MEMORY); + + auto rawDecoderPtr = decoder.get(); + auto onDoneCb = [rawDecoderPtr, context, successCb, failureCb, resultArray, resultSuccess, resultFailure]( + app::CommandSender * commandSender) { + if ([resultFailure count] > 0 || [resultSuccess count] == 0) { + // Failure + if (failureCb) { + if ([resultFailure count] > 0) { + failureCb(context, [MTRError errorToCHIPErrorCode:resultFailure[0]]); + } else { + failureCb(context, CHIP_ERROR_WRITE_FAILED); + } + } + } else { + // Success + if (successCb) { + successCb(context, resultArray); } } - } else { - // Success - if (successCb) { - successCb(context, resultArray); - } - } - chip::Platform::Delete(commandSender); - chip::Platform::Delete(rawDecoderPtr); - }; + chip::Platform::Delete(commandSender); + chip::Platform::Delete(rawDecoderPtr); + }; - decoder->SetOnDoneCallback(onDoneCb); + decoder->SetOnDoneCallback(onDoneCb); - auto commandSender - = chip::Platform::MakeUnique(decoder.get(), [self internalDevice]->GetExchangeManager(), false); - VerifyOrReturnError(commandSender != nullptr, CHIP_ERROR_NO_MEMORY); + auto commandSender + = chip::Platform::MakeUnique(decoder.get(), [self internalDevice]->GetExchangeManager(), false); + VerifyOrReturnError(commandSender != nullptr, CHIP_ERROR_NO_MEMORY); - ReturnErrorOnFailure(commandSender->AddRequestData(commandPath, NSObjectData(commandFields), - (timeoutMs == nil) ? NullOptional : Optional([timeoutMs unsignedShortValue]))); - ReturnErrorOnFailure(commandSender->SendCommandRequest([self internalDevice]->GetSecureSession().Value())); + ReturnErrorOnFailure(commandSender->AddRequestData(commandPath, NSObjectData(commandFields), + (timeoutMs == nil) ? NullOptional : Optional([timeoutMs unsignedShortValue]))); + ReturnErrorOnFailure(commandSender->SendCommandRequest([self internalDevice]->GetSecureSession().Value())); - decoder.release(); - commandSender.release(); - return CHIP_NO_ERROR; - }); + decoder.release(); + commandSender.release(); + return CHIP_NO_ERROR; + }); } - (void)subscribeAttributeWithEndpointId:(NSNumber * _Nullable)endpointId - clusterId:(NSNumber * _Nullable)clusterId - attributeId:(NSNumber * _Nullable)attributeId - minInterval:(NSNumber *)minInterval - maxInterval:(NSNumber *)maxInterval - params:(MTRSubscribeParams * _Nullable)params - clientQueue:(dispatch_queue_t)clientQueue - reportHandler:(MTRDeviceResponseHandler)reportHandler - subscriptionEstablished:(SubscriptionEstablishedHandler)subscriptionEstablishedHandler + clusterId:(NSNumber * _Nullable)clusterId + attributeId:(NSNumber * _Nullable)attributeId + minInterval:(NSNumber *)minInterval + maxInterval:(NSNumber *)maxInterval + params:(MTRSubscribeParams * _Nullable)params + clientQueue:(dispatch_queue_t)clientQueue + reportHandler:(MTRDeviceResponseHandler)reportHandler + subscriptionEstablished:(SubscriptionEstablishedHandler)subscriptionEstablishedHandler { - dispatch_async(DeviceLayer::PlatformMgrImpl().GetWorkQueue(), ^ { + dispatch_async(DeviceLayer::PlatformMgrImpl().GetWorkQueue(), ^{ auto onReportCb = [clientQueue, reportHandler](const app::ConcreteAttributePath & attribPath, const NSObjectData & data) { id valueObject = data.GetDecodedObject(); app::ConcreteAttributePath pathCopy = attribPath; - dispatch_async(clientQueue, ^ { + dispatch_async(clientQueue, ^{ reportHandler( -@[ @ { MTRAttributePathKey : [[MTRAttributePath alloc] initWithPath:pathCopy], MTRDataKey : valueObject } ], - nil); + @[ @ { MTRAttributePathKey : [[MTRAttributePath alloc] initWithPath:pathCopy], MTRDataKey : valueObject } ], + nil); }); }; auto establishedOrFailed = chip::Platform::MakeShared(NO); auto onFailureCb = [establishedOrFailed, clientQueue, subscriptionEstablishedHandler, reportHandler]( - const app::ConcreteAttributePath * attribPath, CHIP_ERROR error) { + const app::ConcreteAttributePath * attribPath, CHIP_ERROR error) { if (!(*establishedOrFailed)) { *establishedOrFailed = YES; if (subscriptionEstablishedHandler) { @@ -1177,7 +1150,7 @@ - (void)subscribeAttributeWithEndpointId:(NSNumber * _Nullable)endpointId } } if (reportHandler) { - dispatch_async(clientQueue, ^ { + dispatch_async(clientQueue, ^{ reportHandler(nil, [MTRError errorForCHIPErrorCode:error]); }); } @@ -1224,16 +1197,16 @@ - (void)subscribeAttributeWithEndpointId:(NSNumber * _Nullable)endpointId }; auto callback = chip::Platform::MakeUnique>( - container.pathParams->mClusterId, container.pathParams->mAttributeId, onReportCb, onFailureCb, onDone, onEstablishedCb); + container.pathParams->mClusterId, container.pathParams->mAttributeId, onReportCb, onFailureCb, onDone, onEstablishedCb); auto readClient = Platform::New(engine, [self internalDevice]->GetExchangeManager(), - callback -> GetBufferedCallback(), chip::app::ReadClient::InteractionType::Subscribe); + callback -> GetBufferedCallback(), chip::app::ReadClient::InteractionType::Subscribe); err = readClient->SendAutoResubscribeRequest(std::move(readParams)); if (err != CHIP_NO_ERROR) { if (reportHandler) { - dispatch_async(clientQueue, ^ { + dispatch_async(clientQueue, ^{ reportHandler(nil, [MTRError errorForCHIPErrorCode:err]); }); } @@ -1320,8 +1293,8 @@ - (instancetype)initWithPath:(const ConcreteDataAttributePath &)path + (instancetype)attributePathWithEndpointId:(NSNumber *)endpoint clusterId:(NSNumber *)clusterId attributeId:(NSNumber *)attributeId { ConcreteDataAttributePath path(static_cast([endpoint unsignedShortValue]), - static_cast([clusterId unsignedLongValue]), - static_cast([attributeId unsignedLongValue])); + static_cast([clusterId unsignedLongValue]), + static_cast([attributeId unsignedLongValue])); return [[MTRAttributePath alloc] initWithPath:path]; } @@ -1341,7 +1314,7 @@ - (instancetype)initWithPath:(const ConcreteEventPath &)path + (instancetype)eventPathWithEndpointId:(NSNumber *)endpoint clusterId:(NSNumber *)clusterId eventId:(NSNumber *)eventId { ConcreteEventPath path(static_cast([endpoint unsignedShortValue]), - static_cast([clusterId unsignedLongValue]), static_cast([eventId unsignedLongValue])); + static_cast([clusterId unsignedLongValue]), static_cast([eventId unsignedLongValue])); return [[MTREventPath alloc] initWithPath:path]; } @@ -1361,7 +1334,7 @@ - (instancetype)initWithPath:(const ConcreteCommandPath &)path + (instancetype)commandPathWithEndpointId:(NSNumber *)endpoint clusterId:(NSNumber *)clusterId commandId:(NSNumber *)commandId { ConcreteCommandPath path(static_cast([endpoint unsignedShortValue]), - static_cast([clusterId unsignedLongValue]), static_cast([commandId unsignedLongValue])); + static_cast([clusterId unsignedLongValue]), static_cast([commandId unsignedLongValue])); return [[MTRCommandPath alloc] initWithPath:path]; } @@ -1381,11 +1354,11 @@ - (instancetype)initWithPath:(const ConcreteDataAttributePath &)path value:(null @implementation MTREventReport - (instancetype)initWithPath:(const ConcreteEventPath &)path - eventNumber:(NSNumber *)eventNumber - priority:(NSNumber *)priority - timestamp:(NSNumber *)timestamp - value:(nullable id)value - error:(nullable NSError *)error + eventNumber:(NSNumber *)eventNumber + priority:(NSNumber *)priority + timestamp:(NSNumber *)timestamp + value:(nullable id)value + error:(nullable NSError *)error { if (self = [super init]) { _path = [[MTREventPath alloc] initWithPath:path]; @@ -1414,20 +1387,18 @@ - (instancetype)initWithPath:(const ConcreteEventPath &)path __block NSArray * eventReports = mEventReports; mEventReports = nil; if (mAttributeReportCallback && attributeReports.count) { - dispatch_async(mQueue, ^ { + dispatch_async(mQueue, ^{ mAttributeReportCallback(attributeReports); }); } if (mEventReportCallback && eventReports.count) { - dispatch_async(mQueue, ^ { + dispatch_async(mQueue, ^{ mEventReportCallback(eventReports); }); } } -void SubscriptionCallback::OnReportEnd() { - ReportData(); -} +void SubscriptionCallback::OnReportEnd() { ReportData(); } void SubscriptionCallback::OnEventData(const EventHeader & aEventHeader, TLV::TLVReader * apData, const StatusIB * apStatus) { @@ -1458,11 +1429,11 @@ - (instancetype)initWithPath:(const ConcreteEventPath &)path } [mEventReports addObject:[[MTREventReport alloc] initWithPath:aEventHeader.mPath - eventNumber:@(aEventHeader.mEventNumber) - priority:@((uint8_t) aEventHeader.mPriorityLevel) - timestamp:@(aEventHeader.mTimestamp.mValue) - value:value - error:error]]; + eventNumber:@(aEventHeader.mEventNumber) + priority:@((uint8_t) aEventHeader.mPriorityLevel) + timestamp:@(aEventHeader.mTimestamp.mValue) + value:value + error:error]]; } void SubscriptionCallback::OnAttributeData( @@ -1524,19 +1495,19 @@ - (instancetype)initWithPath:(const ConcreteEventPath &)path void SubscriptionCallback::OnDeallocatePaths(ReadPrepareParams && aReadPrepareParams) { VerifyOrDie((aReadPrepareParams.mAttributePathParamsListSize == 0 && aReadPrepareParams.mpAttributePathParamsList == nullptr) - || (aReadPrepareParams.mAttributePathParamsListSize == 1 && aReadPrepareParams.mpAttributePathParamsList != nullptr)); + || (aReadPrepareParams.mAttributePathParamsListSize == 1 && aReadPrepareParams.mpAttributePathParamsList != nullptr)); if (aReadPrepareParams.mpAttributePathParamsList) { delete aReadPrepareParams.mpAttributePathParamsList; } VerifyOrDie((aReadPrepareParams.mDataVersionFilterListSize == 0 && aReadPrepareParams.mpDataVersionFilterList == nullptr) - || (aReadPrepareParams.mDataVersionFilterListSize == 1 && aReadPrepareParams.mpDataVersionFilterList != nullptr)); + || (aReadPrepareParams.mDataVersionFilterListSize == 1 && aReadPrepareParams.mpDataVersionFilterList != nullptr)); if (aReadPrepareParams.mpDataVersionFilterList != nullptr) { delete aReadPrepareParams.mpDataVersionFilterList; } VerifyOrDie((aReadPrepareParams.mEventPathParamsListSize == 0 && aReadPrepareParams.mpEventPathParamsList == nullptr) - || (aReadPrepareParams.mEventPathParamsListSize == 1 && aReadPrepareParams.mpEventPathParamsList != nullptr)); + || (aReadPrepareParams.mEventPathParamsListSize == 1 && aReadPrepareParams.mpEventPathParamsList != nullptr)); if (aReadPrepareParams.mpEventPathParamsList) { delete aReadPrepareParams.mpEventPathParamsList; } @@ -1549,13 +1520,9 @@ - (instancetype)initWithPath:(const ConcreteEventPath &)path } } -void SubscriptionCallback::ReportError(CHIP_ERROR err) { - ReportError([MTRError errorForCHIPErrorCode:err]); -} +void SubscriptionCallback::ReportError(CHIP_ERROR err) { ReportError([MTRError errorForCHIPErrorCode:err]); } -void SubscriptionCallback::ReportError(const StatusIB & status) { - ReportError([MTRError errorForIMStatus:status]); -} +void SubscriptionCallback::ReportError(const StatusIB & status) { ReportError([MTRError errorForIMStatus:status]); } void SubscriptionCallback::ReportError(NSError * _Nullable err) { @@ -1576,7 +1543,7 @@ - (instancetype)initWithPath:(const ConcreteEventPath &)path mEventReportCallback = nil; __auto_type onDoneHandler = mOnDoneHandler; mOnDoneHandler = nil; - dispatch_async(mQueue, ^ { + dispatch_async(mQueue, ^{ callback(err); if (onDoneHandler) { onDoneHandler(); diff --git a/src/darwin/Framework/CHIP/MTRCluster.mm b/src/darwin/Framework/CHIP/MTRCluster.mm index 25c882de169785..17d943996bdba8 100644 --- a/src/darwin/Framework/CHIP/MTRCluster.mm +++ b/src/darwin/Framework/CHIP/MTRCluster.mm @@ -38,7 +38,7 @@ - (instancetype)initWithQueue:(dispatch_queue_t)queue - (chip::CharSpan)asCharSpan:(NSString *)value { return chip::CharSpan(static_cast([value dataUsingEncoding:NSUTF8StringEncoding].bytes), - [value lengthOfBytesUsingEncoding:NSUTF8StringEncoding]); + [value lengthOfBytesUsingEncoding:NSUTF8StringEncoding]); } @end diff --git a/src/darwin/Framework/CHIP/MTRDeviceConnectionBridge.mm b/src/darwin/Framework/CHIP/MTRDeviceConnectionBridge.mm index ff139b027f5df3..2ad2c2f6c08f83 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceConnectionBridge.mm +++ b/src/darwin/Framework/CHIP/MTRDeviceConnectionBridge.mm @@ -23,7 +23,7 @@ { auto * object = static_cast(context); MTRBaseDevice * chipDevice = [[MTRBaseDevice alloc] initWithDevice:device]; - dispatch_async(object->mQueue, ^ { + dispatch_async(object->mQueue, ^{ object->mCompletionHandler(chipDevice, nil); object->Release(); }); @@ -32,7 +32,7 @@ void MTRDeviceConnectionBridge::OnConnectionFailure(void * context, chip::PeerId peerId, CHIP_ERROR error) { auto * object = static_cast(context); - dispatch_async(object->mQueue, ^ { + dispatch_async(object->mQueue, ^{ object->mCompletionHandler(nil, [MTRError errorForCHIPErrorCode:error]); object->Release(); }); diff --git a/src/darwin/Framework/CHIP/MTRDeviceController.mm b/src/darwin/Framework/CHIP/MTRDeviceController.mm index 3790def9600809..a123b251f00dd5 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceController.mm +++ b/src/darwin/Framework/CHIP/MTRDeviceController.mm @@ -161,7 +161,7 @@ - (BOOL)startup:(MTRDeviceControllerStartupParamsInternal *)startupParams return NO; } - dispatch_sync(_chipWorkQueue, ^ { + dispatch_sync(_chipWorkQueue, ^{ if ([self isRunning]) { return; } @@ -183,8 +183,8 @@ - (BOOL)startup:(MTRDeviceControllerStartupParamsInternal *)startupParams } if (startupParams.operationalCertificate != nil && startupParams.operationalKeypair == nil - && (!startupParams.fabricIndex.HasValue() - || !startupParams.keystore->HasOpKeypairForFabric(startupParams.fabricIndex.Value()))) { + && (!startupParams.fabricIndex.HasValue() + || !startupParams.keystore->HasOpKeypairForFabric(startupParams.fabricIndex.Value()))) { MTR_LOG_ERROR("Have no operational keypair for our operational certificate"); return; } @@ -201,7 +201,7 @@ - (BOOL)startup:(MTRDeviceControllerStartupParamsInternal *)startupParams signingKeypair = &_signingKeypairBridge; } errorCode = _operationalCredentialsDelegate->Init(_factory.storageDelegateBridge, signingKeypair, startupParams.ipk, - startupParams.rootCertificate, startupParams.intermediateCertificate); + startupParams.rootCertificate, startupParams.intermediateCertificate); if ([self checkForStartError:(CHIP_NO_ERROR == errorCode) logMsg:kErrorOperationalCredentialsInit]) { return; } @@ -241,7 +241,7 @@ - (BOOL)startup:(MTRDeviceControllerStartupParamsInternal *)startupParams if (commissionerParams.operationalKeypair != nullptr) { errorCode = _operationalCredentialsDelegate->GenerateNOC([startupParams.nodeId unsignedLongLongValue], - startupParams.fabricId, chip::kUndefinedCATs, commissionerParams.operationalKeypair->Pubkey(), noc); + startupParams.fabricId, chip::kUndefinedCATs, commissionerParams.operationalKeypair->Pubkey(), noc); if ([self checkForStartError:(CHIP_NO_ERROR == errorCode) logMsg:kErrorGenerateNOC]) { return; @@ -262,7 +262,7 @@ - (BOOL)startup:(MTRDeviceControllerStartupParamsInternal *)startupParams } errorCode = _operationalCredentialsDelegate->GenerateNOC( - [startupParams.nodeId unsignedLongLongValue], startupParams.fabricId, chip::kUndefinedCATs, pubKey, noc); + [startupParams.nodeId unsignedLongLongValue], startupParams.fabricId, chip::kUndefinedCATs, pubKey, noc); if ([self checkForStartError:(CHIP_NO_ERROR == errorCode) logMsg:kErrorGenerateNOC]) { return; @@ -290,7 +290,7 @@ - (BOOL)startup:(MTRDeviceControllerStartupParamsInternal *)startupParams } errorCode = chip::Credentials::SetSingleIpkEpochKey( - _factory.groupData, fabricIdx, _operationalCredentialsDelegate->GetIPK(), compressedId); + _factory.groupData, fabricIdx, _operationalCredentialsDelegate->GetIPK(), compressedId); if ([self checkForStartError:(CHIP_NO_ERROR == errorCode) logMsg:kErrorIPKInit]) { return; } @@ -312,7 +312,7 @@ - (NSNumber *)controllerNodeId return nil; } __block NSNumber * nodeID; - dispatch_sync(_chipWorkQueue, ^ { + dispatch_sync(_chipWorkQueue, ^{ if (![self isRunning]) { MTR_LOG_ERROR("A controller has no node id if it has not been started"); nodeID = nil; @@ -324,9 +324,9 @@ - (NSNumber *)controllerNodeId } - (BOOL)pairDevice:(uint64_t)deviceID - discriminator:(uint16_t)discriminator - setupPINCode:(uint32_t)setupPINCode - error:(NSError * __autoreleasing *)error + discriminator:(uint16_t)discriminator + setupPINCode:(uint32_t)setupPINCode + error:(NSError * __autoreleasing *)error { __block CHIP_ERROR errorCode = CHIP_ERROR_INCORRECT_STATE; __block BOOL success = NO; @@ -334,7 +334,7 @@ - (BOOL)pairDevice:(uint64_t)deviceID success = ![self checkForError:errorCode logMsg:kErrorNotRunning error:error]; return success; } - dispatch_sync(_chipWorkQueue, ^ { + dispatch_sync(_chipWorkQueue, ^{ std::string manualPairingCode; chip::SetupPayload payload; payload.discriminator = discriminator; @@ -356,10 +356,10 @@ - (BOOL)pairDevice:(uint64_t)deviceID } - (BOOL)pairDevice:(uint64_t)deviceID - address:(NSString *)address - port:(uint16_t)port - setupPINCode:(uint32_t)setupPINCode - error:(NSError * __autoreleasing *)error + address:(NSString *)address + port:(uint16_t)port + setupPINCode:(uint32_t)setupPINCode + error:(NSError * __autoreleasing *)error { __block CHIP_ERROR errorCode = CHIP_ERROR_INCORRECT_STATE; __block BOOL success = NO; @@ -367,7 +367,7 @@ - (BOOL)pairDevice:(uint64_t)deviceID success = ![self checkForError:errorCode logMsg:kErrorNotRunning error:error]; return success; } - dispatch_sync(_chipWorkQueue, ^ { + dispatch_sync(_chipWorkQueue, ^{ chip::Inet::IPAddress addr; chip::Inet::IPAddress::FromString([address UTF8String], addr); chip::Transport::PeerAddress peerAddress = chip::Transport::PeerAddress::UDP(addr, port); @@ -391,7 +391,7 @@ - (BOOL)pairDevice:(uint64_t)deviceID onboardingPayload:(NSString *)onboardingPa success = ![self checkForError:errorCode logMsg:kErrorNotRunning error:error]; return success; } - dispatch_sync(_chipWorkQueue, ^ { + dispatch_sync(_chipWorkQueue, ^{ if ([self isRunning]) { _operationalCredentialsDelegate->SetDeviceID(deviceID); errorCode = self.cppCommissioner->EstablishPASEConnection(deviceID, [onboardingPayload UTF8String]); @@ -402,8 +402,8 @@ - (BOOL)pairDevice:(uint64_t)deviceID onboardingPayload:(NSString *)onboardingPa } - (BOOL)commissionDevice:(uint64_t)deviceId - commissioningParams:(MTRCommissioningParameters *)commissioningParams - error:(NSError * __autoreleasing *)error + commissioningParams:(MTRCommissioningParameters *)commissioningParams + error:(NSError * __autoreleasing *)error { __block CHIP_ERROR errorCode = CHIP_ERROR_INCORRECT_STATE; __block BOOL success = NO; @@ -411,7 +411,7 @@ - (BOOL)commissionDevice:(uint64_t)deviceId success = ![self checkForError:errorCode logMsg:kErrorNotRunning error:error]; return success; } - dispatch_sync(_chipWorkQueue, ^ { + dispatch_sync(_chipWorkQueue, ^{ if ([self isRunning]) { chip::Controller::CommissioningParameters params; if (commissioningParams.CSRNonce) { @@ -420,11 +420,11 @@ - (BOOL)commissionDevice:(uint64_t)deviceId } if (commissioningParams.attestationNonce) { params.SetAttestationNonce(chip::ByteSpan( - (uint8_t *) commissioningParams.attestationNonce.bytes, commissioningParams.attestationNonce.length)); + (uint8_t *) commissioningParams.attestationNonce.bytes, commissioningParams.attestationNonce.length)); } if (commissioningParams.threadOperationalDataset) { params.SetThreadOperationalDataset(chip::ByteSpan((uint8_t *) commissioningParams.threadOperationalDataset.bytes, - commissioningParams.threadOperationalDataset.length)); + commissioningParams.threadOperationalDataset.length)); } if (commissioningParams.wifiSSID && commissioningParams.wifiCredentials) { chip::ByteSpan ssid((uint8_t *) commissioningParams.wifiSSID.bytes, commissioningParams.wifiSSID.length); @@ -439,7 +439,7 @@ - (BOOL)commissionDevice:(uint64_t)deviceId chip::Optional timeoutSecs; if (commissioningParams.failSafeExpiryTimeoutSecs) { timeoutSecs = chip::MakeOptional( - static_cast([commissioningParams.failSafeExpiryTimeoutSecs unsignedIntValue])); + static_cast([commissioningParams.failSafeExpiryTimeoutSecs unsignedIntValue])); } _deviceAttestationDelegateBridge = new MTRDeviceAttestationDelegateBridge( self, commissioningParams.deviceAttestationDelegate, _chipWorkQueue, timeoutSecs); @@ -455,8 +455,8 @@ - (BOOL)commissionDevice:(uint64_t)deviceId } - (BOOL)continueCommissioningDevice:(void *)device - ignoreAttestationFailure:(BOOL)ignoreAttestationFailure - error:(NSError * __autoreleasing *)error + ignoreAttestationFailure:(BOOL)ignoreAttestationFailure + error:(NSError * __autoreleasing *)error { __block CHIP_ERROR errorCode = CHIP_ERROR_INCORRECT_STATE; __block BOOL success = NO; @@ -464,15 +464,15 @@ - (BOOL)continueCommissioningDevice:(void *)device success = ![self checkForError:errorCode logMsg:kErrorNotRunning error:error]; return success; } - dispatch_sync(_chipWorkQueue, ^ { + dispatch_sync(_chipWorkQueue, ^{ if ([self isRunning]) { auto lastAttestationResult = _deviceAttestationDelegateBridge - ? _deviceAttestationDelegateBridge->attestationVerificationResult() - : chip::Credentials::AttestationVerificationResult::kSuccess; + ? _deviceAttestationDelegateBridge->attestationVerificationResult() + : chip::Credentials::AttestationVerificationResult::kSuccess; chip::DeviceProxy * deviceProxy = static_cast(device); errorCode = self.cppCommissioner->ContinueCommissioningAfterDeviceAttestationFailure(deviceProxy, - ignoreAttestationFailure ? chip::Credentials::AttestationVerificationResult::kSuccess : lastAttestationResult); + ignoreAttestationFailure ? chip::Credentials::AttestationVerificationResult::kSuccess : lastAttestationResult); } success = ![self checkForError:errorCode logMsg:kErrorPairDevice error:error]; }); @@ -487,7 +487,7 @@ - (BOOL)stopDevicePairing:(uint64_t)deviceID error:(NSError * __autoreleasing *) success = ![self checkForError:errorCode logMsg:kErrorNotRunning error:error]; return success; } - dispatch_sync(_chipWorkQueue, ^ { + dispatch_sync(_chipWorkQueue, ^{ if ([self isRunning]) { _operationalCredentialsDelegate->ResetDeviceID(); errorCode = self.cppCommissioner->StopPairing(deviceID); @@ -523,13 +523,13 @@ - (BOOL)getDevice:(uint64_t)deviceID queue:(dispatch_queue_t)queue completionHan if (![self isRunning]) { NSError * error; [self checkForError:errorCode logMsg:kErrorNotRunning error:&error]; - dispatch_async(queue, ^ { + dispatch_async(queue, ^{ completionHandler(nil, error); }); return NO; } - dispatch_async(_chipWorkQueue, ^ { + dispatch_async(_chipWorkQueue, ^{ if ([self isRunning]) { MTRDeviceConnectionBridge * connectionBridge = new MTRDeviceConnectionBridge(completionHandler, queue); errorCode = connectionBridge->connect(self->_cppCommissioner, deviceID); @@ -559,7 +559,7 @@ - (BOOL)openPairingWindow:(uint64_t)deviceID duration:(NSUInteger)duration error } err = chip::Controller::AutoCommissioningWindowOpener::OpenBasicCommissioningWindow( - self.cppCommissioner, deviceID, chip::System::Clock::Seconds16(static_cast(duration))); + self.cppCommissioner, deviceID, chip::System::Clock::Seconds16(static_cast(duration))); if (err != CHIP_NO_ERROR) { MTR_LOG_ERROR("Error(%s): Open Pairing Window failed", chip::ErrorStr(err)); @@ -573,10 +573,10 @@ - (BOOL)openPairingWindow:(uint64_t)deviceID duration:(NSUInteger)duration error } - (NSString *)openPairingWindowWithPIN:(uint64_t)deviceID - duration:(NSUInteger)duration - discriminator:(NSUInteger)discriminator - setupPIN:(NSUInteger)setupPIN - error:(NSError * __autoreleasing *)error + duration:(NSUInteger)duration + discriminator:(NSUInteger)discriminator + setupPIN:(NSUInteger)setupPIN + error:(NSError * __autoreleasing *)error { CHIP_ERROR err = CHIP_NO_ERROR; @@ -600,9 +600,9 @@ - (NSString *)openPairingWindowWithPIN:(uint64_t)deviceID chip::SetupPayload setupPayload; err = chip::Controller::AutoCommissioningWindowOpener::OpenCommissioningWindow(self.cppCommissioner, deviceID, - chip::System::Clock::Seconds16(static_cast(duration)), chip::Crypto::kSpake2p_Min_PBKDF_Iterations, - static_cast(discriminator), chip::MakeOptional(static_cast(setupPIN)), chip::NullOptional, - setupPayload); + chip::System::Clock::Seconds16(static_cast(duration)), chip::Crypto::kSpake2p_Min_PBKDF_Iterations, + static_cast(discriminator), chip::MakeOptional(static_cast(setupPIN)), chip::NullOptional, + setupPayload); if (err != CHIP_NO_ERROR) { MTR_LOG_ERROR("Error(%s): Open Pairing Window failed", chip::ErrorStr(err)); @@ -627,7 +627,7 @@ - (NSString *)openPairingWindowWithPIN:(uint64_t)deviceID - (void)setPairingDelegate:(id)delegate queue:(dispatch_queue_t)queue { - dispatch_async(_chipWorkQueue, ^ { + dispatch_async(_chipWorkQueue, ^{ self->_pairingDelegateBridge->setDelegate(delegate, queue); }); } @@ -709,8 +709,8 @@ @implementation MTRDeviceController (InternalMethods) } - (CHIP_ERROR)isRunningOnFabric:(chip::FabricTable *)fabricTable - fabricIndex:(chip::FabricIndex)fabricIndex - isRunning:(BOOL *)isRunning + fabricIndex:(chip::FabricIndex)fabricIndex + isRunning:(BOOL *)isRunning { if (![self isRunning]) { *isRunning = NO;