From 8ea423ae5981596e67304ebc7b2e5072b48ba8c8 Mon Sep 17 00:00:00 2001 From: Kevin Schoedel <67607049+kpschoedel@users.noreply.github.com> Date: Thu, 11 Mar 2021 11:49:18 -0500 Subject: [PATCH] #### Problem (#5319) - `BitFlags.h` has relatively unsafe deprecated functions. - Some bit flags use `enum` rather than type-safe `enum class`. #### Summary of Changes - Removed deprecated `SetFlags()`, `ClearFlags()`, and `GetFlags()`, replacing uses with `BitFlags`. - BitFlags.h changes: - Default to use `std::underlying_type` rather than requiring it as a template parameter. - Added `BitFlags` operations to reduce uses of type-unsafe `Raw()` and `SetRaw()`: - Multi-argument constructors. - `operator FlagsEnum()`. - `ClearAll()`. - `HasAny()` and `HasAll()`, following the pattern of the existing `HasOnly()`. - Binary `&`. - Converted various bit flag types from `enum` to `enum class`: - BLEEndPoint::ConnectionStateFlags - BLEEndPoint::TimerStateFlags - BLEManagerImpl::Flags - Command::CommandPathFlags - Encoding::HexFlags - GenericConfigurationManagerImpl::Flags - GenericConnectivityManagerImpl_Thread::Flags - GenericConnectivityManagerImpl_WiFi::ConnectivityFlags - bdx::RangeControlFlags - bdx::StatusCode - bdx::TransferControlFlags - bdx::TransferRole Reland of 4b8d5582 (#5232) to a logic error in `*/BLEManagerImpl.cpp` and a large accidental deletion in `K32W/BLEManagerImpl.cpp`. --- src/app/Command.cpp | 18 +- src/app/Command.h | 25 +- .../tests/integration/chip_im_initiator.cpp | 4 +- .../tests/integration/chip_im_responder.cpp | 4 +- .../util/ember-compatibility-functions.cpp | 2 +- .../templates/chip/CHIPClusters-src.zapt | 2 +- src/ble/BLEEndPoint.cpp | 107 +++--- src/ble/BLEEndPoint.h | 36 +- src/ble/BtpEngine.cpp | 47 +-- src/ble/BtpEngine.h | 20 +- src/controller/CHIPClusters.cpp | 186 +++++----- src/credentials/CHIPCert.cpp | 39 +- src/credentials/CHIPCert.h | 64 ++-- src/credentials/CHIPCertFromX509.cpp | 3 +- src/credentials/CHIPCertToX509.cpp | 19 +- .../tests/CHIPCert_test_vectors.cpp | 6 +- src/credentials/tests/CHIPCert_test_vectors.h | 7 +- src/credentials/tests/TestChipCert.cpp | 114 +++--- .../GenericConfigurationManagerImpl.cpp | 47 ++- .../GenericConfigurationManagerImpl.h | 18 +- .../GenericConnectivityManagerImpl_Thread.cpp | 14 +- .../GenericConnectivityManagerImpl_Thread.h | 19 +- .../GenericConnectivityManagerImpl_WiFi.h | 10 +- src/lib/support/BitFlags.h | 233 ++++++++---- src/lib/support/BytesToHex.cpp | 6 +- src/lib/support/BytesToHex.h | 6 +- src/messaging/ExchangeContext.h | 4 +- src/messaging/Flags.h | 6 +- src/messaging/ReliableMessageContext.cpp | 4 +- src/messaging/ReliableMessageContext.h | 6 +- src/platform/EFR32/BLEManagerImpl.cpp | 39 +- src/platform/EFR32/BLEManagerImpl.h | 22 +- src/platform/ESP32/BLEManagerImpl.h | 36 +- .../ESP32/ConnectivityManagerImpl.cpp | 16 +- src/platform/ESP32/ConnectivityManagerImpl.h | 10 +- .../ESP32/bluedroid/BLEManagerImpl.cpp | 114 +++--- src/platform/ESP32/nimble/BLEManagerImpl.cpp | 74 ++-- src/platform/K32W/BLEManagerImpl.cpp | 56 ++- src/platform/K32W/BLEManagerImpl.h | 17 +- src/platform/Linux/BLEManagerImpl.cpp | 71 ++-- src/platform/Linux/BLEManagerImpl.h | 32 +- .../Linux/ConnectivityManagerImpl.cpp | 15 +- src/platform/Linux/ConnectivityManagerImpl.h | 4 +- src/platform/Linux/bluez/Helper.cpp | 2 +- src/platform/Zephyr/BLEManagerImpl.cpp | 42 +-- src/platform/Zephyr/BLEManagerImpl.h | 22 +- src/platform/cc13x2_26x2/BLEManagerImpl.cpp | 55 ++- src/platform/qpg6100/BLEManagerImpl.cpp | 52 +-- src/platform/qpg6100/BLEManagerImpl.h | 25 +- src/protocols/bdx/BdxMessages.cpp | 77 ++-- src/protocols/bdx/BdxMessages.h | 56 +-- src/protocols/bdx/BdxTransferSession.cpp | 341 +++++++++--------- src/protocols/bdx/BdxTransferSession.h | 30 +- src/protocols/bdx/tests/TestBdxMessages.cpp | 9 +- .../bdx/tests/TestBdxTransferSession.cpp | 180 ++++----- .../AdditionalDataPayloadGenerator.cpp | 2 +- .../AdditionalDataPayloadGenerator.h | 2 +- src/transport/raw/MessageHeader.cpp | 8 +- src/transport/raw/MessageHeader.h | 8 +- 59 files changed, 1293 insertions(+), 1200 deletions(-) diff --git a/src/app/Command.cpp b/src/app/Command.cpp index 110999635d5cf7..432e39b7075070 100644 --- a/src/app/Command.cpp +++ b/src/app/Command.cpp @@ -152,18 +152,10 @@ chip::TLV::TLVWriter & Command::CreateCommandDataElementTLVWriter() return mCommandDataWriter; } -CHIP_ERROR Command::AddCommand(chip::EndpointId aEndpintId, chip::GroupId aGroupId, chip::ClusterId aClusterId, - chip::CommandId aCommandId, uint8_t aFlags) +CHIP_ERROR Command::AddCommand(chip::EndpointId aEndpointId, chip::GroupId aGroupId, chip::ClusterId aClusterId, + chip::CommandId aCommandId, BitFlags aFlags) { - CommandParams commandParams; - - memset(&commandParams, 0, sizeof(CommandParams)); - - commandParams.EndpointId = aEndpintId; - commandParams.GroupId = aGroupId; - commandParams.ClusterId = aClusterId; - commandParams.CommandId = aCommandId; - commandParams.Flags = aFlags; + CommandParams commandParams(aEndpointId, aGroupId, aClusterId, aCommandId, aFlags); return AddCommand(commandParams); } @@ -191,12 +183,12 @@ CHIP_ERROR Command::AddCommand(CommandParams & aCommandParams) CommandDataElement::Builder commandDataElement = mInvokeCommandBuilder.GetCommandListBuilder().CreateCommandDataElementBuilder(); CommandPath::Builder commandPath = commandDataElement.CreateCommandPathBuilder(); - if (aCommandParams.Flags & kCommandPathFlag_EndpointIdValid) + if (aCommandParams.Flags.Has(CommandPathFlags::kEndpointIdValid)) { commandPath.EndpointId(aCommandParams.EndpointId); } - if (aCommandParams.Flags & kCommandPathFlag_GroupIdValid) + if (aCommandParams.Flags.Has(CommandPathFlags::kGroupIdValid)) { commandPath.GroupId(aCommandParams.GroupId); } diff --git a/src/app/Command.h b/src/app/Command.h index 19ebc7d0e43bd6..5103e05514831a 100644 --- a/src/app/Command.h +++ b/src/app/Command.h @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2020-2021 Project CHIP Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -29,6 +29,7 @@ #include #include #include +#include #include #include #include @@ -59,25 +60,31 @@ class Command Sending, //< The invoke command message has sent out the invoke command }; + enum class CommandPathFlags : uint8_t + { + kEndpointIdValid = 0x01, /**< Set when the EndpointId field is valid */ + kGroupIdValid = 0x02, /**< Set when the GroupId field is valid */ + }; + /** * Encapsulates arguments to be passed into SendCommand(). * */ struct CommandParams { + CommandParams(chip::EndpointId endpointId, chip::GroupId groupId, chip::ClusterId clusterId, chip::CommandId commandId, + const BitFlags & flags) : + EndpointId(endpointId), + GroupId(groupId), ClusterId(clusterId), CommandId(commandId), Flags(flags) + {} + chip::EndpointId EndpointId; chip::GroupId GroupId; chip::ClusterId ClusterId; chip::CommandId CommandId; - uint8_t Flags; + BitFlags Flags; }; - enum CommandPathFlags - { - kCommandPathFlag_EndpointIdValid = 0x0001, /**< Set when the EndpointId field is valid */ - kCommandPathFlag_GroupIdValid = 0x0002, /**< Set when the GroupId field is valid */ - } CommandPathFlags; - /** * Initialize the Command object. Within the lifetime * of this instance, this method is invoked once after object @@ -110,7 +117,7 @@ class Command chip::TLV::TLVWriter & CreateCommandDataElementTLVWriter(); CHIP_ERROR AddCommand(chip::EndpointId aEndpintId, chip::GroupId aGroupId, chip::ClusterId aClusterId, - chip::CommandId aCommandId, uint8_t Flags); + chip::CommandId aCommandId, BitFlags Flags); CHIP_ERROR AddCommand(CommandParams & aCommandParams); CHIP_ERROR AddStatusCode(const uint16_t aGeneralCode, const uint32_t aProtocolId, const uint16_t aProtocolCode, const chip::ClusterId aClusterId); diff --git a/src/app/tests/integration/chip_im_initiator.cpp b/src/app/tests/integration/chip_im_initiator.cpp index c35de4bc95a86e..a536fa9e263ca9 100644 --- a/src/app/tests/integration/chip_im_initiator.cpp +++ b/src/app/tests/integration/chip_im_initiator.cpp @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2020-2021 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. @@ -90,7 +90,7 @@ CHIP_ERROR SendCommandRequest(void) kTestGroupId, // GroupId kTestClusterId, // ClusterId kTestCommandId, // CommandId - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; // Add command data here diff --git a/src/app/tests/integration/chip_im_responder.cpp b/src/app/tests/integration/chip_im_responder.cpp index bde7daf7610907..f4f3d3dfcbb57f 100644 --- a/src/app/tests/integration/chip_im_responder.cpp +++ b/src/app/tests/integration/chip_im_responder.cpp @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2020-2021 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. @@ -60,7 +60,7 @@ void DispatchSingleClusterCommand(chip::ClusterId aClusterId, chip::CommandId aC kTestGroupId, // GroupId kTestClusterId, // ClusterId kTestCommandId, // CommandId - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; // Add command data here diff --git a/src/app/util/ember-compatibility-functions.cpp b/src/app/util/ember-compatibility-functions.cpp index 017d7a0d5df228..981ec253e6fffc 100644 --- a/src/app/util/ember-compatibility-functions.cpp +++ b/src/app/util/ember-compatibility-functions.cpp @@ -73,7 +73,7 @@ bool IMEmberAfSendDefaultResponseWithCallback(EmberAfStatus status) 0, // GroupId imCompatibilityEmberApsFrame.clusterId, imCompatibilityEmberAfCluster.commandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; chip::TLV::TLVType dummyType = chip::TLV::kTLVType_NotSpecified; chip::TLV::TLVWriter writer = currentCommandObject->CreateCommandDataElementTLVWriter(); diff --git a/src/app/zap-templates/templates/chip/CHIPClusters-src.zapt b/src/app/zap-templates/templates/chip/CHIPClusters-src.zapt index bcfa34eca00cb4..b06cb3c7832109 100644 --- a/src/app/zap-templates/templates/chip/CHIPClusters-src.zapt +++ b/src/app/zap-templates/templates/chip/CHIPClusters-src.zapt @@ -26,7 +26,7 @@ CHIP_ERROR {{asCamelCased clusterName false}}Cluster::{{asCamelCased name false} (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, k{{asCamelCased name false}}CommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); diff --git a/src/ble/BLEEndPoint.cpp b/src/ble/BLEEndPoint.cpp index 6abdb70877ffe8..aaf0d52c7aec3f 100644 --- a/src/ble/BLEEndPoint.cpp +++ b/src/ble/BLEEndPoint.cpp @@ -272,7 +272,7 @@ void BLEEndPoint::HandleSubscribeReceived() void BLEEndPoint::HandleSubscribeComplete() { ChipLogProgress(Ble, "subscribe complete, ep = %p", this); - SetFlag(mConnStateFlags, kConnState_GattOperationInFlight, false); + mConnStateFlags.Clear(ConnectionStateFlag::kGattOperationInFlight); BLE_ERROR err = DriveSending(); @@ -295,7 +295,7 @@ bool BLEEndPoint::IsConnected(uint8_t state) const bool BLEEndPoint::IsUnsubscribePending() const { - return (GetFlag(mTimerStateFlags, kTimerState_UnsubscribeTimerRunning)); + return mTimerStateFlags.Has(TimerStateFlag::kUnsubscribeTimerRunning); } void BLEEndPoint::Abort() @@ -392,7 +392,7 @@ void BLEEndPoint::FinalizeClose(uint8_t oldState, uint8_t flags, BLE_ERROR err) } else // Otherwise, try to signal close to remote device before end point releases BLE connection and frees itself. { - if (mRole == kBleRole_Central && GetFlag(mConnStateFlags, kConnState_DidBeginSubscribe)) + if (mRole == kBleRole_Central && mConnStateFlags.Has(ConnectionStateFlag::kDidBeginSubscribe)) { // Cancel send and receive-ack timers, if running. StopAckReceivedTimer(); @@ -420,10 +420,10 @@ void BLEEndPoint::FinalizeClose(uint8_t oldState, uint8_t flags, BLE_ERROR err) } // Mark unsubscribe GATT operation in progress. - SetFlag(mConnStateFlags, kConnState_GattOperationInFlight, true); + mConnStateFlags.Set(ConnectionStateFlag::kGattOperationInFlight); } } - else // mRole == kBleRole_Peripheral, OR GetFlag(mTimerStateFlags, kConnState_DidBeginSubscribe) == false... + else // mRole == kBleRole_Peripheral, OR mTimerStateFlags.Has(ConnectionStateFlag::kDidBeginSubscribe) == false... { Free(); } @@ -456,7 +456,7 @@ void BLEEndPoint::ReleaseBleConnection() { if (mConnObj != BLE_CONNECTION_UNINITIALIZED) { - if (GetFlag(mConnStateFlags, kConnState_AutoClose)) + if (mConnStateFlags.Has(ConnectionStateFlag::kAutoClose)) { ChipLogProgress(Ble, "Auto-closing end point's BLE connection."); mBle->mPlatformDelegate->CloseConnection(mConnObj); @@ -562,11 +562,10 @@ BLE_ERROR BLEEndPoint::Init(BleLayer * bleLayer, BLE_CONNECTION_OBJECT connObj, mRefCount = 1; // BLEEndPoint data members: - mConnObj = connObj; - mRole = role; - mConnStateFlags = 0; - mTimerStateFlags = 0; - SetFlag(mConnStateFlags, kConnState_AutoClose, autoClose); + mConnObj = connObj; + mRole = role; + mTimerStateFlags.ClearAll(); + mConnStateFlags.ClearAll().Set(ConnectionStateFlag::kAutoClose, autoClose); mLocalReceiveWindowSize = 0; mRemoteReceiveWindowSize = 0; mReceiveWindowMaxSize = 0; @@ -686,7 +685,7 @@ BLE_ERROR BLEEndPoint::Send(PacketBufferHandle data) bool BLEEndPoint::PrepareNextFragment(PacketBufferHandle && data, bool & sentAck) { // If we have a pending fragment acknowledgement to send, piggyback it on the fragment we're about to transmit. - if (GetFlag(mTimerStateFlags, kTimerState_SendAckTimerRunning)) + if (mTimerStateFlags.Has(TimerStateFlag::kSendAckTimerRunning)) { // Reset local receive window counter. mLocalReceiveWindowSize = mReceiveWindowMaxSize; @@ -818,10 +817,10 @@ BLE_ERROR BLEEndPoint::HandleHandshakeConfirmationReceived() err = BLE_ERROR_GATT_SUBSCRIBE_FAILED); // We just sent a GATT subscribe request, so make sure to attempt unsubscribe on close. - SetFlag(mConnStateFlags, kConnState_DidBeginSubscribe, true); + mConnStateFlags.Set(ConnectionStateFlag::kDidBeginSubscribe); // Mark GATT operation in progress for subscribe request. - SetFlag(mConnStateFlags, kConnState_GattOperationInFlight, true); + mConnStateFlags.Set(ConnectionStateFlag::kGattOperationInFlight); } else // (mRole == kBleRole_Peripheral), verified on Init { @@ -882,12 +881,12 @@ BLE_ERROR BLEEndPoint::HandleFragmentConfirmationReceived() // TODO Packet buffer high water mark optimization: if ack pending, but fragmenter state == complete, free fragmenter's // tx buf before sending ack. - if (GetFlag(mConnStateFlags, kConnState_StandAloneAckInFlight)) + if (mConnStateFlags.Has(ConnectionStateFlag::kStandAloneAckInFlight)) { // If confirmation was received for stand-alone ack, free its tx buffer. mAckToSend = nullptr; - SetFlag(mConnStateFlags, kConnState_StandAloneAckInFlight, false); + mConnStateFlags.Clear(ConnectionStateFlag::kStandAloneAckInFlight); } // If local receive window size has shrunk to or below immediate ack threshold, AND a message fragment is not @@ -922,12 +921,12 @@ BLE_ERROR BLEEndPoint::HandleGattSendConfirmationReceived() ChipLogDebugBleEndPoint(Ble, "entered HandleGattSendConfirmationReceived"); // Mark outstanding GATT operation as finished. - SetFlag(mConnStateFlags, kConnState_GattOperationInFlight, false); + mConnStateFlags.Clear(ConnectionStateFlag::kGattOperationInFlight); // If confirmation was for outbound portion of BTP connect handshake... - if (!GetFlag(mConnStateFlags, kConnState_CapabilitiesConfReceived)) + if (!mConnStateFlags.Has(ConnectionStateFlag::kCapabilitiesConfReceived)) { - SetFlag(mConnStateFlags, kConnState_CapabilitiesConfReceived, true); + mConnStateFlags.Set(ConnectionStateFlag::kCapabilitiesConfReceived); return HandleHandshakeConfirmationReceived(); } @@ -970,7 +969,7 @@ BLE_ERROR BLEEndPoint::DoSendStandAloneAck() mLocalReceiveWindowSize = mReceiveWindowMaxSize; ChipLogDebugBleEndPoint(Ble, "reset local rx window on stand-alone ack tx, size = %u", mLocalReceiveWindowSize); - SetFlag(mConnStateFlags, kConnState_StandAloneAckInFlight, true); + mConnStateFlags.Set(ConnectionStateFlag::kStandAloneAckInFlight); // Start ack received timer, if it's not already running. err = StartAckReceivedTimer(); @@ -989,12 +988,12 @@ BLE_ERROR BLEEndPoint::DriveSending() // If receiver's window is almost closed and we don't have an ack to send, OR we do have an ack to send but // receiver's window is completely empty, OR another GATT operation is in flight, awaiting confirmation... if ((mRemoteReceiveWindowSize <= BTP_WINDOW_NO_ACK_SEND_THRESHOLD && - !GetFlag(mTimerStateFlags, kTimerState_SendAckTimerRunning) && mAckToSend.IsNull()) || - (mRemoteReceiveWindowSize == 0) || (GetFlag(mConnStateFlags, kConnState_GattOperationInFlight))) + !mTimerStateFlags.Has(TimerStateFlag::kSendAckTimerRunning) && mAckToSend.IsNull()) || + (mRemoteReceiveWindowSize == 0) || (mConnStateFlags.Has(ConnectionStateFlag::kGattOperationInFlight))) { #ifdef CHIP_BLE_END_POINT_DEBUG_LOGGING_ENABLED if (mRemoteReceiveWindowSize <= BTP_WINDOW_NO_ACK_SEND_THRESHOLD && - !GetFlag(mTimerStateFlags, kTimerState_SendAckTimerRunning) && mAckToSend == NULL) + !mTimerStateFlags.Has(TimerStateFlag::kSendAckTimerRunning) && mAckToSend == NULL) { ChipLogDebugBleEndPoint(Ble, "NO SEND: receive window almost closed, and no ack to send"); } @@ -1004,7 +1003,7 @@ BLE_ERROR BLEEndPoint::DriveSending() ChipLogDebugBleEndPoint(Ble, "NO SEND: remote receive window closed"); } - if (GetFlag(mConnStateFlags, kConnState_GattOperationInFlight)) + if (mConnStateFlags.Has(ConnectionStateFlag::kGattOperationInFlight)) { ChipLogDebugBleEndPoint(Ble, "NO SEND: Gatt op in flight"); } @@ -1273,13 +1272,13 @@ BLE_ERROR BLEEndPoint::Receive(PacketBufferHandle data) } // If we're receiving the first inbound packet of a BLE transport connection handshake... - if (!GetFlag(mConnStateFlags, kConnState_CapabilitiesMsgReceived)) + if (!mConnStateFlags.Has(ConnectionStateFlag::kCapabilitiesMsgReceived)) { if (mRole == kBleRole_Central) // If we're a central receiving a capabilities response indication... { // Ensure end point's in the right state before continuing. VerifyOrExit(mState == kState_Connecting, err = BLE_ERROR_INCORRECT_STATE); - SetFlag(mConnStateFlags, kConnState_CapabilitiesMsgReceived, true); + mConnStateFlags.Set(ConnectionStateFlag::kCapabilitiesMsgReceived); err = HandleCapabilitiesResponseReceived(std::move(data)); SuccessOrExit(err); @@ -1288,7 +1287,7 @@ BLE_ERROR BLEEndPoint::Receive(PacketBufferHandle data) { // Ensure end point's in the right state before continuing. VerifyOrExit(mState == kState_Ready, err = BLE_ERROR_INCORRECT_STATE); - SetFlag(mConnStateFlags, kConnState_CapabilitiesMsgReceived, true); + mConnStateFlags.Set(ConnectionStateFlag::kCapabilitiesMsgReceived); err = HandleCapabilitiesRequestReceived(std::move(data)); @@ -1391,7 +1390,7 @@ BLE_ERROR BLEEndPoint::Receive(PacketBufferHandle data) if (mBtpEngine.HasUnackedData()) { if (mLocalReceiveWindowSize <= BLE_CONFIG_IMMEDIATE_ACK_WINDOW_THRESHOLD && - !GetFlag(mConnStateFlags, kConnState_GattOperationInFlight)) + !mConnStateFlags.Has(ConnectionStateFlag::kGattOperationInFlight)) { ChipLogDebugBleEndPoint(Ble, "sending immediate ack"); err = DriveStandAloneAck(); @@ -1446,14 +1445,14 @@ BLE_ERROR BLEEndPoint::Receive(PacketBufferHandle data) bool BLEEndPoint::SendWrite(PacketBufferHandle && buf) { - SetFlag(mConnStateFlags, kConnState_GattOperationInFlight, true); + mConnStateFlags.Set(ConnectionStateFlag::kGattOperationInFlight); return mBle->mPlatformDelegate->SendWriteRequest(mConnObj, &CHIP_BLE_SVC_ID, &mBle->CHIP_BLE_CHAR_1_ID, std::move(buf)); } bool BLEEndPoint::SendIndication(PacketBufferHandle && buf) { - SetFlag(mConnStateFlags, kConnState_GattOperationInFlight, true); + mConnStateFlags.Set(ConnectionStateFlag::kGattOperationInFlight); return mBle->mPlatformDelegate->SendIndication(mConnObj, &CHIP_BLE_SVC_ID, &mBle->CHIP_BLE_CHAR_2_ID, std::move(buf)); } @@ -1465,7 +1464,7 @@ BLE_ERROR BLEEndPoint::StartConnectTimer() timerErr = mBle->mSystemLayer->StartTimer(BLE_CONNECT_TIMEOUT_MS, HandleConnectTimeout, this); VerifyOrExit(timerErr == CHIP_SYSTEM_NO_ERROR, err = BLE_ERROR_START_TIMER_FAILED); - SetFlag(mTimerStateFlags, kTimerState_ConnectTimerRunning, true); + mTimerStateFlags.Set(TimerStateFlag::kConnectTimerRunning); exit: return err; @@ -1478,7 +1477,7 @@ BLE_ERROR BLEEndPoint::StartReceiveConnectionTimer() timerErr = mBle->mSystemLayer->StartTimer(BLE_CONNECT_TIMEOUT_MS, HandleReceiveConnectionTimeout, this); VerifyOrExit(timerErr == CHIP_SYSTEM_NO_ERROR, err = BLE_ERROR_START_TIMER_FAILED); - SetFlag(mTimerStateFlags, kTimerState_ReceiveConnectionTimerRunning, true); + mTimerStateFlags.Set(TimerStateFlag::kReceiveConnectionTimerRunning); exit: return err; @@ -1489,12 +1488,12 @@ BLE_ERROR BLEEndPoint::StartAckReceivedTimer() BLE_ERROR err = BLE_NO_ERROR; chip::System::Error timerErr; - if (!GetFlag(mTimerStateFlags, kTimerState_AckReceivedTimerRunning)) + if (!mTimerStateFlags.Has(TimerStateFlag::kAckReceivedTimerRunning)) { timerErr = mBle->mSystemLayer->StartTimer(BTP_ACK_RECEIVED_TIMEOUT_MS, HandleAckReceivedTimeout, this); VerifyOrExit(timerErr == CHIP_SYSTEM_NO_ERROR, err = BLE_ERROR_START_TIMER_FAILED); - SetFlag(mTimerStateFlags, kTimerState_AckReceivedTimerRunning, true); + mTimerStateFlags.Set(TimerStateFlag::kAckReceivedTimerRunning); } exit: @@ -1505,7 +1504,7 @@ BLE_ERROR BLEEndPoint::RestartAckReceivedTimer() { BLE_ERROR err = BLE_NO_ERROR; - VerifyOrExit(GetFlag(mTimerStateFlags, kTimerState_AckReceivedTimerRunning), err = BLE_ERROR_INCORRECT_STATE); + VerifyOrExit(mTimerStateFlags.Has(TimerStateFlag::kAckReceivedTimerRunning), err = BLE_ERROR_INCORRECT_STATE); StopAckReceivedTimer(); @@ -1523,13 +1522,13 @@ BLE_ERROR BLEEndPoint::StartSendAckTimer() ChipLogDebugBleEndPoint(Ble, "entered StartSendAckTimer"); - if (!GetFlag(mTimerStateFlags, kTimerState_SendAckTimerRunning)) + if (!mTimerStateFlags.Has(TimerStateFlag::kSendAckTimerRunning)) { ChipLogDebugBleEndPoint(Ble, "starting new SendAckTimer"); timerErr = mBle->mSystemLayer->StartTimer(BTP_ACK_SEND_TIMEOUT_MS, HandleSendAckTimeout, this); VerifyOrExit(timerErr == CHIP_SYSTEM_NO_ERROR, err = BLE_ERROR_START_TIMER_FAILED); - SetFlag(mTimerStateFlags, kTimerState_SendAckTimerRunning, true); + mTimerStateFlags.Set(TimerStateFlag::kSendAckTimerRunning); } exit: @@ -1543,7 +1542,7 @@ BLE_ERROR BLEEndPoint::StartUnsubscribeTimer() timerErr = mBle->mSystemLayer->StartTimer(BLE_UNSUBSCRIBE_TIMEOUT_MS, HandleUnsubscribeTimeout, this); VerifyOrExit(timerErr == CHIP_SYSTEM_NO_ERROR, err = BLE_ERROR_START_TIMER_FAILED); - SetFlag(mTimerStateFlags, kTimerState_UnsubscribeTimerRunning, true); + mTimerStateFlags.Set(TimerStateFlag::kUnsubscribeTimerRunning); exit: return err; @@ -1553,35 +1552,35 @@ void BLEEndPoint::StopConnectTimer() { // Cancel any existing connect timer. mBle->mSystemLayer->CancelTimer(HandleConnectTimeout, this); - SetFlag(mTimerStateFlags, kTimerState_ConnectTimerRunning, false); + mTimerStateFlags.Clear(TimerStateFlag::kConnectTimerRunning); } void BLEEndPoint::StopReceiveConnectionTimer() { // Cancel any existing receive connection timer. mBle->mSystemLayer->CancelTimer(HandleReceiveConnectionTimeout, this); - SetFlag(mTimerStateFlags, kTimerState_ReceiveConnectionTimerRunning, false); + mTimerStateFlags.Clear(TimerStateFlag::kReceiveConnectionTimerRunning); } void BLEEndPoint::StopAckReceivedTimer() { // Cancel any existing ack-received timer. mBle->mSystemLayer->CancelTimer(HandleAckReceivedTimeout, this); - SetFlag(mTimerStateFlags, kTimerState_AckReceivedTimerRunning, false); + mTimerStateFlags.Clear(TimerStateFlag::kAckReceivedTimerRunning); } void BLEEndPoint::StopSendAckTimer() { // Cancel any existing send-ack timer. mBle->mSystemLayer->CancelTimer(HandleSendAckTimeout, this); - SetFlag(mTimerStateFlags, kTimerState_SendAckTimerRunning, false); + mTimerStateFlags.Clear(TimerStateFlag::kSendAckTimerRunning); } void BLEEndPoint::StopUnsubscribeTimer() { // Cancel any existing unsubscribe timer. mBle->mSystemLayer->CancelTimer(HandleUnsubscribeTimeout, this); - SetFlag(mTimerStateFlags, kTimerState_UnsubscribeTimerRunning, false); + mTimerStateFlags.Clear(TimerStateFlag::kUnsubscribeTimerRunning); } void BLEEndPoint::HandleConnectTimeout(chip::System::Layer * systemLayer, void * appState, chip::System::Error err) @@ -1589,10 +1588,10 @@ void BLEEndPoint::HandleConnectTimeout(chip::System::Layer * systemLayer, void * BLEEndPoint * ep = static_cast(appState); // Check for event-based timer race condition. - if (GetFlag(ep->mTimerStateFlags, kTimerState_ConnectTimerRunning)) + if (ep->mTimerStateFlags.Has(TimerStateFlag::kConnectTimerRunning)) { ChipLogError(Ble, "connect handshake timed out, closing ep %p", ep); - SetFlag(ep->mTimerStateFlags, kTimerState_ConnectTimerRunning, false); + ep->mTimerStateFlags.Clear(TimerStateFlag::kConnectTimerRunning); ep->DoClose(kBleCloseFlag_AbortTransmission, BLE_ERROR_CONNECT_TIMED_OUT); } } @@ -1602,10 +1601,10 @@ void BLEEndPoint::HandleReceiveConnectionTimeout(chip::System::Layer * systemLay BLEEndPoint * ep = static_cast(appState); // Check for event-based timer race condition. - if (GetFlag(ep->mTimerStateFlags, kTimerState_ReceiveConnectionTimerRunning)) + if (ep->mTimerStateFlags.Has(TimerStateFlag::kReceiveConnectionTimerRunning)) { ChipLogError(Ble, "receive handshake timed out, closing ep %p", ep); - SetFlag(ep->mTimerStateFlags, kTimerState_ReceiveConnectionTimerRunning, false); + ep->mTimerStateFlags.Clear(TimerStateFlag::kReceiveConnectionTimerRunning); ep->DoClose(kBleCloseFlag_SuppressCallback | kBleCloseFlag_AbortTransmission, BLE_ERROR_RECEIVE_TIMED_OUT); } } @@ -1615,11 +1614,11 @@ void BLEEndPoint::HandleAckReceivedTimeout(chip::System::Layer * systemLayer, vo BLEEndPoint * ep = static_cast(appState); // Check for event-based timer race condition. - if (GetFlag(ep->mTimerStateFlags, kTimerState_AckReceivedTimerRunning)) + if (ep->mTimerStateFlags.Has(TimerStateFlag::kAckReceivedTimerRunning)) { ChipLogError(Ble, "ack recv timeout, closing ep %p", ep); ep->mBtpEngine.LogStateDebug(); - SetFlag(ep->mTimerStateFlags, kTimerState_AckReceivedTimerRunning, false); + ep->mTimerStateFlags.Clear(TimerStateFlag::kAckReceivedTimerRunning); ep->DoClose(kBleCloseFlag_AbortTransmission, BLE_ERROR_FRAGMENT_ACK_TIMED_OUT); } } @@ -1629,12 +1628,12 @@ void BLEEndPoint::HandleSendAckTimeout(chip::System::Layer * systemLayer, void * BLEEndPoint * ep = static_cast(appState); // Check for event-based timer race condition. - if (GetFlag(ep->mTimerStateFlags, kTimerState_SendAckTimerRunning)) + if (ep->mTimerStateFlags.Has(TimerStateFlag::kSendAckTimerRunning)) { - SetFlag(ep->mTimerStateFlags, kTimerState_SendAckTimerRunning, false); + ep->mTimerStateFlags.Clear(TimerStateFlag::kSendAckTimerRunning); // If previous stand-alone ack isn't still in flight... - if (!GetFlag(ep->mConnStateFlags, kConnState_StandAloneAckInFlight)) + if (!ep->mConnStateFlags.Has(ConnectionStateFlag::kStandAloneAckInFlight)) { BLE_ERROR sendErr = ep->DriveStandAloneAck(); @@ -1651,10 +1650,10 @@ void BLEEndPoint::HandleUnsubscribeTimeout(chip::System::Layer * systemLayer, vo BLEEndPoint * ep = static_cast(appState); // Check for event-based timer race condition. - if (GetFlag(ep->mTimerStateFlags, kTimerState_UnsubscribeTimerRunning)) + if (ep->mTimerStateFlags.Has(TimerStateFlag::kUnsubscribeTimerRunning)) { ChipLogError(Ble, "unsubscribe timed out, ble ep %p", ep); - SetFlag(ep->mTimerStateFlags, kTimerState_UnsubscribeTimerRunning, false); + ep->mTimerStateFlags.Clear(TimerStateFlag::kUnsubscribeTimerRunning); ep->HandleUnsubscribeComplete(); } } diff --git a/src/ble/BLEEndPoint.h b/src/ble/BLEEndPoint.h index 36daf0de7af5ff..cc1aa3a03119d7 100644 --- a/src/ble/BLEEndPoint.h +++ b/src/ble/BLEEndPoint.h @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2020-2021 Project CHIP Authors * Copyright (c) 2014-2017 Nest Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -107,26 +107,26 @@ class DLL_EXPORT BLEEndPoint : public BleLayerObject private: // Private data members: - enum ConnectionStateFlags + enum class ConnectionStateFlag : uint8_t { - kConnState_AutoClose = 0x01, // End point should close underlying BLE conn on BTP close. - kConnState_CapabilitiesConfReceived = 0x02, // GATT confirmation received for sent capabilities req/resp. - kConnState_CapabilitiesMsgReceived = 0x04, // Capabilities request or response message received. - kConnState_DidBeginSubscribe = 0x08, // GATT subscribe request sent; must unsubscribe on close. - kConnState_StandAloneAckInFlight = 0x10, // Stand-alone ack in flight, awaiting GATT confirmation. - kConnState_GattOperationInFlight = 0x20 // GATT write, indication, subscribe, or unsubscribe in flight, - // awaiting GATT confirmation. + kAutoClose = 0x01, // End point should close underlying BLE conn on BTP close. + kCapabilitiesConfReceived = 0x02, // GATT confirmation received for sent capabilities req/resp. + kCapabilitiesMsgReceived = 0x04, // Capabilities request or response message received. + kDidBeginSubscribe = 0x08, // GATT subscribe request sent; must unsubscribe on close. + kStandAloneAckInFlight = 0x10, // Stand-alone ack in flight, awaiting GATT confirmation. + kGattOperationInFlight = 0x20 // GATT write, indication, subscribe, or unsubscribe in flight, + // awaiting GATT confirmation. }; - enum TimerStateFlags + enum class TimerStateFlag : uint8_t { - kTimerState_ConnectTimerRunning = 0x01, // BTP connect completion timer running. - kTimerState_ReceiveConnectionTimerRunning = 0x02, // BTP receive connection completion timer running. - kTimerState_AckReceivedTimerRunning = 0x04, // Ack received timer running due to unacked sent fragment. - kTimerState_SendAckTimerRunning = 0x08, // Send ack timer running; indicates pending ack to send. - kTimerState_UnsubscribeTimerRunning = 0x10, // Unsubscribe completion timer running. + kConnectTimerRunning = 0x01, // BTP connect completion timer running. + kReceiveConnectionTimerRunning = 0x02, // BTP receive connection completion timer running. + kAckReceivedTimerRunning = 0x04, // Ack received timer running due to unacked sent fragment. + kSendAckTimerRunning = 0x08, // Send ack timer running; indicates pending ack to send. + kUnsubscribeTimerRunning = 0x10, // Unsubscribe completion timer running. #if CHIP_ENABLE_CHIPOBLE_TEST - kTimerState_UnderTestTimerRunnung = 0x80 // running throughput Tx test + kUnderTestTimerRunnung = 0x80 // running throughput Tx test #endif }; @@ -147,8 +147,8 @@ class DLL_EXPORT BLEEndPoint : public BleLayerObject BtpEngine mBtpEngine; BleRole mRole; - uint8_t mConnStateFlags; - uint8_t mTimerStateFlags; + BitFlags mConnStateFlags; + BitFlags mTimerStateFlags; SequenceNumber_t mLocalReceiveWindowSize; SequenceNumber_t mRemoteReceiveWindowSize; SequenceNumber_t mReceiveWindowMaxSize; diff --git a/src/ble/BtpEngine.cpp b/src/ble/BtpEngine.cpp index ef83b90a7133b7..4b62c98c2139e1 100644 --- a/src/ble/BtpEngine.cpp +++ b/src/ble/BtpEngine.cpp @@ -55,10 +55,10 @@ static inline void IncSeqNum(SequenceNumber_t & a_seq_num) a_seq_num = static_cast(0xff & ((a_seq_num) + 1)); } -static inline bool DidReceiveData(uint8_t rx_flags) +static inline bool DidReceiveData(BitFlags rx_flags) { - return (GetFlag(rx_flags, BtpEngine::kHeaderFlag_StartMessage) || GetFlag(rx_flags, BtpEngine::kHeaderFlag_ContinueMessage) || - GetFlag(rx_flags, BtpEngine::kHeaderFlag_EndMessage)); + return rx_flags.HasAny(BtpEngine::HeaderFlags::kStartMessage, BtpEngine::HeaderFlags::kContinueMessage, + BtpEngine::HeaderFlags::kEndMessage); } static void PrintBufDebug(const System::PacketBufferHandle & buf) @@ -213,7 +213,7 @@ BLE_ERROR BtpEngine::EncodeStandAloneAck(const PacketBufferHandle & data) characteristic = data->Start(); // Since there's no preexisting message payload, we can write BTP header without adjusting data start pointer. - characteristic[0] = kHeaderFlag_FragmentAck; + characteristic[0] = static_cast(HeaderFlags::kFragmentAck); // Acknowledge most recently received sequence number. characteristic[1] = GetAndRecordRxAckSeqNum(); @@ -245,8 +245,8 @@ BLE_ERROR BtpEngine::EncodeStandAloneAck(const PacketBufferHandle & data) BLE_ERROR BtpEngine::HandleCharacteristicReceived(System::PacketBufferHandle data, SequenceNumber_t & receivedAck, bool & didReceiveAck) { - BLE_ERROR err = BLE_NO_ERROR; - uint8_t rx_flags = 0; + BLE_ERROR err = BLE_NO_ERROR; + BitFlags rx_flags; // BLE data uses little-endian byte order. Encoding::LittleEndian::Reader reader(data->Start(), data->DataLength()); @@ -255,15 +255,15 @@ BLE_ERROR BtpEngine::HandleCharacteristicReceived(System::PacketBufferHandle dat mRxCharCount++; // Get header flags, always in first byte. - VerifyOrExit(reader.Read8(&rx_flags).StatusCode() == CHIP_NO_ERROR, err = BLE_ERROR_MESSAGE_INCOMPLETE); + VerifyOrExit(reader.Read8(rx_flags.RawStorage()).StatusCode() == CHIP_NO_ERROR, err = BLE_ERROR_MESSAGE_INCOMPLETE); #if CHIP_ENABLE_CHIPOBLE_TEST - if (GetFlag(rx_flags, kHeaderFlag_CommandMessage)) + if (rx_flags.Has(HeaderFlags::kCommandMessage)) SetRxPacketType(kType_Control); else SetRxPacketType(kType_Data); #endif - didReceiveAck = GetFlag(rx_flags, kHeaderFlag_FragmentAck); + didReceiveAck = rx_flags.Has(HeaderFlags::kFragmentAck); // Get ack number, if any. if (didReceiveAck) @@ -309,7 +309,7 @@ BLE_ERROR BtpEngine::HandleCharacteristicReceived(System::PacketBufferHandle dat Encoding::LittleEndian::Reader startReader(data->Start(), data->DataLength()); // Verify StartMessage header flag set. - VerifyOrExit(rx_flags & kHeaderFlag_StartMessage, err = BLE_ERROR_INVALID_BTP_HEADER_FLAGS); + VerifyOrExit(rx_flags.Has(HeaderFlags::kStartMessage), err = BLE_ERROR_INVALID_BTP_HEADER_FLAGS); VerifyOrExit(startReader.Read16(&mRxLength).StatusCode() == CHIP_NO_ERROR, err = BLE_ERROR_MESSAGE_INCOMPLETE); @@ -328,10 +328,10 @@ BLE_ERROR BtpEngine::HandleCharacteristicReceived(System::PacketBufferHandle dat else if (mRxState == kState_InProgress) { // Verify StartMessage header flag NOT set, since we're in the middle of receiving a message. - VerifyOrExit((rx_flags & kHeaderFlag_StartMessage) == 0, err = BLE_ERROR_INVALID_BTP_HEADER_FLAGS); + VerifyOrExit(!rx_flags.Has(HeaderFlags::kStartMessage), err = BLE_ERROR_INVALID_BTP_HEADER_FLAGS); // Verify ContinueMessage or EndMessage header flag set. - VerifyOrExit((rx_flags & kHeaderFlag_ContinueMessage) || (rx_flags & kHeaderFlag_EndMessage), + VerifyOrExit(rx_flags.HasAny(HeaderFlags::kContinueMessage, HeaderFlags::kEndMessage), err = BLE_ERROR_INVALID_BTP_HEADER_FLAGS); // Add received fragment to reassembled message buffer. @@ -348,7 +348,7 @@ BLE_ERROR BtpEngine::HandleCharacteristicReceived(System::PacketBufferHandle dat ExitNow(); } - if (rx_flags & kHeaderFlag_EndMessage) + if (rx_flags.Has(HeaderFlags::kEndMessage)) { // Trim remainder, if any, of the received packet buffer based on sender-specified length of reassembled message. int padding = mRxBuf->DataLength() - mRxLength; @@ -372,7 +372,7 @@ BLE_ERROR BtpEngine::HandleCharacteristicReceived(System::PacketBufferHandle dat mRxState = kState_Error; // Dump protocol engine state, plus header flags and received data length. - ChipLogError(Ble, "HandleCharacteristicReceived failed, err = %d, rx_flags = %u", err, rx_flags); + ChipLogError(Ble, "HandleCharacteristicReceived failed, err = %d, rx_flags = %u", err, rx_flags.Raw()); if (didReceiveAck) { ChipLogError(Ble, "With rx'd ack = %u", receivedAck); @@ -457,17 +457,16 @@ bool BtpEngine::HandleCharacteristicSend(System::PacketBufferHandle data, bool s characteristic -= header_size; mTxBuf->SetStart(characteristic); uint8_t cursor = 1; // first position past header flags byte - - characteristic[0] = kHeaderFlag_StartMessage; + BitFlags headerFlags(HeaderFlags::kStartMessage); #if CHIP_ENABLE_CHIPOBLE_TEST if (TxPacketType() == kType_Control) - SetFlag(characteristic[0], kHeaderFlag_CommandMessage, true); + headerFlags.Set(HeaderFlags::kCommandMessage); #endif if (send_ack) { - SetFlag(characteristic[0], kHeaderFlag_FragmentAck, true); + headerFlags.Set(HeaderFlags::kFragmentAck); characteristic[cursor++] = GetAndRecordRxAckSeqNum(); ChipLogDebugBtpEngine(Ble, "===> encoded piggybacked ack, ack_num = %u", characteristic[cursor - 1]); } @@ -480,7 +479,7 @@ bool BtpEngine::HandleCharacteristicSend(System::PacketBufferHandle data, bool s { mTxBuf->SetDataLength(static_cast(mTxLength + cursor)); mTxLength = 0; - SetFlag(characteristic[0], kHeaderFlag_EndMessage, true); + headerFlags.Set(HeaderFlags::kEndMessage); mTxState = kState_Complete; mTxPacketCount++; } @@ -490,6 +489,7 @@ bool BtpEngine::HandleCharacteristicSend(System::PacketBufferHandle data, bool s mTxLength = static_cast((mTxLength + cursor) - mTxFragmentSize); } + characteristic[0] = headerFlags.Raw(); ChipLogDebugBtpEngine(Ble, ">>> CHIPoBle preparing to send first fragment:"); PrintBufDebug(data); } @@ -510,16 +510,16 @@ bool BtpEngine::HandleCharacteristicSend(System::PacketBufferHandle data, bool s mTxBuf->SetStart(characteristic); uint8_t cursor = 1; // first position past header flags byte - characteristic[0] = kHeaderFlag_ContinueMessage; + BitFlags headerFlags(HeaderFlags::kContinueMessage); #if CHIP_ENABLE_CHIPOBLE_TEST if (TxPacketType() == kType_Control) - SetFlag(characteristic[0], kHeaderFlag_CommandMessage, true); + headerFlags.Set(HeaderFlags::kCommandMessage); #endif if (send_ack) { - SetFlag(characteristic[0], kHeaderFlag_FragmentAck, true); + headerFlags.Set(HeaderFlags::kFragmentAck); characteristic[cursor++] = GetAndRecordRxAckSeqNum(); ChipLogDebugBtpEngine(Ble, "===> encoded piggybacked ack, ack_num = %u", characteristic[cursor - 1]); } @@ -530,7 +530,7 @@ bool BtpEngine::HandleCharacteristicSend(System::PacketBufferHandle data, bool s { mTxBuf->SetDataLength(static_cast(mTxLength + cursor)); mTxLength = 0; - SetFlag(characteristic[0], kHeaderFlag_EndMessage, true); + headerFlags.Set(HeaderFlags::kEndMessage); mTxState = kState_Complete; mTxPacketCount++; } @@ -540,6 +540,7 @@ bool BtpEngine::HandleCharacteristicSend(System::PacketBufferHandle data, bool s mTxLength = static_cast((mTxLength + cursor) - mTxFragmentSize); } + characteristic[0] = headerFlags.Raw(); ChipLogDebugBtpEngine(Ble, ">>> CHIPoBle preparing to send additional fragment:"); PrintBufDebug(mTxBuf); } diff --git a/src/ble/BtpEngine.h b/src/ble/BtpEngine.h index 9b7a6c5c20e2e3..43dda04434ef49 100644 --- a/src/ble/BtpEngine.h +++ b/src/ble/BtpEngine.h @@ -87,16 +87,17 @@ class BtpEngine kState_Error = 3 } State_t; // [READ-ONLY] Current state - enum + // Masks for BTP fragment header flag bits. + enum class HeaderFlags : uint8_t { - kHeaderFlag_StartMessage = 0x01, - kHeaderFlag_ContinueMessage = 0x02, - kHeaderFlag_EndMessage = 0x04, - kHeaderFlag_FragmentAck = 0x08, + kStartMessage = 0x01, + kContinueMessage = 0x02, + kEndMessage = 0x04, + kFragmentAck = 0x08, #if CHIP_ENABLE_CHIPOBLE_TEST - kHeaderFlag_CommandMessage = 0x10, + kCommandMessage = 0x10, #endif - }; // Masks for BTP fragment header flag bits. + }; static const uint16_t sDefaultFragmentSize; static const uint16_t sMaxFragmentSize; @@ -129,7 +130,10 @@ class BtpEngine inline SequenceNumber_t SetRxPacketSeq(SequenceNumber_t seq) { return (mRxPacketSeq = seq); } inline SequenceNumber_t TxPacketSeq() { return mTxPacketSeq; } inline SequenceNumber_t RxPacketSeq() { return mRxPacketSeq; } - inline bool IsCommandPacket(const PacketBufferHandle & p) { return GetFlag(*(p->Start()), kHeaderFlag_CommandMessage); } + inline bool IsCommandPacket(const PacketBufferHandle & p) + { + return BitFlags(*(p->Start())).Has(HeaderFlags::kCommandMessage); + } inline void PushPacketTag(const PacketBufferHandle & p, PacketType_t type) { p->SetStart(p->Start() - sizeof(type)); diff --git a/src/controller/CHIPClusters.cpp b/src/controller/CHIPClusters.cpp index f6145a98e38df1..9a339244aeb899 100644 --- a/src/controller/CHIPClusters.cpp +++ b/src/controller/CHIPClusters.cpp @@ -114,7 +114,7 @@ CHIP_ERROR BarrierControlCluster::BarrierControlGoToPercent(Callback::Cancelable (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kBarrierControlGoToPercentCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -148,7 +148,7 @@ CHIP_ERROR BarrierControlCluster::BarrierControlStop(Callback::Cancelable * onSu (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kBarrierControlStopCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -227,7 +227,7 @@ CHIP_ERROR BasicCluster::MfgSpecificPing(Callback::Cancelable * onSuccessCallbac (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kMfgSpecificPingCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -257,7 +257,7 @@ CHIP_ERROR BasicCluster::ResetToFactoryDefaults(Callback::Cancelable * onSuccess (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kResetToFactoryDefaultsCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -319,7 +319,7 @@ CHIP_ERROR BindingCluster::Bind(Callback::Cancelable * onSuccessCallback, Callba (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kBindCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -360,7 +360,7 @@ CHIP_ERROR BindingCluster::Unbind(Callback::Cancelable * onSuccessCallback, Call (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kUnbindCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -416,7 +416,7 @@ CHIP_ERROR ColorControlCluster::MoveColor(Callback::Cancelable * onSuccessCallba (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kMoveColorCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -458,7 +458,7 @@ CHIP_ERROR ColorControlCluster::MoveColorTemperature(Callback::Cancelable * onSu (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kMoveColorTemperatureCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -502,7 +502,7 @@ CHIP_ERROR ColorControlCluster::MoveHue(Callback::Cancelable * onSuccessCallback (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kMoveHueCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -542,7 +542,7 @@ CHIP_ERROR ColorControlCluster::MoveSaturation(Callback::Cancelable * onSuccessC (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kMoveSaturationCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -583,7 +583,7 @@ CHIP_ERROR ColorControlCluster::MoveToColor(Callback::Cancelable * onSuccessCall (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kMoveToColorCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -626,7 +626,7 @@ CHIP_ERROR ColorControlCluster::MoveToColorTemperature(Callback::Cancelable * on (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kMoveToColorTemperatureCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -667,7 +667,7 @@ CHIP_ERROR ColorControlCluster::MoveToHue(Callback::Cancelable * onSuccessCallba (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kMoveToHueCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -710,7 +710,7 @@ CHIP_ERROR ColorControlCluster::MoveToHueAndSaturation(Callback::Cancelable * on (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kMoveToHueAndSaturationCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -753,7 +753,7 @@ CHIP_ERROR ColorControlCluster::MoveToSaturation(Callback::Cancelable * onSucces (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kMoveToSaturationCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -794,7 +794,7 @@ CHIP_ERROR ColorControlCluster::StepColor(Callback::Cancelable * onSuccessCallba (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kStepColorCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -838,7 +838,7 @@ CHIP_ERROR ColorControlCluster::StepColorTemperature(Callback::Cancelable * onSu (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kStepColorTemperatureCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -886,7 +886,7 @@ CHIP_ERROR ColorControlCluster::StepHue(Callback::Cancelable * onSuccessCallback (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kStepHueCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -929,7 +929,7 @@ CHIP_ERROR ColorControlCluster::StepSaturation(Callback::Cancelable * onSuccessC (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kStepSaturationCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -971,7 +971,7 @@ CHIP_ERROR ColorControlCluster::StopMoveStep(Callback::Cancelable * onSuccessCal (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kStopMoveStepCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -1610,7 +1610,7 @@ CHIP_ERROR ContentLaunchCluster::LaunchContent(Callback::Cancelable * onSuccessC (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kLaunchContentCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -1640,7 +1640,7 @@ CHIP_ERROR ContentLaunchCluster::LaunchURL(Callback::Cancelable * onSuccessCallb (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kLaunchURLCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -1687,7 +1687,7 @@ CHIP_ERROR DoorLockCluster::ClearAllPins(Callback::Cancelable * onSuccessCallbac (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kClearAllPinsCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -1717,7 +1717,7 @@ CHIP_ERROR DoorLockCluster::ClearAllRfids(Callback::Cancelable * onSuccessCallba (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kClearAllRfidsCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -1748,7 +1748,7 @@ CHIP_ERROR DoorLockCluster::ClearHolidaySchedule(Callback::Cancelable * onSucces (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kClearHolidayScheduleCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -1781,7 +1781,7 @@ CHIP_ERROR DoorLockCluster::ClearPin(Callback::Cancelable * onSuccessCallback, C (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kClearPinCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -1814,7 +1814,7 @@ CHIP_ERROR DoorLockCluster::ClearRfid(Callback::Cancelable * onSuccessCallback, (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kClearRfidCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -1847,7 +1847,7 @@ CHIP_ERROR DoorLockCluster::ClearWeekdaySchedule(Callback::Cancelable * onSucces (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kClearWeekdayScheduleCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -1883,7 +1883,7 @@ CHIP_ERROR DoorLockCluster::ClearYeardaySchedule(Callback::Cancelable * onSucces (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kClearYeardayScheduleCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -1919,7 +1919,7 @@ CHIP_ERROR DoorLockCluster::GetHolidaySchedule(Callback::Cancelable * onSuccessC (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kGetHolidayScheduleCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -1952,7 +1952,7 @@ CHIP_ERROR DoorLockCluster::GetLogRecord(Callback::Cancelable * onSuccessCallbac (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kGetLogRecordCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -1985,7 +1985,7 @@ CHIP_ERROR DoorLockCluster::GetPin(Callback::Cancelable * onSuccessCallback, Cal (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kGetPinCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -2018,7 +2018,7 @@ CHIP_ERROR DoorLockCluster::GetRfid(Callback::Cancelable * onSuccessCallback, Ca (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kGetRfidCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -2051,7 +2051,7 @@ CHIP_ERROR DoorLockCluster::GetUserType(Callback::Cancelable * onSuccessCallback (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kGetUserTypeCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -2084,7 +2084,7 @@ CHIP_ERROR DoorLockCluster::GetWeekdaySchedule(Callback::Cancelable * onSuccessC (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kGetWeekdayScheduleCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -2120,7 +2120,7 @@ CHIP_ERROR DoorLockCluster::GetYeardaySchedule(Callback::Cancelable * onSuccessC (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kGetYeardayScheduleCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -2155,7 +2155,7 @@ CHIP_ERROR DoorLockCluster::LockDoor(Callback::Cancelable * onSuccessCallback, C (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kLockDoorCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -2189,7 +2189,7 @@ CHIP_ERROR DoorLockCluster::SetHolidaySchedule(Callback::Cancelable * onSuccessC (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kSetHolidayScheduleCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -2229,7 +2229,7 @@ CHIP_ERROR DoorLockCluster::SetPin(Callback::Cancelable * onSuccessCallback, Cal (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kSetPinCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -2269,7 +2269,7 @@ CHIP_ERROR DoorLockCluster::SetRfid(Callback::Cancelable * onSuccessCallback, Ca (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kSetRfidCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -2309,7 +2309,7 @@ CHIP_ERROR DoorLockCluster::SetUserType(Callback::Cancelable * onSuccessCallback (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kSetUserTypeCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -2345,7 +2345,7 @@ CHIP_ERROR DoorLockCluster::SetWeekdaySchedule(Callback::Cancelable * onSuccessC (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kSetWeekdayScheduleCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -2391,7 +2391,7 @@ CHIP_ERROR DoorLockCluster::SetYeardaySchedule(Callback::Cancelable * onSuccessC (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kSetYeardayScheduleCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -2431,7 +2431,7 @@ CHIP_ERROR DoorLockCluster::UnlockDoor(Callback::Cancelable * onSuccessCallback, (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kUnlockDoorCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -2464,7 +2464,7 @@ CHIP_ERROR DoorLockCluster::UnlockWithTimeout(Callback::Cancelable * onSuccessCa (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kUnlockWithTimeoutCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -2556,7 +2556,7 @@ CHIP_ERROR GeneralCommissioningCluster::ArmFailSafe(Callback::Cancelable * onSuc (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kArmFailSafeCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -2594,7 +2594,7 @@ CHIP_ERROR GeneralCommissioningCluster::CommissioningComplete(Callback::Cancelab (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kCommissioningCompleteCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -2626,7 +2626,7 @@ CHIP_ERROR GeneralCommissioningCluster::SetFabric(Callback::Cancelable * onSucce (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kSetFabricCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -2707,7 +2707,7 @@ CHIP_ERROR GroupsCluster::AddGroup(Callback::Cancelable * onSuccessCallback, Cal (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kAddGroupCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -2742,7 +2742,7 @@ CHIP_ERROR GroupsCluster::AddGroupIfIdentifying(Callback::Cancelable * onSuccess (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kAddGroupIfIdentifyingCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -2778,7 +2778,7 @@ CHIP_ERROR GroupsCluster::GetGroupMembership(Callback::Cancelable * onSuccessCal (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kGetGroupMembershipCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -2813,7 +2813,7 @@ CHIP_ERROR GroupsCluster::RemoveAllGroups(Callback::Cancelable * onSuccessCallba (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kRemoveAllGroupsCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -2844,7 +2844,7 @@ CHIP_ERROR GroupsCluster::RemoveGroup(Callback::Cancelable * onSuccessCallback, (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kRemoveGroupCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -2877,7 +2877,7 @@ CHIP_ERROR GroupsCluster::ViewGroup(Callback::Cancelable * onSuccessCallback, Ca (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kViewGroupCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -2996,7 +2996,7 @@ CHIP_ERROR IdentifyCluster::Identify(Callback::Cancelable * onSuccessCallback, C (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kIdentifyCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -3028,7 +3028,7 @@ CHIP_ERROR IdentifyCluster::IdentifyQuery(Callback::Cancelable * onSuccessCallba (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kIdentifyQueryCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -3091,7 +3091,7 @@ CHIP_ERROR LevelControlCluster::Move(Callback::Cancelable * onSuccessCallback, C (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kMoveCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -3131,7 +3131,7 @@ CHIP_ERROR LevelControlCluster::MoveToLevel(Callback::Cancelable * onSuccessCall (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kMoveToLevelCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -3172,7 +3172,7 @@ CHIP_ERROR LevelControlCluster::MoveToLevelWithOnOff(Callback::Cancelable * onSu (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kMoveToLevelWithOnOffCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -3208,7 +3208,7 @@ CHIP_ERROR LevelControlCluster::MoveWithOnOff(Callback::Cancelable * onSuccessCa (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kMoveWithOnOffCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -3244,7 +3244,7 @@ CHIP_ERROR LevelControlCluster::Step(Callback::Cancelable * onSuccessCallback, C (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kStepCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -3286,7 +3286,7 @@ CHIP_ERROR LevelControlCluster::StepWithOnOff(Callback::Cancelable * onSuccessCa (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kStepWithOnOffCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -3324,7 +3324,7 @@ CHIP_ERROR LevelControlCluster::Stop(Callback::Cancelable * onSuccessCallback, C (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kStopCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -3358,7 +3358,7 @@ CHIP_ERROR LevelControlCluster::StopWithOnOff(Callback::Cancelable * onSuccessCa (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kStopWithOnOffCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -3475,7 +3475,7 @@ CHIP_ERROR MediaPlaybackCluster::FastForwardRequest(Callback::Cancelable * onSuc (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kFastForwardRequestCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -3505,7 +3505,7 @@ CHIP_ERROR MediaPlaybackCluster::NextRequest(Callback::Cancelable * onSuccessCal (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kNextRequestCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -3535,7 +3535,7 @@ CHIP_ERROR MediaPlaybackCluster::PauseRequest(Callback::Cancelable * onSuccessCa (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kPauseRequestCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -3565,7 +3565,7 @@ CHIP_ERROR MediaPlaybackCluster::PlayRequest(Callback::Cancelable * onSuccessCal (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kPlayRequestCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -3595,7 +3595,7 @@ CHIP_ERROR MediaPlaybackCluster::PreviousRequest(Callback::Cancelable * onSucces (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kPreviousRequestCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -3625,7 +3625,7 @@ CHIP_ERROR MediaPlaybackCluster::RewindRequest(Callback::Cancelable * onSuccessC (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kRewindRequestCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -3656,7 +3656,7 @@ CHIP_ERROR MediaPlaybackCluster::SkipBackwardRequest(Callback::Cancelable * onSu (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kSkipBackwardRequestCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -3687,7 +3687,7 @@ CHIP_ERROR MediaPlaybackCluster::SkipForwardRequest(Callback::Cancelable * onSuc (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kSkipForwardRequestCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -3718,7 +3718,7 @@ CHIP_ERROR MediaPlaybackCluster::StartOverRequest(Callback::Cancelable * onSucce (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kStartOverRequestCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -3748,7 +3748,7 @@ CHIP_ERROR MediaPlaybackCluster::StopRequest(Callback::Cancelable * onSuccessCal (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kStopRequestCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -3805,7 +3805,7 @@ CHIP_ERROR NetworkCommissioningCluster::AddThreadNetwork(Callback::Cancelable * (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kAddThreadNetworkCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -3844,7 +3844,7 @@ CHIP_ERROR NetworkCommissioningCluster::AddWiFiNetwork(Callback::Cancelable * on (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kAddWiFiNetworkCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -3885,7 +3885,7 @@ CHIP_ERROR NetworkCommissioningCluster::DisableNetwork(Callback::Cancelable * on (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kDisableNetworkCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -3924,7 +3924,7 @@ CHIP_ERROR NetworkCommissioningCluster::EnableNetwork(Callback::Cancelable * onS (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kEnableNetworkCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -3963,7 +3963,7 @@ CHIP_ERROR NetworkCommissioningCluster::GetLastNetworkCommissioningResult(Callba (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kGetLastNetworkCommissioningResultCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -3998,7 +3998,7 @@ CHIP_ERROR NetworkCommissioningCluster::RemoveNetwork(Callback::Cancelable * onS (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kRemoveNetworkCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -4037,7 +4037,7 @@ CHIP_ERROR NetworkCommissioningCluster::ScanNetworks(Callback::Cancelable * onSu (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kScanNetworksCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -4077,7 +4077,7 @@ CHIP_ERROR NetworkCommissioningCluster::UpdateThreadNetwork(Callback::Cancelable (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kUpdateThreadNetworkCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -4116,7 +4116,7 @@ CHIP_ERROR NetworkCommissioningCluster::UpdateWiFiNetwork(Callback::Cancelable * (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kUpdateWiFiNetworkCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -4172,7 +4172,7 @@ CHIP_ERROR OnOffCluster::Off(Callback::Cancelable * onSuccessCallback, Callback: (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kOffCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -4202,7 +4202,7 @@ CHIP_ERROR OnOffCluster::On(Callback::Cancelable * onSuccessCallback, Callback:: (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kOnCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -4232,7 +4232,7 @@ CHIP_ERROR OnOffCluster::Toggle(Callback::Cancelable * onSuccessCallback, Callba (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kToggleCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -4301,7 +4301,7 @@ CHIP_ERROR ScenesCluster::AddScene(Callback::Cancelable * onSuccessCallback, Cal (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kAddSceneCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -4347,7 +4347,7 @@ CHIP_ERROR ScenesCluster::GetSceneMembership(Callback::Cancelable * onSuccessCal (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kGetSceneMembershipCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -4380,7 +4380,7 @@ CHIP_ERROR ScenesCluster::RecallScene(Callback::Cancelable * onSuccessCallback, (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kRecallSceneCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -4418,7 +4418,7 @@ CHIP_ERROR ScenesCluster::RemoveAllScenes(Callback::Cancelable * onSuccessCallba (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kRemoveAllScenesCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -4451,7 +4451,7 @@ CHIP_ERROR ScenesCluster::RemoveScene(Callback::Cancelable * onSuccessCallback, (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kRemoveSceneCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -4486,7 +4486,7 @@ CHIP_ERROR ScenesCluster::StoreScene(Callback::Cancelable * onSuccessCallback, C (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kStoreSceneCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); @@ -4521,7 +4521,7 @@ CHIP_ERROR ScenesCluster::ViewScene(Callback::Cancelable * onSuccessCallback, Ca (void) onFailureCallback; app::Command::CommandParams cmdParams = { mEndpoint, /* group id */ 0, mClusterId, kViewSceneCommandId, - (chip::app::Command::kCommandPathFlag_EndpointIdValid) }; + (chip::app::Command::CommandPathFlags::kEndpointIdValid) }; app::Command * ZCLcommand = mDevice->GetCommandSender(); TLV::TLVWriter writer = ZCLcommand->CreateCommandDataElementTLVWriter(); diff --git a/src/credentials/CHIPCert.cpp b/src/credentials/CHIPCert.cpp index 90246c40202657..b7800ec9976647 100644 --- a/src/credentials/CHIPCert.cpp +++ b/src/credentials/CHIPCert.cpp @@ -143,8 +143,7 @@ void ChipCertificateSet::Clear() mCertCount = 0; } -CHIP_ERROR ChipCertificateSet::LoadCert(const uint8_t * chipCert, uint32_t chipCertLen, - BitFlags decodeFlags) +CHIP_ERROR ChipCertificateSet::LoadCert(const uint8_t * chipCert, uint32_t chipCertLen, BitFlags decodeFlags) { CHIP_ERROR err; TLVReader reader; @@ -161,7 +160,7 @@ CHIP_ERROR ChipCertificateSet::LoadCert(const uint8_t * chipCert, uint32_t chipC return err; } -CHIP_ERROR ChipCertificateSet::LoadCert(TLVReader & reader, BitFlags decodeFlags) +CHIP_ERROR ChipCertificateSet::LoadCert(TLVReader & reader, BitFlags decodeFlags) { CHIP_ERROR err; ASN1Writer writer; // ASN1Writer is used to encode TBS portion of the certificate for the purpose of signature @@ -192,8 +191,7 @@ CHIP_ERROR ChipCertificateSet::LoadCert(TLVReader & reader, BitFlagsmCertFlags.Has(CertFlags::kExtPresent_SubjectKeyId) && - cert->mCertFlags.Has(CertFlags::kExtPresent_AuthKeyId), + VerifyOrExit(cert->mCertFlags.HasAll(CertFlags::kExtPresent_SubjectKeyId, CertFlags::kExtPresent_AuthKeyId), err = CHIP_ERROR_UNSUPPORTED_CERT_FORMAT); // Verify the cert was signed with ECDSA-SHA256. This is the only signature algorithm currently supported. @@ -248,8 +246,7 @@ CHIP_ERROR ChipCertificateSet::LoadCert(TLVReader & reader, BitFlags decodeFlags) +CHIP_ERROR ChipCertificateSet::LoadCerts(const uint8_t * chipCerts, uint32_t chipCertsLen, BitFlags decodeFlags) { CHIP_ERROR err; TLVReader reader; @@ -275,7 +272,7 @@ CHIP_ERROR ChipCertificateSet::LoadCerts(const uint8_t * chipCerts, uint32_t chi return err; } -CHIP_ERROR ChipCertificateSet::LoadCerts(TLVReader & reader, BitFlags decodeFlags) +CHIP_ERROR ChipCertificateSet::LoadCerts(TLVReader & reader, BitFlags decodeFlags) { CHIP_ERROR err; uint8_t initialCertCount = mCertCount; @@ -463,7 +460,7 @@ CHIP_ERROR ChipCertificateSet::VerifySignature(const ChipCertificateData * cert, } CHIP_ERROR ChipCertificateSet::ValidateCert(const ChipCertificateData * cert, ValidationContext & context, - BitFlags validateFlags, uint8_t depth) + BitFlags validateFlags, uint8_t depth) { CHIP_ERROR err = CHIP_NO_ERROR; ChipCertificateData * caCert = nullptr; @@ -499,19 +496,19 @@ CHIP_ERROR ChipCertificateSet::ValidateCert(const ChipCertificateData * cert, Va { // If a set of desired key usages has been specified, verify that the key usage extension exists // in the certificate and that the corresponding usages are supported. - if (context.mRequiredKeyUsages.Raw() != 0) + if (context.mRequiredKeyUsages.HasAny()) { VerifyOrExit(cert->mCertFlags.Has(CertFlags::kExtPresent_KeyUsage) && - cert->mKeyUsageFlags.Has(context.mRequiredKeyUsages.Raw()), + cert->mKeyUsageFlags.HasAll(context.mRequiredKeyUsages), err = CHIP_ERROR_CERT_USAGE_NOT_ALLOWED); } // If a set of desired key purposes has been specified, verify that the extended key usage extension // exists in the certificate and that the corresponding purposes are supported. - if (context.mRequiredKeyPurposes.Raw() != 0) + if (context.mRequiredKeyPurposes.HasAny()) { VerifyOrExit(cert->mCertFlags.Has(CertFlags::kExtPresent_ExtendedKeyUsage) && - cert->mKeyPurposeFlags.Has(context.mRequiredKeyPurposes.Raw()), + cert->mKeyPurposeFlags.HasAll(context.mRequiredKeyPurposes), err = CHIP_ERROR_CERT_USAGE_NOT_ALLOWED); } @@ -577,8 +574,8 @@ CHIP_ERROR ChipCertificateSet::ValidateCert(const ChipCertificateData * cert, Va } CHIP_ERROR ChipCertificateSet::FindValidCert(const ChipDN & subjectDN, const CertificateKeyId & subjectKeyId, - ValidationContext & context, BitFlags validateFlags, - uint8_t depth, ChipCertificateData *& cert) + ValidationContext & context, BitFlags validateFlags, uint8_t depth, + ChipCertificateData *& cert) { CHIP_ERROR err; @@ -646,9 +643,9 @@ void ChipCertificateData::Clear() mPubKeyCurveOID = 0; mPubKeyAlgoOID = 0; mSigAlgoOID = 0; - mCertFlags.SetRaw(0); - mKeyUsageFlags.SetRaw(0); - mKeyPurposeFlags.SetRaw(0); + mCertFlags.ClearAll(); + mKeyUsageFlags.ClearAll(); + mKeyPurposeFlags.ClearAll(); mPathLenConstraint = 0; mCertType = kCertType_NotSpecified; mSignature.R = nullptr; @@ -663,9 +660,9 @@ void ValidationContext::Reset() mEffectiveTime = 0; mTrustAnchor = nullptr; mSigningCert = nullptr; - mRequiredKeyUsages.SetRaw(0); - mRequiredKeyPurposes.SetRaw(0); - mValidateFlags.SetRaw(0); + mRequiredKeyUsages.ClearAll(); + mRequiredKeyPurposes.ClearAll(); + mValidateFlags.ClearAll(); mRequiredCertType = kCertType_NotSpecified; } diff --git a/src/credentials/CHIPCert.h b/src/credentials/CHIPCert.h index 4774efd31ef2e2..362d8ce825fee2 100644 --- a/src/credentials/CHIPCert.h +++ b/src/credentials/CHIPCert.h @@ -241,22 +241,22 @@ struct ChipCertificateData void Clear(); - ChipDN mSubjectDN; /**< Certificate Subject DN. */ - ChipDN mIssuerDN; /**< Certificate Issuer DN. */ - CertificateKeyId mSubjectKeyId; /**< Certificate Subject public key identifier. */ - CertificateKeyId mAuthKeyId; /**< Certificate Authority public key identifier. */ - uint32_t mNotBeforeTime; /**< Certificate validity: Not Before field. */ - uint32_t mNotAfterTime; /**< Certificate validity: Not After field. */ - const uint8_t * mPublicKey; /**< Pointer to the certificate public key. */ - uint8_t mPublicKeyLen; /**< Certificate public key length. */ - uint16_t mPubKeyCurveOID; /**< Public key Elliptic Curve CHIP OID. */ - uint16_t mPubKeyAlgoOID; /**< Public key algorithm CHIP OID. */ - uint16_t mSigAlgoOID; /**< Certificate signature algorithm CHIP OID. */ - BitFlags mCertFlags; /**< Certificate data flags. */ - BitFlags mKeyUsageFlags; /**< Certificate key usage extensions flags. */ - BitFlags mKeyPurposeFlags; /**< Certificate extended key usage extensions flags. */ - uint8_t mPathLenConstraint; /**< Basic constraint: path length. */ - uint8_t mCertType; /**< Certificate type. */ + ChipDN mSubjectDN; /**< Certificate Subject DN. */ + ChipDN mIssuerDN; /**< Certificate Issuer DN. */ + CertificateKeyId mSubjectKeyId; /**< Certificate Subject public key identifier. */ + CertificateKeyId mAuthKeyId; /**< Certificate Authority public key identifier. */ + uint32_t mNotBeforeTime; /**< Certificate validity: Not Before field. */ + uint32_t mNotAfterTime; /**< Certificate validity: Not After field. */ + const uint8_t * mPublicKey; /**< Pointer to the certificate public key. */ + uint8_t mPublicKeyLen; /**< Certificate public key length. */ + uint16_t mPubKeyCurveOID; /**< Public key Elliptic Curve CHIP OID. */ + uint16_t mPubKeyAlgoOID; /**< Public key algorithm CHIP OID. */ + uint16_t mSigAlgoOID; /**< Certificate signature algorithm CHIP OID. */ + BitFlags mCertFlags; /**< Certificate data flags. */ + BitFlags mKeyUsageFlags; /**< Certificate key usage extensions flags. */ + BitFlags mKeyPurposeFlags; /**< Certificate extended key usage extensions flags. */ + uint8_t mPathLenConstraint; /**< Basic constraint: path length. */ + uint8_t mCertType; /**< Certificate type. */ struct { const uint8_t * R; /**< Pointer to the R element of the signature, encoded as ASN.1 DER Integer. */ @@ -275,16 +275,16 @@ struct ChipCertificateData */ struct ValidationContext { - uint32_t mEffectiveTime; /**< Current CHIP Epoch UTC time. */ - const ChipCertificateData * mTrustAnchor; /**< Pointer to the Trust Anchor Certificate data structure. */ - const ChipCertificateData * mSigningCert; /**< Pointer to the Signing Certificate data structure. */ - BitFlags mRequiredKeyUsages; /**< Key usage extensions that should be present in the - validated certificate. */ - BitFlags mRequiredKeyPurposes; /**< Extended Key usage extensions that should be present - in the validated certificate. */ - BitFlags mValidateFlags; /**< Certificate validation flags, specifying how a certificate - should be validated. */ - uint8_t mRequiredCertType; /**< Required certificate type. */ + uint32_t mEffectiveTime; /**< Current CHIP Epoch UTC time. */ + const ChipCertificateData * mTrustAnchor; /**< Pointer to the Trust Anchor Certificate data structure. */ + const ChipCertificateData * mSigningCert; /**< Pointer to the Signing Certificate data structure. */ + BitFlags mRequiredKeyUsages; /**< Key usage extensions that should be present in the + validated certificate. */ + BitFlags mRequiredKeyPurposes; /**< Extended Key usage extensions that should be present + in the validated certificate. */ + BitFlags mValidateFlags; /**< Certificate validation flags, specifying how a certificate + should be validated. */ + uint8_t mRequiredCertType; /**< Required certificate type. */ void Reset(); }; @@ -350,7 +350,7 @@ class DLL_EXPORT ChipCertificateSet * * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise **/ - CHIP_ERROR LoadCert(const uint8_t * chipCert, uint32_t chipCertLen, BitFlags decodeFlags); + CHIP_ERROR LoadCert(const uint8_t * chipCert, uint32_t chipCertLen, BitFlags decodeFlags); /** * @brief Load CHIP certificate into set. @@ -363,7 +363,7 @@ class DLL_EXPORT ChipCertificateSet * * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise **/ - CHIP_ERROR LoadCert(chip::TLV::TLVReader & reader, BitFlags decodeFlags); + CHIP_ERROR LoadCert(chip::TLV::TLVReader & reader, BitFlags decodeFlags); /** * @brief Load CHIP certificates into set. @@ -377,7 +377,7 @@ class DLL_EXPORT ChipCertificateSet * * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise **/ - CHIP_ERROR LoadCerts(const uint8_t * chipCerts, uint32_t chipCertsLen, BitFlags decodeFlags); + CHIP_ERROR LoadCerts(const uint8_t * chipCerts, uint32_t chipCertsLen, BitFlags decodeFlags); /** * @brief Load CHIP certificates into set. @@ -391,7 +391,7 @@ class DLL_EXPORT ChipCertificateSet * * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise **/ - CHIP_ERROR LoadCerts(chip::TLV::TLVReader & reader, BitFlags decodeFlags); + CHIP_ERROR LoadCerts(chip::TLV::TLVReader & reader, BitFlags decodeFlags); /** * @brief Add trusted anchor key to the certificate set. @@ -505,7 +505,7 @@ class DLL_EXPORT ChipCertificateSet * @return Returns a CHIP_ERROR on validation or other error, CHIP_NO_ERROR otherwise **/ CHIP_ERROR FindValidCert(const ChipDN & subjectDN, const CertificateKeyId & subjectKeyId, ValidationContext & context, - BitFlags validateFlags, uint8_t depth, ChipCertificateData *& cert); + BitFlags validateFlags, uint8_t depth, ChipCertificateData *& cert); /** * @brief Validate CHIP certificate. @@ -518,7 +518,7 @@ class DLL_EXPORT ChipCertificateSet * @return Returns a CHIP_ERROR on validation or other error, CHIP_NO_ERROR otherwise **/ CHIP_ERROR ValidateCert(const ChipCertificateData * cert, ValidationContext & context, - BitFlags validateFlags, uint8_t depth); + BitFlags validateFlags, uint8_t depth); }; /** diff --git a/src/credentials/CHIPCertFromX509.cpp b/src/credentials/CHIPCertFromX509.cpp index 51cdbf863cee3c..4f8854911055c5 100644 --- a/src/credentials/CHIPCertFromX509.cpp +++ b/src/credentials/CHIPCertFromX509.cpp @@ -363,8 +363,7 @@ static CHIP_ERROR ConvertExtension(ASN1Reader & reader, TLVWriter & writer) VerifyOrExit(keyUsageBits <= UINT16_MAX, err = ASN1_ERROR_INVALID_ENCODING); // Check that only supported flags are set. - BitFlags keyUsageFlags; - keyUsageFlags.SetRaw(static_cast(keyUsageBits)); + BitFlags keyUsageFlags(static_cast(keyUsageBits)); VerifyOrExit(keyUsageFlags.HasOnly( KeyUsageFlags::kDigitalSignature, KeyUsageFlags::kNonRepudiation, KeyUsageFlags::kKeyEncipherment, KeyUsageFlags::kDataEncipherment, KeyUsageFlags::kKeyAgreement, KeyUsageFlags::kKeyCertSign, diff --git a/src/credentials/CHIPCertToX509.cpp b/src/credentials/CHIPCertToX509.cpp index bb6fe2ccbe4745..3a2c09c2a38edf 100644 --- a/src/credentials/CHIPCertToX509.cpp +++ b/src/credentials/CHIPCertToX509.cpp @@ -382,7 +382,6 @@ static CHIP_ERROR DecodeConvertKeyUsageExtension(TLVReader & reader, ASN1Writer { CHIP_ERROR err; uint64_t keyUsageBits; - BitFlags keyUsageFlags; certData.mCertFlags.Set(CertFlags::kExtPresent_KeyUsage); @@ -395,16 +394,18 @@ static CHIP_ERROR DecodeConvertKeyUsageExtension(TLVReader & reader, ASN1Writer VerifyOrExit(keyUsageBits <= UINT16_MAX, err = CHIP_ERROR_UNSUPPORTED_CERT_FORMAT); - keyUsageFlags.SetRaw(static_cast(keyUsageBits)); - VerifyOrExit(keyUsageFlags.HasOnly(KeyUsageFlags::kDigitalSignature, KeyUsageFlags::kNonRepudiation, - KeyUsageFlags::kKeyEncipherment, KeyUsageFlags::kDataEncipherment, - KeyUsageFlags::kKeyAgreement, KeyUsageFlags::kKeyCertSign, KeyUsageFlags::kCRLSign, - KeyUsageFlags::kEncipherOnly, KeyUsageFlags::kEncipherOnly), - err = CHIP_ERROR_UNSUPPORTED_CERT_FORMAT); + { + BitFlags keyUsageFlags(static_cast(keyUsageBits)); + VerifyOrExit(keyUsageFlags.HasOnly(KeyUsageFlags::kDigitalSignature, KeyUsageFlags::kNonRepudiation, + KeyUsageFlags::kKeyEncipherment, KeyUsageFlags::kDataEncipherment, + KeyUsageFlags::kKeyAgreement, KeyUsageFlags::kKeyCertSign, KeyUsageFlags::kCRLSign, + KeyUsageFlags::kEncipherOnly, KeyUsageFlags::kEncipherOnly), + err = CHIP_ERROR_UNSUPPORTED_CERT_FORMAT); - ASN1_ENCODE_BIT_STRING(static_cast(keyUsageBits)); + ASN1_ENCODE_BIT_STRING(static_cast(keyUsageBits)); - certData.mKeyUsageFlags = keyUsageFlags; + certData.mKeyUsageFlags = keyUsageFlags; + } exit: return err; diff --git a/src/credentials/tests/CHIPCert_test_vectors.cpp b/src/credentials/tests/CHIPCert_test_vectors.cpp index 36893894ef0d0a..2126f59ea033b1 100644 --- a/src/credentials/tests/CHIPCert_test_vectors.cpp +++ b/src/credentials/tests/CHIPCert_test_vectors.cpp @@ -46,7 +46,7 @@ extern const uint8_t gTestCerts[] = { extern const size_t gNumTestCerts = sizeof(gTestCerts) / sizeof(gTestCerts[0]); -CHIP_ERROR GetTestCert(uint8_t certType, BitFlags certLoadFlags, const uint8_t *& certData, +CHIP_ERROR GetTestCert(uint8_t certType, BitFlags certLoadFlags, const uint8_t *& certData, uint32_t & certDataLen) { CHIP_ERROR err; @@ -103,8 +103,8 @@ const char * GetTestCertName(uint8_t certType) return nullptr; } -CHIP_ERROR LoadTestCert(ChipCertificateSet & certSet, uint8_t certType, BitFlags certLoadFlags, - BitFlags decodeFlags) +CHIP_ERROR LoadTestCert(ChipCertificateSet & certSet, uint8_t certType, BitFlags certLoadFlags, + BitFlags decodeFlags) { CHIP_ERROR err; ChipCertificateData * cert; diff --git a/src/credentials/tests/CHIPCert_test_vectors.h b/src/credentials/tests/CHIPCert_test_vectors.h index 3a2169405a9b44..15cd65ffb87cf9 100644 --- a/src/credentials/tests/CHIPCert_test_vectors.h +++ b/src/credentials/tests/CHIPCert_test_vectors.h @@ -28,6 +28,7 @@ #include #include +#include #include namespace chip { @@ -58,11 +59,11 @@ enum class TestCertLoadFlags : uint8_t kSetAppDefinedCertType = 0x20, }; -extern CHIP_ERROR GetTestCert(uint8_t certType, BitFlags certLoadFlags, const uint8_t *& certData, +extern CHIP_ERROR GetTestCert(uint8_t certType, BitFlags certLoadFlags, const uint8_t *& certData, uint32_t & certDataLen); extern const char * GetTestCertName(uint8_t certType); -extern CHIP_ERROR LoadTestCert(ChipCertificateSet & certSet, uint8_t certType, BitFlags certLoadFlags, - BitFlags decodeFlags); +extern CHIP_ERROR LoadTestCert(ChipCertificateSet & certSet, uint8_t certType, BitFlags certLoadFlags, + BitFlags decodeFlags); extern const uint8_t gTestCerts[]; extern const size_t gNumTestCerts; diff --git a/src/credentials/tests/TestChipCert.cpp b/src/credentials/tests/TestChipCert.cpp index deeb94b8b590fb..92ffdc1d9556e0 100644 --- a/src/credentials/tests/TestChipCert.cpp +++ b/src/credentials/tests/TestChipCert.cpp @@ -48,59 +48,59 @@ enum // (in either CHIP or DER form), or to decode the certificates. }; -static const BitFlags sIgnoreNotBeforeFlag(CertValidateFlags::kIgnoreNotBefore); -static const BitFlags sIgnoreNotAfterFlag(CertValidateFlags::kIgnoreNotAfter); - -static const BitFlags sNullDecodeFlag; -static const BitFlags sGenTBSHashFlag(CertDecodeFlags::kGenerateTBSHash); -static const BitFlags sTrustAnchorFlag(CertDecodeFlags::kIsTrustAnchor); - -static const BitFlags sNullLoadFlag; -static const BitFlags sDerFormFlag(TestCertLoadFlags::kDERForm); -static const BitFlags sSupIsCAFlag(TestCertLoadFlags::kSuppressIsCA); -static const BitFlags sSupKeyUsageFlag(TestCertLoadFlags::kSuppressKeyUsage); -static const BitFlags sSupKeyCertSignFlag(TestCertLoadFlags::kSuppressKeyCertSign); -static const BitFlags sPathLenZeroFlag(TestCertLoadFlags::kSetPathLenConstZero); -static const BitFlags sAppDefCertTypeFlag(TestCertLoadFlags::kSetAppDefinedCertType); - -static const BitFlags sNullKPFlag; -static const BitFlags sSA(KeyPurposeFlags::kServerAuth); -static const BitFlags sCA(KeyPurposeFlags::kClientAuth); -static const BitFlags sCS(KeyPurposeFlags::kCodeSigning); -static const BitFlags sEP(KeyPurposeFlags::kEmailProtection); -static const BitFlags sTS(KeyPurposeFlags::kTimeStamping); -static const BitFlags sOS(KeyPurposeFlags::kOCSPSigning); -static const BitFlags sSAandCA(sSA.Raw() | sCA.Raw()); -static const BitFlags sSAandCS(sSA.Raw() | sCS.Raw()); -static const BitFlags sSAandEP(sSA.Raw() | sEP.Raw()); -static const BitFlags sSAandTS(sSA.Raw() | sTS.Raw()); - -static const BitFlags sNullKUFlag; -static const BitFlags sDS(KeyUsageFlags::kDigitalSignature); -static const BitFlags sNR(KeyUsageFlags::kNonRepudiation); -static const BitFlags sKE(KeyUsageFlags::kKeyEncipherment); -static const BitFlags sDE(KeyUsageFlags::kDataEncipherment); -static const BitFlags sKA(KeyUsageFlags::kKeyAgreement); -static const BitFlags sKC(KeyUsageFlags::kKeyCertSign); -static const BitFlags sCR(KeyUsageFlags::kCRLSign); -static const BitFlags sEO(KeyUsageFlags::kEncipherOnly); -static const BitFlags sDO(KeyUsageFlags::kDecipherOnly); -static const BitFlags sDSandNR(sDS.Raw() | sNR.Raw()); -static const BitFlags sDSandKE(sDS.Raw() | sKE.Raw()); -static const BitFlags sDSandDE(sDS.Raw() | sDE.Raw()); -static const BitFlags sDSandKA(sDS.Raw() | sKA.Raw()); -static const BitFlags sDSandKC(sDS.Raw() | sKC.Raw()); -static const BitFlags sDSandCR(sDS.Raw() | sCR.Raw()); -static const BitFlags sDSandEO(sDS.Raw() | sEO.Raw()); -static const BitFlags sDSandDO(sDS.Raw() | sDO.Raw()); -static const BitFlags sKCandDS(sKC.Raw() | sDS.Raw()); -static const BitFlags sKCandNR(sKC.Raw() | sNR.Raw()); -static const BitFlags sKCandKE(sKC.Raw() | sKE.Raw()); -static const BitFlags sKCandDE(sKC.Raw() | sDE.Raw()); -static const BitFlags sKCandKA(sKC.Raw() | sKA.Raw()); -static const BitFlags sKCandCR(sKC.Raw() | sCR.Raw()); -static const BitFlags sKCandEO(sKC.Raw() | sEO.Raw()); -static const BitFlags sKCandDO(sKC.Raw() | sDO.Raw()); +static const BitFlags sIgnoreNotBeforeFlag(CertValidateFlags::kIgnoreNotBefore); +static const BitFlags sIgnoreNotAfterFlag(CertValidateFlags::kIgnoreNotAfter); + +static const BitFlags sNullDecodeFlag; +static const BitFlags sGenTBSHashFlag(CertDecodeFlags::kGenerateTBSHash); +static const BitFlags sTrustAnchorFlag(CertDecodeFlags::kIsTrustAnchor); + +static const BitFlags sNullLoadFlag; +static const BitFlags sDerFormFlag(TestCertLoadFlags::kDERForm); +static const BitFlags sSupIsCAFlag(TestCertLoadFlags::kSuppressIsCA); +static const BitFlags sSupKeyUsageFlag(TestCertLoadFlags::kSuppressKeyUsage); +static const BitFlags sSupKeyCertSignFlag(TestCertLoadFlags::kSuppressKeyCertSign); +static const BitFlags sPathLenZeroFlag(TestCertLoadFlags::kSetPathLenConstZero); +static const BitFlags sAppDefCertTypeFlag(TestCertLoadFlags::kSetAppDefinedCertType); + +static const BitFlags sNullKPFlag; +static const BitFlags sSA(KeyPurposeFlags::kServerAuth); +static const BitFlags sCA(KeyPurposeFlags::kClientAuth); +static const BitFlags sCS(KeyPurposeFlags::kCodeSigning); +static const BitFlags sEP(KeyPurposeFlags::kEmailProtection); +static const BitFlags sTS(KeyPurposeFlags::kTimeStamping); +static const BitFlags sOS(KeyPurposeFlags::kOCSPSigning); +static const BitFlags sSAandCA(sSA, sCA); +static const BitFlags sSAandCS(sSA, sCS); +static const BitFlags sSAandEP(sSA, sEP); +static const BitFlags sSAandTS(sSA, sTS); + +static const BitFlags sNullKUFlag; +static const BitFlags sDS(KeyUsageFlags::kDigitalSignature); +static const BitFlags sNR(KeyUsageFlags::kNonRepudiation); +static const BitFlags sKE(KeyUsageFlags::kKeyEncipherment); +static const BitFlags sDE(KeyUsageFlags::kDataEncipherment); +static const BitFlags sKA(KeyUsageFlags::kKeyAgreement); +static const BitFlags sKC(KeyUsageFlags::kKeyCertSign); +static const BitFlags sCR(KeyUsageFlags::kCRLSign); +static const BitFlags sEO(KeyUsageFlags::kEncipherOnly); +static const BitFlags sDO(KeyUsageFlags::kDecipherOnly); +static const BitFlags sDSandNR(sDS, sNR); +static const BitFlags sDSandKE(sDS, sKE); +static const BitFlags sDSandDE(sDS, sDE); +static const BitFlags sDSandKA(sDS, sKA); +static const BitFlags sDSandKC(sDS, sKC); +static const BitFlags sDSandCR(sDS, sCR); +static const BitFlags sDSandEO(sDS, sEO); +static const BitFlags sDSandDO(sDS, sDO); +static const BitFlags sKCandDS(sKC, sDS); +static const BitFlags sKCandNR(sKC, sNR); +static const BitFlags sKCandKE(sKC, sKE); +static const BitFlags sKCandDE(sKC, sDE); +static const BitFlags sKCandKA(sKC, sKA); +static const BitFlags sKCandCR(sKC, sCR); +static const BitFlags sKCandEO(sKC, sEO); +static const BitFlags sKCandDO(sKC, sDO); static CHIP_ERROR LoadStandardCerts(ChipCertificateSet & certSet) { @@ -207,8 +207,8 @@ static void TestChipCert_CertValidation(nlTestSuite * inSuite, void * inContext) struct { uint8_t Type; - BitFlags DecodeFlags; - BitFlags LoadFlags; + BitFlags DecodeFlags; + BitFlags LoadFlags; } InputCerts[kMaxCertsPerTestCase]; }; @@ -475,8 +475,8 @@ static void TestChipCert_CertUsage(nlTestSuite * inSuite, void * inContext) struct UsageTestCase { uint8_t mCertIndex; - BitFlags mRequiredKeyUsages; - BitFlags mRequiredKeyPurposes; + BitFlags mRequiredKeyUsages; + BitFlags mRequiredKeyPurposes; CHIP_ERROR mExpectedResult; }; diff --git a/src/include/platform/internal/GenericConfigurationManagerImpl.cpp b/src/include/platform/internal/GenericConfigurationManagerImpl.cpp index 024d66371424bc..9cde2a4db75aad 100644 --- a/src/include/platform/internal/GenericConfigurationManagerImpl.cpp +++ b/src/include/platform/internal/GenericConfigurationManagerImpl.cpp @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2020-2021 Project CHIP Authors * Copyright (c) 2019-2020 Google LLC. * Copyright (c) 2018 Nest Labs, Inc. * @@ -50,15 +50,14 @@ namespace Internal { template CHIP_ERROR GenericConfigurationManagerImpl::_Init() { - mFlags = 0; - // Cache flags indicating whether the device is currently service provisioned, is a member of a fabric, // is paired to an account, and/or provisioned with operational credentials. - SetFlag(mFlags, kFlag_IsServiceProvisioned, Impl()->ConfigValueExists(ImplClass::kConfigKey_ServiceConfig)); - SetFlag(mFlags, kFlag_IsMemberOfFabric, Impl()->ConfigValueExists(ImplClass::kConfigKey_FabricId)); - SetFlag(mFlags, kFlag_IsPairedToAccount, Impl()->ConfigValueExists(ImplClass::kConfigKey_PairedAccountId)); - SetFlag(mFlags, kFlag_OperationalDeviceCredentialsProvisioned, - Impl()->ConfigValueExists(ImplClass::kConfigKey_OperationalDeviceCert)); + mFlags.ClearAll() + .Set(Flags::kIsServiceProvisioned, Impl()->ConfigValueExists(ImplClass::kConfigKey_ServiceConfig)) + .Set(Flags::kIsMemberOfFabric, Impl()->ConfigValueExists(ImplClass::kConfigKey_FabricId)) + .Set(Flags::kIsPairedToAccount, Impl()->ConfigValueExists(ImplClass::kConfigKey_PairedAccountId)) + .Set(Flags::kOperationalDeviceCredentialsProvisioned, + Impl()->ConfigValueExists(ImplClass::kConfigKey_OperationalDeviceCert)); #if CHIP_ENABLE_ROTATING_DEVICE_ID mLifetimePersistedCounter.Init(CHIP_CONFIG_LIFETIIME_PERSISTED_COUNTER_KEY); @@ -524,7 +523,7 @@ CHIP_ERROR GenericConfigurationManagerImpl::_ClearOperationalDeviceCr Impl()->ClearConfigValue(ImplClass::kConfigKey_OperationalDeviceICACerts); Impl()->ClearConfigValue(ImplClass::kConfigKey_OperationalDevicePrivateKey); - ClearFlag(mFlags, kFlag_OperationalDeviceCredentialsProvisioned); + mFlags.Clear(Flags::kOperationalDeviceCredentialsProvisioned); return CHIP_NO_ERROR; } @@ -532,19 +531,19 @@ CHIP_ERROR GenericConfigurationManagerImpl::_ClearOperationalDeviceCr template bool GenericConfigurationManagerImpl::_OperationalDeviceCredentialsProvisioned() { - return ::chip::GetFlag(mFlags, kFlag_OperationalDeviceCredentialsProvisioned); + return mFlags.Has(Flags::kOperationalDeviceCredentialsProvisioned); } template bool GenericConfigurationManagerImpl::UseManufacturerCredentialsAsOperational() { - return ::chip::GetFlag(mFlags, kFlag_UseManufacturerCredentialsAsOperational); + return mFlags.Has(Flags::kUseManufacturerCredentialsAsOperational); } template void GenericConfigurationManagerImpl::_UseManufacturerCredentialsAsOperational(bool val) { - SetFlag(mFlags, kFlag_UseManufacturerCredentialsAsOperational, val); + mFlags.Set(Flags::kUseManufacturerCredentialsAsOperational, val); } #endif // CHIP_DEVICE_CONFIG_ENABLE_JUST_IN_TIME_PROVISIONING @@ -627,11 +626,11 @@ CHIP_ERROR GenericConfigurationManagerImpl::_StoreFabricId(uint64_t f { err = Impl()->WriteConfigValue(ImplClass::kConfigKey_FabricId, fabricId); SuccessOrExit(err); - SetFlag(mFlags, kFlag_IsMemberOfFabric); + mFlags.Set(Flags::kIsMemberOfFabric); } else { - ClearFlag(mFlags, kFlag_IsMemberOfFabric); + mFlags.Clear(Flags::kIsMemberOfFabric); err = Impl()->ClearConfigValue(ImplClass::kConfigKey_FabricId); SuccessOrExit(err); } @@ -689,7 +688,7 @@ CHIP_ERROR GenericConfigurationManagerImpl::_StorePairedAccountId(con err = Impl()->WriteConfigValueStr(ImplClass::kConfigKey_PairedAccountId, accountId, accountIdLen); SuccessOrExit(err); - SetFlag(mFlags, kFlag_IsPairedToAccount, (accountId != nullptr && accountIdLen != 0)); + mFlags.Set(Flags::kIsPairedToAccount, (accountId != nullptr && accountIdLen != 0)); exit: return err; @@ -712,8 +711,8 @@ CHIP_ERROR GenericConfigurationManagerImpl::_StoreServiceProvisioning err = _StorePairedAccountId(accountId, accountIdLen); SuccessOrExit(err); - SetFlag(mFlags, kFlag_IsServiceProvisioned); - SetFlag(mFlags, kFlag_IsPairedToAccount, (accountId != nullptr && accountIdLen != 0)); + mFlags.Set(Flags::kIsServiceProvisioned); + mFlags.Set(Flags::kIsPairedToAccount, (accountId != nullptr && accountIdLen != 0)); exit: if (err != CHIP_NO_ERROR) @@ -721,8 +720,8 @@ CHIP_ERROR GenericConfigurationManagerImpl::_StoreServiceProvisioning Impl()->ClearConfigValue(ImplClass::kConfigKey_ServiceId); Impl()->ClearConfigValue(ImplClass::kConfigKey_ServiceConfig); Impl()->ClearConfigValue(ImplClass::kConfigKey_PairedAccountId); - ClearFlag(mFlags, kFlag_IsServiceProvisioned); - ClearFlag(mFlags, kFlag_IsPairedToAccount); + mFlags.Clear(Flags::kIsServiceProvisioned); + mFlags.Clear(Flags::kIsPairedToAccount); } return err; } @@ -757,8 +756,8 @@ CHIP_ERROR GenericConfigurationManagerImpl::_ClearServiceProvisioning PlatformMgr().PostEvent(&event); } - ClearFlag(mFlags, kFlag_IsServiceProvisioned); - ClearFlag(mFlags, kFlag_IsPairedToAccount); + mFlags.Clear(Flags::kIsServiceProvisioned); + mFlags.Clear(Flags::kIsPairedToAccount); return CHIP_NO_ERROR; } @@ -851,19 +850,19 @@ GenericConfigurationManagerImpl::_GetBLEDeviceIdentificationInfo(Ble: template bool GenericConfigurationManagerImpl::_IsServiceProvisioned() { - return ::chip::GetFlag(mFlags, kFlag_IsServiceProvisioned); + return mFlags.Has(Flags::kIsServiceProvisioned); } template bool GenericConfigurationManagerImpl::_IsMemberOfFabric() { - return ::chip::GetFlag(mFlags, kFlag_IsMemberOfFabric); + return mFlags.Has(Flags::kIsMemberOfFabric); } template bool GenericConfigurationManagerImpl::_IsPairedToAccount() { - return ::chip::GetFlag(mFlags, kFlag_IsPairedToAccount); + return mFlags.Has(Flags::kIsPairedToAccount); } template diff --git a/src/include/platform/internal/GenericConfigurationManagerImpl.h b/src/include/platform/internal/GenericConfigurationManagerImpl.h index 5632a933a10b32..15fb258d753c5e 100644 --- a/src/include/platform/internal/GenericConfigurationManagerImpl.h +++ b/src/include/platform/internal/GenericConfigurationManagerImpl.h @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2020-2021 Project CHIP Authors * Copyright (c) 2019-2020 Google LLC. * Copyright (c) 2018 Nest Labs, Inc. * @@ -25,6 +25,8 @@ #pragma once +#include + #if CHIP_ENABLE_ROTATING_DEVICE_ID #include #endif @@ -125,16 +127,16 @@ class GenericConfigurationManagerImpl void _LogDeviceConfig(); protected: - enum + enum class Flags : uint8_t { - kFlag_IsServiceProvisioned = 0x01, - kFlag_IsMemberOfFabric = 0x02, - kFlag_IsPairedToAccount = 0x04, - kFlag_OperationalDeviceCredentialsProvisioned = 0x08, - kFlag_UseManufacturerCredentialsAsOperational = 0x10, + kIsServiceProvisioned = 0x01, + kIsMemberOfFabric = 0x02, + kIsPairedToAccount = 0x04, + kOperationalDeviceCredentialsProvisioned = 0x08, + kUseManufacturerCredentialsAsOperational = 0x10, }; - uint8_t mFlags; + BitFlags mFlags; #if CHIP_ENABLE_ROTATING_DEVICE_ID chip::LifetimePersistedCounter mLifetimePersistedCounter; #endif diff --git a/src/include/platform/internal/GenericConnectivityManagerImpl_Thread.cpp b/src/include/platform/internal/GenericConnectivityManagerImpl_Thread.cpp index 62c83513d78280..da76c0cd184fa6 100644 --- a/src/include/platform/internal/GenericConnectivityManagerImpl_Thread.cpp +++ b/src/include/platform/internal/GenericConnectivityManagerImpl_Thread.cpp @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2020-2021 Project CHIP Authors * Copyright (c) 2019 Nest Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -55,7 +55,7 @@ void GenericConnectivityManagerImpl_Thread::_OnPlatformEvent(const Ch template ConnectivityManager::ThreadMode GenericConnectivityManagerImpl_Thread::_GetThreadMode() { - if (GetFlag(mFlags, kFlag_IsApplicationControlled)) + if (mFlags.Has(Flags::kIsApplicationControlled)) { return ConnectivityManager::kThreadMode_ApplicationControlled; } @@ -75,11 +75,11 @@ CHIP_ERROR GenericConnectivityManagerImpl_Thread::_SetThreadMode(Conn if (val == ConnectivityManager::kThreadMode_ApplicationControlled) { - SetFlag(mFlags, kFlag_IsApplicationControlled); + mFlags.Set(Flags::kIsApplicationControlled); } else { - ClearFlag(mFlags, kFlag_IsApplicationControlled); + mFlags.Clear(Flags::kIsApplicationControlled); err = ThreadStackMgrImpl().SetThreadEnabled(val == ConnectivityManager::kThreadMode_Enabled); SuccessOrExit(err); @@ -92,15 +92,15 @@ CHIP_ERROR GenericConnectivityManagerImpl_Thread::_SetThreadMode(Conn template void GenericConnectivityManagerImpl_Thread::UpdateServiceConnectivity() { - bool haveServiceConnectivity = false; + constexpr bool haveServiceConnectivity = false; // If service connectivity via Thread has changed, post an event signaling the change. - if (GetFlag(mFlags, kFlag_HaveServiceConnectivity) != haveServiceConnectivity) + if (mFlags.Has(Flags::kHaveServiceConnectivity) != haveServiceConnectivity) { ChipLogProgress(DeviceLayer, "ConnectivityManager: Service connectivity via Thread %s", (haveServiceConnectivity) ? "ESTABLISHED" : "LOST"); - SetFlag(mFlags, kFlag_HaveServiceConnectivity, haveServiceConnectivity); + mFlags.Set(Flags::kHaveServiceConnectivity, haveServiceConnectivity); { ChipDeviceEvent event; diff --git a/src/include/platform/internal/GenericConnectivityManagerImpl_Thread.h b/src/include/platform/internal/GenericConnectivityManagerImpl_Thread.h index 5cb683a9e1138b..cdf127104227b9 100644 --- a/src/include/platform/internal/GenericConnectivityManagerImpl_Thread.h +++ b/src/include/platform/internal/GenericConnectivityManagerImpl_Thread.h @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2020-2021 Project CHIP Authors * Copyright (c) 2019 Nest Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -25,6 +25,9 @@ #pragma once #include +#include + +#include namespace chip { namespace DeviceLayer { @@ -73,13 +76,13 @@ class GenericConnectivityManagerImpl_Thread private: // ===== Private members reserved for use by this class only. - enum Flags + enum class Flags : uint8_t { - kFlag_HaveServiceConnectivity = 0x01, - kFlag_IsApplicationControlled = 0x02 + kHaveServiceConnectivity = 0x01, + kIsApplicationControlled = 0x02 }; - uint8_t mFlags; + BitFlags mFlags; ImplClass * Impl() { return static_cast(this); } }; @@ -87,7 +90,7 @@ class GenericConnectivityManagerImpl_Thread template inline void GenericConnectivityManagerImpl_Thread::_Init() { - mFlags = 0; + mFlags.ClearAll(); } template @@ -99,7 +102,7 @@ inline bool GenericConnectivityManagerImpl_Thread::_IsThreadEnabled() template inline bool GenericConnectivityManagerImpl_Thread::_IsThreadApplicationControlled() { - return GetFlag(mFlags, kFlag_IsApplicationControlled); + return mFlags.Has(Flags::kIsApplicationControlled); } template @@ -150,7 +153,7 @@ inline CHIP_ERROR GenericConnectivityManagerImpl_Thread::_SetThreadPo template inline bool GenericConnectivityManagerImpl_Thread::_HaveServiceConnectivityViaThread() { - return GetFlag(mFlags, kFlag_HaveServiceConnectivity); + return mFlags.Has(Flags::kHaveServiceConnectivity); } } // namespace Internal diff --git a/src/include/platform/internal/GenericConnectivityManagerImpl_WiFi.h b/src/include/platform/internal/GenericConnectivityManagerImpl_WiFi.h index fb10bbb62e6fe1..a363a4ac609e7f 100644 --- a/src/include/platform/internal/GenericConnectivityManagerImpl_WiFi.h +++ b/src/include/platform/internal/GenericConnectivityManagerImpl_WiFi.h @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2020-2021 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. @@ -82,11 +82,11 @@ class GenericConnectivityManagerImpl_WiFi static const char * _WiFiAPStateToStr(ConnectivityManager::WiFiAPState state); protected: - enum Flags + enum class ConnectivityFlags : uint16_t { - kFlag_HaveIPv4InternetConnectivity = 0x0001, - kFlag_HaveIPv6InternetConnectivity = 0x0002, - kFlag_AwaitingConnectivity = 0x0010, + kHaveIPv4InternetConnectivity = 0x0001, + kHaveIPv6InternetConnectivity = 0x0002, + kAwaitingConnectivity = 0x0010, }; private: diff --git a/src/lib/support/BitFlags.h b/src/lib/support/BitFlags.h index 4d22b66c952b60..fb99ed9d7d9d45 100644 --- a/src/lib/support/BitFlags.h +++ b/src/lib/support/BitFlags.h @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2020-2021 Project CHIP Authors * Copyright (c) 2013-2017 Nest Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -27,6 +27,7 @@ #include +#include #include namespace chip { @@ -34,115 +35,217 @@ namespace chip { /** * Stores bit flags in a type safe manner. * + * @tparam FlagsEnum is an `enum` or (preferably) `enum class` type. * @tparam StorageType is the underlying storage type (like uint16_t, uint32_t etc.) - * @tparam FlagsEnum is the typesafe flags setting + * and defaults to the underlying storage type of `FlagsEnum`. */ -template +template > class BitFlags { public: static_assert(sizeof(StorageType) >= sizeof(FlagsEnum), "All flags should fit in the storage type"); + using IntegerType = StorageType; - BitFlags() {} - BitFlags(const BitFlags &) = default; + BitFlags() : mValue(0) {} + BitFlags(const BitFlags & other) = default; BitFlags & operator=(const BitFlags &) = default; - explicit BitFlags(FlagsEnum v) { Set(v); } + explicit BitFlags(FlagsEnum value) : mValue(static_cast(value)) {} + explicit BitFlags(IntegerType value) : mValue(value) {} - explicit BitFlags(StorageType value) { SetRaw(value); } + template + BitFlags(FlagsEnum flag, Args &&... args) : mValue(Or(flag, std::forward(args)...)) + {} + + template + BitFlags(const BitFlags & flags, Args &&... args) : mValue(Or(flags, std::forward(args)...)) + {} - BitFlags & Set(FlagsEnum v) + template + BitFlags(IntegerType value, Args &&... args) : mValue(value | Or(std::forward(args)...)) + {} + + /** + * Set flag(s). + * + * @param other Flag(s) to set. Any flags not set in @a other are unaffected. + */ + BitFlags & Set(const BitFlags & other) { - mValue = static_cast(mValue | static_cast(v)); + mValue |= other.mValue; return *this; } - BitFlags & Clear(FlagsEnum v) + /** + * Set flag(s). + * + * @param flag Typed flag(s) to set. Any flags not in @a v are unaffected. + */ + BitFlags & Set(FlagsEnum flag) { - mValue &= static_cast(~static_cast(v)); + mValue |= static_cast(flag); return *this; } - BitFlags & Set(FlagsEnum v, bool isSet) { return isSet ? Set(v) : Clear(v); } - - bool Has(FlagsEnum v) const { return (mValue & static_cast(v)) != 0; } - - bool Has(StorageType other) const { return (mValue & other) == other; } + /** + * Set or clear flag(s). + * + * @param flag Typed flag(s) to set or clear. Any flags not in @a flag are unaffected. + * @param isSet If true, set the flag; if false, clear it. + */ + BitFlags & Set(FlagsEnum flag, bool isSet) { return isSet ? Set(flag) : Clear(flag); } + + /** + * Clear flag(s). + * + * @param other Typed flag(s) to clear. Any flags not in @a other are unaffected. + */ + BitFlags & Clear(const BitFlags & other) + { + mValue &= ~other.mValue; + return *this; + } - BitFlags & Set(const BitFlags & other) + /** + * Clear flag(s). + * + * @param flag Typed flag(s) to clear. Any flags not in @a flag are unaffected. + */ + BitFlags & Clear(FlagsEnum flag) { - mValue |= other.mValue; + mValue &= static_cast(~static_cast(flag)); return *this; } - StorageType Raw() const { return mValue; } - BitFlags & SetRaw(StorageType value) + /** + * Clear all flags. + */ + BitFlags & ClearAll() { - mValue = value; + mValue = 0; return *this; } - /** Check that no flags outside the arguments are set.*/ + /** + * Check whether flag(s) are set. + * + * @param flag Flag(s) to test. + * @returns True if any flag in @a flag is set, otherwise false. + */ + bool Has(FlagsEnum flag) const { return (mValue & static_cast(flag)) != 0; } + + /** + * Check that no flags outside the arguments are set. + * + * @param args Flags to test. Arguments can be BitFlags, BitFlags, or FlagsEnum. + * @returns True if no flag is set other than those passed. + * False if any flag is set other than those passed. + * + * @note Flags passed need not be set; this test only requires that no *other* flags be set. + */ template bool HasOnly(Args &&... args) const { - return IsZeroAfterClearing(mValue, std::forward(args)...); + return (mValue & Or(std::forward(args)...)) == mValue; } -private: - StorageType mValue = 0; + /** + * Check that all given flags are set. + * + * @param args Flags to test. Arguments can be BitFlags, BitFlags, or FlagsEnum. + * @returns True if all given flags are set. + * False if any given flag is not set. + */ + template + bool HasAll(Args &&... args) const + { + const IntegerType all = Or(std::forward(args)...); + return (mValue & all) == all; + } + /** + * Check that at least one of the given flags is set. + * + * @param args Flags to test. Arguments can be BitFlags, BitFlags, or FlagsEnum. + * @returns True if all given flags are set. + * False if any given flag is not set. + */ template - static bool IsZeroAfterClearing(StorageType value, FlagsEnum flagToClear, Args &&... args) + bool HasAny(Args &&... args) const { - value &= static_cast(~static_cast(flagToClear)); - return IsZeroAfterClearing(value, std::forward(args)...); + return (mValue & Or(std::forward(args)...)) != 0; } - static bool IsZeroAfterClearing(StorageType value) { return value == 0; } -}; + /** + * Check that at least one flag is set. + * + * @returns True if any flag is set, false otherwise. + */ + bool HasAny() const { return mValue != 0; } + + /** + * Find the logical intersection of flags. + * + * @param lhs Some flags. + * @param rhs Some flags. + * @returns Flags set in both @a lhs and @a rhs. + * + * @note: A multi-argument `BitFlags` constructor serves the function of `operator|`. + */ + friend BitFlags operator&(BitFlags lhs, const BitFlags & rhs) + { + return BitFlags(lhs.mValue & rhs.mValue); + } -/** - * @deprecated Use typesafe BitFlags class instead. - */ -template -inline bool GetFlag(const FlagsT & inFlags, const FlagT inFlag) -{ - return (inFlags & static_cast(inFlag)) != 0; -} + /** + * Get the flags as the type FlagsEnum. + * + * @note This allows easily storing flags as a base FlagsEnum in a POD type, + * and enables equality comparisons. + */ + operator FlagsEnum() const { return static_cast(mValue); } + + /** + * Set and/or clear all flags with a value of the underlying storage type. + * + * @param value New storage value. + */ + BitFlags & SetRaw(IntegerType value) + { + mValue = value; + return *this; + } -/** - * @deprecated Use typesafe BitFlags class instead. - */ -template -inline void ClearFlag(FlagsT & inFlags, const FlagT inFlag) -{ - inFlags &= static_cast(~static_cast(inFlag)); -} + /** + * Get the flags as the underlying integer type. + * + * @note This is intended to be used only to store flags into a raw binary record. + */ + IntegerType Raw() const { return mValue; } -/** - * @deprecated Use typesafe BitFlags class instead. - */ -template -inline void SetFlag(FlagsT & inFlags, const FlagT inFlag) -{ - inFlags = static_cast(inFlags | static_cast(inFlag)); -} + /** + * Get the address of the flags as a pointer to the underlying integer type. + * + * @note This is intended to be used only to read flags from a raw binary record. + */ + StorageType * RawStorage() { return &mValue; } -/** - * @deprecated Use typesafe BitFlags class instead. - */ -template -inline void SetFlag(FlagsT & inFlags, const FlagT inFlag, const bool inValue) -{ - if (inValue) +private: + // Find the union of BitFlags and/or FlagsEnum values. + template + static constexpr IntegerType Or(FlagsEnum flag, Args &&... args) { - SetFlag(inFlags, inFlag); + return static_cast(flag) | Or(std::forward(args)...); } - else + template + static constexpr IntegerType Or(const BitFlags & flags, Args &&... args) { - ClearFlag(inFlags, inFlag); + return flags.mValue | Or(std::forward(args)...); } -} + static constexpr IntegerType Or(FlagsEnum value) { return static_cast(value); } + static constexpr IntegerType Or(const BitFlags & flags) { return flags.Raw(); } + + StorageType mValue = 0; +}; } // namespace chip diff --git a/src/lib/support/BytesToHex.cpp b/src/lib/support/BytesToHex.cpp index e1f40939c5f738..11b2714b891826 100644 --- a/src/lib/support/BytesToHex.cpp +++ b/src/lib/support/BytesToHex.cpp @@ -38,7 +38,7 @@ char NibbleToHex(uint8_t nibble, bool uppercase) } // namespace -CHIP_ERROR BytesToHex(const uint8_t * src_bytes, size_t src_size, char * dest_hex, size_t dest_size_max, HexFlags flags) +CHIP_ERROR BytesToHex(const uint8_t * src_bytes, size_t src_size, char * dest_hex, size_t dest_size_max, BitFlags flags) { if ((src_bytes == nullptr) || (dest_hex == nullptr)) { @@ -52,14 +52,14 @@ CHIP_ERROR BytesToHex(const uint8_t * src_bytes, size_t src_size, char * dest_he return CHIP_ERROR_INVALID_ARGUMENT; } - bool nul_terminate = (static_cast(flags) & static_cast(HexFlags::kNullTerminate)) != 0; + bool nul_terminate = flags.Has(HexFlags::kNullTerminate); size_t expected_output_size = (src_size * 2u) + (nul_terminate ? 1u : 0u); if (dest_size_max < expected_output_size) { return CHIP_ERROR_BUFFER_TOO_SMALL; } - bool uppercase = (static_cast(flags) & static_cast(HexFlags::kUppercase)) != 0; + bool uppercase = flags.Has(HexFlags::kUppercase); char * cursor = dest_hex; for (size_t byte_idx = 0; byte_idx < src_size; ++byte_idx) { diff --git a/src/lib/support/BytesToHex.h b/src/lib/support/BytesToHex.h index b62617b5250572..bbd20251840af4 100644 --- a/src/lib/support/BytesToHex.h +++ b/src/lib/support/BytesToHex.h @@ -18,13 +18,15 @@ #pragma once #include +#include + #include #include namespace chip { namespace Encoding { -enum HexFlags : int +enum class HexFlags : int { kNone = 0u, // Use uppercase A-F if set otherwise, lowercase a-f @@ -68,7 +70,7 @@ enum HexFlags : int * @return CHIP_NO_ERROR on success */ -CHIP_ERROR BytesToHex(const uint8_t * src_bytes, size_t src_size, char * dest_hex, size_t dest_size_max, HexFlags flags); +CHIP_ERROR BytesToHex(const uint8_t * src_bytes, size_t src_size, char * dest_hex, size_t dest_size_max, BitFlags flags); // Alias for Uppercase option, no null-termination inline CHIP_ERROR BytesToUppercaseHexBuffer(const uint8_t * src_bytes, size_t src_size, char * dest_hex_buf, size_t dest_size_max) diff --git a/src/messaging/ExchangeContext.h b/src/messaging/ExchangeContext.h index 2c9917aec2cda6..35e33d4f54255a 100644 --- a/src/messaging/ExchangeContext.h +++ b/src/messaging/ExchangeContext.h @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2020-2021 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. @@ -205,7 +205,7 @@ class DLL_EXPORT ExchangeContext : public ReferenceCounted mFlags; // Internal state flags + BitFlags mFlags; // Internal state flags /** * Search for an existing exchange that the message applies to. diff --git a/src/messaging/Flags.h b/src/messaging/Flags.h index aafa7d8812ff2c..61d7dd827f2da8 100644 --- a/src/messaging/Flags.h +++ b/src/messaging/Flags.h @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2020-2021 Project CHIP Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -55,7 +55,7 @@ enum class MessageFlagValues : uint32_t kViaEphemeralUDPPort = 0x00040000, }; -using MessageFlags = BitFlags; +using MessageFlags = BitFlags; enum class SendMessageFlags : uint16_t { @@ -76,7 +76,7 @@ enum class SendMessageFlags : uint16_t kNoAutoRequestAck = 0x0400, }; -using SendFlags = BitFlags; +using SendFlags = BitFlags; } // namespace Messaging } // namespace chip diff --git a/src/messaging/ReliableMessageContext.cpp b/src/messaging/ReliableMessageContext.cpp index 577e9a8beed7ff..d1cefb95bf5823 100644 --- a/src/messaging/ReliableMessageContext.cpp +++ b/src/messaging/ReliableMessageContext.cpp @@ -181,7 +181,7 @@ CHIP_ERROR ReliableMessageContext::HandleRcvdAck(uint32_t AckMsgId) return err; } -CHIP_ERROR ReliableMessageContext::HandleNeedsAck(uint32_t MessageId, BitFlags MsgFlags) +CHIP_ERROR ReliableMessageContext::HandleNeedsAck(uint32_t MessageId, BitFlags MsgFlags) { CHIP_ERROR err = CHIP_NO_ERROR; @@ -260,7 +260,7 @@ CHIP_ERROR ReliableMessageContext::SendStandaloneAckMessage() if (mExchange != nullptr) { err = mExchange->SendMessage(Protocols::SecureChannel::MsgType::StandaloneAck, std::move(msgBuf), - BitFlags{ SendMessageFlags::kNoAutoRequestAck }); + BitFlags{ SendMessageFlags::kNoAutoRequestAck }); } else { diff --git a/src/messaging/ReliableMessageContext.h b/src/messaging/ReliableMessageContext.h index 77c55dbf4ba075..57bf18e688ca07 100644 --- a/src/messaging/ReliableMessageContext.h +++ b/src/messaging/ReliableMessageContext.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2020-2021 Project CHIP Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -203,12 +203,12 @@ class ReliableMessageContext kFlagMsgRcvdFromPeer = 0x0080, }; - BitFlags mFlags; // Internal state flags + BitFlags mFlags; // Internal state flags void Retain(); void Release(); CHIP_ERROR HandleRcvdAck(uint32_t AckMsgId); - CHIP_ERROR HandleNeedsAck(uint32_t MessageId, BitFlags Flags); + CHIP_ERROR HandleNeedsAck(uint32_t MessageId, BitFlags Flags); private: friend class ReliableMessageMgr; diff --git a/src/platform/EFR32/BLEManagerImpl.cpp b/src/platform/EFR32/BLEManagerImpl.cpp index 85d44f32a1e858..82e040402e1c90 100644 --- a/src/platform/EFR32/BLEManagerImpl.cpp +++ b/src/platform/EFR32/BLEManagerImpl.cpp @@ -171,7 +171,7 @@ CHIP_ERROR BLEManagerImpl::_Init() CHIP_DEVICE_CONFIG_BLE_APP_TASK_PRIORITY, /* Priority at which the task is created. */ NULL); /* Variable to hold the task's data structure. */ - mFlags = CHIP_DEVICE_CONFIG_CHIPOBLE_ENABLE_ADVERTISING_AUTOSTART ? kFlag_AdvertisingEnabled : 0; + mFlags.ClearAll().Set(Flags::kAdvertisingEnabled, CHIP_DEVICE_CONFIG_CHIPOBLE_ENABLE_ADVERTISING_AUTOSTART); PlatformMgr().ScheduleWork(DriveBLEState, 0); exit: @@ -315,9 +315,9 @@ CHIP_ERROR BLEManagerImpl::_SetAdvertisingEnabled(bool val) VerifyOrExit(mServiceMode != ConnectivityManager::kCHIPoBLEServiceMode_NotSupported, err = CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE); - if (GetFlag(mFlags, kFlag_AdvertisingEnabled) != val) + if (mFlags.Has(Flags::kAdvertisingEnabled) != val) { - SetFlag(mFlags, kFlag_AdvertisingEnabled, val); + mFlags.Set(Flags::kAdvertisingEnabled, val); PlatformMgr().ScheduleWork(DriveBLEState, 0); } @@ -331,9 +331,9 @@ CHIP_ERROR BLEManagerImpl::_SetFastAdvertisingEnabled(bool val) VerifyOrExit(mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_NotSupported, err = CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE); - if (GetFlag(mFlags, kFlag_FastAdvertisingEnabled) != val) + if (mFlags.Has(Flags::kFastAdvertisingEnabled) != val) { - SetFlag(mFlags, kFlag_FastAdvertisingEnabled, val); + mFlags.Set(Flags::kFastAdvertisingEnabled, val); PlatformMgr().ScheduleWork(DriveBLEState, 0); } @@ -366,7 +366,7 @@ CHIP_ERROR BLEManagerImpl::_SetDeviceName(const char * deviceName) return CHIP_ERROR_INVALID_ARGUMENT; } strcpy(mDeviceName, deviceName); - SetFlag(mFlags, kFlag_DeviceNameSet, true); + mFlags.Set(Flags::kDeviceNameSet); ChipLogProgress(DeviceLayer, "Setting device name to : \"%s\"", deviceName); static_assert(kMaxDeviceNameLength <= UINT16_MAX, "deviceName length might not fit in a uint8_t"); ret = sl_bt_gatt_server_write_attribute_value(gattdb_device_name, 0, strlen(deviceName), (uint8_t *) deviceName); @@ -539,14 +539,14 @@ void BLEManagerImpl::DriveBLEState(void) CHIP_ERROR err = CHIP_NO_ERROR; // Check if BLE stack is initialized - VerifyOrExit(GetFlag(mFlags, kFlag_EFRBLEStackInitialized), /* */); + VerifyOrExit(mFlags.Has(Flags::kEFRBLEStackInitialized), /* */); // Start advertising if needed... - if (mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_Enabled && GetFlag(mFlags, kFlag_AdvertisingEnabled)) + if (mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_Enabled && mFlags.Has(Flags::kAdvertisingEnabled)) { // Start/re-start advertising if not already started, or if there is a pending change // to the advertising configuration. - if (!GetFlag(mFlags, kFlag_Advertising) || GetFlag(mFlags, kFlag_RestartAdvertising)) + if (!mFlags.Has(Flags::kAdvertising) || mFlags.Has(Flags::kRestartAdvertising)) { err = StartAdvertising(); SuccessOrExit(err); @@ -554,7 +554,7 @@ void BLEManagerImpl::DriveBLEState(void) } // Otherwise, stop advertising if it is enabled. - else if (GetFlag(mFlags, kFlag_Advertising)) + else if (mFlags.Has(Flags::kAdvertising)) { err = StopAdvertising(); SuccessOrExit(err); @@ -587,7 +587,7 @@ CHIP_ERROR BLEManagerImpl::ConfigureAdvertisingData(void) err = ConfigurationMgr().GetBLEDeviceIdentificationInfo(mDeviceIdInfo); SuccessOrExit(err); - if (!GetFlag(mFlags, kFlag_DeviceNameSet)) + if (!mFlags.Has(Flags::kDeviceNameSet)) { snprintf(mDeviceName, sizeof(mDeviceName), "%s%04" PRIX32, CHIP_DEVICE_CONFIG_BLE_DEVICE_NAME_PREFIX, (uint32_t) 0); @@ -685,10 +685,10 @@ CHIP_ERROR BLEManagerImpl::StartAdvertising(void) err = ConfigureAdvertisingData(); SuccessOrExit(err); - ClearFlag(mFlags, kFlag_RestartAdvertising); + mFlags.Clear(Flags::kRestartAdvertising); interval_min = interval_max = - ((numConnectionss == 0 && !ConfigurationMgr().IsPairedToAccount()) || GetFlag(mFlags, kFlag_FastAdvertisingEnabled)) + ((numConnectionss == 0 && !ConfigurationMgr().IsPairedToAccount()) || mFlags.Has(Flags::kFastAdvertisingEnabled)) ? CHIP_DEVICE_CONFIG_BLE_FAST_ADVERTISING_INTERVAL : CHIP_DEVICE_CONFIG_BLE_SLOW_ADVERTISING_INTERVAL; @@ -700,7 +700,7 @@ CHIP_ERROR BLEManagerImpl::StartAdvertising(void) if (SL_STATUS_OK == ret) { - SetFlag(mFlags, kFlag_Advertising, true); + mFlags.Set(Flags::kAdvertising); } err = MapBLEError(ret); @@ -714,10 +714,9 @@ CHIP_ERROR BLEManagerImpl::StopAdvertising(void) CHIP_ERROR err = CHIP_NO_ERROR; sl_status_t ret; - if (GetFlag(mFlags, kFlag_Advertising)) + if (mFlags.Has(Flags::kAdvertising)) { - ClearFlag(mFlags, kFlag_Advertising); - ClearFlag(mFlags, kFlag_RestartAdvertising); + mFlags.Clear(Flags::kAdvertising).Clear(Flags::kRestartAdvertising); ret = sl_bt_advertiser_stop(advertising_set_handle); sl_bt_advertiser_delete_set(advertising_set_handle); @@ -754,7 +753,7 @@ void BLEManagerImpl::UpdateMtu(volatile sl_bt_msg_t * evt) void BLEManagerImpl::HandleBootEvent(void) { - SetFlag(mFlags, kFlag_EFRBLEStackInitialized, true); + mFlags.Set(Flags::kEFRBLEStackInitialized); PlatformMgr().ScheduleWork(DriveBLEState, 0); } @@ -768,7 +767,7 @@ void BLEManagerImpl::HandleConnectEvent(volatile sl_bt_msg_t * evt) AddConnection(connHandle, bondingHandle); - // SetFlag(mFlags, kFlag_RestartAdvertising, true); + // mFlags.Set(Flags::kRestartAdvertising); PlatformMgr().ScheduleWork(DriveBLEState, 0); } @@ -808,7 +807,7 @@ void BLEManagerImpl::HandleConnectionCloseEvent(volatile sl_bt_msg_t * evt) // Arrange to re-enable connectable advertising in case it was disabled due to the // maximum connection limit being reached. - SetFlag(mFlags, kFlag_RestartAdvertising, true); + mFlags.Set(Flags::kRestartAdvertising); PlatformMgr().ScheduleWork(DriveBLEState, 0); } } diff --git a/src/platform/EFR32/BLEManagerImpl.h b/src/platform/EFR32/BLEManagerImpl.h index 84cfc6d0c9b80c..3d1df68cbecfaa 100644 --- a/src/platform/EFR32/BLEManagerImpl.h +++ b/src/platform/EFR32/BLEManagerImpl.h @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2020-2021 Project CHIP Authors * Copyright (c) 2019 Nest Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -90,14 +90,14 @@ class BLEManagerImpl final : public BLEManager, private BleLayer, private BlePla // ===== Private members reserved for use by this class only. - enum + enum class Flags : uint16_t { - kFlag_AdvertisingEnabled = 0x0001, - kFlag_FastAdvertisingEnabled = 0x0002, - kFlag_Advertising = 0x0004, - kFlag_RestartAdvertising = 0x0008, - kFlag_EFRBLEStackInitialized = 0x0010, - kFlag_DeviceNameSet = 0x0020, + kAdvertisingEnabled = 0x0001, + kFastAdvertisingEnabled = 0x0002, + kAdvertising = 0x0004, + kRestartAdvertising = 0x0008, + kEFRBLEStackInitialized = 0x0010, + kDeviceNameSet = 0x0020, }; enum @@ -121,7 +121,7 @@ class BLEManagerImpl final : public BLEManager, private BleLayer, private BlePla CHIPoBLEConState mBleConnections[kMaxConnections]; uint8_t mIndConfId[kMaxConnections]; CHIPoBLEServiceMode mServiceMode; - uint16_t mFlags; + BitFlags mFlags; char mDeviceName[kMaxDeviceNameLength + 1]; // The advertising set handle allocated from Bluetooth stack. uint8_t advertising_set_handle = 0xff; @@ -182,12 +182,12 @@ inline BLEManager::CHIPoBLEServiceMode BLEManagerImpl::_GetCHIPoBLEServiceMode(v inline bool BLEManagerImpl::_IsAdvertisingEnabled(void) { - return GetFlag(mFlags, kFlag_AdvertisingEnabled); + return mFlags.Has(Flags::kAdvertisingEnabled); } inline bool BLEManagerImpl::_IsFastAdvertisingEnabled(void) { - return GetFlag(mFlags, kFlag_FastAdvertisingEnabled); + return mFlags.Has(Flags::kFastAdvertisingEnabled); } } // namespace Internal diff --git a/src/platform/ESP32/BLEManagerImpl.h b/src/platform/ESP32/BLEManagerImpl.h index 0cafee56d59a10..702a0ac37c310a 100644 --- a/src/platform/ESP32/BLEManagerImpl.h +++ b/src/platform/ESP32/BLEManagerImpl.h @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2020-2021 Project CHIP Authors * Copyright (c) 2018 Nest Labs, Inc. * All rights reserved. * @@ -117,20 +117,20 @@ class BLEManagerImpl final : public BLEManager, // ===== Private members reserved for use by this class only. - enum + enum class Flags : uint16_t { - kFlag_AsyncInitCompleted = 0x0001, /**< One-time asynchronous initialization actions have been performed. */ - kFlag_ESPBLELayerInitialized = 0x0002, /**< The ESP BLE layer has been initialized. */ - kFlag_AppRegistered = 0x0004, /**< The CHIPoBLE application has been registered with the ESP BLE layer. */ - kFlag_AttrsRegistered = 0x0008, /**< The CHIPoBLE GATT attributes have been registered with the ESP BLE layer. */ - kFlag_GATTServiceStarted = 0x0010, /**< The CHIPoBLE GATT service has been started. */ - kFlag_AdvertisingConfigured = 0x0020, /**< CHIPoBLE advertising has been configured in the ESP BLE layer. */ - kFlag_Advertising = 0x0040, /**< The system is currently CHIPoBLE advertising. */ - kFlag_ControlOpInProgress = 0x0080, /**< An async control operation has been issued to the ESP BLE layer. */ - kFlag_AdvertisingEnabled = 0x0100, /**< The application has enabled CHIPoBLE advertising. */ - kFlag_FastAdvertisingEnabled = 0x0200, /**< The application has enabled fast advertising. */ - kFlag_UseCustomDeviceName = 0x0400, /**< The application has configured a custom BLE device name. */ - kFlag_AdvertisingRefreshNeeded = 0x0800, /**< The advertising configuration/state in ESP BLE layer needs to be updated. */ + kAsyncInitCompleted = 0x0001, /**< One-time asynchronous initialization actions have been performed. */ + kESPBLELayerInitialized = 0x0002, /**< The ESP BLE layer has been initialized. */ + kAppRegistered = 0x0004, /**< The CHIPoBLE application has been registered with the ESP BLE layer. */ + kAttrsRegistered = 0x0008, /**< The CHIPoBLE GATT attributes have been registered with the ESP BLE layer. */ + kGATTServiceStarted = 0x0010, /**< The CHIPoBLE GATT service has been started. */ + kAdvertisingConfigured = 0x0020, /**< CHIPoBLE advertising has been configured in the ESP BLE layer. */ + kAdvertising = 0x0040, /**< The system is currently CHIPoBLE advertising. */ + kControlOpInProgress = 0x0080, /**< An async control operation has been issued to the ESP BLE layer. */ + kAdvertisingEnabled = 0x0100, /**< The application has enabled CHIPoBLE advertising. */ + kFastAdvertisingEnabled = 0x0200, /**< The application has enabled fast advertising. */ + kUseCustomDeviceName = 0x0400, /**< The application has configured a custom BLE device name. */ + kAdvertisingRefreshNeeded = 0x0800, /**< The advertising configuration/state in ESP BLE layer needs to be updated. */ }; enum @@ -183,7 +183,7 @@ class BLEManagerImpl final : public BLEManager, uint16_t mRXCharAttrHandle; uint16_t mTXCharAttrHandle; uint16_t mTXCharCCCDAttrHandle; - uint16_t mFlags; + BitFlags mFlags; char mDeviceName[kMaxDeviceNameLength + 1]; void DriveBLEState(void); @@ -266,17 +266,17 @@ inline BLEManager::CHIPoBLEServiceMode BLEManagerImpl::_GetCHIPoBLEServiceMode(v inline bool BLEManagerImpl::_IsAdvertisingEnabled(void) { - return GetFlag(mFlags, kFlag_AdvertisingEnabled); + return mFlags.Has(Flags::kAdvertisingEnabled); } inline bool BLEManagerImpl::_IsFastAdvertisingEnabled(void) { - return GetFlag(mFlags, kFlag_FastAdvertisingEnabled); + return mFlags.Has(Flags::kFastAdvertisingEnabled); } inline bool BLEManagerImpl::_IsAdvertising(void) { - return GetFlag(mFlags, kFlag_Advertising); + return mFlags.Has(Flags::kAdvertising); } } // namespace Internal diff --git a/src/platform/ESP32/ConnectivityManagerImpl.cpp b/src/platform/ESP32/ConnectivityManagerImpl.cpp index 8c0aff5c4c43ee..caa48dedf5c276 100644 --- a/src/platform/ESP32/ConnectivityManagerImpl.cpp +++ b/src/platform/ESP32/ConnectivityManagerImpl.cpp @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2020-2021 Project CHIP Authors * Copyright (c) 2018 Nest Labs, Inc. * All rights reserved. * @@ -401,7 +401,7 @@ CHIP_ERROR ConnectivityManagerImpl::_Init() mWiFiAPState = kWiFiAPState_NotActive; mWiFiStationReconnectIntervalMS = CHIP_DEVICE_CONFIG_WIFI_STATION_RECONNECT_INTERVAL; mWiFiAPIdleTimeoutMS = CHIP_DEVICE_CONFIG_WIFI_AP_IDLE_TIMEOUT; - mFlags = 0; + mFlags.SetRaw(0); // TODO Initialize the Chip Addressing and Routing Module. @@ -902,10 +902,10 @@ void ConnectivityManagerImpl::DriveAPState(::chip::System::Layer * aLayer, void void ConnectivityManagerImpl::UpdateInternetConnectivityState(void) { - bool haveIPv4Conn = false; - bool haveIPv6Conn = false; - bool hadIPv4Conn = GetFlag(mFlags, kFlag_HaveIPv4InternetConnectivity); - bool hadIPv6Conn = GetFlag(mFlags, kFlag_HaveIPv6InternetConnectivity); + bool haveIPv4Conn = false; + bool haveIPv6Conn = false; + const bool hadIPv4Conn = mFlags.Has(ConnectivityFlags::kHaveIPv4InternetConnectivity); + const bool hadIPv6Conn = mFlags.Has(ConnectivityFlags::kHaveIPv6InternetConnectivity); IPAddress addr; // If the WiFi station is currently in the connected state... @@ -962,8 +962,8 @@ void ConnectivityManagerImpl::UpdateInternetConnectivityState(void) if (haveIPv4Conn != hadIPv4Conn || haveIPv6Conn != hadIPv6Conn) { // Update the current state. - SetFlag(mFlags, kFlag_HaveIPv4InternetConnectivity, haveIPv4Conn); - SetFlag(mFlags, kFlag_HaveIPv6InternetConnectivity, haveIPv6Conn); + mFlags.Set(ConnectivityFlags::kHaveIPv4InternetConnectivity, haveIPv4Conn) + .Set(ConnectivityFlags::kHaveIPv6InternetConnectivity, haveIPv6Conn); // Alert other components of the state change. ChipDeviceEvent event; diff --git a/src/platform/ESP32/ConnectivityManagerImpl.h b/src/platform/ESP32/ConnectivityManagerImpl.h index 2a532932fdbc1f..f698f3839e1d55 100644 --- a/src/platform/ESP32/ConnectivityManagerImpl.h +++ b/src/platform/ESP32/ConnectivityManagerImpl.h @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2020-2021 Project CHIP Authors * Copyright (c) 2018 Nest Labs, Inc. * All rights reserved. * @@ -28,6 +28,7 @@ #include #endif #include +#include #include "esp_event.h" @@ -67,6 +68,7 @@ class ConnectivityManagerImpl final : public ConnectivityManager, friend class ConnectivityManager; private: + using Flags = GenericConnectivityManagerImpl_WiFi::ConnectivityFlags; // ===== Members that implement the ConnectivityManager abstract interface. WiFiStationMode _GetWiFiStationMode(void); @@ -114,7 +116,7 @@ class ConnectivityManagerImpl final : public ConnectivityManager, WiFiAPState mWiFiAPState; uint32_t mWiFiStationReconnectIntervalMS; uint32_t mWiFiAPIdleTimeoutMS; - uint16_t mFlags; + BitFlags mFlags; void DriveStationState(void); void OnStationConnected(void); @@ -172,12 +174,12 @@ inline uint32_t ConnectivityManagerImpl::_GetWiFiAPIdleTimeoutMS(void) inline bool ConnectivityManagerImpl::_HaveIPv4InternetConnectivity(void) { - return ::chip::GetFlag(mFlags, kFlag_HaveIPv4InternetConnectivity); + return mFlags.Has(Flags::kHaveIPv4InternetConnectivity); } inline bool ConnectivityManagerImpl::_HaveIPv6InternetConnectivity(void) { - return ::chip::GetFlag(mFlags, kFlag_HaveIPv6InternetConnectivity); + return mFlags.Has(Flags::kHaveIPv6InternetConnectivity); } inline bool ConnectivityManagerImpl::_CanStartWiFiScan() diff --git a/src/platform/ESP32/bluedroid/BLEManagerImpl.cpp b/src/platform/ESP32/bluedroid/BLEManagerImpl.cpp index 82810b3bf2a7c0..55f9d021f37240 100644 --- a/src/platform/ESP32/bluedroid/BLEManagerImpl.cpp +++ b/src/platform/ESP32/bluedroid/BLEManagerImpl.cpp @@ -140,7 +140,7 @@ CHIP_ERROR BLEManagerImpl::_Init() mRXCharAttrHandle = 0; mTXCharAttrHandle = 0; mTXCharCCCDAttrHandle = 0; - mFlags = CHIP_DEVICE_CONFIG_CHIPOBLE_ENABLE_ADVERTISING_AUTOSTART ? kFlag_AdvertisingEnabled : 0; + mFlags.ClearAll().Set(Flags::kAdvertisingEnabled, CHIP_DEVICE_CONFIG_CHIPOBLE_ENABLE_ADVERTISING_AUTOSTART); memset(mDeviceName, 0, sizeof(mDeviceName)); PlatformMgr().ScheduleWork(DriveBLEState, 0); @@ -172,9 +172,9 @@ CHIP_ERROR BLEManagerImpl::_SetAdvertisingEnabled(bool val) VerifyOrExit(mServiceMode != ConnectivityManager::kCHIPoBLEServiceMode_NotSupported, err = CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE); - if (GetFlag(mFlags, kFlag_AdvertisingEnabled) != val) + if (mFlags.Has(Flags::kAdvertisingEnabled) != val) { - SetFlag(mFlags, kFlag_AdvertisingEnabled, val); + mFlags.Set(Flags::kAdvertisingEnabled, val); PlatformMgr().ScheduleWork(DriveBLEState, 0); } @@ -188,9 +188,9 @@ CHIP_ERROR BLEManagerImpl::_SetFastAdvertisingEnabled(bool val) VerifyOrExit(mServiceMode != ConnectivityManager::kCHIPoBLEServiceMode_NotSupported, err = CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE); - if (GetFlag(mFlags, kFlag_FastAdvertisingEnabled) != val) + if (mFlags.Has(Flags::kFastAdvertisingEnabled) != val) { - SetFlag(mFlags, kFlag_FastAdvertisingEnabled, val); + mFlags.Set(Flags::kFastAdvertisingEnabled, val); PlatformMgr().ScheduleWork(DriveBLEState, 0); } @@ -221,12 +221,12 @@ CHIP_ERROR BLEManagerImpl::_SetDeviceName(const char * deviceName) return CHIP_ERROR_INVALID_ARGUMENT; } strcpy(mDeviceName, deviceName); - SetFlag(mFlags, kFlag_UseCustomDeviceName); + mFlags.Set(Flags::kUseCustomDeviceName); } else { mDeviceName[0] = 0; - ClearFlag(mFlags, kFlag_UseCustomDeviceName); + mFlags.Clear(Flags::kUseCustomDeviceName); } return CHIP_NO_ERROR; } @@ -271,15 +271,15 @@ void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) #if CHIP_DEVICE_CONFIG_CHIPOBLE_DISABLE_ADVERTISING_WHEN_PROVISIONED if (ConfigurationMgr().IsFullyProvisioned()) { - ClearFlag(mFlags, kFlag_AdvertisingEnabled); + mFlags.Clear(Flags::kAdvertisingEnabled); ChipLogProgress(DeviceLayer, "CHIPoBLE advertising disabled because device is fully provisioned"); } #endif // CHIP_DEVICE_CONFIG_CHIPOBLE_DISABLE_ADVERTISING_WHEN_PROVISIONED // Force the advertising configuration to be refreshed to reflect new provisioning state. ChipLogProgress(DeviceLayer, "Updating advertising data"); - ClearFlag(mFlags, kFlag_AdvertisingConfigured); - SetFlag(mFlags, kFlag_AdvertisingRefreshNeeded); + mFlags.Clear(Flags::kAdvertisingConfigured); + mFlags.Set(Flags::kAdvertisingRefreshNeeded); DriveBLEState(); @@ -317,8 +317,8 @@ bool BLEManagerImpl::CloseConnection(BLE_CONNECTION_OBJECT conId) ReleaseConnectionState(conId); // Force a refresh of the advertising state. - SetFlag(mFlags, kFlag_AdvertisingRefreshNeeded); - ClearFlag(mFlags, kFlag_AdvertisingConfigured); + mFlags.Set(Flags::kAdvertisingRefreshNeeded); + mFlags.Clear(Flags::kAdvertisingConfigured); PlatformMgr().ScheduleWork(DriveBLEState, 0); return (err == CHIP_NO_ERROR); @@ -390,33 +390,33 @@ void BLEManagerImpl::DriveBLEState(void) CHIP_ERROR err = CHIP_NO_ERROR; // Perform any initialization actions that must occur after the Chip task is running. - if (!GetFlag(mFlags, kFlag_AsyncInitCompleted)) + if (!mFlags.Has(Flags::kAsyncInitCompleted)) { - SetFlag(mFlags, kFlag_AsyncInitCompleted); + mFlags.Set(Flags::kAsyncInitCompleted); // If CHIP_DEVICE_CONFIG_CHIPOBLE_DISABLE_ADVERTISING_WHEN_PROVISIONED is enabled, // disable CHIPoBLE advertising if the device is fully provisioned. #if CHIP_DEVICE_CONFIG_CHIPOBLE_DISABLE_ADVERTISING_WHEN_PROVISIONED if (ConfigurationMgr().IsFullyProvisioned()) { - ClearFlag(mFlags, kFlag_AdvertisingEnabled); + mFlags.Clear(Flags::kAdvertisingEnabled); ChipLogProgress(DeviceLayer, "CHIPoBLE advertising disabled because device is fully provisioned"); } #endif // CHIP_DEVICE_CONFIG_CHIPOBLE_DISABLE_ADVERTISING_WHEN_PROVISIONED } // If there's already a control operation in progress, wait until it completes. - VerifyOrExit(!GetFlag(mFlags, kFlag_ControlOpInProgress), /* */); + VerifyOrExit(!mFlags.Has(Flags::kControlOpInProgress), /* */); // Initializes the ESP BLE layer if needed. - if (mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_Enabled && !GetFlag(mFlags, kFlag_ESPBLELayerInitialized)) + if (mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_Enabled && !mFlags.Has(Flags::kESPBLELayerInitialized)) { err = InitESPBleLayer(); SuccessOrExit(err); } // Register the CHIPoBLE application with the ESP BLE layer if needed. - if (mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_Enabled && !GetFlag(mFlags, kFlag_AppRegistered)) + if (mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_Enabled && !mFlags.Has(Flags::kAppRegistered)) { err = esp_ble_gatts_app_register(CHIPoBLEAppId); if (err != CHIP_NO_ERROR) @@ -425,13 +425,13 @@ void BLEManagerImpl::DriveBLEState(void) ExitNow(); } - SetFlag(mFlags, kFlag_ControlOpInProgress); + mFlags.Set(Flags::kControlOpInProgress); ExitNow(); } // Register the CHIPoBLE GATT attributes with the ESP BLE layer if needed. - if (mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_Enabled && !GetFlag(mFlags, kFlag_AttrsRegistered)) + if (mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_Enabled && !mFlags.Has(Flags::kAttrsRegistered)) { err = esp_ble_gatts_create_attr_tab(CHIPoBLEGATTAttrs, mAppIf, CHIPoBLEGATTAttrCount, 0); if (err != CHIP_NO_ERROR) @@ -440,13 +440,13 @@ void BLEManagerImpl::DriveBLEState(void) ExitNow(); } - SetFlag(mFlags, kFlag_ControlOpInProgress); + mFlags.Set(Flags::kControlOpInProgress); ExitNow(); } // Start the CHIPoBLE GATT service if needed. - if (mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_Enabled && !GetFlag(mFlags, kFlag_GATTServiceStarted)) + if (mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_Enabled && !mFlags.Has(Flags::kGATTServiceStarted)) { err = esp_ble_gatts_start_service(mServiceAttrHandle); if (err != CHIP_NO_ERROR) @@ -455,14 +455,14 @@ void BLEManagerImpl::DriveBLEState(void) ExitNow(); } - SetFlag(mFlags, kFlag_ControlOpInProgress); + mFlags.Set(Flags::kControlOpInProgress); ExitNow(); } // If the application has enabled CHIPoBLE and BLE advertising... if (mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_Enabled && - GetFlag(mFlags, kFlag_AdvertisingEnabled) + mFlags.Has(Flags::kAdvertisingEnabled) #if CHIP_DEVICE_CONFIG_CHIPOBLE_SINGLE_CONNECTION // and no connections are active... && (_NumConnections() == 0) @@ -471,12 +471,12 @@ void BLEManagerImpl::DriveBLEState(void) { // Start/re-start advertising if not already advertising, or if the advertising state of the // ESP BLE layer needs to be refreshed. - if (!GetFlag(mFlags, kFlag_Advertising) || GetFlag(mFlags, kFlag_AdvertisingRefreshNeeded)) + if (!mFlags.Has(Flags::kAdvertising) || mFlags.Has(Flags::kAdvertisingRefreshNeeded)) { // Configure advertising data if it hasn't been done yet. This is an asynchronous step which // must complete before advertising can be started. When that happens, this method will // be called again, and execution will proceed to the code below. - if (!GetFlag(mFlags, kFlag_AdvertisingConfigured)) + if (!mFlags.Has(Flags::kAdvertisingConfigured)) { err = ConfigureAdvertisingData(); ExitNow(); @@ -491,7 +491,7 @@ void BLEManagerImpl::DriveBLEState(void) // Otherwise stop advertising if needed... else { - if (GetFlag(mFlags, kFlag_Advertising)) + if (mFlags.Has(Flags::kAdvertising)) { err = esp_ble_gap_stop_advertising(); if (err != CHIP_NO_ERROR) @@ -500,14 +500,14 @@ void BLEManagerImpl::DriveBLEState(void) ExitNow(); } - SetFlag(mFlags, kFlag_ControlOpInProgress); + mFlags.Set(Flags::kControlOpInProgress); ExitNow(); } } // Stop the CHIPoBLE GATT service if needed. - if (mServiceMode != ConnectivityManager::kCHIPoBLEServiceMode_Enabled && GetFlag(mFlags, kFlag_GATTServiceStarted)) + if (mServiceMode != ConnectivityManager::kCHIPoBLEServiceMode_Enabled && mFlags.Has(Flags::kGATTServiceStarted)) { // TODO: what to do about existing connections?? @@ -518,7 +518,7 @@ void BLEManagerImpl::DriveBLEState(void) ExitNow(); } - SetFlag(mFlags, kFlag_ControlOpInProgress); + mFlags.Set(Flags::kControlOpInProgress); ExitNow(); } @@ -535,7 +535,7 @@ CHIP_ERROR BLEManagerImpl::InitESPBleLayer(void) { CHIP_ERROR err = CHIP_NO_ERROR; - VerifyOrExit(!GetFlag(mFlags, kFlag_ESPBLELayerInitialized), /* */); + VerifyOrExit(!mFlags.Has(Flags::kESPBLELayerInitialized), /* */); // If the ESP Bluetooth controller has not been initialized... if (esp_bt_controller_get_status() == ESP_BT_CONTROLLER_STATUS_IDLE) @@ -615,7 +615,7 @@ CHIP_ERROR BLEManagerImpl::InitESPBleLayer(void) } SuccessOrExit(err); - SetFlag(mFlags, kFlag_ESPBLELayerInitialized); + mFlags.Set(Flags::kESPBLELayerInitialized); exit: return err; @@ -632,7 +632,7 @@ CHIP_ERROR BLEManagerImpl::ConfigureAdvertisingData(void) uint16_t discriminator; SuccessOrExit(err = ConfigurationMgr().GetSetupDiscriminator(discriminator)); - if (!GetFlag(mFlags, kFlag_UseCustomDeviceName)) + if (!mFlags.Has(Flags::kUseCustomDeviceName)) { snprintf(mDeviceName, sizeof(mDeviceName), "%s%04u", CHIP_DEVICE_CONFIG_BLE_DEVICE_NAME_PREFIX, discriminator); mDeviceName[kMaxDeviceNameLength] = 0; @@ -675,7 +675,7 @@ CHIP_ERROR BLEManagerImpl::ConfigureAdvertisingData(void) ExitNow(); } - SetFlag(mFlags, kFlag_ControlOpInProgress); + mFlags.Set(Flags::kControlOpInProgress); exit: return err; @@ -708,7 +708,7 @@ CHIP_ERROR BLEManagerImpl::StartAdvertising(void) // Advertise in fast mode if not fully provisioned and there are no CHIPoBLE connections, or // if the application has expressly requested fast advertising. advertParams.adv_int_min = advertParams.adv_int_max = - ((numCons == 0 && !ConfigurationMgr().IsFullyProvisioned()) || GetFlag(mFlags, kFlag_FastAdvertisingEnabled)) + ((numCons == 0 && !ConfigurationMgr().IsFullyProvisioned()) || mFlags.Has(Flags::kFastAdvertisingEnabled)) ? CHIP_DEVICE_CONFIG_BLE_FAST_ADVERTISING_INTERVAL : CHIP_DEVICE_CONFIG_BLE_SLOW_ADVERTISING_INTERVAL; @@ -722,7 +722,7 @@ CHIP_ERROR BLEManagerImpl::StartAdvertising(void) ExitNow(); } - SetFlag(mFlags, kFlag_ControlOpInProgress); + mFlags.Set(Flags::kControlOpInProgress); exit: return err; @@ -734,7 +734,7 @@ void BLEManagerImpl::HandleGATTControlEvent(esp_gatts_cb_event_t event, esp_gatt bool controlOpComplete = false; // Ignore GATT control events that do not pertain to the CHIPoBLE application, except for ESP_GATTS_REG_EVT. - if (event != ESP_GATTS_REG_EVT && (!GetFlag(mFlags, kFlag_AppRegistered) || gatts_if != mAppIf)) + if (event != ESP_GATTS_REG_EVT && (!mFlags.Has(Flags::kAppRegistered) || gatts_if != mAppIf)) { ExitNow(); } @@ -754,7 +754,7 @@ void BLEManagerImpl::HandleGATTControlEvent(esp_gatts_cb_event_t event, esp_gatt // Save the 'interface type' assigned to the CHIPoBLE application by the ESP BLE layer. mAppIf = gatts_if; - SetFlag(mFlags, kFlag_AppRegistered); + mFlags.Set(Flags::kAppRegistered); controlOpComplete = true; } @@ -774,7 +774,7 @@ void BLEManagerImpl::HandleGATTControlEvent(esp_gatts_cb_event_t event, esp_gatt mTXCharAttrHandle = param->add_attr_tab.handles[kAttrIndex_TXCharValue]; mTXCharCCCDAttrHandle = param->add_attr_tab.handles[kAttrIndex_TXCharCCCDValue]; - SetFlag(mFlags, kFlag_AttrsRegistered); + mFlags.Set(Flags::kAttrsRegistered); controlOpComplete = true; break; @@ -789,7 +789,7 @@ void BLEManagerImpl::HandleGATTControlEvent(esp_gatts_cb_event_t event, esp_gatt ChipLogProgress(DeviceLayer, "CHIPoBLE GATT service started"); - SetFlag(mFlags, kFlag_GATTServiceStarted); + mFlags.Set(Flags::kGATTServiceStarted); controlOpComplete = true; break; @@ -804,7 +804,7 @@ void BLEManagerImpl::HandleGATTControlEvent(esp_gatts_cb_event_t event, esp_gatt ChipLogProgress(DeviceLayer, "CHIPoBLE GATT service stopped"); - ClearFlag(mFlags, kFlag_GATTServiceStarted); + mFlags.Clear(Flags::kGATTServiceStarted); controlOpComplete = true; break; @@ -826,7 +826,7 @@ void BLEManagerImpl::HandleGATTControlEvent(esp_gatts_cb_event_t event, esp_gatt } if (controlOpComplete) { - ClearFlag(mFlags, kFlag_ControlOpInProgress); + mFlags.Clear(Flags::kControlOpInProgress); PlatformMgr().ScheduleWork(DriveBLEState, 0); } } @@ -835,7 +835,7 @@ void BLEManagerImpl::HandleGATTCommEvent(esp_gatts_cb_event_t event, esp_gatt_if { // Ignore the event if the CHIPoBLE service hasn't been started, or if the event is for a different // BLE application. - if (!GetFlag(sInstance.mFlags, kFlag_GATTServiceStarted) || gatts_if != sInstance.mAppIf) + if (!sInstance.mFlags.Has(Flags::kGATTServiceStarted) || gatts_if != sInstance.mAppIf) { return; } @@ -850,8 +850,8 @@ void BLEManagerImpl::HandleGATTCommEvent(esp_gatts_cb_event_t event, esp_gatt_if // Receiving a connection stops the advertising processes. So force a refresh of the advertising // state. - SetFlag(mFlags, kFlag_AdvertisingRefreshNeeded); - ClearFlag(mFlags, kFlag_AdvertisingConfigured); + mFlags.Set(Flags::kAdvertisingRefreshNeeded); + mFlags.Clear(Flags::kAdvertisingConfigured); PlatformMgr().ScheduleWork(DriveBLEState, 0); break; @@ -1110,8 +1110,8 @@ void BLEManagerImpl::HandleDisconnect(esp_ble_gatts_cb_param_t * param) PlatformMgr().PostEvent(&event); // Force a refresh of the advertising state. - SetFlag(mFlags, kFlag_AdvertisingRefreshNeeded); - ClearFlag(mFlags, kFlag_AdvertisingConfigured); + mFlags.Set(Flags::kAdvertisingRefreshNeeded); + mFlags.Clear(Flags::kAdvertisingConfigured); PlatformMgr().ScheduleWork(DriveBLEState, 0); } } @@ -1212,8 +1212,8 @@ void BLEManagerImpl::HandleGAPEvent(esp_gap_ble_cb_event_t event, esp_ble_gap_cb ExitNow(err = ESP_ERR_INVALID_RESPONSE); } - SetFlag(sInstance.mFlags, kFlag_AdvertisingConfigured); - ClearFlag(sInstance.mFlags, kFlag_ControlOpInProgress); + sInstance.mFlags.Set(Flags::kAdvertisingConfigured); + sInstance.mFlags.Clear(Flags::kControlOpInProgress); break; @@ -1225,15 +1225,15 @@ void BLEManagerImpl::HandleGAPEvent(esp_gap_ble_cb_event_t event, esp_ble_gap_cb ExitNow(err = ESP_ERR_INVALID_RESPONSE); } - ClearFlag(sInstance.mFlags, kFlag_ControlOpInProgress); - ClearFlag(sInstance.mFlags, kFlag_AdvertisingRefreshNeeded); + sInstance.mFlags.Clear(Flags::kControlOpInProgress); + sInstance.mFlags.Clear(Flags::kAdvertisingRefreshNeeded); // Transition to the Advertising state... - if (!GetFlag(sInstance.mFlags, kFlag_Advertising)) + if (!sInstance.mFlags.Has(Flags::kAdvertising)) { ChipLogProgress(DeviceLayer, "CHIPoBLE advertising started"); - SetFlag(sInstance.mFlags, kFlag_Advertising); + sInstance.mFlags.Set(Flags::kAdvertising); // Post a CHIPoBLEAdvertisingChange(Started) event. { @@ -1254,13 +1254,13 @@ void BLEManagerImpl::HandleGAPEvent(esp_gap_ble_cb_event_t event, esp_ble_gap_cb ExitNow(err = ESP_ERR_INVALID_RESPONSE); } - ClearFlag(sInstance.mFlags, kFlag_ControlOpInProgress); - ClearFlag(sInstance.mFlags, kFlag_AdvertisingRefreshNeeded); + sInstance.mFlags.Clear(Flags::kControlOpInProgress); + sInstance.mFlags.Clear(Flags::kAdvertisingRefreshNeeded); // Transition to the not Advertising state... - if (GetFlag(sInstance.mFlags, kFlag_Advertising)) + if (sInstance.mFlags.Has(Flags::kAdvertising)) { - ClearFlag(sInstance.mFlags, kFlag_Advertising); + sInstance.mFlags.Clear(Flags::kAdvertising); ChipLogProgress(DeviceLayer, "CHIPoBLE advertising stopped"); diff --git a/src/platform/ESP32/nimble/BLEManagerImpl.cpp b/src/platform/ESP32/nimble/BLEManagerImpl.cpp index 1a6dddf8b63267..1960d9dab2e2fd 100644 --- a/src/platform/ESP32/nimble/BLEManagerImpl.cpp +++ b/src/platform/ESP32/nimble/BLEManagerImpl.cpp @@ -129,8 +129,8 @@ CHIP_ERROR BLEManagerImpl::_Init() mRXCharAttrHandle = 0; mTXCharCCCDAttrHandle = 0; - mFlags = CHIP_DEVICE_CONFIG_CHIPOBLE_ENABLE_ADVERTISING_AUTOSTART ? kFlag_AdvertisingEnabled : 0; - mNumGAPCons = 0; + mFlags.ClearAll().Set(Flags::kAdvertisingEnabled, CHIP_DEVICE_CONFIG_CHIPOBLE_ENABLE_ADVERTISING_AUTOSTART); + mNumGAPCons = 0; memset(mCons, 0, sizeof(mCons)); mServiceMode = ConnectivityManager::kCHIPoBLEServiceMode_Enabled; memset(mDeviceName, 0, sizeof(mDeviceName)); @@ -164,9 +164,9 @@ CHIP_ERROR BLEManagerImpl::_SetAdvertisingEnabled(bool val) VerifyOrExit(mServiceMode != ConnectivityManager::kCHIPoBLEServiceMode_NotSupported, err = CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE); - if (GetFlag(mFlags, kFlag_AdvertisingEnabled) != val) + if (mFlags.Has(Flags::kAdvertisingEnabled) != val) { - SetFlag(mFlags, kFlag_AdvertisingEnabled, val); + mFlags.Set(Flags::kAdvertisingEnabled, val); PlatformMgr().ScheduleWork(DriveBLEState, 0); } @@ -180,9 +180,9 @@ CHIP_ERROR BLEManagerImpl::_SetFastAdvertisingEnabled(bool val) VerifyOrExit(mServiceMode != ConnectivityManager::kCHIPoBLEServiceMode_NotSupported, err = CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE); - if (GetFlag(mFlags, kFlag_FastAdvertisingEnabled) != val) + if (mFlags.Has(Flags::kFastAdvertisingEnabled) != val) { - SetFlag(mFlags, kFlag_FastAdvertisingEnabled, val); + mFlags.Set(Flags::kFastAdvertisingEnabled, val); PlatformMgr().ScheduleWork(DriveBLEState, 0); } @@ -212,12 +212,12 @@ CHIP_ERROR BLEManagerImpl::_SetDeviceName(const char * deviceName) return CHIP_ERROR_INVALID_ARGUMENT; } strcpy(mDeviceName, deviceName); - SetFlag(mFlags, kFlag_UseCustomDeviceName); + mFlags.Set(Flags::kUseCustomDeviceName); } else { mDeviceName[0] = 0; - ClearFlag(mFlags, kFlag_UseCustomDeviceName); + mFlags.Clear(Flags::kUseCustomDeviceName); } exit: @@ -265,15 +265,15 @@ void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) #if CHIP_DEVICE_CONFIG_CHIPOBLE_DISABLE_ADVERTISING_WHEN_PROVISIONED if (ConfigurationMgr().IsFullyProvisioned()) { - ClearFlag(mFlags, kFlag_AdvertisingEnabled); + mFlags.Clear(Flags::kAdvertisingEnabled); ChipLogProgress(DeviceLayer, "CHIPoBLE advertising disabled because device is fully provisioned"); } #endif // CHIP_DEVICE_CONFIG_CHIPOBLE_DISABLE_ADVERTISING_WHEN_PROVISIONED // Force the advertising configuration to be refreshed to reflect new provisioning state. ChipLogProgress(DeviceLayer, "Updating advertising data"); - ClearFlag(mFlags, kFlag_AdvertisingConfigured); - SetFlag(mFlags, kFlag_AdvertisingRefreshNeeded); + mFlags.Clear(Flags::kAdvertisingConfigured); + mFlags.Set(Flags::kAdvertisingRefreshNeeded); DriveBLEState(); break; @@ -309,8 +309,8 @@ bool BLEManagerImpl::CloseConnection(BLE_CONNECTION_OBJECT conId) } // Force a refresh of the advertising state. - SetFlag(mFlags, kFlag_AdvertisingRefreshNeeded); - ClearFlag(mFlags, kFlag_AdvertisingConfigured); + mFlags.Set(Flags::kAdvertisingRefreshNeeded); + mFlags.Clear(Flags::kAdvertisingConfigured); PlatformMgr().ScheduleWork(DriveBLEState, 0); return (err == CHIP_NO_ERROR); @@ -384,23 +384,23 @@ void BLEManagerImpl::DriveBLEState(void) CHIP_ERROR err = CHIP_NO_ERROR; // Perform any initialization actions that must occur after the Chip task is running. - if (!GetFlag(mFlags, kFlag_AsyncInitCompleted)) + if (!mFlags.Has(Flags::kAsyncInitCompleted)) { - SetFlag(mFlags, kFlag_AsyncInitCompleted); + mFlags.Set(Flags::kAsyncInitCompleted); // If CHIP_DEVICE_CONFIG_CHIPOBLE_DISABLE_ADVERTISING_WHEN_PROVISIONED is enabled, // disable CHIPoBLE advertising if the device is fully provisioned. #if CHIP_DEVICE_CONFIG_CHIPOBLE_DISABLE_ADVERTISING_WHEN_PROVISIONED if (ConfigurationMgr().IsFullyProvisioned()) { - ClearFlag(mFlags, kFlag_AdvertisingEnabled); + mFlags.Clear(Flags::kAdvertisingEnabled); ChipLogProgress(DeviceLayer, "CHIPoBLE advertising disabled because device is fully provisioned"); } #endif // CHIP_DEVICE_CONFIG_CHIPOBLE_DISABLE_ADVERTISING_WHEN_PROVISIONED } // Initializes the ESP BLE layer if needed. - if (mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_Enabled && !GetFlag(mFlags, kFlag_ESPBLELayerInitialized)) + if (mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_Enabled && !mFlags.Has(Flags::kESPBLELayerInitialized)) { err = InitESPBleLayer(); SuccessOrExit(err); @@ -413,7 +413,7 @@ void BLEManagerImpl::DriveBLEState(void) // If the application has enabled CHIPoBLE and BLE advertising... if (mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_Enabled && - GetFlag(mFlags, kFlag_AdvertisingEnabled) + mFlags.Has(Flags::kAdvertisingEnabled) #if CHIP_DEVICE_CONFIG_CHIPOBLE_SINGLE_CONNECTION // and no connections are active... && (_NumConnections() == 0) @@ -422,12 +422,12 @@ void BLEManagerImpl::DriveBLEState(void) { // Start/re-start advertising if not already advertising, or if the advertising state of the // ESP BLE layer needs to be refreshed. - if (!GetFlag(mFlags, kFlag_Advertising) || GetFlag(mFlags, kFlag_AdvertisingRefreshNeeded)) + if (!mFlags.Has(Flags::kAdvertising) || mFlags.Has(Flags::kAdvertisingRefreshNeeded)) { // Configure advertising data if it hasn't been done yet. This is an asynchronous step which // must complete before advertising can be started. When that happens, this method will // be called again, and execution will proceed to the code below. - if (!GetFlag(mFlags, kFlag_AdvertisingConfigured)) + if (!mFlags.Has(Flags::kAdvertisingConfigured)) { err = ConfigureAdvertisingData(); if (err != CHIP_NO_ERROR) @@ -446,13 +446,13 @@ void BLEManagerImpl::DriveBLEState(void) ExitNow(); } - ClearFlag(mFlags, kFlag_AdvertisingRefreshNeeded); + mFlags.Clear(Flags::kAdvertisingRefreshNeeded); // Transition to the Advertising state... - if (!GetFlag(mFlags, kFlag_Advertising)) + if (!mFlags.Has(Flags::kAdvertising)) { ChipLogProgress(DeviceLayer, "CHIPoBLE advertising started"); - SetFlag(mFlags, kFlag_Advertising); + mFlags.Set(Flags::kAdvertising); // Post a CHIPoBLEAdvertisingChange(Started) event. { @@ -468,7 +468,7 @@ void BLEManagerImpl::DriveBLEState(void) // Otherwise stop advertising if needed... else { - if (GetFlag(mFlags, kFlag_Advertising)) + if (mFlags.Has(Flags::kAdvertising)) { ret = ble_gap_adv_stop(); if (ret != 0) @@ -478,12 +478,12 @@ void BLEManagerImpl::DriveBLEState(void) ExitNow(); } - // ClearFlag(mFlags, kFlag_AdvertisingRefreshNeeded); + // mFlags.Clear(Flags::kAdvertisingRefreshNeeded); // Transition to the not Advertising state... - if (GetFlag(mFlags, kFlag_Advertising)) + if (mFlags.Has(Flags::kAdvertising)) { - ClearFlag(mFlags, kFlag_Advertising); + mFlags.Clear(Flags::kAdvertising); ChipLogProgress(DeviceLayer, "CHIPoBLE advertising stopped"); @@ -506,7 +506,7 @@ void BLEManagerImpl::DriveBLEState(void) } // Stop the CHIPoBLE GATT service if needed. - if (mServiceMode != ConnectivityManager::kCHIPoBLEServiceMode_Enabled && GetFlag(mFlags, kFlag_GATTServiceStarted)) + if (mServiceMode != ConnectivityManager::kCHIPoBLEServiceMode_Enabled && mFlags.Has(Flags::kGATTServiceStarted)) { // TODO: Not supported } @@ -528,8 +528,8 @@ void BLEManagerImpl::bleprph_on_sync(void) { int rc; - SetFlag(sInstance.mFlags, kFlag_ESPBLELayerInitialized); - SetFlag(sInstance.mFlags, kFlag_GATTServiceStarted); + sInstance.mFlags.Set(Flags::kESPBLELayerInitialized); + sInstance.mFlags.Set(Flags::kGATTServiceStarted); ESP_LOGI(TAG, "BLE host-controller synced"); uint8_t own_addr_type = BLE_OWN_ADDR_PUBLIC; @@ -554,7 +554,7 @@ CHIP_ERROR BLEManagerImpl::InitESPBleLayer(void) { CHIP_ERROR err = CHIP_NO_ERROR; - VerifyOrExit(!GetFlag(mFlags, kFlag_ESPBLELayerInitialized), /* */); + VerifyOrExit(!mFlags.Has(Flags::kESPBLELayerInitialized), /* */); for (int i = 0; i < kMaxConnections; i++) { @@ -609,7 +609,7 @@ CHIP_ERROR BLEManagerImpl::ConfigureAdvertisingData(void) uint16_t discriminator; SuccessOrExit(err = ConfigurationMgr().GetSetupDiscriminator(discriminator)); - if (!GetFlag(mFlags, kFlag_UseCustomDeviceName)) + if (!mFlags.Has(Flags::kUseCustomDeviceName)) { snprintf(mDeviceName, sizeof(mDeviceName), "%s%04u", CHIP_DEVICE_CONFIG_BLE_DEVICE_NAME_PREFIX, discriminator); mDeviceName[kMaxDeviceNameLength] = 0; @@ -809,8 +809,8 @@ CHIP_ERROR BLEManagerImpl::HandleGAPConnect(struct ble_gap_event * gapEvent) VerifyOrExit(err != CHIP_ERROR_NO_MEMORY, err = CHIP_NO_ERROR); SuccessOrExit(err); - SetFlag(mFlags, kFlag_AdvertisingRefreshNeeded); - ClearFlag(mFlags, kFlag_AdvertisingConfigured); + mFlags.Set(Flags::kAdvertisingRefreshNeeded); + mFlags.Clear(Flags::kAdvertisingConfigured); exit: return err; @@ -847,8 +847,8 @@ CHIP_ERROR BLEManagerImpl::HandleGAPDisconnect(struct ble_gap_event * gapEvent) // Force a reconfiguration of advertising in case we switched to non-connectable mode when // the BLE connection was established. - SetFlag(mFlags, kFlag_AdvertisingRefreshNeeded); - ClearFlag(mFlags, kFlag_AdvertisingConfigured); + mFlags.Set(Flags::kAdvertisingRefreshNeeded); + mFlags.Clear(Flags::kAdvertisingConfigured); return CHIP_NO_ERROR; } @@ -1025,7 +1025,7 @@ CHIP_ERROR BLEManagerImpl::StartAdvertising(void) } #endif // CHIP_DEVICE_CONFIG_ENABLE_THREAD - ClearFlag(mFlags, kFlag_AdvertisingRefreshNeeded); + mFlags.Clear(Flags::kAdvertisingRefreshNeeded); // Advertise connectable if we haven't reached the maximum number of connections. size_t numCons = _NumConnections(); diff --git a/src/platform/K32W/BLEManagerImpl.cpp b/src/platform/K32W/BLEManagerImpl.cpp index 4baa04054302cd..09c216c6e5a8e3 100644 --- a/src/platform/K32W/BLEManagerImpl.cpp +++ b/src/platform/K32W/BLEManagerImpl.cpp @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2020-2021 Project CHIP Authors * Copyright (c) 2020 Nest Labs, Inc. * All rights reserved. * @@ -119,7 +119,6 @@ EventGroupHandle_t bleAppTaskLoopEvent; /* keep the device ID of the connected peer */ uint8_t device_id; -uint16_t mFlags; const uint8_t ShortUUID_CHIPoBLEService[] = { 0xAF, 0xFE }; const ChipBleUUID ChipUUID_CHIPoBLEChar_RX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, @@ -140,7 +139,7 @@ CHIP_ERROR BLEManagerImpl::_Init() mServiceMode = ConnectivityManager::kCHIPoBLEServiceMode_Enabled; // Check if BLE stack is initialized - VerifyOrExit(!GetFlag(mFlags, kFlag_K32WBLEStackInitialized), err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrExit(!mFlags.Has(Flags::kK32WBLEStackInitialized), err = CHIP_ERROR_INCORRECT_STATE); // Initialize the Chip BleLayer. err = BleLayer::Init(this, this, &SystemLayer); @@ -194,8 +193,8 @@ CHIP_ERROR BLEManagerImpl::_Init() GattServer_RegisterHandlesForWriteNotifications(1, attChipRxHandle); - SetFlag(mFlags, kFlag_K32WBLEStackInitialized, true); - SetFlag(mFlags, kFlag_AdvertisingEnabled, CHIP_DEVICE_CONFIG_CHIPOBLE_ENABLE_ADVERTISING_AUTOSTART ? true : false); + mFlags.Set(Flags::kK32WBLEStackInitialized); + mFlags.Set(Flags::kAdvertisingEnabled, CHIP_DEVICE_CONFIG_CHIPOBLE_ENABLE_ADVERTISING_AUTOSTART ? true : false); PlatformMgr().ScheduleWork(DriveBLEState, 0); exit: @@ -218,12 +217,12 @@ uint16_t BLEManagerImpl::_NumConnections(void) bool BLEManagerImpl::_IsAdvertisingEnabled(void) { - return GetFlag(mFlags, kFlag_AdvertisingEnabled); + return mFlags.Has(Flags::kAdvertisingEnabled); } bool BLEManagerImpl::_IsFastAdvertisingEnabled(void) { - return GetFlag(mFlags, kFlag_FastAdvertisingEnabled); + return mFlags.Has(Flags::kFastAdvertisingEnabled); } bool BLEManagerImpl::RemoveConnection(uint8_t connectionHandle) @@ -308,9 +307,9 @@ CHIP_ERROR BLEManagerImpl::_SetAdvertisingEnabled(bool val) VerifyOrExit(mServiceMode != ConnectivityManager::kCHIPoBLEServiceMode_NotSupported, err = CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE); - if (GetFlag(mFlags, kFlag_AdvertisingEnabled) != val) + if (mFlags.Has(Flags::kAdvertisingEnabled) != val) { - SetFlag(mFlags, kFlag_AdvertisingEnabled, val); + mFlags.Set(Flags::kAdvertisingEnabled, val); PlatformMgr().ScheduleWork(DriveBLEState, 0); } @@ -324,9 +323,9 @@ CHIP_ERROR BLEManagerImpl::_SetFastAdvertisingEnabled(bool val) VerifyOrExit(mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_NotSupported, err = CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE); - if (GetFlag(mFlags, kFlag_FastAdvertisingEnabled) != val) + if (mFlags.Has(Flags::kFastAdvertisingEnabled) != val) { - SetFlag(mFlags, kFlag_FastAdvertisingEnabled, val); + mFlags.Set(Flags::kFastAdvertisingEnabled, val); PlatformMgr().ScheduleWork(DriveBLEState, 0); } @@ -358,13 +357,13 @@ CHIP_ERROR BLEManagerImpl::_SetDeviceName(const char * deviceName) } memset(mDeviceName, 0, kMaxDeviceNameLength); strcpy(mDeviceName, deviceName); - SetFlag(mFlags, kFlag_DeviceNameSet, true); + mFlags.Set(Flags::kDeviceNameSet); ChipLogProgress(DeviceLayer, "Setting device name to : \"%s\"", deviceName); } else { mDeviceName[0] = 0; - SetFlag(mFlags, kFlag_DeviceNameSet, false); + mFlags.Clear(Flags::kDeviceNameSet); } return CHIP_NO_ERROR; @@ -403,7 +402,7 @@ void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) case DeviceEventType::kServiceProvisioningChange: ChipLogProgress(DeviceLayer, "_OnPlatformEvent kServiceProvisioningChange"); - ClearFlag(mFlags, kFlag_AdvertisingEnabled); + mFlags.Clear(Flags::kAdvertisingEnabled); PlatformMgr().ScheduleWork(DriveBLEState, 0); break; #endif // CHIP_DEVICE_CONFIG_CHIPOBLE_DISABLE_ADVERTISING_WHEN_PROVISIONED @@ -764,7 +763,7 @@ CHIP_ERROR BLEManagerImpl::ConfigureAdvertisingData(void) return chipErr; } - if (!GetFlag(mFlags, kFlag_DeviceNameSet)) + if (!mFlags.Has(Flags::kDeviceNameSet)) { memset(mDeviceName, 0, kMaxDeviceNameLength); snprintf(mDeviceName, kMaxDeviceNameLength, "%s%04u", CHIP_DEVICE_CONFIG_BLE_DEVICE_NAME_PREFIX, discriminator); @@ -809,8 +808,7 @@ CHIP_ERROR BLEManagerImpl::ConfigureAdvertisingData(void) scanRsp.aAdStructures = scan_rsp_data; /**************** Prepare advertising parameters *************************************/ - advInterval = - ((NumConnections() == 0 && !ConfigurationMgr().IsPairedToAccount()) || GetFlag(mFlags, kFlag_FastAdvertisingEnabled)) + advInterval = ((NumConnections() == 0 && !ConfigurationMgr().IsPairedToAccount()) || mFlags.Has(Flags::kFastAdvertisingEnabled)) ? (CHIP_DEVICE_CONFIG_BLE_FAST_ADVERTISING_INTERVAL * 3) : CHIP_DEVICE_CONFIG_BLE_SLOW_ADVERTISING_INTERVAL; @@ -839,8 +837,8 @@ CHIP_ERROR BLEManagerImpl::ConfigureAdvertisingData(void) CHIP_ERROR BLEManagerImpl::StartAdvertising(void) { - SetFlag(mFlags, kFlag_Advertising, true); - ClearFlag(mFlags, kFlag_RestartAdvertising); + mFlags.Set(Flags::kAdvertising); + mFlags.Clear(Flags::kRestartAdvertising); return ConfigureAdvertisingData(); } @@ -849,10 +847,10 @@ CHIP_ERROR BLEManagerImpl::StopAdvertising(void) { ble_err_t err; - if (GetFlag(mFlags, kFlag_Advertising)) + if (mFlags.Has(Flags::kAdvertising)) { - ClearFlag(mFlags, kFlag_Advertising); - ClearFlag(mFlags, kFlag_RestartAdvertising); + mFlags.Clear(Flags::kAdvertising); + mFlags.Clear(Flags::kRestartAdvertising); err = blekw_stop_advertising(); if (err != BLE_OK) @@ -869,29 +867,29 @@ void BLEManagerImpl::DriveBLEState(void) CHIP_ERROR err = CHIP_NO_ERROR; // Check if BLE stack is initialized - VerifyOrExit(GetFlag(mFlags, kFlag_K32WBLEStackInitialized), /* */); + VerifyOrExit(mFlags.Has(Flags::kK32WBLEStackInitialized), /* */); #if CHIP_DEVICE_CONFIG_CHIPOBLE_DISABLE_ADVERTISING_WHEN_PROVISIONED if (ConfigurationMgr().IsFullyProvisioned()) { - ClearFlag(mFlags, kFlag_AdvertisingEnabled); + mFlags.Clear(Flags::kAdvertisingEnabled); ChipLogProgress(DeviceLayer, "CHIPoBLE advertising disabled because device is fully provisioned"); } #endif // CHIP_DEVICE_CONFIG_CHIPOBLE_DISABLE_ADVERTISING_WHEN_PROVISIONED // Start advertising if needed... - if (mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_Enabled && GetFlag(mFlags, kFlag_AdvertisingEnabled)) + if (mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_Enabled && mFlags.Has(Flags::kAdvertisingEnabled)) { // Start/re-start advertising if not already started, or if there is a pending change // to the advertising configuration. - if (!GetFlag(mFlags, kFlag_Advertising) || GetFlag(mFlags, kFlag_RestartAdvertising)) + if (!mFlags.Has(Flags::kAdvertising) || mFlags.Has(Flags::kRestartAdvertising)) { err = StartAdvertising(); SuccessOrExit(err); } } // Otherwise, stop advertising if it is enabled. - else if (GetFlag(mFlags, kFlag_Advertising)) + else if (mFlags.Has(Flags::kAdvertising)) { err = StopAdvertising(); SuccessOrExit(err); @@ -977,7 +975,7 @@ void BLEManagerImpl::HandleConnectEvent(blekw_msg_t * msg) device_id = device_id_loc; blekw_start_connection_timeout(); sInstance.AddConnection(device_id_loc); - SetFlag(mFlags, kFlag_RestartAdvertising, true); + mFlags.Set(Flags::kRestartAdvertising); PlatformMgr().ScheduleWork(DriveBLEState, 0); } @@ -994,7 +992,7 @@ void BLEManagerImpl::HandleConnectionCloseEvent(blekw_msg_t * msg) event.CHIPoBLEConnectionError.Reason = BLE_ERROR_REMOTE_DEVICE_DISCONNECTED; PlatformMgr().PostEvent(&event); - SetFlag(mFlags, kFlag_RestartAdvertising, true); + mFlags.Set(Flags::kRestartAdvertising); PlatformMgr().ScheduleWork(DriveBLEState, 0); } } diff --git a/src/platform/K32W/BLEManagerImpl.h b/src/platform/K32W/BLEManagerImpl.h index 22e632a1567a1f..c31b9fb200c3ba 100644 --- a/src/platform/K32W/BLEManagerImpl.h +++ b/src/platform/K32W/BLEManagerImpl.h @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2020-2021 Project CHIP Authors * Copyright (c) 2020 Nest Labs, Inc. * All rights reserved. * @@ -107,15 +107,16 @@ class BLEManagerImpl final : public BLEManager, private BleLayer, private BlePla // ===== Private members reserved for use by this class only. - enum + enum class Flags : uint8_t { - kFlag_AdvertisingEnabled = 0x0001, - kFlag_FastAdvertisingEnabled = 0x0002, - kFlag_Advertising = 0x0004, - kFlag_RestartAdvertising = 0x0008, - kFlag_K32WBLEStackInitialized = 0x0010, - kFlag_DeviceNameSet = 0x0020, + kAdvertisingEnabled = 0x0001, + kFastAdvertisingEnabled = 0x0002, + kAdvertising = 0x0004, + kRestartAdvertising = 0x0008, + kK32WBLEStackInitialized = 0x0010, + kDeviceNameSet = 0x0020, }; + BitFlags mFlags; enum { diff --git a/src/platform/Linux/BLEManagerImpl.cpp b/src/platform/Linux/BLEManagerImpl.cpp index 803d31efa70b85..e1a60696143a50 100644 --- a/src/platform/Linux/BLEManagerImpl.cpp +++ b/src/platform/Linux/BLEManagerImpl.cpp @@ -69,8 +69,8 @@ CHIP_ERROR BLEManagerImpl::_Init() SuccessOrExit(err); mServiceMode = ConnectivityManager::kCHIPoBLEServiceMode_Enabled; - mFlags = (CHIP_DEVICE_CONFIG_CHIPOBLE_ENABLE_ADVERTISING_AUTOSTART && !mIsCentral) ? kFlag_AdvertisingEnabled : 0; - mAppState = nullptr; + mFlags.ClearAll().Set(Flags::kAdvertisingEnabled, CHIP_DEVICE_CONFIG_CHIPOBLE_ENABLE_ADVERTISING_AUTOSTART && !mIsCentral); + mAppState = nullptr; memset(mDeviceName, 0, sizeof(mDeviceName)); @@ -103,9 +103,9 @@ CHIP_ERROR BLEManagerImpl::_SetAdvertisingEnabled(bool val) { CHIP_ERROR err = CHIP_NO_ERROR; - if (GetFlag(mFlags, kFlag_AdvertisingEnabled) != val) + if (mFlags.Has(Flags::kAdvertisingEnabled) != val) { - SetFlag(mFlags, kFlag_AdvertisingEnabled, val); + mFlags.Set(Flags::kAdvertisingEnabled, val); } PlatformMgr().ScheduleWork(DriveBLEState, 0); @@ -119,9 +119,9 @@ CHIP_ERROR BLEManagerImpl::_SetFastAdvertisingEnabled(bool val) VerifyOrExit(mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_NotSupported, err = CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE); - if (GetFlag(mFlags, kFlag_FastAdvertisingEnabled) != val) + if (mFlags.Has(Flags::kFastAdvertisingEnabled) != val) { - SetFlag(mFlags, kFlag_FastAdvertisingEnabled, val); + mFlags.Set(Flags::kFastAdvertisingEnabled, val); PlatformMgr().ScheduleWork(DriveBLEState, 0); } @@ -150,7 +150,7 @@ CHIP_ERROR BLEManagerImpl::_SetDeviceName(const char * deviceName) { VerifyOrExit(strlen(deviceName) < kMaxDeviceNameLength, err = CHIP_ERROR_INVALID_ARGUMENT); strcpy(mDeviceName, deviceName); - SetFlag(mFlags, kFlag_UseCustomDeviceName); + mFlags.Set(Flags::kUseCustomDeviceName); } else { @@ -158,7 +158,7 @@ CHIP_ERROR BLEManagerImpl::_SetDeviceName(const char * deviceName) SuccessOrExit(err = ConfigurationMgr().GetSetupDiscriminator(discriminator)); snprintf(mDeviceName, sizeof(mDeviceName), "%s%04u", CHIP_DEVICE_CONFIG_BLE_DEVICE_NAME_PREFIX, discriminator); mDeviceName[kMaxDeviceNameLength] = 0; - ClearFlag(mFlags, kFlag_UseCustomDeviceName); + mFlags.Clear(Flags::kUseCustomDeviceName); } exit: @@ -240,13 +240,13 @@ void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) #if CHIP_DEVICE_CONFIG_CHIPOBLE_DISABLE_ADVERTISING_WHEN_PROVISIONED if (ConfigurationMgr().IsFullyProvisioned()) { - ClearFlag(mFlags, kFlag_AdvertisingEnabled); + mFlags.Clear(Flags::kAdvertisingEnabled); ChipLogProgress(DeviceLayer, "CHIPoBLE advertising disabled because device is fully provisioned"); } #endif // CHIP_DEVICE_CONFIG_CHIPOBLE_DISABLE_ADVERTISING_WHEN_PROVISIONED // Force the advertising configuration to be refreshed to reflect new provisioning state. - ClearFlag(mFlags, kFlag_AdvertisingConfigured); + mFlags.Clear(Flags::kAdvertisingConfigured); DriveBLEState(); break; @@ -284,38 +284,35 @@ void BLEManagerImpl::HandlePlatformSpecificBLEEvent(const ChipDeviceEvent * apEv break; case DeviceEventType::kPlatformLinuxBLEPeripheralAdvConfiguredComplete: VerifyOrExit(apEvent->Platform.BLEPeripheralAdvConfiguredComplete.mIsSuccess, err = CHIP_ERROR_INCORRECT_STATE); - SetFlag(sInstance.mFlags, kFlag_AdvertisingConfigured); - ClearFlag(sInstance.mFlags, kFlag_ControlOpInProgress); + sInstance.mFlags.Set(Flags::kAdvertisingConfigured).Clear(Flags::kControlOpInProgress); controlOpComplete = true; ChipLogProgress(DeviceLayer, "CHIPoBLE advertising config complete"); break; case DeviceEventType::kPlatformLinuxBLEPeripheralAdvStartComplete: VerifyOrExit(apEvent->Platform.BLEPeripheralAdvStartComplete.mIsSuccess, err = CHIP_ERROR_INCORRECT_STATE); - ClearFlag(sInstance.mFlags, kFlag_ControlOpInProgress); - ClearFlag(sInstance.mFlags, kFlag_AdvertisingRefreshNeeded); + sInstance.mFlags.Clear(Flags::kControlOpInProgress).Clear(Flags::kAdvertisingRefreshNeeded); - if (!GetFlag(sInstance.mFlags, kFlag_Advertising)) + if (!sInstance.mFlags.Has(Flags::kAdvertising)) { - SetFlag(sInstance.mFlags, kFlag_Advertising); + sInstance.mFlags.Set(Flags::kAdvertising); } break; case DeviceEventType::kPlatformLinuxBLEPeripheralAdvStopComplete: VerifyOrExit(apEvent->Platform.BLEPeripheralAdvStopComplete.mIsSuccess, err = CHIP_ERROR_INCORRECT_STATE); - ClearFlag(sInstance.mFlags, kFlag_ControlOpInProgress); - ClearFlag(sInstance.mFlags, kFlag_AdvertisingRefreshNeeded); + sInstance.mFlags.Clear(Flags::kControlOpInProgress).Clear(Flags::kAdvertisingRefreshNeeded); // Transition to the not Advertising state... - if (GetFlag(sInstance.mFlags, kFlag_Advertising)) + if (sInstance.mFlags.Has(Flags::kAdvertising)) { - ClearFlag(sInstance.mFlags, kFlag_Advertising); + sInstance.mFlags.Clear(Flags::kAdvertising); ChipLogProgress(DeviceLayer, "CHIPoBLE advertising stopped"); } break; case DeviceEventType::kPlatformLinuxBLEPeripheralRegisterAppComplete: VerifyOrExit(apEvent->Platform.BLEPeripheralRegisterAppComplete.mIsSuccess, err = CHIP_ERROR_INCORRECT_STATE); - SetFlag(mFlags, kFlag_AppRegistered); + mFlags.Set(Flags::kAppRegistered); controlOpComplete = true; break; default: @@ -327,12 +324,12 @@ void BLEManagerImpl::HandlePlatformSpecificBLEEvent(const ChipDeviceEvent * apEv { ChipLogError(DeviceLayer, "Disabling CHIPoBLE service due to error: %s", ErrorStr(err)); mServiceMode = ConnectivityManager::kCHIPoBLEServiceMode_Disabled; - ClearFlag(sInstance.mFlags, kFlag_ControlOpInProgress); + sInstance.mFlags.Clear(Flags::kControlOpInProgress); } if (controlOpComplete) { - ClearFlag(mFlags, kFlag_ControlOpInProgress); + mFlags.Clear(Flags::kControlOpInProgress); DriveBLEState(); } } @@ -542,16 +539,16 @@ void BLEManagerImpl::DriveBLEState() CHIP_ERROR err = CHIP_NO_ERROR; // Perform any initialization actions that must occur after the Chip task is running. - if (!GetFlag(mFlags, kFlag_AsyncInitCompleted)) + if (!mFlags.Has(Flags::kAsyncInitCompleted)) { - SetFlag(mFlags, kFlag_AsyncInitCompleted); + mFlags.Set(Flags::kAsyncInitCompleted); // If CHIP_DEVICE_CONFIG_CHIPOBLE_DISABLE_ADVERTISING_WHEN_PROVISIONED is enabled, // disable CHIPoBLE advertising if the device is fully provisioned. #if CHIP_DEVICE_CONFIG_CHIPOBLE_DISABLE_ADVERTISING_WHEN_PROVISIONED if (ConfigurationMgr().IsFullyProvisioned()) { - ClearFlag(mFlags, kFlag_AdvertisingEnabled); + mFlags.Clear(Flags::kAdvertisingEnabled); ChipLogProgress(DeviceLayer, "CHIPoBLE advertising disabled because device is fully provisioned"); } #endif // CHIP_DEVICE_CONFIG_CHIPOBLE_DISABLE_ADVERTISING_WHEN_PROVISIONED @@ -559,35 +556,35 @@ void BLEManagerImpl::DriveBLEState() } // If there's already a control operation in progress, wait until it completes. - VerifyOrExit(!GetFlag(mFlags, kFlag_ControlOpInProgress), /* */); + VerifyOrExit(!mFlags.Has(Flags::kControlOpInProgress), /* */); // Initializes the Bluez BLE layer if needed. - if (mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_Enabled && !GetFlag(mFlags, kFlag_BluezBLELayerInitialized)) + if (mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_Enabled && !mFlags.Has(Flags::kBluezBLELayerInitialized)) { err = InitBluezBleLayer(mIsCentral, nullptr, mBLEAdvConfig, mpEndpoint); SuccessOrExit(err); - SetFlag(mFlags, kFlag_BluezBLELayerInitialized); + mFlags.Set(Flags::kBluezBLELayerInitialized); } // Register the CHIPoBLE application with the Bluez BLE layer if needed. - if (!mIsCentral && mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_Enabled && !GetFlag(mFlags, kFlag_AppRegistered)) + if (!mIsCentral && mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_Enabled && !mFlags.Has(Flags::kAppRegistered)) { err = BluezGattsAppRegister(mpEndpoint); - SetFlag(mFlags, kFlag_ControlOpInProgress); + mFlags.Set(Flags::kControlOpInProgress); ExitNow(); } // If the application has enabled CHIPoBLE and BLE advertising... - if (mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_Enabled && GetFlag(mFlags, kFlag_AdvertisingEnabled)) + if (mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_Enabled && mFlags.Has(Flags::kAdvertisingEnabled)) { // Start/re-start advertising if not already advertising, or if the advertising state of the // Bluez BLE layer needs to be refreshed. - if (!GetFlag(mFlags, kFlag_Advertising) || GetFlag(mFlags, kFlag_AdvertisingRefreshNeeded)) + if (!mFlags.Has(Flags::kAdvertising) || mFlags.Has(Flags::kAdvertisingRefreshNeeded)) { // Configure advertising data if it hasn't been done yet. This is an asynchronous step which // must complete before advertising can be started. When that happens, this method will // be called again, and execution will proceed to the code below. - if (!GetFlag(mFlags, kFlag_AdvertisingConfigured)) + if (!mFlags.Has(Flags::kAdvertisingConfigured)) { err = BluezAdvertisementSetup(mpEndpoint); ExitNow(); @@ -597,7 +594,7 @@ void BLEManagerImpl::DriveBLEState() err = StartBLEAdvertising(); SuccessOrExit(err); - SetFlag(sInstance.mFlags, kFlag_Advertising); + sInstance.mFlags.Set(Flags::kAdvertising); ExitNow(); } } @@ -605,11 +602,11 @@ void BLEManagerImpl::DriveBLEState() // Otherwise stop advertising if needed... else { - if (GetFlag(mFlags, kFlag_Advertising)) + if (mFlags.Has(Flags::kAdvertising)) { err = StopBLEAdvertising(); SuccessOrExit(err); - SetFlag(mFlags, kFlag_ControlOpInProgress); + mFlags.Set(Flags::kControlOpInProgress); ExitNow(); } diff --git a/src/platform/Linux/BLEManagerImpl.h b/src/platform/Linux/BLEManagerImpl.h index 318202f3491c8d..7e9f5672baeb00 100644 --- a/src/platform/Linux/BLEManagerImpl.h +++ b/src/platform/Linux/BLEManagerImpl.h @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2020-2021 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. @@ -163,18 +163,18 @@ class BLEManagerImpl final : public BLEManager, static BLEManagerImpl sInstance; // ===== Private members reserved for use by this class only. - enum + enum class Flags : uint16_t { - kFlag_AsyncInitCompleted = 0x0001, /**< One-time asynchronous initialization actions have been performed. */ - kFlag_BluezBLELayerInitialized = 0x0002, /**< The Bluez layer has been initialized. */ - kFlag_AppRegistered = 0x0004, /**< The CHIPoBLE application has been registered with the Bluez layer. */ - kFlag_AdvertisingConfigured = 0x0008, /**< CHIPoBLE advertising has been configured in the Bluez layer. */ - kFlag_Advertising = 0x0010, /**< The system is currently CHIPoBLE advertising. */ - kFlag_ControlOpInProgress = 0x0020, /**< An async control operation has been issued to the ESP BLE layer. */ - kFlag_AdvertisingEnabled = 0x0040, /**< The application has enabled CHIPoBLE advertising. */ - kFlag_FastAdvertisingEnabled = 0x0080, /**< The application has enabled fast advertising. */ - kFlag_UseCustomDeviceName = 0x0100, /**< The application has configured a custom BLE device name. */ - kFlag_AdvertisingRefreshNeeded = 0x0200, /**< The advertising configuration/state in BLE layer needs to be updated. */ + kAsyncInitCompleted = 0x0001, /**< One-time asynchronous initialization actions have been performed. */ + kBluezBLELayerInitialized = 0x0002, /**< The Bluez layer has been initialized. */ + kAppRegistered = 0x0004, /**< The CHIPoBLE application has been registered with the Bluez layer. */ + kAdvertisingConfigured = 0x0008, /**< CHIPoBLE advertising has been configured in the Bluez layer. */ + kAdvertising = 0x0010, /**< The system is currently CHIPoBLE advertising. */ + kControlOpInProgress = 0x0020, /**< An async control operation has been issued to the ESP BLE layer. */ + kAdvertisingEnabled = 0x0040, /**< The application has enabled CHIPoBLE advertising. */ + kFastAdvertisingEnabled = 0x0080, /**< The application has enabled fast advertising. */ + kUseCustomDeviceName = 0x0100, /**< The application has configured a custom BLE device name. */ + kAdvertisingRefreshNeeded = 0x0200, /**< The advertising configuration/state in BLE layer needs to be updated. */ }; enum @@ -196,7 +196,7 @@ class BLEManagerImpl final : public BLEManager, CHIPoBLEServiceMode mServiceMode; BLEAdvConfig mBLEAdvConfig; BLEScanConfig mBLEScanConfig; - uint16_t mFlags; + BitFlags mFlags; char mDeviceName[kMaxDeviceNameLength + 1]; bool mIsCentral = false; BluezEndpoint * mpEndpoint = nullptr; @@ -237,17 +237,17 @@ inline BLEManager::CHIPoBLEServiceMode BLEManagerImpl::_GetCHIPoBLEServiceMode() inline bool BLEManagerImpl::_IsAdvertisingEnabled() { - return GetFlag(mFlags, kFlag_AdvertisingEnabled); + return mFlags.Has(Flags::kAdvertisingEnabled); } inline bool BLEManagerImpl::_IsFastAdvertisingEnabled() { - return GetFlag(mFlags, kFlag_FastAdvertisingEnabled); + return mFlags.Has(Flags::kFastAdvertisingEnabled); } inline bool BLEManagerImpl::_IsAdvertising() { - return GetFlag(mFlags, kFlag_Advertising); + return mFlags.Has(Flags::kAdvertising); } } // namespace Internal diff --git a/src/platform/Linux/ConnectivityManagerImpl.cpp b/src/platform/Linux/ConnectivityManagerImpl.cpp index 8426e65380f5d5..f73e0dc8a4259e 100644 --- a/src/platform/Linux/ConnectivityManagerImpl.cpp +++ b/src/platform/Linux/ConnectivityManagerImpl.cpp @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2020-2021 Project CHIP Authors * Copyright (c) 2019 Nest Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -256,17 +256,18 @@ void ConnectivityManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) #if CHIP_DEVICE_CONFIG_ENABLE_WPA -uint16_t ConnectivityManagerImpl::mConnectivityFlag; +BitFlags::ConnectivityFlags> + ConnectivityManagerImpl::mConnectivityFlag; struct GDBusWpaSupplicant ConnectivityManagerImpl::mWpaSupplicant; bool ConnectivityManagerImpl::_HaveIPv4InternetConnectivity() { - return ((mConnectivityFlag & kFlag_HaveIPv4InternetConnectivity) != 0); + return mConnectivityFlag.Has(ConnectivityFlags::kHaveIPv4InternetConnectivity); } bool ConnectivityManagerImpl::_HaveIPv6InternetConnectivity() { - return ((mConnectivityFlag & kFlag_HaveIPv6InternetConnectivity) != 0); + return mConnectivityFlag.Has(ConnectivityFlags::kHaveIPv6InternetConnectivity); } ConnectivityManager::WiFiStationMode ConnectivityManagerImpl::_GetWiFiStationMode() @@ -327,8 +328,8 @@ bool ConnectivityManagerImpl::_IsWiFiStationConnected() state = wpa_fi_w1_wpa_supplicant1_interface_get_state(mWpaSupplicant.iface); if (g_strcmp0(state, "completed") == 0) { - SetFlag(mConnectivityFlag, kFlag_HaveIPv4InternetConnectivity, true); - SetFlag(mConnectivityFlag, kFlag_HaveIPv6InternetConnectivity, true); + mConnectivityFlag.Set(ConnectivityFlags::kHaveIPv4InternetConnectivity) + .Set(ConnectivityFlags::kHaveIPv6InternetConnectivity); ret = true; } @@ -620,7 +621,7 @@ void ConnectivityManagerImpl::_OnWpaProxyReady(GObject * source_object, GAsyncRe void ConnectivityManagerImpl::StartWiFiManagement() { - mConnectivityFlag = 0; + mConnectivityFlag.ClearAll(); mWpaSupplicant.state = GDBusWpaSupplicant::INIT; mWpaSupplicant.scanState = GDBusWpaSupplicant::WIFI_SCANNING_IDLE; mWpaSupplicant.proxy = nullptr; diff --git a/src/platform/Linux/ConnectivityManagerImpl.h b/src/platform/Linux/ConnectivityManagerImpl.h index fbcd9e052897a2..f381470e11db2f 100644 --- a/src/platform/Linux/ConnectivityManagerImpl.h +++ b/src/platform/Linux/ConnectivityManagerImpl.h @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2020-2021 Project CHIP Authors * Copyright (c) 2018 Nest Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -148,7 +148,7 @@ class ConnectivityManagerImpl final : public ConnectivityManager, static void _OnWpaInterfaceReady(GObject * source_object, GAsyncResult * res, gpointer user_data); static void _OnWpaInterfaceProxyReady(GObject * source_object, GAsyncResult * res, gpointer user_data); - static uint16_t mConnectivityFlag; + static BitFlags mConnectivityFlag; static struct GDBusWpaSupplicant mWpaSupplicant; #endif diff --git a/src/platform/Linux/bluez/Helper.cpp b/src/platform/Linux/bluez/Helper.cpp index 701feea6c6b61f..0f452ec4a19a44 100644 --- a/src/platform/Linux/bluez/Helper.cpp +++ b/src/platform/Linux/bluez/Helper.cpp @@ -1192,7 +1192,7 @@ static void UpdateAdditionalDataCharacteristic(BluezGattCharacteristic1 * charac char serialNumber[ConfigurationManager::kMaxSerialNumberLength + 1]; size_t serialNumberSize = 0; uint16_t lifetimeCounter = 0; - BitFlags additionalDataFields; + BitFlags additionalDataFields; #if CHIP_ENABLE_ROTATING_DEVICE_ID err = ConfigurationMgr().GetSerialNumber(serialNumber, sizeof(serialNumber), serialNumberSize); diff --git a/src/platform/Zephyr/BLEManagerImpl.cpp b/src/platform/Zephyr/BLEManagerImpl.cpp index 7396d486c882e0..7da119a618f21e 100644 --- a/src/platform/Zephyr/BLEManagerImpl.cpp +++ b/src/platform/Zephyr/BLEManagerImpl.cpp @@ -92,8 +92,8 @@ CHIP_ERROR BLEManagerImpl::_Init() CHIP_ERROR err; mServiceMode = ConnectivityManager::kCHIPoBLEServiceMode_Enabled; - mFlags = CHIP_DEVICE_CONFIG_CHIPOBLE_ENABLE_ADVERTISING_AUTOSTART ? kFlag_AdvertisingEnabled : 0; - mGAPConns = 0; + mFlags.ClearAll().Set(Flags::kAdvertisingEnabled, CHIP_DEVICE_CONFIG_CHIPOBLE_ENABLE_ADVERTISING_AUTOSTART); + mGAPConns = 0; memset(mSubscribedConns, 0, sizeof(mSubscribedConns)); @@ -128,16 +128,16 @@ void BLEManagerImpl::DriveBLEState() ChipLogDetail(DeviceLayer, "In DriveBLEState"); // Perform any initialization actions that must occur after the CHIP task is running. - if (!GetFlag(mFlags, kFlag_AsyncInitCompleted)) + if (!mFlags.Has(Flags::kAsyncInitCompleted)) { - SetFlag(mFlags, kFlag_AsyncInitCompleted); + mFlags.Set(Flags::kAsyncInitCompleted); // If CHIP_DEVICE_CONFIG_CHIPOBLE_DISABLE_ADVERTISING_WHEN_PROVISIONED is enabled, // disable CHIPoBLE advertising if the device is fully provisioned. #if CHIP_DEVICE_CONFIG_CHIPOBLE_DISABLE_ADVERTISING_WHEN_PROVISIONED if (ConfigurationMgr().IsFullyProvisioned()) { - ClearFlag(mFlags, kFlag_AdvertisingEnabled); + mFlags.Clear(Flags::kAdvertisingEnabled); ChipLogProgress(DeviceLayer, "CHIPoBLE advertising disabled because device is fully provisioned"); } #endif // CHIP_DEVICE_CONFIG_CHIPOBLE_DISABLE_ADVERTISING_WHEN_PROVISIONED @@ -145,7 +145,7 @@ void BLEManagerImpl::DriveBLEState() // If the application has enabled CHIPoBLE and BLE advertising... if (mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_Enabled && - GetFlag(mFlags, kFlag_AdvertisingEnabled) + mFlags.Has(Flags::kAdvertisingEnabled) #if CHIP_DEVICE_CONFIG_CHIPOBLE_SINGLE_CONNECTION // and no connections are active... && (NumConnections() == 0) @@ -154,7 +154,7 @@ void BLEManagerImpl::DriveBLEState() { // Start/re-start advertising if not already advertising, or if the // advertising state needs to be refreshed. - if (!GetFlag(mFlags, kFlag_Advertising) || GetFlag(mFlags, kFlag_AdvertisingRefreshNeeded)) + if (!mFlags.Has(Flags::kAdvertising) || mFlags.Has(Flags::kAdvertisingRefreshNeeded)) { err = StartAdvertising(); SuccessOrExit(err); @@ -204,7 +204,7 @@ CHIP_ERROR BLEManagerImpl::StartAdvertising(void) // If necessary, inform the ThreadStackManager that CHIPoBLE advertising is about to start. #if CHIP_DEVICE_CONFIG_ENABLE_THREAD - if (!GetFlag(mFlags, kFlag_Advertising)) + if (!mFlags.Has(Flags::kAdvertising)) { ThreadStackMgr().OnCHIPoBLEAdvertisingStart(); } @@ -225,11 +225,11 @@ CHIP_ERROR BLEManagerImpl::StartAdvertising(void) VerifyOrExit(err == CHIP_NO_ERROR, err = MapErrorZephyr(err)); // Transition to the Advertising state... - if (!GetFlag(mFlags, kFlag_Advertising)) + if (!mFlags.Has(Flags::kAdvertising)) { ChipLogProgress(DeviceLayer, "CHIPoBLE advertising started"); - SetFlag(mFlags, kFlag_Advertising); + mFlags.Set(Flags::kAdvertising); // Post a CHIPoBLEAdvertisingChange(Started) event. { @@ -255,9 +255,9 @@ CHIP_ERROR BLEManagerImpl::StopAdvertising(void) VerifyOrExit(err == CHIP_NO_ERROR, err = MapErrorZephyr(err)); // Transition to the not Advertising state... - if (GetFlag(mFlags, kFlag_Advertising)) + if (mFlags.Has(Flags::kAdvertising)) { - ClearFlag(mFlags, kFlag_Advertising); + mFlags.Clear(Flags::kAdvertising); ChipLogProgress(DeviceLayer, "CHIPoBLE advertising stopped"); @@ -305,11 +305,11 @@ CHIP_ERROR BLEManagerImpl::_SetAdvertisingEnabled(bool val) VerifyOrExit(mServiceMode != ConnectivityManager::kCHIPoBLEServiceMode_NotSupported, err = CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE); - if (GetFlag(mFlags, kFlag_AdvertisingEnabled) != val) + if (mFlags.Has(Flags::kAdvertisingEnabled) != val) { ChipLogDetail(DeviceLayer, "SetAdvertisingEnabled(%s)", val ? "true" : "false"); - SetFlag(mFlags, kFlag_AdvertisingEnabled, val); + mFlags.Set(Flags::kAdvertisingEnabled, val); PlatformMgr().ScheduleWork(DriveBLEState, 0); } @@ -323,11 +323,11 @@ CHIP_ERROR BLEManagerImpl::_SetFastAdvertisingEnabled(bool val) VerifyOrExit(mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_NotSupported, err = CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE); - if (GetFlag(mFlags, kFlag_FastAdvertisingEnabled) != val) + if (mFlags.Has(Flags::kFastAdvertisingEnabled) != val) { ChipLogDetail(DeviceLayer, "SetFastAdvertisingEnabled(%s)", val ? "true" : "false"); - SetFlag(mFlags, kFlag_FastAdvertisingEnabled, val); + mFlags.Set(Flags::kFastAdvertisingEnabled, val); PlatformMgr().ScheduleWork(DriveBLEState, 0); } @@ -372,7 +372,7 @@ CHIP_ERROR BLEManagerImpl::HandleGAPConnect(const ChipDeviceEvent * event) ChipLogProgress(DeviceLayer, "Current number of connections: %" PRIu16 "/%" PRIu16, NumConnections(), CONFIG_BT_MAX_CONN); - SetFlag(mFlags, kFlag_AdvertisingRefreshNeeded); + mFlags.Set(Flags::kAdvertisingRefreshNeeded); PlatformMgr().ScheduleWork(DriveBLEState, 0); bt_conn_unref(connEvent->BtConn); @@ -418,7 +418,7 @@ CHIP_ERROR BLEManagerImpl::HandleGAPDisconnect(const ChipDeviceEvent * event) // Force a reconfiguration of advertising in case we switched to non-connectable mode when // the BLE connection was established. - SetFlag(mFlags, kFlag_AdvertisingRefreshNeeded); + mFlags.Set(Flags::kAdvertisingRefreshNeeded); PlatformMgr().ScheduleWork(DriveBLEState, 0); return CHIP_NO_ERROR; @@ -530,13 +530,13 @@ void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) #if CHIP_DEVICE_CONFIG_CHIPOBLE_DISABLE_ADVERTISING_WHEN_PROVISIONED if (ConfigurationMgr().IsFullyProvisioned()) { - ClearFlag(mFlags, kFlag_AdvertisingEnabled); + mFlags.Clear(Flags::kAdvertisingEnabled); ChipLogProgress(DeviceLayer, "CHIPoBLE advertising disabled because device is fully provisioned"); } #endif // CHIP_DEVICE_CONFIG_CHIPOBLE_DISABLE_ADVERTISING_WHEN_PROVISIONED // Force the advertising state to be refreshed to reflect new provisioning state. - SetFlag(mFlags, kFlag_AdvertisingRefreshNeeded); + mFlags.Set(Flags::kAdvertisingRefreshNeeded); DriveBLEState(); @@ -674,7 +674,7 @@ bool BLEManagerImpl::UnsetSubscribed(bt_conn * conn) uint32_t BLEManagerImpl::GetAdvertisingInterval() { - return (NumConnections() == 0 && !ConfigurationMgr().IsFullyProvisioned()) || GetFlag(mFlags, kFlag_FastAdvertisingEnabled) + return (NumConnections() == 0 && !ConfigurationMgr().IsFullyProvisioned()) || mFlags.Has(Flags::kFastAdvertisingEnabled) ? CHIP_DEVICE_CONFIG_BLE_FAST_ADVERTISING_INTERVAL : CHIP_DEVICE_CONFIG_BLE_SLOW_ADVERTISING_INTERVAL; } diff --git a/src/platform/Zephyr/BLEManagerImpl.h b/src/platform/Zephyr/BLEManagerImpl.h index d7fe37fa9d04b7..957613781f0a7d 100644 --- a/src/platform/Zephyr/BLEManagerImpl.h +++ b/src/platform/Zephyr/BLEManagerImpl.h @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2020-2021 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. @@ -93,19 +93,19 @@ class BLEManagerImpl final : public BLEManager, private BleLayer, private BlePla // ===== Private members reserved for use by this class only. - enum + enum class Flags : uint8_t { - kFlag_AsyncInitCompleted = 0x0001, /**< One-time asynchronous initialization actions have been performed. */ - kFlag_AdvertisingEnabled = 0x0002, /**< The application has enabled CHIPoBLE advertising. */ - kFlag_FastAdvertisingEnabled = 0x0004, /**< The application has enabled fast advertising. */ - kFlag_Advertising = 0x0008, /**< The system is currently CHIPoBLE advertising. */ - kFlag_AdvertisingRefreshNeeded = + kAsyncInitCompleted = 0x0001, /**< One-time asynchronous initialization actions have been performed. */ + kAdvertisingEnabled = 0x0002, /**< The application has enabled CHIPoBLE advertising. */ + kFastAdvertisingEnabled = 0x0004, /**< The application has enabled fast advertising. */ + kAdvertising = 0x0008, /**< The system is currently CHIPoBLE advertising. */ + kAdvertisingRefreshNeeded = 0x0010, /**< The advertising state/configuration has changed, but the SoftDevice has yet to be updated. */ }; struct ServiceData; - uint16_t mFlags; + BitFlags mFlags; uint16_t mGAPConns; CHIPoBLEServiceMode mServiceMode; bool mSubscribedConns[CONFIG_BT_MAX_CONN]; @@ -182,17 +182,17 @@ inline BLEManager::CHIPoBLEServiceMode BLEManagerImpl::_GetCHIPoBLEServiceMode(v inline bool BLEManagerImpl::_IsAdvertisingEnabled(void) { - return GetFlag(mFlags, kFlag_AdvertisingEnabled); + return mFlags.Has(Flags::kAdvertisingEnabled); } inline bool BLEManagerImpl::_IsFastAdvertisingEnabled(void) { - return GetFlag(mFlags, kFlag_FastAdvertisingEnabled); + return mFlags.Has(Flags::kFastAdvertisingEnabled); } inline bool BLEManagerImpl::_IsAdvertising(void) { - return GetFlag(mFlags, kFlag_Advertising); + return mFlags.Has(Flags::kAdvertising); } } // namespace Internal diff --git a/src/platform/cc13x2_26x2/BLEManagerImpl.cpp b/src/platform/cc13x2_26x2/BLEManagerImpl.cpp index a5476acc3ed394..d844c9a8537910 100644 --- a/src/platform/cc13x2_26x2/BLEManagerImpl.cpp +++ b/src/platform/cc13x2_26x2/BLEManagerImpl.cpp @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2020-2021 Project CHIP Authors * Copyright (c) 2019 Nest Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -113,7 +113,7 @@ CHIP_ERROR BLEManagerImpl::_Init(void) /* Register BLE Stack assert handler */ RegisterAssertCback(AssertHandler); - mFlags = CHIP_DEVICE_CONFIG_CHIPOBLE_ENABLE_ADVERTISING_AUTOSTART ? kFlag_AdvertisingEnabled : 0; + mFlags.ClearAll().Set(Flags::kAdvertisingEnabled, CHIP_DEVICE_CONFIG_CHIPOBLE_ENABLE_ADVERTISING_AUTOSTART); mServiceMode = ConnectivityManager::kCHIPoBLEServiceMode_Enabled; OnChipBleConnectReceived = HandleIncomingBleConnection; @@ -137,13 +137,13 @@ CHIP_ERROR BLEManagerImpl::_SetCHIPoBLEServiceMode(BLEManager::CHIPoBLEServiceMo bool BLEManagerImpl::_IsAdvertisingEnabled(void) { - return GetFlag(mFlags, kFlag_AdvertisingEnabled); + return mFlags.Has(Flags::kAdvertisingEnabled); } /* Post event to app processing loop to begin CHIP advertising */ CHIP_ERROR BLEManagerImpl::_SetAdvertisingEnabled(bool val) { - SetFlag(mFlags, kFlag_AdvertisingEnabled, val); + mFlags.Set(Flags::kAdvertisingEnabled, val); /* Send event to process state change request */ return DriveBLEState(); @@ -151,16 +151,16 @@ CHIP_ERROR BLEManagerImpl::_SetAdvertisingEnabled(bool val) bool BLEManagerImpl::_IsFastAdvertisingEnabled(void) { - return GetFlag(mFlags, kFlag_FastAdvertisingEnabled); + return mFlags.Has(Flags::kFastAdvertisingEnabled); } CHIP_ERROR BLEManagerImpl::_SetFastAdvertisingEnabled(bool val) { CHIP_ERROR ret = CHIP_NO_ERROR; - if (!GetFlag(mFlags, kFlag_FastAdvertisingEnabled)) + if (!mFlags.Has(Flags::kFastAdvertisingEnabled)) { - SetFlag(mFlags, kFlag_FastAdvertisingEnabled, val); + mFlags.Set(Flags::kFastAdvertisingEnabled, val); /* Send event to process state change request */ ret = DriveBLEState(); @@ -170,7 +170,7 @@ CHIP_ERROR BLEManagerImpl::_SetFastAdvertisingEnabled(bool val) bool BLEManagerImpl::_IsAdvertising(void) { - return GetFlag(mFlags, kFlag_Advertising); + return mFlags.Has(Flags::kAdvertising); } CHIP_ERROR BLEManagerImpl::_GetDeviceName(char * buf, size_t bufSize) @@ -197,7 +197,7 @@ CHIP_ERROR BLEManagerImpl::_SetDeviceName(const char * deviceName) { strncpy(mDeviceName, deviceName, strlen(deviceName)); - SetFlag(mFlags, kFlag_BLEStackGATTNameUpdate, true); + mFlags.Set(Flags::kBLEStackGATTNameUpdate); ret = DriveBLEState(); } @@ -409,7 +409,7 @@ void BLEManagerImpl::AdvInit(void) ConfigurationMgr().GetBLEDeviceIdentificationInfo(mDeviceIdInfo); // Verify device name was not already set - if (!GetFlag(sInstance.mFlags, kFlag_BLEStackGATTNameSet)) + if (!sInstance.mFlags.Has(Flags::kBLEStackGATTNameSet)) { /* Default device name is CHIP- */ deviceDiscriminator = mDeviceIdInfo.GetDeviceDiscriminator(); @@ -758,13 +758,13 @@ void BLEManagerImpl::ProcessEvtHdrMsg(QueuedEvt_t * pMsg) /* Advertising flag set, either advertising or fast adv is enabled: Do nothing */ /* Advertising flag not set, neither advertising nor fast adv is enabled: do nothing */ /* Advertising flag not set, either advertising or fast adv is enabled: Turn on */ - if (!GetFlag(sInstance.mFlags, kFlag_Advertising)) + if (!sInstance.mFlags.Has(Flags::kAdvertising)) { BLEMGR_LOG("BLEMGR: BLE Process Application Message: Not advertising"); - if (GetFlag(sInstance.mFlags, kFlag_AdvertisingEnabled)) + if (sInstance.mFlags.Has(Flags::kAdvertisingEnabled)) { - ClearFlag(sInstance.mFlags, kFlag_FastAdvertisingEnabled); + sInstance.mFlags.Clear(Flags::kFastAdvertisingEnabled); BLEMGR_LOG("BLEMGR: BLE Process Application Message: Slow Advertising Enabled"); // Send notification to thread manager that CHIPoBLE advertising is starting @@ -780,11 +780,11 @@ void BLEManagerImpl::ProcessEvtHdrMsg(QueuedEvt_t * pMsg) // Start advertisement timer Util_startClock(&sInstance.clkAdvTimeout); - SetFlag(sInstance.mFlags, kFlag_Advertising, true); + sInstance.mFlags.Set(Flags::kAdvertising); } - else if (GetFlag(sInstance.mFlags, kFlag_FastAdvertisingEnabled)) + else if (sInstance.mFlags.Has(Flags::kFastAdvertisingEnabled)) { - ClearFlag(sInstance.mFlags, kFlag_AdvertisingEnabled); + sInstance.mFlags.Clear(Flags::kAdvertisingEnabled); BLEMGR_LOG("BLEMGR: BLE Process Application Message: Fast Advertising Enabled"); @@ -795,28 +795,27 @@ void BLEManagerImpl::ProcessEvtHdrMsg(QueuedEvt_t * pMsg) // Enable legacy advertising for set #1 status = (bStatus_t) GapAdv_enable(sInstance.advHandleLegacy, GAP_ADV_ENABLE_OPTIONS_USE_MAX, 0); assert(status == SUCCESS); - SetFlag(sInstance.mFlags, kFlag_Advertising, true); + sInstance.mFlags.Set(Flags::kAdvertising); } } /* Advertising flag set, neither advertising nor fast adv is enabled: Turn off*/ - else if (!GetFlag(sInstance.mFlags, kFlag_AdvertisingEnabled) && - !GetFlag(sInstance.mFlags, kFlag_FastAdvertisingEnabled)) + else if (!sInstance.mFlags.Has(Flags::kAdvertisingEnabled) && !sInstance.mFlags.Has(Flags::kFastAdvertisingEnabled)) { BLEMGR_LOG("BLEMGR: BLE Process Application Message: Advertising disables"); // Stop advertising GapAdv_disable(sInstance.advHandleLegacy); - ClearFlag(sInstance.mFlags, kFlag_Advertising); + sInstance.mFlags.Clear(Flags::kAdvertising); Util_stopClock(&sInstance.clkAdvTimeout); } } - if (GetFlag(sInstance.mFlags, kFlag_BLEStackGATTNameUpdate)) + if (sInstance.mFlags.Has(Flags::kBLEStackGATTNameUpdate)) { - ClearFlag(sInstance.mFlags, kFlag_BLEStackGATTNameUpdate); + sInstance.mFlags.Clear(Flags::kBLEStackGATTNameUpdate); // Indicate that Device name has been set externally - SetFlag(mFlags, kFlag_BLEStackGATTNameSet, true); + mFlags.Set(Flags::kBLEStackGATTNameSet); // Set the Device Name characteristic in the GAP GATT Service GGS_SetParameter(GGS_DEVICE_NAME_ATT, GAP_DEVICE_NAME_LEN, sInstance.mDeviceName); @@ -1026,7 +1025,7 @@ void BLEManagerImpl::ProcessGapMessage(gapEventHdr_t * pMsg) AdvInit(); - SetFlag(sInstance.mFlags, kFlag_BLEStackInitialized, true); + sInstance.mFlags.Set(Flags::kBLEStackInitialized); /* Trigger post-initialization state update */ DriveBLEState(); @@ -1060,13 +1059,13 @@ void BLEManagerImpl::ProcessGapMessage(gapEventHdr_t * pMsg) if (numActive < MAX_NUM_BLE_CONNS) { // Start advertising since there is room for more connections. Advertisements stop automatically following connection. - ClearFlag(sInstance.mFlags, kFlag_Advertising); + sInstance.mFlags.Clear(Flags::kAdvertising); } else { // Stop advertising since there is no room for more connections BLEMGR_LOG("BLEMGR: BLE event GAP_LINK_ESTABLISHED_EVENT: MAX connections"); - ClearFlag(sInstance.mFlags, kFlag_FastAdvertisingEnabled | kFlag_AdvertisingEnabled | kFlag_Advertising); + sInstance.mFlags.Clear(Flags::kFastAdvertisingEnabled).Clear(Flags::kAdvertisingEnabled.Clear(Flags::kAdvertising); } /* Stop advertisement timeout timer */ @@ -1686,11 +1685,11 @@ void BLEManagerImpl::AdvTimeoutHandler(uintptr_t arg) { BLEMGR_LOG("BLEMGR: AdvTimeoutHandler"); - if (GetFlag(sInstance.mFlags, kFlag_AdvertisingEnabled)) + if (sInstance.mFlags.Has(Flags::kAdvertisingEnabled)) { BLEMGR_LOG("BLEMGR: AdvTimeoutHandler ble adv 15 minute timeout"); - SetFlag(sInstance.mFlags, kFlag_AdvertisingEnabled, false); + sInstance.mFlags.Clear(Flags::kAdvertisingEnabled); /* Send event to process state change request */ DriveBLEState(); diff --git a/src/platform/qpg6100/BLEManagerImpl.cpp b/src/platform/qpg6100/BLEManagerImpl.cpp index b831e9bf71d2db..5c55c2841b4e68 100644 --- a/src/platform/qpg6100/BLEManagerImpl.cpp +++ b/src/platform/qpg6100/BLEManagerImpl.cpp @@ -68,8 +68,8 @@ CHIP_ERROR BLEManagerImpl::_Init() CHIP_ERROR err; mServiceMode = ConnectivityManager::kCHIPoBLEServiceMode_Enabled; - mFlags = CHIP_DEVICE_CONFIG_CHIPOBLE_ENABLE_ADVERTISING_AUTOSTART ? kFlag_AdvertisingEnabled : 0; - mNumGAPCons = 0; + mFlags.ClearAll().Set(Flags::kAdvertisingEnabled, CHIP_DEVICE_CONFIG_CHIPOBLE_ENABLE_ADVERTISING_AUTOSTART); + mNumGAPCons = 0; for (int i = 0; i < kMaxConnections; i++) { mSubscribedConIds[i] = BLE_CONNECTION_UNINITIALIZED; @@ -115,9 +115,9 @@ CHIP_ERROR BLEManagerImpl::_SetAdvertisingEnabled(bool val) VerifyOrExit(mServiceMode != ConnectivityManager::kCHIPoBLEServiceMode_NotSupported, err = CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE); - if (GetFlag(mFlags, kFlag_AdvertisingEnabled) != val) + if (mFlags.Has(Flags::kAdvertisingEnabled) != val) { - SetFlag(mFlags, kFlag_AdvertisingEnabled, val); + mFlags.Set(Flags::kAdvertisingEnabled, val); PlatformMgr().ScheduleWork(DriveBLEState, 0); } @@ -131,9 +131,9 @@ CHIP_ERROR BLEManagerImpl::_SetFastAdvertisingEnabled(bool val) VerifyOrExit(mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_NotSupported, err = CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE); - if (GetFlag(mFlags, kFlag_FastAdvertisingEnabled) != val) + if (mFlags.Has(Flags::kFastAdvertisingEnabled) != val) { - SetFlag(mFlags, kFlag_FastAdvertisingEnabled, val); + mFlags.Set(Flags::kFastAdvertisingEnabled, val); PlatformMgr().ScheduleWork(DriveBLEState, 0); } @@ -209,13 +209,13 @@ void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) #if CHIP_DEVICE_CONFIG_CHIPOBLE_DISABLE_ADVERTISING_WHEN_PROVISIONED if (ConfigurationMgr().IsFullyProvisioned()) { - ClearFlag(mFlags, kFlag_AdvertisingEnabled); + mFlags.Clear(Flags::kAdvertisingEnabled); ChipLogProgress(DeviceLayer, "CHIPoBLE advertising disabled because device is fully provisioned"); } #endif // CHIP_DEVICE_CONFIG_CHIPOBLE_DISABLE_ADVERTISING_WHEN_PROVISIONED // Force the advertising state to be refreshed to reflect new provisioning state. - SetFlag(mFlags, kFlag_AdvertisingRefreshNeeded); + mFlags.Set(Flags::kAdvertisingRefreshNeeded); DriveBLEState(); @@ -353,16 +353,16 @@ void BLEManagerImpl::DriveBLEState(void) CHIP_ERROR err = CHIP_NO_ERROR; // Perform any initialization actions that must occur after the CHIP task is running. - if (!GetFlag(mFlags, kFlag_AsyncInitCompleted)) + if (!mFlags.Has(Flags::kAsyncInitCompleted)) { - SetFlag(mFlags, kFlag_AsyncInitCompleted); + mFlags.Set(Flags::kAsyncInitCompleted); // If CHIP_DEVICE_CONFIG_CHIPOBLE_DISABLE_ADVERTISING_WHEN_PROVISIONED is enabled, // disable CHIPoBLE advertising if the device is fully provisioned. #if CHIP_DEVICE_CONFIG_CHIPOBLE_DISABLE_ADVERTISING_WHEN_PROVISIONED if (ConfigurationMgr().IsFullyProvisioned()) { - ClearFlag(mFlags, kFlag_AdvertisingEnabled); + mFlags.Clear(Flags::kAdvertisingEnabled); ChipLogProgress(DeviceLayer, "CHIPoBLE advertising disabled because device is fully provisioned"); } #endif // CHIP_DEVICE_CONFIG_CHIPOBLE_DISABLE_ADVERTISING_WHEN_PROVISIONED @@ -370,7 +370,7 @@ void BLEManagerImpl::DriveBLEState(void) // If the application has enabled CHIPoBLE and BLE advertising... if (mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_Enabled && - GetFlag(mFlags, kFlag_AdvertisingEnabled) + mFlags.Has(Flags::kAdvertisingEnabled) #if CHIP_DEVICE_CONFIG_CHIPOBLE_SINGLE_CONNECTION // and no connections are active... && (mNumGAPCons == 0) @@ -379,7 +379,7 @@ void BLEManagerImpl::DriveBLEState(void) { // Start/re-start BLE advertising if not already advertising, or if the // advertising state of the underlying stack needs to be refreshed. - if (!GetFlag(mFlags, kFlag_Advertising) || GetFlag(mFlags, kFlag_AdvertisingRefreshNeeded)) + if (!mFlags.Has(Flags::kAdvertising) || mFlags.Has(Flags::kAdvertisingRefreshNeeded)) { err = StartAdvertising(); SuccessOrExit(err); @@ -415,7 +415,7 @@ CHIP_ERROR BLEManagerImpl::ConfigureAdvertisingData(void) err = ConfigurationMgr().GetBLEDeviceIdentificationInfo(mDeviceIdInfo); SuccessOrExit(err); - if (!GetFlag(mFlags, kFlag_DeviceNameSet)) + if (!mFlags.Has(Flags::kDeviceNameSet)) { snprintf(mDeviceName, sizeof(mDeviceName), "%s%04" PRIX32, CHIP_DEVICE_CONFIG_BLE_DEVICE_NAME_PREFIX, (uint32_t) 0); @@ -474,9 +474,9 @@ CHIP_ERROR BLEManagerImpl::StartAdvertising(void) err = ConfigureAdvertisingData(); SuccessOrExit(err); - SetFlag(mFlags, kFlag_Advertising, true); + mFlags.Set(Flags::kAdvertising); - interval = ((mNumGAPCons == 0 && !ConfigurationMgr().IsPairedToAccount()) || GetFlag(mFlags, kFlag_FastAdvertisingEnabled)) + interval = ((mNumGAPCons == 0 && !ConfigurationMgr().IsPairedToAccount()) || mFlags.Has(Flags::kFastAdvertisingEnabled)) ? CHIP_DEVICE_CONFIG_BLE_FAST_ADVERTISING_INTERVAL : CHIP_DEVICE_CONFIG_BLE_SLOW_ADVERTISING_INTERVAL; @@ -498,9 +498,9 @@ CHIP_ERROR BLEManagerImpl::StopAdvertising(void) SuccessOrExit(err); // Transition to the not Advertising state... - if (GetFlag(mFlags, kFlag_Advertising)) + if (mFlags.Has(Flags::kAdvertising)) { - ClearFlag(mFlags, kFlag_Advertising); + mFlags.Clear(Flags::kAdvertising); ChipLogProgress(DeviceLayer, "CHIPoBLE advertising stopped"); @@ -648,14 +648,14 @@ void BLEManagerImpl::HandleDmMsg(qvCHIP_Ble_DmEvt_t * pDmEvt) ExitNow(); } - ClearFlag(sInstance.mFlags, kFlag_AdvertisingRefreshNeeded); + sInstance.mFlags.Clear(Flags::kAdvertisingRefreshNeeded); // Transition to the Advertising state... - if (!GetFlag(sInstance.mFlags, kFlag_Advertising)) + if (!sInstance.mFlags.Has(Flags::kAdvertising)) { ChipLogProgress(DeviceLayer, "CHIPoBLE advertising started"); - SetFlag(sInstance.mFlags, kFlag_Advertising, true); + sInstance.mFlags.Set(Flags::kAdvertising); // Post a CHIPoBLEAdvertisingChange(Started) event. { @@ -674,12 +674,12 @@ void BLEManagerImpl::HandleDmMsg(qvCHIP_Ble_DmEvt_t * pDmEvt) ExitNow(); } - ClearFlag(sInstance.mFlags, kFlag_AdvertisingRefreshNeeded); + sInstance.mFlags.Clear(Flags::kAdvertisingRefreshNeeded); // Transition to the not Advertising state... - if (GetFlag(sInstance.mFlags, kFlag_Advertising)) + if (sInstance.mFlags.Has(Flags::kAdvertising)) { - ClearFlag(sInstance.mFlags, kFlag_Advertising); + sInstance.mFlags.Clear(Flags::kAdvertising); ChipLogProgress(DeviceLayer, "CHIPoBLE advertising stopped"); @@ -706,7 +706,7 @@ void BLEManagerImpl::HandleDmMsg(qvCHIP_Ble_DmEvt_t * pDmEvt) // Receiving a connection stops the advertising processes. So force a refresh of the advertising // state. - SetFlag(mFlags, kFlag_AdvertisingRefreshNeeded); + mFlags.Set(Flags::kAdvertisingRefreshNeeded); PlatformMgr().ScheduleWork(DriveBLEState, 0); break; } @@ -742,7 +742,7 @@ void BLEManagerImpl::HandleDmMsg(qvCHIP_Ble_DmEvt_t * pDmEvt) PlatformMgr().PostEvent(&event); } - SetFlag(mFlags, kFlag_AdvertisingRefreshNeeded); + mFlags.Set(Flags::kAdvertisingRefreshNeeded); PlatformMgr().ScheduleWork(DriveBLEState, 0); break; } diff --git a/src/platform/qpg6100/BLEManagerImpl.h b/src/platform/qpg6100/BLEManagerImpl.h index dd08bab188e90e..8de51c449f6d52 100644 --- a/src/platform/qpg6100/BLEManagerImpl.h +++ b/src/platform/qpg6100/BLEManagerImpl.h @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2020-2021 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. @@ -87,15 +87,14 @@ class BLEManagerImpl final : public BLEManager, private BleLayer, private BlePla // ===== Private members reserved for use by this class only. - enum + enum class Flags : uint16_t { - kFlag_AsyncInitCompleted = 0x0001, /**< One-time asynchronous initialization actions have been performed. */ - kFlag_AdvertisingEnabled = 0x0002, /**< The application has enabled CHIPoBLE advertising. */ - kFlag_FastAdvertisingEnabled = 0x0004, /**< The application has enabled fast advertising. */ - kFlag_Advertising = 0x0008, /**< The system is currently CHIPoBLE advertising. */ - kFlag_AdvertisingRefreshNeeded = - 0x0010, /**< The advertising state/configuration state in the BLE layer needs to be updated. */ - kFlag_DeviceNameSet = 0x0020, + kAsyncInitCompleted = 0x0001, /**< One-time asynchronous initialization actions have been performed. */ + kAdvertisingEnabled = 0x0002, /**< The application has enabled CHIPoBLE advertising. */ + kFastAdvertisingEnabled = 0x0004, /**< The application has enabled fast advertising. */ + kAdvertising = 0x0008, /**< The system is currently CHIPoBLE advertising. */ + kAdvertisingRefreshNeeded = 0x0010, /**< The advertising state/configuration state in the BLE layer needs to be updated. */ + kDeviceNameSet = 0x0020, }; enum @@ -106,7 +105,7 @@ class BLEManagerImpl final : public BLEManager, private BleLayer, private BlePla }; CHIPoBLEServiceMode mServiceMode; - uint16_t mFlags; + BitFlags mFlags; char mDeviceName[kMaxDeviceNameLength + 1]; uint16_t mNumGAPCons; uint16_t mSubscribedConIds[kMaxConnections]; @@ -173,17 +172,17 @@ inline BLEManager::CHIPoBLEServiceMode BLEManagerImpl::_GetCHIPoBLEServiceMode(v inline bool BLEManagerImpl::_IsAdvertisingEnabled(void) { - return GetFlag(mFlags, kFlag_AdvertisingEnabled); + return mFlags.Has(Flags::kAdvertisingEnabled); } inline bool BLEManagerImpl::_IsFastAdvertisingEnabled(void) { - return GetFlag(mFlags, kFlag_FastAdvertisingEnabled); + return mFlags.Has(Flags::kFastAdvertisingEnabled); } inline bool BLEManagerImpl::_IsAdvertising(void) { - return GetFlag(mFlags, kFlag_Advertising); + return mFlags.Has(Flags::kAdvertising); } } // namespace Internal diff --git a/src/protocols/bdx/BdxMessages.cpp b/src/protocols/bdx/BdxMessages.cpp index b64c7b899b7593..bd9bf780c52d86 100644 --- a/src/protocols/bdx/BdxMessages.cpp +++ b/src/protocols/bdx/BdxMessages.cpp @@ -42,18 +42,16 @@ using namespace chip::Encoding::LittleEndian; // the size of the message (even if the message is incomplete or filled out incorrectly). BufferWriter & TransferInit::WriteToBuffer(BufferWriter & aBuffer) const { - uint8_t proposedTransferCtl = 0; - bool widerange = (StartOffset > std::numeric_limits::max()) || (MaxLength > std::numeric_limits::max()); + const BitFlags proposedTransferCtl(Version & kVersionMask, TransferCtlOptions); + const bool widerange = + (StartOffset > std::numeric_limits::max()) || (MaxLength > std::numeric_limits::max()); - proposedTransferCtl |= Version & kVersionMask; - proposedTransferCtl = proposedTransferCtl | TransferCtlOptions.Raw(); + BitFlags rangeCtlFlags; + rangeCtlFlags.Set(RangeControlFlags::kDefLen, MaxLength > 0); + rangeCtlFlags.Set(RangeControlFlags::kStartOffset, StartOffset > 0); + rangeCtlFlags.Set(RangeControlFlags::kWiderange, widerange); - BitFlags rangeCtlFlags; - rangeCtlFlags.Set(kRange_DefLen, MaxLength > 0); - rangeCtlFlags.Set(kRange_StartOffset, StartOffset > 0); - rangeCtlFlags.Set(kRange_Widerange, widerange); - - aBuffer.Put(proposedTransferCtl); + aBuffer.Put(proposedTransferCtl.Raw()); aBuffer.Put(rangeCtlFlags.Raw()); aBuffer.Put16(MaxBlockSize); @@ -98,22 +96,20 @@ CHIP_ERROR TransferInit::Parse(System::PacketBufferHandle aBuffer) { CHIP_ERROR err = CHIP_NO_ERROR; uint8_t proposedTransferCtl; - uint8_t rangeCtl; uint32_t tmpUint32Value = 0; // Used for reading non-wide length and offset fields uint8_t * bufStart = aBuffer->Start(); Reader bufReader(bufStart, aBuffer->DataLength()); - BitFlags rangeCtlFlags; + BitFlags rangeCtlFlags; - SuccessOrExit(bufReader.Read8(&proposedTransferCtl).Read8(&rangeCtl).Read16(&MaxBlockSize).StatusCode()); + SuccessOrExit(bufReader.Read8(&proposedTransferCtl).Read8(rangeCtlFlags.RawStorage()).Read16(&MaxBlockSize).StatusCode()); Version = proposedTransferCtl & kVersionMask; TransferCtlOptions.SetRaw(static_cast(proposedTransferCtl & ~kVersionMask)); - rangeCtlFlags.SetRaw(rangeCtl); StartOffset = 0; - if (rangeCtlFlags.Has(kRange_StartOffset)) + if (rangeCtlFlags.Has(RangeControlFlags::kStartOffset)) { - if (rangeCtlFlags.Has(kRange_Widerange)) + if (rangeCtlFlags.Has(RangeControlFlags::kWiderange)) { SuccessOrExit(bufReader.Read64(&StartOffset).StatusCode()); } @@ -125,9 +121,9 @@ CHIP_ERROR TransferInit::Parse(System::PacketBufferHandle aBuffer) } MaxLength = 0; - if (rangeCtlFlags.Has(kRange_DefLen)) + if (rangeCtlFlags.Has(RangeControlFlags::kDefLen)) { - if (rangeCtlFlags.Has(kRange_Widerange)) + if (rangeCtlFlags.Has(RangeControlFlags::kWiderange)) { SuccessOrExit(bufReader.Read64(&MaxLength).StatusCode()); } @@ -189,7 +185,7 @@ bool TransferInit::operator==(const TransferInit & another) const metadataMatches = (memcmp(Metadata, another.Metadata, MetadataLength) == 0); } - return ((Version == another.Version) && (TransferCtlOptions.Raw() == another.TransferCtlOptions.Raw()) && + return ((Version == another.Version) && (TransferCtlOptions == another.TransferCtlOptions) && (StartOffset == another.StartOffset) && (MaxLength == another.MaxLength) && (MaxBlockSize == another.MaxBlockSize) && fileDesMatches && metadataMatches); } @@ -198,12 +194,9 @@ bool TransferInit::operator==(const TransferInit & another) const // the size of the message (even if the message is incomplete or filled out incorrectly). Encoding::LittleEndian::BufferWriter & SendAccept::WriteToBuffer(Encoding::LittleEndian::BufferWriter & aBuffer) const { - uint8_t transferCtl = 0; - - transferCtl |= Version & kVersionMask; - transferCtl = transferCtl | TransferCtlFlags.Raw(); + const BitFlags transferCtl(Version & kVersionMask, TransferCtlFlags); - aBuffer.Put(transferCtl); + aBuffer.Put(transferCtl.Raw()); aBuffer.Put16(MaxBlockSize); if (Metadata != nullptr) @@ -266,7 +259,7 @@ bool SendAccept::operator==(const SendAccept & another) const metadataMatches = (memcmp(Metadata, another.Metadata, MetadataLength) == 0); } - return ((Version == another.Version) && (TransferCtlFlags.Raw() == another.TransferCtlFlags.Raw()) && + return ((Version == another.Version) && (TransferCtlFlags == another.TransferCtlFlags) && (MaxBlockSize == another.MaxBlockSize) && metadataMatches); } @@ -274,18 +267,15 @@ bool SendAccept::operator==(const SendAccept & another) const // the size of the message (even if the message is incomplete or filled out incorrectly). Encoding::LittleEndian::BufferWriter & ReceiveAccept::WriteToBuffer(Encoding::LittleEndian::BufferWriter & aBuffer) const { - uint8_t transferCtl = 0; - bool widerange = (StartOffset > std::numeric_limits::max()) || (Length > std::numeric_limits::max()); - - transferCtl |= Version & kVersionMask; - transferCtl = transferCtl | TransferCtlFlags.Raw(); + const BitFlags transferCtlFlags(Version & kVersionMask, TransferCtlFlags); + const bool widerange = (StartOffset > std::numeric_limits::max()) || (Length > std::numeric_limits::max()); - BitFlags rangeCtlFlags; - rangeCtlFlags.Set(kRange_DefLen, Length > 0); - rangeCtlFlags.Set(kRange_StartOffset, StartOffset > 0); - rangeCtlFlags.Set(kRange_Widerange, widerange); + BitFlags rangeCtlFlags; + rangeCtlFlags.Set(RangeControlFlags::kDefLen, Length > 0); + rangeCtlFlags.Set(RangeControlFlags::kStartOffset, StartOffset > 0); + rangeCtlFlags.Set(RangeControlFlags::kWiderange, widerange); - aBuffer.Put(transferCtl); + aBuffer.Put(transferCtlFlags.Raw()); aBuffer.Put(rangeCtlFlags.Raw()); aBuffer.Put16(MaxBlockSize); @@ -324,25 +314,22 @@ CHIP_ERROR ReceiveAccept::Parse(System::PacketBufferHandle aBuffer) { CHIP_ERROR err = CHIP_NO_ERROR; uint8_t transferCtl = 0; - uint8_t rangeCtl = 0; uint32_t tmpUint32Value = 0; // Used for reading non-wide length and offset fields uint8_t * bufStart = aBuffer->Start(); Reader bufReader(bufStart, aBuffer->DataLength()); - BitFlags rangeCtlFlags; + BitFlags rangeCtlFlags; - SuccessOrExit(bufReader.Read8(&transferCtl).Read8(&rangeCtl).Read16(&MaxBlockSize).StatusCode()); + SuccessOrExit(bufReader.Read8(&transferCtl).Read8(rangeCtlFlags.RawStorage()).Read16(&MaxBlockSize).StatusCode()); Version = transferCtl & kVersionMask; // Only one of these values should be set. It is up to the caller to verify this. TransferCtlFlags.SetRaw(static_cast(transferCtl & ~kVersionMask)); - rangeCtlFlags.SetRaw(rangeCtl); - StartOffset = 0; - if (rangeCtlFlags.Has(kRange_StartOffset)) + if (rangeCtlFlags.Has(RangeControlFlags::kStartOffset)) { - if (rangeCtlFlags.Has(kRange_Widerange)) + if (rangeCtlFlags.Has(RangeControlFlags::kWiderange)) { SuccessOrExit(bufReader.Read64(&StartOffset).StatusCode()); } @@ -354,9 +341,9 @@ CHIP_ERROR ReceiveAccept::Parse(System::PacketBufferHandle aBuffer) } Length = 0; - if (rangeCtlFlags.Has(kRange_DefLen)) + if (rangeCtlFlags.Has(RangeControlFlags::kDefLen)) { - if (rangeCtlFlags.Has(kRange_Widerange)) + if (rangeCtlFlags.Has(RangeControlFlags::kWiderange)) { SuccessOrExit(bufReader.Read64(&Length).StatusCode()); } @@ -406,7 +393,7 @@ bool ReceiveAccept::operator==(const ReceiveAccept & another) const metadataMatches = (memcmp(Metadata, another.Metadata, MetadataLength) == 0); } - return ((Version == another.Version) && (TransferCtlFlags.Raw() == another.TransferCtlFlags.Raw()) && + return ((Version == another.Version) && (TransferCtlFlags == another.TransferCtlFlags) && (StartOffset == another.StartOffset) && (MaxBlockSize == another.MaxBlockSize) && (Length == another.Length) && metadataMatches); } diff --git a/src/protocols/bdx/BdxMessages.h b/src/protocols/bdx/BdxMessages.h index 6dabe6b978e6b3..ccef89f494c372 100644 --- a/src/protocols/bdx/BdxMessages.h +++ b/src/protocols/bdx/BdxMessages.h @@ -45,39 +45,39 @@ enum class MessageType : uint8_t BlockAckEOF = 0x14, }; -enum StatusCode : uint16_t +enum class StatusCode : uint16_t { - kStatus_None = 0x0000, - kStatus_Overflow = 0x0011, - kStatus_LengthTooLarge = 0x0012, - kStatus_LengthTooShort = 0x0013, - kStatus_LengthMismatch = 0x0014, - kStatus_LengthRequired = 0x0015, - kStatus_BadMessageContents = 0x0016, - kStatus_BadBlockCounter = 0x0017, - kStatus_TransferFailedUnknownError = 0x001F, - kStatus_ServerBadState = 0x0020, - kStatus_FailureToSend = 0x0021, - kStatus_TransferMethodNotSupported = 0x0050, - kStatus_FileDesignatorUnknown = 0x0051, - kStatus_StartOffsetNotSupported = 0x0052, - kStatus_VersionNotSupported = 0x0053, - kStatus_Unknown = 0x005F, + kNone = 0x0000, + kOverflow = 0x0011, + kLengthTooLarge = 0x0012, + kLengthTooShort = 0x0013, + kLengthMismatch = 0x0014, + kLengthRequired = 0x0015, + kBadMessageContents = 0x0016, + kBadBlockCounter = 0x0017, + kTransferFailedUnknownError = 0x001F, + kServerBadState = 0x0020, + kFailureToSend = 0x0021, + kTransferMethodNotSupported = 0x0050, + kFileDesignatorUnknown = 0x0051, + kStartOffsetNotSupported = 0x0052, + kVersionNotSupported = 0x0053, + kUnknown = 0x005F, }; -enum TransferControlFlags : uint8_t +enum class TransferControlFlags : uint8_t { // first 4 bits reserved for version - kControl_SenderDrive = (1U << 4), - kControl_ReceiverDrive = (1U << 5), - kControl_Async = (1U << 6), + kSenderDrive = (1U << 4), + kReceiverDrive = (1U << 5), + kAsync = (1U << 6), }; -enum RangeControlFlags : uint8_t +enum class RangeControlFlags : uint8_t { - kRange_DefLen = (1U), - kRange_StartOffset = (1U << 1), - kRange_Widerange = (1U << 4), + kDefLen = (1U), + kStartOffset = (1U << 1), + kWiderange = (1U << 4), }; /** @@ -136,7 +136,7 @@ struct TransferInit : public BdxMessage bool operator==(const TransferInit &) const; // Proposed Transfer Control (required) - BitFlags TransferCtlOptions; + BitFlags TransferCtlOptions; uint8_t Version = 0; ///< The highest version supported by the sender // All required @@ -175,7 +175,7 @@ struct SendAccept : public BdxMessage bool operator==(const SendAccept &) const; // Transfer Control (required, only one should be set) - BitFlags TransferCtlFlags; + BitFlags TransferCtlFlags; uint8_t Version = 0; ///< The agreed upon version for the transfer (required) uint16_t MaxBlockSize = 0; ///< Chosen max block size to use in transfer (required) @@ -206,7 +206,7 @@ struct ReceiveAccept : public BdxMessage bool operator==(const ReceiveAccept &) const; // Transfer Control (required, only one should be set) - BitFlags TransferCtlFlags; + BitFlags TransferCtlFlags; // All required uint8_t Version = 0; ///< The agreed upon version for the transfer diff --git a/src/protocols/bdx/BdxTransferSession.cpp b/src/protocols/bdx/BdxTransferSession.cpp index cea58bfbea2284..57245c5f280b8c 100644 --- a/src/protocols/bdx/BdxTransferSession.cpp +++ b/src/protocols/bdx/BdxTransferSession.cpp @@ -67,12 +67,12 @@ namespace bdx { TransferSession::TransferSession() { - mSuppportedXferOpts.SetRaw(0); + mSuppportedXferOpts.ClearAll(); } void TransferSession::PollOutput(OutputEvent & event, uint64_t curTimeMs) { - event = OutputEvent(kNone); + event = OutputEvent(OutputEventType::kNone); if (mShouldInitTimeoutStart) { @@ -82,60 +82,60 @@ void TransferSession::PollOutput(OutputEvent & event, uint64_t curTimeMs) if (mAwaitingResponse && ((curTimeMs - mTimeoutStartTimeMs) >= mTimeoutMs)) { - event = OutputEvent(kTransferTimeout); - mState = kErrorState; + event = OutputEvent(OutputEventType::kTransferTimeout); + mState = TransferState::kErrorState; mAwaitingResponse = false; return; } switch (mPendingOutput) { - case kNone: - event = OutputEvent(kNone); + case OutputEventType::kNone: + event = OutputEvent(OutputEventType::kNone); break; - case kInternalError: - event = OutputEvent::StatusReportEvent(kInternalError, mStatusReportData); + case OutputEventType::kInternalError: + event = OutputEvent::StatusReportEvent(OutputEventType::kInternalError, mStatusReportData); break; - case kStatusReceived: - event = OutputEvent::StatusReportEvent(kStatusReceived, mStatusReportData); + case OutputEventType::kStatusReceived: + event = OutputEvent::StatusReportEvent(OutputEventType::kStatusReceived, mStatusReportData); break; - case kMsgToSend: - event = OutputEvent(kMsgToSend); + case OutputEventType::kMsgToSend: + event = OutputEvent(OutputEventType::kMsgToSend); event.MsgData = std::move(mPendingMsgHandle); mTimeoutStartTimeMs = curTimeMs; break; - case kInitReceived: + case OutputEventType::kInitReceived: event = OutputEvent::TransferInitEvent(mTransferRequestData, std::move(mPendingMsgHandle)); break; - case kAcceptReceived: + case OutputEventType::kAcceptReceived: event = OutputEvent::TransferAcceptEvent(mTransferAcceptData, std::move(mPendingMsgHandle)); break; - case kQueryReceived: - event = OutputEvent(kQueryReceived); + case OutputEventType::kQueryReceived: + event = OutputEvent(OutputEventType::kQueryReceived); break; - case kBlockReceived: + case OutputEventType::kBlockReceived: event = OutputEvent::BlockDataEvent(mBlockEventData, std::move(mPendingMsgHandle)); break; - case kAckReceived: - event = OutputEvent(kAckReceived); + case OutputEventType::kAckReceived: + event = OutputEvent(OutputEventType::kAckReceived); break; - case kAckEOFReceived: - event = OutputEvent(kAckEOFReceived); + case OutputEventType::kAckEOFReceived: + event = OutputEvent(OutputEventType::kAckEOFReceived); break; default: - event = OutputEvent(kNone); + event = OutputEvent(OutputEventType::kNone); break; } // If there's no other pending output but an error occured or was received, then continue to output the error. // This ensures that when the TransferSession encounters an error and needs to send a StatusReport, both a kMsgToSend and a // kInternalError output event will be emitted. - if (event.EventType == kNone && mState == kErrorState) + if (event.EventType == OutputEventType::kNone && mState == TransferState::kErrorState) { - event = OutputEvent::StatusReportEvent(kInternalError, mStatusReportData); + event = OutputEvent::StatusReportEvent(OutputEventType::kInternalError, mStatusReportData); } - mPendingOutput = kNone; + mPendingOutput = OutputEventType::kNone; } CHIP_ERROR TransferSession::StartTransfer(TransferRole role, const TransferInitData & initData, uint32_t timeoutMs) @@ -144,50 +144,50 @@ CHIP_ERROR TransferSession::StartTransfer(TransferRole role, const TransferInitD MessageType msgType; TransferInit initMsg; - VerifyOrExit(mState == kUnitialized, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrExit(mState == TransferState::kUnitialized, err = CHIP_ERROR_INCORRECT_STATE); mRole = role; mTimeoutMs = timeoutMs; // Set transfer parameters. They may be overridden later by an Accept message - mSuppportedXferOpts.SetRaw(initData.TransferCtlFlagsRaw); + mSuppportedXferOpts = initData.TransferCtlFlags; mMaxSupportedBlockSize = initData.MaxBlockSize; mStartOffset = initData.StartOffset; mTransferLength = initData.Length; // Prepare TransferInit message - initMsg.TransferCtlOptions.SetRaw(initData.TransferCtlFlagsRaw); - initMsg.Version = kBdxVersion; - initMsg.MaxBlockSize = mMaxSupportedBlockSize; - initMsg.StartOffset = mStartOffset; - initMsg.MaxLength = mTransferLength; - initMsg.FileDesignator = initData.FileDesignator; - initMsg.FileDesLength = initData.FileDesLength; - initMsg.Metadata = initData.Metadata; - initMsg.MetadataLength = initData.MetadataLength; + initMsg.TransferCtlOptions = initData.TransferCtlFlags; + initMsg.Version = kBdxVersion; + initMsg.MaxBlockSize = mMaxSupportedBlockSize; + initMsg.StartOffset = mStartOffset; + initMsg.MaxLength = mTransferLength; + initMsg.FileDesignator = initData.FileDesignator; + initMsg.FileDesLength = initData.FileDesLength; + initMsg.Metadata = initData.Metadata; + initMsg.MetadataLength = initData.MetadataLength; err = WriteToPacketBuffer(initMsg, mPendingMsgHandle); SuccessOrExit(err); - msgType = (mRole == kRole_Sender) ? MessageType::SendInit : MessageType::ReceiveInit; + msgType = (mRole == TransferRole::kSender) ? MessageType::SendInit : MessageType::ReceiveInit; err = AttachHeader(msgType, mPendingMsgHandle); SuccessOrExit(err); - mState = kAwaitingAccept; + mState = TransferState::kAwaitingAccept; mAwaitingResponse = true; - mPendingOutput = kMsgToSend; + mPendingOutput = OutputEventType::kMsgToSend; exit: return err; } -CHIP_ERROR TransferSession::WaitForTransfer(TransferRole role, BitFlags xferControlOpts, +CHIP_ERROR TransferSession::WaitForTransfer(TransferRole role, BitFlags xferControlOpts, uint16_t maxBlockSize, uint32_t timeoutMs) { CHIP_ERROR err = CHIP_NO_ERROR; - VerifyOrExit(mState == kUnitialized, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrExit(mState == TransferState::kUnitialized, err = CHIP_ERROR_INCORRECT_STATE); // Used to determine compatibility with any future TransferInit parameters mRole = role; @@ -195,7 +195,7 @@ CHIP_ERROR TransferSession::WaitForTransfer(TransferRole role, BitFlags proposedControlOpts; + const BitFlags proposedControlOpts(mTransferRequestData.TransferCtlFlags); - VerifyOrExit(mState == kNegotiateTransferParams, err = CHIP_ERROR_INCORRECT_STATE); - VerifyOrExit(mPendingOutput == kNone, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrExit(mState == TransferState::kNegotiateTransferParams, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrExit(mPendingOutput == OutputEventType::kNone, err = CHIP_ERROR_INCORRECT_STATE); // Don't allow a Control method that wasn't supported by the initiator // MaxBlockSize can't be larger than the proposed value - proposedControlOpts.SetRaw(mTransferRequestData.TransferCtlFlagsRaw); VerifyOrExit(proposedControlOpts.Has(acceptData.ControlMode), err = CHIP_ERROR_INVALID_ARGUMENT); VerifyOrExit(acceptData.MaxBlockSize <= mTransferRequestData.MaxBlockSize, err = CHIP_ERROR_INVALID_ARGUMENT); mTransferMaxBlockSize = acceptData.MaxBlockSize; - if (mRole == kRole_Sender) + if (mRole == TransferRole::kSender) { mStartOffset = acceptData.StartOffset; mTransferLength = acceptData.Length; @@ -254,12 +253,12 @@ CHIP_ERROR TransferSession::AcceptTransfer(const TransferAcceptData & acceptData SuccessOrExit(err); } - mPendingOutput = kMsgToSend; + mPendingOutput = OutputEventType::kMsgToSend; - mState = kTransferInProgress; + mState = TransferState::kTransferInProgress; - if ((mRole == kRole_Receiver && mControlMode == kControl_SenderDrive) || - (mRole == kRole_Sender && mControlMode == kControl_ReceiverDrive)) + if ((mRole == TransferRole::kReceiver && mControlMode == TransferControlFlags::kSenderDrive) || + (mRole == TransferRole::kSender && mControlMode == TransferControlFlags::kReceiverDrive)) { mAwaitingResponse = true; } @@ -273,9 +272,9 @@ CHIP_ERROR TransferSession::PrepareBlockQuery() CHIP_ERROR err = CHIP_NO_ERROR; BlockQuery queryMsg; - VerifyOrExit(mState == kTransferInProgress, err = CHIP_ERROR_INCORRECT_STATE); - VerifyOrExit(mRole == kRole_Receiver, err = CHIP_ERROR_INCORRECT_STATE); - VerifyOrExit(mPendingOutput == kNone, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrExit(mState == TransferState::kTransferInProgress, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrExit(mRole == TransferRole::kReceiver, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrExit(mPendingOutput == OutputEventType::kNone, err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(!mAwaitingResponse, err = CHIP_ERROR_INCORRECT_STATE); queryMsg.BlockCounter = mNextQueryNum; @@ -286,7 +285,7 @@ CHIP_ERROR TransferSession::PrepareBlockQuery() err = AttachHeader(MessageType::BlockQuery, mPendingMsgHandle); SuccessOrExit(err); - mPendingOutput = kMsgToSend; + mPendingOutput = OutputEventType::kMsgToSend; mAwaitingResponse = true; mLastQueryNum = mNextQueryNum++; @@ -301,9 +300,9 @@ CHIP_ERROR TransferSession::PrepareBlock(const BlockData & inData) DataBlock blockMsg; MessageType msgType; - VerifyOrExit(mState == kTransferInProgress, err = CHIP_ERROR_INCORRECT_STATE); - VerifyOrExit(mRole == kRole_Sender, err = CHIP_ERROR_INCORRECT_STATE); - VerifyOrExit(mPendingOutput == kNone, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrExit(mState == TransferState::kTransferInProgress, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrExit(mRole == TransferRole::kSender, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrExit(mPendingOutput == OutputEventType::kNone, err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(!mAwaitingResponse, err = CHIP_ERROR_INCORRECT_STATE); // Verify non-zero data is provided and is no longer than MaxBlockSize (BlockEOF may contain 0 length data) @@ -320,11 +319,11 @@ CHIP_ERROR TransferSession::PrepareBlock(const BlockData & inData) err = AttachHeader(msgType, mPendingMsgHandle); SuccessOrExit(err); - mPendingOutput = kMsgToSend; + mPendingOutput = OutputEventType::kMsgToSend; if (msgType == MessageType::BlockEOF) { - mState = kAwaitingEOFAck; + mState = TransferState::kAwaitingEOFAck; } mAwaitingResponse = true; @@ -340,12 +339,13 @@ CHIP_ERROR TransferSession::PrepareBlockAck() CounterMessage ackMsg; MessageType msgType; - VerifyOrExit(mRole == kRole_Receiver, err = CHIP_ERROR_INCORRECT_STATE); - VerifyOrExit((mState == kTransferInProgress) || (mState == kReceivedEOF), err = CHIP_ERROR_INCORRECT_STATE); - VerifyOrExit(mPendingOutput == kNone, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrExit(mRole == TransferRole::kReceiver, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrExit((mState == TransferState::kTransferInProgress) || (mState == TransferState::kReceivedEOF), + err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrExit(mPendingOutput == OutputEventType::kNone, err = CHIP_ERROR_INCORRECT_STATE); ackMsg.BlockCounter = mLastBlockNum; - msgType = (mState == kReceivedEOF) ? MessageType::BlockAckEOF : MessageType::BlockAck; + msgType = (mState == TransferState::kReceivedEOF) ? MessageType::BlockAckEOF : MessageType::BlockAck; err = WriteToPacketBuffer(ackMsg, mPendingMsgHandle); SuccessOrExit(err); @@ -353,9 +353,9 @@ CHIP_ERROR TransferSession::PrepareBlockAck() err = AttachHeader(msgType, mPendingMsgHandle); SuccessOrExit(err); - if (mState == kTransferInProgress) + if (mState == TransferState::kTransferInProgress) { - if (mControlMode == kControl_SenderDrive) + if (mControlMode == TransferControlFlags::kSenderDrive) { // In Sender Drive, a BlockAck is implied to also be a query for the next Block, so expect to receive a Block // message. @@ -363,13 +363,13 @@ CHIP_ERROR TransferSession::PrepareBlockAck() mAwaitingResponse = true; } } - else if (mState == kReceivedEOF) + else if (mState == TransferState::kReceivedEOF) { - mState = kTransferDone; + mState = TransferState::kTransferDone; mAwaitingResponse = false; } - mPendingOutput = kMsgToSend; + mPendingOutput = OutputEventType::kMsgToSend; exit: return err; @@ -379,7 +379,8 @@ CHIP_ERROR TransferSession::AbortTransfer(StatusCode reason) { CHIP_ERROR err = CHIP_NO_ERROR; - VerifyOrExit((mState != kUnitialized) && (mState != kTransferDone) && (mState != kErrorState), + VerifyOrExit((mState != TransferState::kUnitialized) && (mState != TransferState::kTransferDone) && + (mState != TransferState::kErrorState), err = CHIP_ERROR_INCORRECT_STATE); PrepareStatusReport(reason); @@ -390,9 +391,9 @@ CHIP_ERROR TransferSession::AbortTransfer(StatusCode reason) void TransferSession::Reset() { - mPendingOutput = kNone; - mState = kUnitialized; - mSuppportedXferOpts.SetRaw(0); + mPendingOutput = OutputEventType::kNone; + mState = TransferState::kUnitialized; + mSuppportedXferOpts.ClearAll(); mTransferVersion = 0; mMaxSupportedBlockSize = 0; mStartOffset = 0; @@ -452,7 +453,7 @@ CHIP_ERROR TransferSession::HandleBdxMessage(PayloadHeader & header, System::Pac MessageType msgType = static_cast(header.GetMessageType()); VerifyOrExit(!msg.IsNull(), err = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(mPendingOutput == kNone, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrExit(mPendingOutput == OutputEventType::kNone, err = CHIP_ERROR_INCORRECT_STATE); switch (msgType) { @@ -501,7 +502,7 @@ CHIP_ERROR TransferSession::HandleStatusReportMessage(PayloadHeader & header, Sy { VerifyOrReturnError(!msg.IsNull(), CHIP_ERROR_INVALID_ARGUMENT); - mState = kErrorState; + mState = TransferState::kErrorState; mAwaitingResponse = false; uint16_t generalCode = 0; @@ -511,9 +512,9 @@ CHIP_ERROR TransferSession::HandleStatusReportMessage(PayloadHeader & header, Sy ReturnErrorOnFailure(reader.Read16(&generalCode).Read32(&protocolId).Read16(&protocolCode).StatusCode()); VerifyOrReturnError((protocolId == Protocols::kProtocol_BDX), CHIP_ERROR_INVALID_MESSAGE_TYPE); - mStatusReportData.StatusCode = protocolCode; + mStatusReportData.statusCode = static_cast(protocolCode); - mPendingOutput = kStatusReceived; + mPendingOutput = OutputEventType::kStatusReceived; return CHIP_NO_ERROR; } @@ -523,19 +524,19 @@ void TransferSession::HandleTransferInit(MessageType msgType, System::PacketBuff CHIP_ERROR err = CHIP_NO_ERROR; TransferInit transferInit; - VerifyOrExit(mState == kAwaitingInitMsg, PrepareStatusReport(kStatus_ServerBadState)); + VerifyOrExit(mState == TransferState::kAwaitingInitMsg, PrepareStatusReport(StatusCode::kServerBadState)); - if (mRole == kRole_Sender) + if (mRole == TransferRole::kSender) { - VerifyOrExit(msgType == MessageType::ReceiveInit, PrepareStatusReport(kStatus_ServerBadState)); + VerifyOrExit(msgType == MessageType::ReceiveInit, PrepareStatusReport(StatusCode::kServerBadState)); } else { - VerifyOrExit(msgType == MessageType::SendInit, PrepareStatusReport(kStatus_ServerBadState)); + VerifyOrExit(msgType == MessageType::SendInit, PrepareStatusReport(StatusCode::kServerBadState)); } err = transferInit.Parse(msgData.Retain()); - VerifyOrExit(err == CHIP_NO_ERROR, PrepareStatusReport(kStatus_BadMessageContents)); + VerifyOrExit(err == CHIP_NO_ERROR, PrepareStatusReport(StatusCode::kBadMessageContents)); ResolveTransferControlOptions(transferInit.TransferCtlOptions); mTransferVersion = ::chip::min(kBdxVersion, transferInit.Version); @@ -546,19 +547,19 @@ void TransferSession::HandleTransferInit(MessageType msgType, System::PacketBuff mTransferLength = transferInit.MaxLength; // Store the Request data to share with the caller for verification - mTransferRequestData.TransferCtlFlagsRaw = transferInit.TransferCtlOptions.Raw(), - mTransferRequestData.MaxBlockSize = transferInit.MaxBlockSize; - mTransferRequestData.StartOffset = transferInit.StartOffset; - mTransferRequestData.Length = transferInit.MaxLength; - mTransferRequestData.FileDesignator = transferInit.FileDesignator; - mTransferRequestData.FileDesLength = transferInit.FileDesLength; - mTransferRequestData.Metadata = transferInit.Metadata; - mTransferRequestData.MetadataLength = transferInit.MetadataLength; + mTransferRequestData.TransferCtlFlags = transferInit.TransferCtlOptions; + mTransferRequestData.MaxBlockSize = transferInit.MaxBlockSize; + mTransferRequestData.StartOffset = transferInit.StartOffset; + mTransferRequestData.Length = transferInit.MaxLength; + mTransferRequestData.FileDesignator = transferInit.FileDesignator; + mTransferRequestData.FileDesLength = transferInit.FileDesLength; + mTransferRequestData.Metadata = transferInit.Metadata; + mTransferRequestData.MetadataLength = transferInit.MetadataLength; mPendingMsgHandle = std::move(msgData); - mPendingOutput = kInitReceived; + mPendingOutput = OutputEventType::kInitReceived; - mState = kNegotiateTransferParams; + mState = TransferState::kNegotiateTransferParams; exit: return; @@ -569,11 +570,11 @@ void TransferSession::HandleReceiveAccept(System::PacketBufferHandle msgData) CHIP_ERROR err = CHIP_NO_ERROR; ReceiveAccept rcvAcceptMsg; - VerifyOrExit(mRole == kRole_Receiver, PrepareStatusReport(kStatus_ServerBadState)); - VerifyOrExit(mState == kAwaitingAccept, PrepareStatusReport(kStatus_ServerBadState)); + VerifyOrExit(mRole == TransferRole::kReceiver, PrepareStatusReport(StatusCode::kServerBadState)); + VerifyOrExit(mState == TransferState::kAwaitingAccept, PrepareStatusReport(StatusCode::kServerBadState)); err = rcvAcceptMsg.Parse(msgData.Retain()); - VerifyOrExit(err == CHIP_NO_ERROR, PrepareStatusReport(kStatus_BadMessageContents)); + VerifyOrExit(err == CHIP_NO_ERROR, PrepareStatusReport(StatusCode::kBadMessageContents)); // Verify that Accept parameters are compatible with the original proposed parameters err = VerifyProposedMode(rcvAcceptMsg.TransferCtlFlags); @@ -593,10 +594,10 @@ void TransferSession::HandleReceiveAccept(System::PacketBufferHandle msgData) mTransferAcceptData.MetadataLength = rcvAcceptMsg.MetadataLength; mPendingMsgHandle = std::move(msgData); - mPendingOutput = kAcceptReceived; + mPendingOutput = OutputEventType::kAcceptReceived; - mAwaitingResponse = (mControlMode == kControl_SenderDrive); - mState = kTransferInProgress; + mAwaitingResponse = (mControlMode == TransferControlFlags::kSenderDrive); + mState = TransferState::kTransferInProgress; exit: return; @@ -607,11 +608,11 @@ void TransferSession::HandleSendAccept(System::PacketBufferHandle msgData) CHIP_ERROR err = CHIP_NO_ERROR; SendAccept sendAcceptMsg; - VerifyOrExit(mRole == kRole_Sender, PrepareStatusReport(kStatus_ServerBadState)); - VerifyOrExit(mState == kAwaitingAccept, PrepareStatusReport(kStatus_ServerBadState)); + VerifyOrExit(mRole == TransferRole::kSender, PrepareStatusReport(StatusCode::kServerBadState)); + VerifyOrExit(mState == TransferState::kAwaitingAccept, PrepareStatusReport(StatusCode::kServerBadState)); err = sendAcceptMsg.Parse(msgData.Retain()); - VerifyOrExit(err == CHIP_NO_ERROR, PrepareStatusReport(kStatus_BadMessageContents)); + VerifyOrExit(err == CHIP_NO_ERROR, PrepareStatusReport(StatusCode::kBadMessageContents)); // Verify that Accept parameters are compatible with the original proposed parameters err = VerifyProposedMode(sendAcceptMsg.TransferCtlFlags); @@ -629,10 +630,10 @@ void TransferSession::HandleSendAccept(System::PacketBufferHandle msgData) mTransferAcceptData.MetadataLength = sendAcceptMsg.MetadataLength; mPendingMsgHandle = std::move(msgData); - mPendingOutput = kAcceptReceived; + mPendingOutput = OutputEventType::kAcceptReceived; - mAwaitingResponse = (mControlMode == kControl_ReceiverDrive); - mState = kTransferInProgress; + mAwaitingResponse = (mControlMode == TransferControlFlags::kReceiverDrive); + mState = TransferState::kTransferInProgress; exit: return; @@ -643,16 +644,16 @@ void TransferSession::HandleBlockQuery(System::PacketBufferHandle msgData) CHIP_ERROR err = CHIP_NO_ERROR; BlockQuery query; - VerifyOrExit(mRole == kRole_Sender, PrepareStatusReport(kStatus_ServerBadState)); - VerifyOrExit(mState == kTransferInProgress, PrepareStatusReport(kStatus_ServerBadState)); - VerifyOrExit(mAwaitingResponse, PrepareStatusReport(kStatus_ServerBadState)); + VerifyOrExit(mRole == TransferRole::kSender, PrepareStatusReport(StatusCode::kServerBadState)); + VerifyOrExit(mState == TransferState::kTransferInProgress, PrepareStatusReport(StatusCode::kServerBadState)); + VerifyOrExit(mAwaitingResponse, PrepareStatusReport(StatusCode::kServerBadState)); err = query.Parse(std::move(msgData)); - VerifyOrExit(err == CHIP_NO_ERROR, PrepareStatusReport(kStatus_BadMessageContents)); + VerifyOrExit(err == CHIP_NO_ERROR, PrepareStatusReport(StatusCode::kBadMessageContents)); - VerifyOrExit(query.BlockCounter == mNextBlockNum, PrepareStatusReport(kStatus_BadBlockCounter)); + VerifyOrExit(query.BlockCounter == mNextBlockNum, PrepareStatusReport(StatusCode::kBadBlockCounter)); - mPendingOutput = kQueryReceived; + mPendingOutput = OutputEventType::kQueryReceived; mAwaitingResponse = false; mLastQueryNum = query.BlockCounter; @@ -666,20 +667,20 @@ void TransferSession::HandleBlock(System::PacketBufferHandle msgData) CHIP_ERROR err = CHIP_NO_ERROR; Block blockMsg; - VerifyOrExit(mRole == kRole_Receiver, PrepareStatusReport(kStatus_ServerBadState)); - VerifyOrExit(mState == kTransferInProgress, PrepareStatusReport(kStatus_ServerBadState)); - VerifyOrExit(mAwaitingResponse, PrepareStatusReport(kStatus_ServerBadState)); + VerifyOrExit(mRole == TransferRole::kReceiver, PrepareStatusReport(StatusCode::kServerBadState)); + VerifyOrExit(mState == TransferState::kTransferInProgress, PrepareStatusReport(StatusCode::kServerBadState)); + VerifyOrExit(mAwaitingResponse, PrepareStatusReport(StatusCode::kServerBadState)); err = blockMsg.Parse(msgData.Retain()); - VerifyOrExit(err == CHIP_NO_ERROR, PrepareStatusReport(kStatus_BadMessageContents)); + VerifyOrExit(err == CHIP_NO_ERROR, PrepareStatusReport(StatusCode::kBadMessageContents)); - VerifyOrExit(blockMsg.BlockCounter == mLastQueryNum, PrepareStatusReport(kStatus_BadBlockCounter)); + VerifyOrExit(blockMsg.BlockCounter == mLastQueryNum, PrepareStatusReport(StatusCode::kBadBlockCounter)); VerifyOrExit((blockMsg.DataLength > 0) && (blockMsg.DataLength <= mTransferMaxBlockSize), - PrepareStatusReport(kStatus_BadMessageContents)); + PrepareStatusReport(StatusCode::kBadMessageContents)); if (IsTransferLengthDefinite()) { - VerifyOrExit(mNumBytesProcessed + blockMsg.DataLength <= mTransferLength, PrepareStatusReport(kStatus_LengthMismatch)); + VerifyOrExit(mNumBytesProcessed + blockMsg.DataLength <= mTransferLength, PrepareStatusReport(StatusCode::kLengthMismatch)); } mBlockEventData.Data = blockMsg.Data; @@ -687,7 +688,7 @@ void TransferSession::HandleBlock(System::PacketBufferHandle msgData) mBlockEventData.IsEof = false; mPendingMsgHandle = std::move(msgData); - mPendingOutput = kBlockReceived; + mPendingOutput = OutputEventType::kBlockReceived; mNumBytesProcessed += blockMsg.DataLength; mLastBlockNum = blockMsg.BlockCounter; @@ -703,28 +704,28 @@ void TransferSession::HandleBlockEOF(System::PacketBufferHandle msgData) CHIP_ERROR err = CHIP_NO_ERROR; BlockEOF blockEOFMsg; - VerifyOrExit(mRole == kRole_Receiver, PrepareStatusReport(kStatus_ServerBadState)); - VerifyOrExit(mState == kTransferInProgress, PrepareStatusReport(kStatus_ServerBadState)); - VerifyOrExit(mAwaitingResponse, PrepareStatusReport(kStatus_ServerBadState)); + VerifyOrExit(mRole == TransferRole::kReceiver, PrepareStatusReport(StatusCode::kServerBadState)); + VerifyOrExit(mState == TransferState::kTransferInProgress, PrepareStatusReport(StatusCode::kServerBadState)); + VerifyOrExit(mAwaitingResponse, PrepareStatusReport(StatusCode::kServerBadState)); err = blockEOFMsg.Parse(msgData.Retain()); - VerifyOrExit(err == CHIP_NO_ERROR, PrepareStatusReport(kStatus_BadMessageContents)); + VerifyOrExit(err == CHIP_NO_ERROR, PrepareStatusReport(StatusCode::kBadMessageContents)); - VerifyOrExit(blockEOFMsg.BlockCounter == mLastQueryNum, PrepareStatusReport(kStatus_BadBlockCounter)); - VerifyOrExit(blockEOFMsg.DataLength <= mTransferMaxBlockSize, PrepareStatusReport(kStatus_BadMessageContents)); + VerifyOrExit(blockEOFMsg.BlockCounter == mLastQueryNum, PrepareStatusReport(StatusCode::kBadBlockCounter)); + VerifyOrExit(blockEOFMsg.DataLength <= mTransferMaxBlockSize, PrepareStatusReport(StatusCode::kBadMessageContents)); mBlockEventData.Data = blockEOFMsg.Data; mBlockEventData.Length = blockEOFMsg.DataLength; mBlockEventData.IsEof = true; mPendingMsgHandle = std::move(msgData); - mPendingOutput = kBlockReceived; + mPendingOutput = OutputEventType::kBlockReceived; mNumBytesProcessed += blockEOFMsg.DataLength; mLastBlockNum = blockEOFMsg.BlockCounter; mAwaitingResponse = false; - mState = kReceivedEOF; + mState = TransferState::kReceivedEOF; exit: return; @@ -735,19 +736,19 @@ void TransferSession::HandleBlockAck(System::PacketBufferHandle msgData) CHIP_ERROR err = CHIP_NO_ERROR; BlockAck ackMsg; - VerifyOrExit(mRole == kRole_Sender, PrepareStatusReport(kStatus_ServerBadState)); - VerifyOrExit(mState == kTransferInProgress, PrepareStatusReport(kStatus_ServerBadState)); - VerifyOrExit(mAwaitingResponse, PrepareStatusReport(kStatus_ServerBadState)); + VerifyOrExit(mRole == TransferRole::kSender, PrepareStatusReport(StatusCode::kServerBadState)); + VerifyOrExit(mState == TransferState::kTransferInProgress, PrepareStatusReport(StatusCode::kServerBadState)); + VerifyOrExit(mAwaitingResponse, PrepareStatusReport(StatusCode::kServerBadState)); err = ackMsg.Parse(std::move(msgData)); - VerifyOrExit(err == CHIP_NO_ERROR, PrepareStatusReport(kStatus_BadMessageContents)); - VerifyOrExit(ackMsg.BlockCounter == mLastBlockNum, PrepareStatusReport(kStatus_BadBlockCounter)); + VerifyOrExit(err == CHIP_NO_ERROR, PrepareStatusReport(StatusCode::kBadMessageContents)); + VerifyOrExit(ackMsg.BlockCounter == mLastBlockNum, PrepareStatusReport(StatusCode::kBadBlockCounter)); - mPendingOutput = kAckReceived; + mPendingOutput = OutputEventType::kAckReceived; // In Receiver Drive, the Receiver can send a BlockAck to indicate receipt of the message and reset the timeout. // In this case, the Sender should wait to receive a BlockQuery next. - mAwaitingResponse = (mControlMode == kControl_ReceiverDrive); + mAwaitingResponse = (mControlMode == TransferControlFlags::kReceiverDrive); exit: return; @@ -758,75 +759,75 @@ void TransferSession::HandleBlockAckEOF(System::PacketBufferHandle msgData) CHIP_ERROR err = CHIP_NO_ERROR; BlockAckEOF ackMsg; - VerifyOrExit(mRole == kRole_Sender, PrepareStatusReport(kStatus_ServerBadState)); - VerifyOrExit(mState == kAwaitingEOFAck, PrepareStatusReport(kStatus_ServerBadState)); - VerifyOrExit(mAwaitingResponse, PrepareStatusReport(kStatus_ServerBadState)); + VerifyOrExit(mRole == TransferRole::kSender, PrepareStatusReport(StatusCode::kServerBadState)); + VerifyOrExit(mState == TransferState::kAwaitingEOFAck, PrepareStatusReport(StatusCode::kServerBadState)); + VerifyOrExit(mAwaitingResponse, PrepareStatusReport(StatusCode::kServerBadState)); err = ackMsg.Parse(std::move(msgData)); - VerifyOrExit(err == CHIP_NO_ERROR, PrepareStatusReport(kStatus_BadMessageContents)); - VerifyOrExit(ackMsg.BlockCounter == mLastBlockNum, PrepareStatusReport(kStatus_BadBlockCounter)); + VerifyOrExit(err == CHIP_NO_ERROR, PrepareStatusReport(StatusCode::kBadMessageContents)); + VerifyOrExit(ackMsg.BlockCounter == mLastBlockNum, PrepareStatusReport(StatusCode::kBadBlockCounter)); - mPendingOutput = kAckEOFReceived; + mPendingOutput = OutputEventType::kAckEOFReceived; mAwaitingResponse = false; - mState = kTransferDone; + mState = TransferState::kTransferDone; exit: return; } -void TransferSession::ResolveTransferControlOptions(const BitFlags & proposed) +void TransferSession::ResolveTransferControlOptions(const BitFlags & proposed) { // Must specify at least one synchronous option - if (!proposed.Has(kControl_SenderDrive) && !proposed.Has(kControl_ReceiverDrive)) + // + if (!proposed.HasAny(TransferControlFlags::kSenderDrive, TransferControlFlags::kReceiverDrive)) { - PrepareStatusReport(kStatus_TransferMethodNotSupported); + PrepareStatusReport(StatusCode::kTransferMethodNotSupported); return; } // Ensure there are options supported by both nodes. Async gets priority. // If there is only one common option, choose that one. Otherwise the application must pick. - BitFlags commonOpts; - commonOpts.SetRaw(proposed.Raw() & mSuppportedXferOpts.Raw()); - if (commonOpts.Raw() == 0) + const BitFlags commonOpts(proposed & mSuppportedXferOpts); + if (!commonOpts.HasAny()) { - PrepareStatusReport(kStatus_TransferMethodNotSupported); + PrepareStatusReport(StatusCode::kTransferMethodNotSupported); } - else if (commonOpts.HasOnly(kControl_Async)) + else if (commonOpts.HasOnly(TransferControlFlags::kAsync)) { - mControlMode = kControl_Async; + mControlMode = TransferControlFlags::kAsync; } - else if (commonOpts.HasOnly(kControl_ReceiverDrive)) + else if (commonOpts.HasOnly(TransferControlFlags::kReceiverDrive)) { - mControlMode = kControl_ReceiverDrive; + mControlMode = TransferControlFlags::kReceiverDrive; } - else if (commonOpts.HasOnly(kControl_SenderDrive)) + else if (commonOpts.HasOnly(TransferControlFlags::kSenderDrive)) { - mControlMode = kControl_SenderDrive; + mControlMode = TransferControlFlags::kSenderDrive; } } -CHIP_ERROR TransferSession::VerifyProposedMode(const BitFlags & proposed) +CHIP_ERROR TransferSession::VerifyProposedMode(const BitFlags & proposed) { TransferControlFlags mode; // Must specify only one mode in Accept messages - if (proposed.HasOnly(kControl_Async)) + if (proposed.HasOnly(TransferControlFlags::kAsync)) { - mode = kControl_Async; + mode = TransferControlFlags::kAsync; } - else if (proposed.HasOnly(kControl_ReceiverDrive)) + else if (proposed.HasOnly(TransferControlFlags::kReceiverDrive)) { - mode = kControl_ReceiverDrive; + mode = TransferControlFlags::kReceiverDrive; } - else if (proposed.HasOnly(kControl_SenderDrive)) + else if (proposed.HasOnly(TransferControlFlags::kSenderDrive)) { - mode = kControl_SenderDrive; + mode = TransferControlFlags::kSenderDrive; } else { - PrepareStatusReport(kStatus_BadMessageContents); + PrepareStatusReport(StatusCode::kBadMessageContents); return CHIP_ERROR_INTERNAL; } @@ -837,7 +838,7 @@ CHIP_ERROR TransferSession::VerifyProposedMode(const BitFlags(Protocols::Common::StatusCode::Failure)); bbuf.Put32(Protocols::kProtocol_BDX); - bbuf.Put16(mStatusReportData.StatusCode); + bbuf.Put16(static_cast(mStatusReportData.statusCode)); mPendingMsgHandle = bbuf.Finalize(); if (mPendingMsgHandle.IsNull()) { - mPendingOutput = kInternalError; + mPendingOutput = OutputEventType::kInternalError; } else { CHIP_ERROR err = AttachHeader(Protocols::Common::MsgType::StatusReport, mPendingMsgHandle); VerifyOrReturn(err == CHIP_NO_ERROR); - mPendingOutput = kMsgToSend; + mPendingOutput = OutputEventType::kMsgToSend; } - mState = kErrorState; + mState = TransferState::kErrorState; mAwaitingResponse = false; // Prevent triggering timeout } @@ -879,7 +880,7 @@ bool TransferSession::IsTransferLengthDefinite() TransferSession::OutputEvent TransferSession::OutputEvent::TransferInitEvent(TransferInitData data, System::PacketBufferHandle msg) { - OutputEvent event(kInitReceived); + OutputEvent event(OutputEventType::kInitReceived); event.MsgData = std::move(msg); event.transferInitData = data; return event; @@ -891,7 +892,7 @@ TransferSession::OutputEvent TransferSession::OutputEvent::TransferInitEvent(Tra */ TransferSession::OutputEvent TransferSession::OutputEvent::TransferAcceptEvent(TransferAcceptData data) { - OutputEvent event(kAcceptReceived); + OutputEvent event(OutputEventType::kAcceptReceived); event.transferAcceptData = data; return event; } @@ -909,7 +910,7 @@ TransferSession::OutputEvent TransferSession::OutputEvent::TransferAcceptEvent(T TransferSession::OutputEvent TransferSession::OutputEvent::BlockDataEvent(BlockData data, System::PacketBufferHandle msg) { - OutputEvent event(kBlockReceived); + OutputEvent event(OutputEventType::kBlockReceived); event.MsgData = std::move(msg); event.blockdata = data; return event; diff --git a/src/protocols/bdx/BdxTransferSession.h b/src/protocols/bdx/BdxTransferSession.h index e3b583146511e0..871f38b75fe770 100644 --- a/src/protocols/bdx/BdxTransferSession.h +++ b/src/protocols/bdx/BdxTransferSession.h @@ -15,16 +15,16 @@ namespace chip { namespace bdx { -enum TransferRole : uint8_t +enum class TransferRole : uint8_t { - kRole_Receiver = 0, - kRole_Sender = 1, + kReceiver = 0, + kSender = 1, }; class DLL_EXPORT TransferSession { public: - enum OutputEventType : uint16_t + enum class OutputEventType : uint16_t { kNone = 0, kMsgToSend, @@ -41,7 +41,7 @@ class DLL_EXPORT TransferSession struct TransferInitData { - uint8_t TransferCtlFlagsRaw = 0; + TransferControlFlags TransferCtlFlags; uint16_t MaxBlockSize = 0; uint64_t StartOffset = 0; @@ -70,7 +70,7 @@ class DLL_EXPORT TransferSession struct StatusReportData { - uint16_t StatusCode; + StatusCode statusCode; }; struct BlockData @@ -99,8 +99,8 @@ class DLL_EXPORT TransferSession StatusReportData statusData; }; - OutputEvent() : EventType(kNone) { statusData = { kStatus_None }; } - OutputEvent(OutputEventType type) : EventType(type) { statusData = { kStatus_None }; } + OutputEvent() : EventType(OutputEventType::kNone) { statusData = { StatusCode::kNone }; } + OutputEvent(OutputEventType type) : EventType(type) { statusData = { StatusCode::kNone }; } static OutputEvent TransferInitEvent(TransferInitData data, System::PacketBufferHandle msg); static OutputEvent TransferAcceptEvent(TransferAcceptData data); @@ -160,7 +160,7 @@ class DLL_EXPORT TransferSession * @return CHIP_ERROR Result of initialization. May also indicate if the TransferSession object is unable to handle this * request. */ - CHIP_ERROR WaitForTransfer(TransferRole role, BitFlags xferControlOpts, uint16_t maxBlockSize, + CHIP_ERROR WaitForTransfer(TransferRole role, BitFlags xferControlOpts, uint16_t maxBlockSize, uint32_t timeoutMs); /** @@ -252,7 +252,7 @@ class DLL_EXPORT TransferSession TransferSession(); private: - enum TransferState : uint8_t + enum class TransferState : uint8_t { kUnitialized, kAwaitingInitMsg, @@ -282,23 +282,23 @@ class DLL_EXPORT TransferSession * Used when handling a TransferInit message. Determines if there are any compatible Transfer control modes between the two * transfer peers. */ - void ResolveTransferControlOptions(const BitFlags & proposed); + void ResolveTransferControlOptions(const BitFlags & proposed); /** * @brief * Used when handling an Accept message. Verifies that the chosen control mode is compatible with the orignal supported modes. */ - CHIP_ERROR VerifyProposedMode(const BitFlags & proposed); + CHIP_ERROR VerifyProposedMode(const BitFlags & proposed); void PrepareStatusReport(StatusCode code); bool IsTransferLengthDefinite(); - OutputEventType mPendingOutput = kNone; - TransferState mState = kUnitialized; + OutputEventType mPendingOutput = OutputEventType::kNone; + TransferState mState = TransferState::kUnitialized; TransferRole mRole; // Indicate supported options pre- transfer accept - BitFlags mSuppportedXferOpts; + BitFlags mSuppportedXferOpts; uint16_t mMaxSupportedBlockSize = 0; // Used to govern transfer once it has been accepted diff --git a/src/protocols/bdx/tests/TestBdxMessages.cpp b/src/protocols/bdx/tests/TestBdxMessages.cpp index bd618afaad2d7f..3fd9b4dbbb3183 100644 --- a/src/protocols/bdx/tests/TestBdxMessages.cpp +++ b/src/protocols/bdx/tests/TestBdxMessages.cpp @@ -43,8 +43,7 @@ void TestTransferInitMessage(nlTestSuite * inSuite, void * inContext) { TransferInit testMsg; - testMsg.TransferCtlOptions.SetRaw(0); - testMsg.TransferCtlOptions.Set(kControl_ReceiverDrive, true); + testMsg.TransferCtlOptions.ClearAll().Set(TransferControlFlags::kReceiverDrive, true); testMsg.Version = 1; // Make sure MaxLength is greater than UINT32_MAX to test widerange being set @@ -69,8 +68,7 @@ void TestSendAcceptMessage(nlTestSuite * inSuite, void * inContext) SendAccept testMsg; testMsg.Version = 1; - testMsg.TransferCtlFlags.SetRaw(0); - testMsg.TransferCtlFlags.Set(kControl_ReceiverDrive, true); + testMsg.TransferCtlFlags.ClearAll().Set(TransferControlFlags::kReceiverDrive, true); testMsg.MaxBlockSize = 256; uint8_t fakeData[5] = { 7, 6, 5, 4, 3 }; @@ -85,8 +83,7 @@ void TestReceiveAcceptMessage(nlTestSuite * inSuite, void * inContext) ReceiveAccept testMsg; testMsg.Version = 1; - testMsg.TransferCtlFlags.SetRaw(0); - testMsg.TransferCtlFlags.Set(kControl_ReceiverDrive, true); + testMsg.TransferCtlFlags.ClearAll().Set(TransferControlFlags::kReceiverDrive, true); // Make sure Length is greater than UINT32_MAX to test widerange being set testMsg.Length = static_cast(std::numeric_limits::max()) + 1; diff --git a/src/protocols/bdx/tests/TestBdxTransferSession.cpp b/src/protocols/bdx/tests/TestBdxTransferSession.cpp index ab362a5e59a2eb..8ee740b6a12b73 100644 --- a/src/protocols/bdx/tests/TestBdxTransferSession.cpp +++ b/src/protocols/bdx/tests/TestBdxTransferSession.cpp @@ -115,9 +115,9 @@ void VerifyStatusReport(nlTestSuite * inSuite, void * inContext, const System::P CHIP_ERROR err = CHIP_NO_ERROR; uint16_t headerSize = 0; PayloadHeader payloadHeader; - uint16_t generalCode = 0; - uint32_t protocolId = 0; - uint16_t protocolCode = 0; + uint16_t generalCode = 0; + uint32_t protocolId = 0; + BitFlags protocolCode; if (msg.IsNull()) { @@ -136,7 +136,7 @@ void VerifyStatusReport(nlTestSuite * inSuite, void * inContext, const System::P } Encoding::LittleEndian::Reader reader(msg->Start(), msg->DataLength()); - err = reader.Skip(headerSize).Read16(&generalCode).Read32(&protocolId).Read16(&protocolCode).StatusCode(); + err = reader.Skip(headerSize).Read16(&generalCode).Read32(&protocolId).Read16(protocolCode.RawStorage()).StatusCode(); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, generalCode == static_cast(Protocols::Common::StatusCode::Failure)); NL_TEST_ASSERT(inSuite, protocolId == Protocols::kProtocol_BDX); @@ -147,19 +147,19 @@ void VerifyNoMoreOutput(nlTestSuite * inSuite, void * inContext, TransferSession { TransferSession::OutputEvent event; transferSession.PollOutput(event, kNoAdvanceTime); - NL_TEST_ASSERT(inSuite, event.EventType == TransferSession::kNone); + NL_TEST_ASSERT(inSuite, event.EventType == TransferSession::OutputEventType::kNone); } // Helper method for initializing two TransferSession objects, generating a TransferInit message, and passing it to a responding // TransferSession. void SendAndVerifyTransferInit(nlTestSuite * inSuite, void * inContext, TransferSession::OutputEvent & outEvent, uint32_t timeoutMs, TransferSession & initiator, TransferRole initiatorRole, TransferSession::TransferInitData initData, - TransferSession & responder, BitFlags & responderControlOpts, + TransferSession & responder, BitFlags & responderControlOpts, uint16_t responderMaxBlock) { CHIP_ERROR err = CHIP_NO_ERROR; - TransferRole responderRole = (initiatorRole == kRole_Sender) ? kRole_Receiver : kRole_Sender; - MessageType expectedInitMsg = (initiatorRole == kRole_Sender) ? MessageType::SendInit : MessageType::ReceiveInit; + TransferRole responderRole = (initiatorRole == TransferRole::kSender) ? TransferRole::kReceiver : TransferRole::kSender; + MessageType expectedInitMsg = (initiatorRole == TransferRole::kSender) ? MessageType::SendInit : MessageType::ReceiveInit; // Initializer responder to wait for transfer err = responder.WaitForTransfer(responderRole, responderControlOpts, responderMaxBlock, timeoutMs); @@ -170,7 +170,7 @@ void SendAndVerifyTransferInit(nlTestSuite * inSuite, void * inContext, Transfer err = initiator.StartTransfer(initiatorRole, initData, timeoutMs); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); initiator.PollOutput(outEvent, kNoAdvanceTime); - NL_TEST_ASSERT(inSuite, outEvent.EventType == TransferSession::kMsgToSend); + NL_TEST_ASSERT(inSuite, outEvent.EventType == TransferSession::OutputEventType::kMsgToSend); VerifyBdxMessageType(inSuite, inContext, outEvent.MsgData, expectedInitMsg); VerifyNoMoreOutput(inSuite, inContext, initiator); @@ -179,14 +179,15 @@ void SendAndVerifyTransferInit(nlTestSuite * inSuite, void * inContext, Transfer NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); responder.PollOutput(outEvent, kNoAdvanceTime); VerifyNoMoreOutput(inSuite, inContext, responder); - NL_TEST_ASSERT(inSuite, outEvent.EventType == TransferSession::kInitReceived); - NL_TEST_ASSERT(inSuite, outEvent.transferInitData.TransferCtlFlagsRaw == initData.TransferCtlFlagsRaw); + NL_TEST_ASSERT(inSuite, outEvent.EventType == TransferSession::OutputEventType::kInitReceived); + NL_TEST_ASSERT(inSuite, outEvent.transferInitData.TransferCtlFlags == initData.TransferCtlFlags); NL_TEST_ASSERT(inSuite, outEvent.transferInitData.MaxBlockSize == initData.MaxBlockSize); NL_TEST_ASSERT(inSuite, outEvent.transferInitData.StartOffset == initData.StartOffset); NL_TEST_ASSERT(inSuite, outEvent.transferInitData.Length == initData.Length); NL_TEST_ASSERT(inSuite, outEvent.transferInitData.FileDesignator != nullptr); NL_TEST_ASSERT(inSuite, outEvent.transferInitData.FileDesLength == initData.FileDesLength); - if (outEvent.EventType == TransferSession::kInitReceived && outEvent.transferInitData.FileDesignator != nullptr) + if (outEvent.EventType == TransferSession::OutputEventType::kInitReceived && + outEvent.transferInitData.FileDesignator != nullptr) { NL_TEST_ASSERT( inSuite, @@ -223,7 +224,7 @@ void SendAndVerifyAcceptMsg(nlTestSuite * inSuite, void * inContext, TransferSes CHIP_ERROR err = CHIP_NO_ERROR; // If the node sending the Accept message is also the one that will send Blocks, then this should be a ReceiveAccept message. - MessageType expectedMsg = (acceptSenderRole == kRole_Sender) ? MessageType::ReceiveAccept : MessageType::SendAccept; + MessageType expectedMsg = (acceptSenderRole == TransferRole::kSender) ? MessageType::ReceiveAccept : MessageType::SendAccept; err = acceptSender.AcceptTransfer(acceptData); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); @@ -231,7 +232,7 @@ void SendAndVerifyAcceptMsg(nlTestSuite * inSuite, void * inContext, TransferSes // Verify Sender emits ReceiveAccept message for sending acceptSender.PollOutput(outEvent, kNoAdvanceTime); VerifyNoMoreOutput(inSuite, inContext, acceptSender); - NL_TEST_ASSERT(inSuite, outEvent.EventType == TransferSession::kMsgToSend); + NL_TEST_ASSERT(inSuite, outEvent.EventType == TransferSession::OutputEventType::kMsgToSend); VerifyBdxMessageType(inSuite, inContext, outEvent.MsgData, expectedMsg); // Pass Accept message to acceptReceiver @@ -243,7 +244,7 @@ void SendAndVerifyAcceptMsg(nlTestSuite * inSuite, void * inContext, TransferSes // Transfer at this point. acceptReceiver.PollOutput(outEvent, kNoAdvanceTime); VerifyNoMoreOutput(inSuite, inContext, acceptReceiver); - NL_TEST_ASSERT(inSuite, outEvent.EventType == TransferSession::kAcceptReceived); + NL_TEST_ASSERT(inSuite, outEvent.EventType == TransferSession::OutputEventType::kAcceptReceived); NL_TEST_ASSERT(inSuite, outEvent.transferAcceptData.ControlMode == acceptData.ControlMode); NL_TEST_ASSERT(inSuite, outEvent.transferAcceptData.MaxBlockSize == acceptData.MaxBlockSize); NL_TEST_ASSERT(inSuite, outEvent.transferAcceptData.StartOffset == acceptData.StartOffset); @@ -277,7 +278,7 @@ void SendAndVerifyQuery(nlTestSuite * inSuite, void * inContext, TransferSession CHIP_ERROR err = querySender.PrepareBlockQuery(); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); querySender.PollOutput(outEvent, kNoAdvanceTime); - NL_TEST_ASSERT(inSuite, outEvent.EventType == TransferSession::kMsgToSend); + NL_TEST_ASSERT(inSuite, outEvent.EventType == TransferSession::OutputEventType::kMsgToSend); VerifyBdxMessageType(inSuite, inContext, outEvent.MsgData, MessageType::BlockQuery); VerifyNoMoreOutput(inSuite, inContext, querySender); @@ -285,7 +286,7 @@ void SendAndVerifyQuery(nlTestSuite * inSuite, void * inContext, TransferSession err = queryReceiver.HandleMessageReceived(std::move(outEvent.MsgData), kNoAdvanceTime); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); queryReceiver.PollOutput(outEvent, kNoAdvanceTime); - NL_TEST_ASSERT(inSuite, outEvent.EventType == TransferSession::kQueryReceived); + NL_TEST_ASSERT(inSuite, outEvent.EventType == TransferSession::OutputEventType::kQueryReceived); VerifyNoMoreOutput(inSuite, inContext, queryReceiver); } @@ -320,7 +321,7 @@ void SendAndVerifyArbitraryBlock(nlTestSuite * inSuite, void * inContext, Transf err = sender.PrepareBlock(blockData); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); sender.PollOutput(outEvent, kNoAdvanceTime); - NL_TEST_ASSERT(inSuite, outEvent.EventType == TransferSession::kMsgToSend); + NL_TEST_ASSERT(inSuite, outEvent.EventType == TransferSession::OutputEventType::kMsgToSend); VerifyBdxMessageType(inSuite, inContext, outEvent.MsgData, expected); VerifyNoMoreOutput(inSuite, inContext, sender); @@ -328,9 +329,9 @@ void SendAndVerifyArbitraryBlock(nlTestSuite * inSuite, void * inContext, Transf err = receiver.HandleMessageReceived(std::move(outEvent.MsgData), kNoAdvanceTime); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); receiver.PollOutput(outEvent, kNoAdvanceTime); - NL_TEST_ASSERT(inSuite, outEvent.EventType == TransferSession::kBlockReceived); + NL_TEST_ASSERT(inSuite, outEvent.EventType == TransferSession::OutputEventType::kBlockReceived); NL_TEST_ASSERT(inSuite, outEvent.blockdata.Data != nullptr); - if (outEvent.EventType == TransferSession::kBlockReceived && outEvent.blockdata.Data != nullptr) + if (outEvent.EventType == TransferSession::OutputEventType::kBlockReceived && outEvent.blockdata.Data != nullptr) { NL_TEST_ASSERT(inSuite, !memcmp(fakeBlockData, outEvent.blockdata.Data, outEvent.blockdata.Length)); } @@ -342,14 +343,14 @@ void SendAndVerifyBlockAck(nlTestSuite * inSuite, void * inContext, TransferSess TransferSession::OutputEvent & outEvent, bool expectEOF) { TransferSession::OutputEventType expectedEventType = - expectEOF ? TransferSession::kAckEOFReceived : TransferSession::kAckReceived; + expectEOF ? TransferSession::OutputEventType::kAckEOFReceived : TransferSession::OutputEventType::kAckReceived; MessageType expectedMsgType = expectEOF ? MessageType::BlockAckEOF : MessageType::BlockAck; // Verify PrepareBlockAck() outputs message to send CHIP_ERROR err = ackSender.PrepareBlockAck(); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); ackSender.PollOutput(outEvent, kNoAdvanceTime); - NL_TEST_ASSERT(inSuite, outEvent.EventType == TransferSession::kMsgToSend); + NL_TEST_ASSERT(inSuite, outEvent.EventType == TransferSession::OutputEventType::kMsgToSend); VerifyBdxMessageType(inSuite, inContext, outEvent.MsgData, expectedMsgType); VerifyNoMoreOutput(inSuite, inContext, ackSender); @@ -379,21 +380,21 @@ void TestInitiatingReceiverReceiverDrive(nlTestSuite * inSuite, void * inContext uint32_t timeoutMs = 1000 * 24; // Chosen specifically for this test - TransferControlFlags driveMode = kControl_ReceiverDrive; + TransferControlFlags driveMode = TransferControlFlags::kReceiverDrive; // ReceiveInit parameters TransferSession::TransferInitData initOptions; - initOptions.TransferCtlFlagsRaw = driveMode; - initOptions.MaxBlockSize = proposedBlockSize; - char testFileDes[9] = { "test.txt" }; - initOptions.FileDesLength = static_cast(strlen(testFileDes)); - initOptions.FileDesignator = reinterpret_cast(testFileDes); + initOptions.TransferCtlFlags = driveMode; + initOptions.MaxBlockSize = proposedBlockSize; + char testFileDes[9] = { "test.txt" }; + initOptions.FileDesLength = static_cast(strlen(testFileDes)); + initOptions.FileDesignator = reinterpret_cast(testFileDes); // Initialize respondingSender and pass ReceiveInit message - BitFlags senderOpts; + BitFlags senderOpts; senderOpts.Set(driveMode); - SendAndVerifyTransferInit(inSuite, inContext, outEvent, timeoutMs, initiatingReceiver, kRole_Receiver, initOptions, + SendAndVerifyTransferInit(inSuite, inContext, outEvent, timeoutMs, initiatingReceiver, TransferRole::kReceiver, initOptions, respondingSender, senderOpts, proposedBlockSize); // Test metadata for Accept message @@ -413,7 +414,7 @@ void TestInitiatingReceiverReceiverDrive(nlTestSuite * inSuite, void * inContext acceptData.Metadata = tlvBuf; acceptData.MetadataLength = metadataSize; - SendAndVerifyAcceptMsg(inSuite, inContext, outEvent, respondingSender, kRole_Sender, acceptData, initiatingReceiver, + SendAndVerifyAcceptMsg(inSuite, inContext, outEvent, respondingSender, TransferRole::kSender, acceptData, initiatingReceiver, initOptions); // Verify that MaxBlockSize was chosen correctly @@ -473,14 +474,14 @@ void TestInitiatingSenderSenderDrive(nlTestSuite * inSuite, void * inContext) TransferSession initiatingSender; TransferSession respondingReceiver; - TransferControlFlags driveMode = kControl_SenderDrive; + TransferControlFlags driveMode = TransferControlFlags::kSenderDrive; // Chosen arbitrarily for this test uint16_t transferBlockSize = 10; uint32_t timeoutMs = 1000 * 24; // Initialize respondingReceiver - BitFlags receiverOpts; + BitFlags receiverOpts; receiverOpts.Set(driveMode); // Test metadata for TransferInit message @@ -493,15 +494,15 @@ void TestInitiatingSenderSenderDrive(nlTestSuite * inSuite, void * inContext) // Initialize struct with TransferInit parameters TransferSession::TransferInitData initOptions; - initOptions.TransferCtlFlagsRaw = driveMode; - initOptions.MaxBlockSize = transferBlockSize; - char testFileDes[9] = { "test.txt" }; - initOptions.FileDesLength = static_cast(strlen(testFileDes)); - initOptions.FileDesignator = reinterpret_cast(testFileDes); - initOptions.Metadata = tlvBuf; - initOptions.MetadataLength = metadataSize; - - SendAndVerifyTransferInit(inSuite, inContext, outEvent, timeoutMs, initiatingSender, kRole_Sender, initOptions, + initOptions.TransferCtlFlags = driveMode; + initOptions.MaxBlockSize = transferBlockSize; + char testFileDes[9] = { "test.txt" }; + initOptions.FileDesLength = static_cast(strlen(testFileDes)); + initOptions.FileDesignator = reinterpret_cast(testFileDes); + initOptions.Metadata = tlvBuf; + initOptions.MetadataLength = metadataSize; + + SendAndVerifyTransferInit(inSuite, inContext, outEvent, timeoutMs, initiatingSender, TransferRole::kSender, initOptions, respondingReceiver, receiverOpts, transferBlockSize); // Verify parsed TLV metadata matches the original @@ -519,7 +520,7 @@ void TestInitiatingSenderSenderDrive(nlTestSuite * inSuite, void * inContext) acceptData.Metadata = nullptr; acceptData.MetadataLength = 0; - SendAndVerifyAcceptMsg(inSuite, inContext, outEvent, respondingReceiver, kRole_Receiver, acceptData, initiatingSender, + SendAndVerifyAcceptMsg(inSuite, inContext, outEvent, respondingReceiver, TransferRole::kReceiver, acceptData, initiatingSender, initOptions); // Test multiple Block -> BlockAck -> Block @@ -542,28 +543,28 @@ void TestBadAcceptMessageFields(nlTestSuite * inSuite, void * inContext) TransferSession respondingSender; uint16_t maxBlockSize = 64; - TransferControlFlags driveMode = kControl_ReceiverDrive; + TransferControlFlags driveMode = TransferControlFlags::kReceiverDrive; uint64_t commonLength = 0; uint64_t commonOffset = 0; uint32_t timeoutMs = 1000 * 24; // Initialize struct with TransferInit parameters TransferSession::TransferInitData initOptions; - initOptions.TransferCtlFlagsRaw = driveMode; - initOptions.MaxBlockSize = maxBlockSize; - initOptions.StartOffset = commonOffset; - initOptions.Length = commonLength; - char testFileDes[9] = { "test.txt" }; // arbitrary file designator - initOptions.FileDesLength = static_cast(strlen(testFileDes)); - initOptions.FileDesignator = reinterpret_cast(testFileDes); - initOptions.Metadata = nullptr; - initOptions.MetadataLength = 0; + initOptions.TransferCtlFlags = driveMode; + initOptions.MaxBlockSize = maxBlockSize; + initOptions.StartOffset = commonOffset; + initOptions.Length = commonLength; + char testFileDes[9] = { "test.txt" }; // arbitrary file designator + initOptions.FileDesLength = static_cast(strlen(testFileDes)); + initOptions.FileDesignator = reinterpret_cast(testFileDes); + initOptions.Metadata = nullptr; + initOptions.MetadataLength = 0; // Responder parameters - BitFlags responderControl; + BitFlags responderControl; responderControl.Set(driveMode); - SendAndVerifyTransferInit(inSuite, inContext, outEvent, timeoutMs, initiatingReceiver, kRole_Receiver, initOptions, + SendAndVerifyTransferInit(inSuite, inContext, outEvent, timeoutMs, initiatingReceiver, TransferRole::kReceiver, initOptions, respondingSender, responderControl, maxBlockSize); // Verify AcceptTransfer() returns error for choosing larger max block size @@ -577,7 +578,8 @@ void TestBadAcceptMessageFields(nlTestSuite * inSuite, void * inContext) // Verify AcceptTransfer() returns error for choosing unsupported transfer control mode TransferSession::TransferAcceptData acceptData2; - acceptData2.ControlMode = (driveMode == kControl_ReceiverDrive) ? kControl_SenderDrive : kControl_ReceiverDrive; + acceptData2.ControlMode = (driveMode == TransferControlFlags::kReceiverDrive) ? TransferControlFlags::kSenderDrive + : TransferControlFlags::kReceiverDrive; acceptData2.MaxBlockSize = maxBlockSize; acceptData2.StartOffset = commonOffset; acceptData2.Length = commonLength; @@ -598,17 +600,17 @@ void TestTimeout(nlTestSuite * inSuite, void * inContext) // Initialize struct with arbitrary TransferInit parameters TransferSession::TransferInitData initOptions; - initOptions.TransferCtlFlagsRaw = kControl_ReceiverDrive; - initOptions.MaxBlockSize = 64; - initOptions.StartOffset = 0; - initOptions.Length = 0; - char testFileDes[9] = { "test.txt" }; // arbitrary file designator - initOptions.FileDesLength = static_cast(strlen(testFileDes)); - initOptions.FileDesignator = reinterpret_cast(testFileDes); - initOptions.Metadata = nullptr; - initOptions.MetadataLength = 0; - - TransferRole role = kRole_Receiver; + initOptions.TransferCtlFlags = TransferControlFlags::kReceiverDrive; + initOptions.MaxBlockSize = 64; + initOptions.StartOffset = 0; + initOptions.Length = 0; + char testFileDes[9] = { "test.txt" }; // arbitrary file designator + initOptions.FileDesLength = static_cast(strlen(testFileDes)); + initOptions.FileDesignator = reinterpret_cast(testFileDes); + initOptions.Metadata = nullptr; + initOptions.MetadataLength = 0; + + TransferRole role = TransferRole::kReceiver; // Verify initiator outputs respective Init message (depending on role) after StartTransfer() err = initiator.StartTransfer(role, initOptions, timeoutMs); @@ -616,13 +618,13 @@ void TestTimeout(nlTestSuite * inSuite, void * inContext) // First PollOutput() should output the TransferInit message initiator.PollOutput(outEvent, startTimeMs); - NL_TEST_ASSERT(inSuite, outEvent.EventType == TransferSession::kMsgToSend); - MessageType expectedInitMsg = (role == kRole_Sender) ? MessageType::SendInit : MessageType::ReceiveInit; + NL_TEST_ASSERT(inSuite, outEvent.EventType == TransferSession::OutputEventType::kMsgToSend); + MessageType expectedInitMsg = (role == TransferRole::kSender) ? MessageType::SendInit : MessageType::ReceiveInit; VerifyBdxMessageType(inSuite, inContext, outEvent.MsgData, expectedInitMsg); // Second PollOutput() with no call to HandleMessageReceived() should result in a timeout. initiator.PollOutput(outEvent, endTimeMs); - NL_TEST_ASSERT(inSuite, outEvent.EventType == TransferSession::kTransferTimeout); + NL_TEST_ASSERT(inSuite, outEvent.EventType == TransferSession::OutputEventType::kTransferTimeout); } // Test that sending the same block twice (with same block counter) results in a StatusReport message with BadBlockCounter. Also @@ -645,21 +647,21 @@ void TestDuplicateBlockError(nlTestSuite * inSuite, void * inContext) uint32_t timeoutMs = 1000 * 24; // Chosen specifically for this test - TransferControlFlags driveMode = kControl_ReceiverDrive; + TransferControlFlags driveMode = TransferControlFlags::kReceiverDrive; // ReceiveInit parameters TransferSession::TransferInitData initOptions; - initOptions.TransferCtlFlagsRaw = driveMode; - initOptions.MaxBlockSize = blockSize; - char testFileDes[9] = { "test.txt" }; - initOptions.FileDesLength = static_cast(strlen(testFileDes)); - initOptions.FileDesignator = reinterpret_cast(testFileDes); + initOptions.TransferCtlFlags = driveMode; + initOptions.MaxBlockSize = blockSize; + char testFileDes[9] = { "test.txt" }; + initOptions.FileDesLength = static_cast(strlen(testFileDes)); + initOptions.FileDesignator = reinterpret_cast(testFileDes); // Initialize respondingSender and pass ReceiveInit message - BitFlags senderOpts; + BitFlags senderOpts; senderOpts.Set(driveMode); - SendAndVerifyTransferInit(inSuite, inContext, outEvent, timeoutMs, initiatingReceiver, kRole_Receiver, initOptions, + SendAndVerifyTransferInit(inSuite, inContext, outEvent, timeoutMs, initiatingReceiver, TransferRole::kReceiver, initOptions, respondingSender, senderOpts, blockSize); // Compose ReceiveAccept parameters struct and give to respondingSender @@ -671,7 +673,7 @@ void TestDuplicateBlockError(nlTestSuite * inSuite, void * inContext) acceptData.Metadata = nullptr; acceptData.MetadataLength = 0; - SendAndVerifyAcceptMsg(inSuite, inContext, outEvent, respondingSender, kRole_Sender, acceptData, initiatingReceiver, + SendAndVerifyAcceptMsg(inSuite, inContext, outEvent, respondingSender, TransferRole::kSender, acceptData, initiatingReceiver, initOptions); SendAndVerifyQuery(inSuite, inContext, respondingSender, initiatingReceiver, outEvent); @@ -685,7 +687,7 @@ void TestDuplicateBlockError(nlTestSuite * inSuite, void * inContext) err = respondingSender.PrepareBlock(blockData); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); respondingSender.PollOutput(eventWithBlock, kNoAdvanceTime); - NL_TEST_ASSERT(inSuite, eventWithBlock.EventType == TransferSession::kMsgToSend); + NL_TEST_ASSERT(inSuite, eventWithBlock.EventType == TransferSession::OutputEventType::kMsgToSend); VerifyBdxMessageType(inSuite, inContext, eventWithBlock.MsgData, MessageType::Block); VerifyNoMoreOutput(inSuite, inContext, respondingSender); System::PacketBufferHandle blockCopy = @@ -695,7 +697,7 @@ void TestDuplicateBlockError(nlTestSuite * inSuite, void * inContext) err = initiatingReceiver.HandleMessageReceived(std::move(eventWithBlock.MsgData), kNoAdvanceTime); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); initiatingReceiver.PollOutput(outEvent, kNoAdvanceTime); - NL_TEST_ASSERT(inSuite, outEvent.EventType == TransferSession::kBlockReceived); + NL_TEST_ASSERT(inSuite, outEvent.EventType == TransferSession::OutputEventType::kBlockReceived); NL_TEST_ASSERT(inSuite, outEvent.blockdata.Data != nullptr); VerifyNoMoreOutput(inSuite, inContext, initiatingReceiver); @@ -705,30 +707,30 @@ void TestDuplicateBlockError(nlTestSuite * inSuite, void * inContext) err = initiatingReceiver.HandleMessageReceived(std::move(blockCopy), kNoAdvanceTime); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); initiatingReceiver.PollOutput(outEvent, kNoAdvanceTime); - NL_TEST_ASSERT(inSuite, outEvent.EventType == TransferSession::kMsgToSend); + NL_TEST_ASSERT(inSuite, outEvent.EventType == TransferSession::OutputEventType::kMsgToSend); System::PacketBufferHandle statusReportMsg = outEvent.MsgData.Retain(); - VerifyStatusReport(inSuite, inContext, std::move(outEvent.MsgData), kStatus_BadBlockCounter); + VerifyStatusReport(inSuite, inContext, std::move(outEvent.MsgData), StatusCode::kBadBlockCounter); // All subsequent PollOutput() calls should return kInternalError for (int i = 0; i < 5; ++i) { initiatingReceiver.PollOutput(outEvent, kNoAdvanceTime); - NL_TEST_ASSERT(inSuite, outEvent.EventType == TransferSession::kInternalError); - NL_TEST_ASSERT(inSuite, outEvent.statusData.StatusCode == kStatus_BadBlockCounter); + NL_TEST_ASSERT(inSuite, outEvent.EventType == TransferSession::OutputEventType::kInternalError); + NL_TEST_ASSERT(inSuite, outEvent.statusData.statusCode == StatusCode::kBadBlockCounter); } err = respondingSender.HandleMessageReceived(std::move(statusReportMsg), kNoAdvanceTime); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); respondingSender.PollOutput(outEvent, kNoAdvanceTime); - NL_TEST_ASSERT(inSuite, outEvent.EventType == TransferSession::kStatusReceived); - NL_TEST_ASSERT(inSuite, outEvent.statusData.StatusCode == kStatus_BadBlockCounter); + NL_TEST_ASSERT(inSuite, outEvent.EventType == TransferSession::OutputEventType::kStatusReceived); + NL_TEST_ASSERT(inSuite, outEvent.statusData.statusCode == StatusCode::kBadBlockCounter); // All subsequent PollOutput() calls should return kInternalError for (int i = 0; i < 5; ++i) { respondingSender.PollOutput(outEvent, kNoAdvanceTime); - NL_TEST_ASSERT(inSuite, outEvent.EventType == TransferSession::kInternalError); - NL_TEST_ASSERT(inSuite, outEvent.statusData.StatusCode == kStatus_BadBlockCounter); + NL_TEST_ASSERT(inSuite, outEvent.EventType == TransferSession::OutputEventType::kInternalError); + NL_TEST_ASSERT(inSuite, outEvent.statusData.statusCode == StatusCode::kBadBlockCounter); } } diff --git a/src/setup_payload/AdditionalDataPayloadGenerator.cpp b/src/setup_payload/AdditionalDataPayloadGenerator.cpp index 5e6d99024dca23..341c0e6c26de9d 100644 --- a/src/setup_payload/AdditionalDataPayloadGenerator.cpp +++ b/src/setup_payload/AdditionalDataPayloadGenerator.cpp @@ -44,7 +44,7 @@ using namespace chip::Encoding::LittleEndian; CHIP_ERROR AdditionalDataPayloadGenerator::generateAdditionalDataPayload(uint16_t lifetimeCounter, const char * serialNumberBuffer, size_t serialNumberBufferSize, PacketBufferHandle & bufferHandle, - BitFlags additionalDataFields) + BitFlags additionalDataFields) { CHIP_ERROR err = CHIP_NO_ERROR; System::PacketBufferTLVWriter writer; diff --git a/src/setup_payload/AdditionalDataPayloadGenerator.h b/src/setup_payload/AdditionalDataPayloadGenerator.h index 6b48edaad3f10e..652b2676c5dc43 100644 --- a/src/setup_payload/AdditionalDataPayloadGenerator.h +++ b/src/setup_payload/AdditionalDataPayloadGenerator.h @@ -71,7 +71,7 @@ class AdditionalDataPayloadGenerator */ CHIP_ERROR generateAdditionalDataPayload(uint16_t lifetimeCounter, const char * serialNumberBuffer, size_t serialNumberBufferSize, chip::System::PacketBufferHandle & bufferHandle, - BitFlags additionalDataFields); + BitFlags additionalDataFields); // Generate Device Rotating ID /** * Generate additional data payload (i.e. TLV encoded). diff --git a/src/transport/raw/MessageHeader.cpp b/src/transport/raw/MessageHeader.cpp index 8a95a74a04f51b..9e05324cbacd53 100644 --- a/src/transport/raw/MessageHeader.cpp +++ b/src/transport/raw/MessageHeader.cpp @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2020-2021 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. @@ -319,9 +319,9 @@ CHIP_ERROR PacketHeader::EncodeBeforeData(const System::PacketBufferHandle & buf CHIP_ERROR PayloadHeader::Encode(uint8_t * data, uint16_t size, uint16_t * encode_size) const { - CHIP_ERROR err = CHIP_NO_ERROR; - uint8_t * p = data; - uint8_t header = mExchangeFlags.Raw(); + CHIP_ERROR err = CHIP_NO_ERROR; + uint8_t * p = data; + const uint8_t header = mExchangeFlags.Raw(); VerifyOrExit(size >= EncodeSizeBytes(), err = CHIP_ERROR_INVALID_ARGUMENT); diff --git a/src/transport/raw/MessageHeader.h b/src/transport/raw/MessageHeader.h index 3a7feca0b02e0c..dfe8d8cabdca18 100644 --- a/src/transport/raw/MessageHeader.h +++ b/src/transport/raw/MessageHeader.h @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2020-2021 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. @@ -95,9 +95,9 @@ enum class FlagValues : uint16_t }; -using Flags = BitFlags; -using ExFlags = BitFlags; -using InternalFlags = BitFlags; +using Flags = BitFlags; +using ExFlags = BitFlags; +using InternalFlags = BitFlags; // Header is a 16-bit value of the form // | 4 bit | 4 bit |8 bit Security Flags|