| /* | |
| * | |
| * Copyright (c) 2020-2026 Project CHIP Authors | |
| * Copyright (c) 2018 Nest Labs, Inc. | |
| * | |
| * Licensed under the Apache License, Version 2.0 (the "License"); | |
| * you may not use this file except in compliance with the License. | |
| * You may obtain a copy of the License at | |
| * | |
| * http://www.apache.org/licenses/LICENSE-2.0 | |
| * | |
| * Unless required by applicable law or agreed to in writing, software | |
| * distributed under the License is distributed on an "AS IS" BASIS, | |
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| * See the License for the specific language governing permissions and | |
| * limitations under the License. | |
| */ | |
| /** | |
| * @file | |
| * Provides an implementation of the BLEManager singleton object | |
| * for Linux platforms. | |
| */ | |
| /** | |
| * Note: BLEManager requires ConnectivityManager to be defined beforehand, | |
| * otherwise we will face circular dependency between them. */ | |
| #include <platform/ConnectivityManager.h> | |
| /** | |
| * Note: Use public include for BLEManager which includes our local | |
| * platform/<PLATFORM>/BLEManagerImpl.h after defining interface class. */ | |
| #include "platform/internal/BLEManager.h" | |
| #include <type_traits> | |
| #include <utility> | |
| #include <ble/Ble.h> | |
| #include <lib/support/CHIPMemString.h> | |
| #include <lib/support/CodeUtils.h> | |
| #include <lib/support/SafeInt.h> | |
| #include <platform/CHIPDeviceLayer.h> | |
| #include <platform/CommissionableDataProvider.h> | |
| #include "bluez/BluezEndpoint.h" | |
| #if !CHIP_DEVICE_CONFIG_SUPPORTS_CONCURRENT_CONNECTION | |
| #include <platform/DeviceControlServer.h> | |
| #endif | |
| using namespace ::nl; | |
| using namespace ::chip::Ble; | |
| namespace chip { | |
| namespace DeviceLayer { | |
| namespace Internal { | |
| namespace { | |
| static constexpr System::Clock::Timeout kNewConnectionScanTimeout = System::Clock::Seconds16(20); | |
| static constexpr System::Clock::Timeout kConnectTimeout = System::Clock::Seconds16(20); | |
| #if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONING_PROXY | |
| // Forwarder used by StartProxyScan / StopProxyScan to translate the | |
| // BlueZ-internal ChipDeviceScannerDelegate events into the public | |
| // BleScanResultCallback shape that the commissioning-proxy app expects. | |
| class ProxyScanForwarder; | |
| // Single in-flight proxy-scan forwarder. Owned across StartProxyScan -> | |
| // StopProxyScan; destroyed and recreated each cycle so the scanner's | |
| // delegate pointer is never stale. | |
| static ProxyScanForwarder * sProxyScanForwarder = nullptr; | |
| // Id of the scan sProxyScanForwarder serves, stamped onto every result it | |
| // queues. A result is copied on the GLib thread and delivered later on the | |
| // Matter event loop, so it outlives the scan that found it; releasing the | |
| // forwarder bumps this, which is what makes such a result recognisably stale. | |
| // Without it the result is handed to whatever scan started next -- a | |
| // background result entering a foreground scan's results, or landing in a | |
| // cache the background-scan registry has just cleared. | |
| static uint32_t sProxyScanGeneration = 0; | |
| // A device is re-reported on every RSSI change, so one device in range costs a report per | |
| // advertisement. Only the background scan needs the repeats, to reset a cached result's | |
| // timer; a device's first report is never suppressed. | |
| // | |
| // The bound is the 1 second minimum CacheTimeout. A repeat waits for the first | |
| // advertisement after the interval, so a device advertising just under it refreshes at | |
| // twice the interval - which has to stay inside that second. | |
| constexpr System::Clock::Timeout kProxyScanCoalesceInterval = System::Clock::Milliseconds32(400); | |
| // One slot per device the proxy can hold a result for. | |
| constexpr size_t kProxyScanCoalesceSlots = CHIP_CONFIG_COMMISSIONING_PROXY_MAX_CACHED_RESULTS; | |
| // Ordered and sized to pack: a 32-bit stamp first leaves no padding, and 3 x uint16 plus | |
| // the flag fill the rest. Milliseconds64 would cost 13 bytes of padding out of 24. | |
| struct ProxyScanReportRecord | |
| { | |
| System::Clock::Milliseconds32 lastReported; | |
| uint16_t discriminator; | |
| uint16_t vendorId; | |
| uint16_t productId; | |
| bool inUse; | |
| }; | |
| static_assert(sizeof(ProxyScanReportRecord) == 12, "ProxyScanReportRecord has grown padding"); | |
| // Work item carried from the GLib scan thread onto the Matter event loop. | |
| struct ProxyScanWorkCtx | |
| { | |
| BLEManagerImpl::BleScanResultCallback cb; | |
| void * ctx; | |
| uint32_t generation; | |
| uint8_t bdAddr[6]; // little-endian (reversed from BlueZ MSB-first) | |
| uint16_t discriminator; | |
| uint16_t vendorId; | |
| uint16_t productId; | |
| }; | |
| static void DispatchProxyScanResult(intptr_t arg) | |
| { | |
| auto * r = reinterpret_cast<ProxyScanWorkCtx *>(arg); | |
| // Runs on the Matter event loop, the only thread that writes | |
| // sProxyScanGeneration, so this comparison needs no lock. | |
| if (r->generation == sProxyScanGeneration) | |
| { | |
| r->cb(r->ctx, r->bdAddr, r->discriminator, r->vendorId, r->productId); | |
| } | |
| else | |
| { | |
| ChipLogDetail(DeviceLayer, "ProxyScan: dropping result from scan %u (current %u)", r->generation, sProxyScanGeneration); | |
| } | |
| delete r; | |
| } | |
| class ProxyScanForwarder : public ChipDeviceScannerDelegate | |
| { | |
| public: | |
| ProxyScanForwarder(BLEManagerImpl::BleScanResultCallback cb, void * ctx, uint32_t generation) : | |
| mCb(cb), mCtx(ctx), mGeneration(generation) | |
| {} | |
| void OnDeviceScanned(BluezDevice1 & device, const chip::Ble::ChipBLEDeviceIdentificationInfo & info) override | |
| { | |
| VerifyOrReturn(mCb != nullptr); | |
| const char * addrStr = bluez_device1_get_address(&device); | |
| VerifyOrReturn(addrStr != nullptr); | |
| unsigned int b[6]; | |
| if (sscanf(addrStr, "%02x:%02x:%02x:%02x:%02x:%02x", &b[0], &b[1], &b[2], &b[3], &b[4], &b[5]) != 6) | |
| { | |
| ChipLogDetail(DeviceLayer, "ProxyScanForwarder: malformed BD_ADDR '%s', skipping", addrStr); | |
| return; | |
| } | |
| // Drop a repeat before it costs an allocation and a work item. | |
| VerifyOrReturn(ShouldForward(info)); | |
| // Schedule the callback onto the Matter event loop so the consumer can | |
| // safely touch SystemLayer timers and the data model. Dispatching via | |
| // ScheduleWork avoids acquiring the CHIP stack lock from this GLib | |
| // thread, which would deadlock when the Matter thread concurrently | |
| // holds the lock inside StopScan()→GLibMatterContextInvokeSync(). | |
| // | |
| // Byte order: BlueZ provides the address MSB-first ("AA:BB:…:FF"). | |
| // ScanResultStruct.Address SHALL be little-endian per spec, so reverse | |
| // the bytes during the copy (index 0 = b[5] = LSB). | |
| auto * work = new ProxyScanWorkCtx{}; | |
| work->cb = mCb; | |
| work->ctx = mCtx; | |
| work->generation = mGeneration; | |
| work->discriminator = info.GetDeviceDiscriminator(); | |
| work->vendorId = info.GetVendorId(); | |
| work->productId = info.GetProductId(); | |
| for (int i = 0; i < 6; ++i) | |
| { | |
| work->bdAddr[i] = static_cast<uint8_t>(b[5 - i]); | |
| } | |
| CHIP_ERROR schedErr = DeviceLayer::PlatformMgr().ScheduleWork(DispatchProxyScanResult, reinterpret_cast<intptr_t>(work)); | |
| if (schedErr != CHIP_NO_ERROR) | |
| { | |
| ChipLogError(DeviceLayer, "ProxyScanForwarder: ScheduleWork failed: %" CHIP_ERROR_FORMAT, schedErr.Format()); | |
| delete work; | |
| } | |
| } | |
| void OnScanComplete() override {} | |
| void OnScanError(CHIP_ERROR) override {} | |
| ~ProxyScanForwarder() override | |
| { | |
| // One line per scan, rather than one per report. | |
| ChipLogDetail(DeviceLayer, "ProxyScanForwarder: scan %u forwarded %u report(s), coalesced %u", mGeneration, mForwarded, | |
| mCoalesced); | |
| } | |
| private: | |
| /// False when this device was already forwarded inside kProxyScanCoalesceInterval. | |
| /// Called only from OnDeviceScanned, so the records need no locking. | |
| bool ShouldForward(const chip::Ble::ChipBLEDeviceIdentificationInfo & info) | |
| { | |
| const auto now = std::chrono::duration_cast<System::Clock::Milliseconds32>(System::SystemClock().GetMonotonicTimestamp()); | |
| const uint16_t discriminator = info.GetDeviceDiscriminator(); | |
| const uint16_t vendorId = info.GetVendorId(); | |
| const uint16_t productId = info.GetProductId(); | |
| ProxyScanReportRecord * freeSlot = nullptr; | |
| for (auto & record : mReported) | |
| { | |
| if (record.inUse && record.discriminator == discriminator && record.vendorId == vendorId && | |
| record.productId == productId) | |
| { | |
| if (now - record.lastReported < kProxyScanCoalesceInterval) | |
| { | |
| mCoalesced++; | |
| return false; | |
| } | |
| record.lastReported = now; | |
| mForwarded++; | |
| return true; | |
| } | |
| if (freeSlot == nullptr && !record.inUse) | |
| { | |
| freeSlot = &record; | |
| } | |
| } | |
| // No slot left: forward unrecorded, so only the coalescing is lost. | |
| if (freeSlot != nullptr) | |
| { | |
| *freeSlot = ProxyScanReportRecord{ now, discriminator, vendorId, productId, true }; | |
| } | |
| mForwarded++; | |
| return true; | |
| } | |
| BLEManagerImpl::BleScanResultCallback mCb; | |
| void * mCtx; | |
| // Immutable once constructed, so the GLib thread can read it unsynchronised. | |
| const uint32_t mGeneration; | |
| ProxyScanReportRecord mReported[kProxyScanCoalesceSlots] = {}; | |
| uint32_t mForwarded = 0; | |
| uint32_t mCoalesced = 0; | |
| }; | |
| /// Tear down the current forwarder and invalidate every result it has queued. | |
| /// The generation bump is what makes an already-scheduled work item stale, so it | |
| /// belongs wherever the forwarder goes away -- the failed-start rollbacks as much | |
| /// as StopProxyScan. | |
| static void ReleaseProxyScanForwarder() | |
| { | |
| delete sProxyScanForwarder; | |
| sProxyScanForwarder = nullptr; | |
| sProxyScanGeneration++; | |
| } | |
| #endif // CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONING_PROXY | |
| static constexpr System::Clock::Timeout kFastAdvertiseTimeout = | |
| System::Clock::Milliseconds32(CHIP_DEVICE_CONFIG_BLE_ADVERTISING_INTERVAL_CHANGE_TIME); | |
| #if CHIP_DEVICE_CONFIG_EXT_ADVERTISING | |
| // The CHIP_DEVICE_CONFIG_BLE_EXT_ADVERTISING_INTERVAL_CHANGE_TIME_MS specifies the transition time | |
| // starting from advertisement commencement. Since the extended advertisement timer is started after | |
| // the fast-to-slow transition, we have to subtract the time spent in fast advertising. | |
| static constexpr System::Clock::Timeout kSlowAdvertiseTimeout = System::Clock::Milliseconds32( | |
| CHIP_DEVICE_CONFIG_BLE_EXT_ADVERTISING_INTERVAL_CHANGE_TIME_MS - CHIP_DEVICE_CONFIG_BLE_ADVERTISING_INTERVAL_CHANGE_TIME); | |
| static_assert(CHIP_DEVICE_CONFIG_BLE_EXT_ADVERTISING_INTERVAL_CHANGE_TIME_MS >= | |
| CHIP_DEVICE_CONFIG_BLE_ADVERTISING_INTERVAL_CHANGE_TIME, | |
| "The extended advertising interval change time must be greater than the fast advertising interval change time"); | |
| #endif | |
| } // namespace | |
| BLEManagerImpl BLEManagerImpl::sInstance; | |
| CHIP_ERROR BLEManagerImpl::_Init() | |
| { | |
| ReturnErrorOnFailure(BleLayer::Init(this, this, this, &DeviceLayer::SystemLayer())); | |
| mServiceMode = ConnectivityManager::kCHIPoBLEServiceMode_Enabled; | |
| mFlags.ClearAll().Set(Flags::kAdvertisingEnabled, CHIP_DEVICE_CONFIG_CHIPOBLE_ENABLE_ADVERTISING_AUTOSTART && !mIsCentral); | |
| mFlags.Set(Flags::kFastAdvertisingEnabled, true); | |
| memset(mDeviceName, 0, sizeof(mDeviceName)); | |
| return DeviceLayer::SystemLayer().ScheduleLambda([this] { DriveBLEState(); }); | |
| } | |
| void BLEManagerImpl::_Shutdown() | |
| { | |
| ++mScanRequestId; | |
| // Make sure that timers are stopped before shutting down the BLE layer. | |
| DeviceLayer::SystemLayer().CancelTimer(HandleScanTimer, this); | |
| DeviceLayer::SystemLayer().CancelTimer(HandleAdvertisingTimer, this); | |
| DeviceLayer::SystemLayer().CancelTimer(HandleConnectTimer, this); | |
| CleanScanConfig(); | |
| #if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONING_PROXY | |
| // Drop proxy-scan ownership while the adapter is still usable, so a later | |
| // StartProxyScan is not refused with CHIP_ERROR_BUSY by a stale forwarder. | |
| (void) StopProxyScan(); | |
| #endif | |
| mDeviceScanner.Shutdown(); | |
| mBLEAdvertisement.Shutdown(); | |
| mEndpoint.Shutdown(); | |
| mBluezObjectManager.Shutdown(); | |
| mFlags.Clear(Flags::kBluezManagerInitialized); | |
| } | |
| CHIP_ERROR BLEManagerImpl::_SetAdvertisingEnabled(bool val) | |
| { | |
| #if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONING_PROXY | |
| // Spec: an already-commissioned Node SHALL NOT commence commissioning | |
| // announcement using Bluetooth LE (DeviceDiscovery.adoc §"announcement of | |
| // a Commissionable Node" — already-commissioned nodes use DNS-SD only). | |
| // For the commissioning-proxy app, BLE has been switched to central role | |
| // after the CP was used for a BLE proxy op (mIsCentral=true). Refuse to | |
| // arm peripheral-mode advertising — DNS-SD remains available for the | |
| // OpenCommissioningWindow path. | |
| if (val && mIsCentral) | |
| { | |
| ChipLogProgress(DeviceLayer, | |
| "_SetAdvertisingEnabled(true) refused: BLE is in central role; " | |
| "DNS-SD advertising is used for OpenCommissioningWindow per spec"); | |
| return CHIP_NO_ERROR; | |
| } | |
| #endif | |
| if (mFlags.Has(Flags::kAdvertisingEnabled) != val) | |
| { | |
| mFlags.Set(Flags::kAdvertisingEnabled, val); | |
| } | |
| return DeviceLayer::SystemLayer().ScheduleLambda([this] { DriveBLEState(); }); | |
| } | |
| CHIP_ERROR BLEManagerImpl::_SetAdvertisingMode(BLEAdvertisingMode mode) | |
| { | |
| switch (mode) | |
| { | |
| case BLEAdvertisingMode::kFastAdvertising: | |
| mFlags.Set(Flags::kFastAdvertisingEnabled, true); | |
| break; | |
| case BLEAdvertisingMode::kSlowAdvertising: | |
| mFlags.Set(Flags::kFastAdvertisingEnabled, false); | |
| break; | |
| default: | |
| return CHIP_ERROR_INVALID_ARGUMENT; | |
| } | |
| mFlags.Set(Flags::kAdvertisingRefreshNeeded); | |
| return DeviceLayer::SystemLayer().ScheduleLambda([this] { DriveBLEState(); }); | |
| } | |
| CHIP_ERROR BLEManagerImpl::_GetDeviceName(char * buf, size_t bufSize) | |
| { | |
| if (strlen(mDeviceName) >= bufSize) | |
| { | |
| return CHIP_ERROR_BUFFER_TOO_SMALL; | |
| } | |
| strcpy(buf, mDeviceName); | |
| return CHIP_NO_ERROR; | |
| } | |
| CHIP_ERROR BLEManagerImpl::_SetDeviceName(const char * deviceName) | |
| { | |
| VerifyOrReturnError(mServiceMode != ConnectivityManager::kCHIPoBLEServiceMode_NotSupported, | |
| CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE); | |
| if (deviceName != nullptr && deviceName[0] != 0) | |
| { | |
| VerifyOrReturnError(strlen(deviceName) < kMaxDeviceNameLength, CHIP_ERROR_INVALID_ARGUMENT); | |
| strcpy(mDeviceName, deviceName); | |
| mFlags.Set(Flags::kUseCustomDeviceName); | |
| } | |
| else | |
| { | |
| uint16_t discriminator; | |
| ReturnErrorOnFailure(GetCommissionableDataProvider()->GetSetupDiscriminator(discriminator)); | |
| snprintf(mDeviceName, sizeof(mDeviceName), "%s%04u", CHIP_DEVICE_CONFIG_BLE_DEVICE_NAME_PREFIX, discriminator); | |
| mDeviceName[kMaxDeviceNameLength] = 0; | |
| mFlags.Clear(Flags::kUseCustomDeviceName); | |
| } | |
| return CHIP_NO_ERROR; | |
| } | |
| uint16_t BLEManagerImpl::_NumConnections() | |
| { | |
| return mEndpoint.GetNumConnections(); | |
| } | |
| CHIP_ERROR BLEManagerImpl::ConfigureBle(uint32_t aAdapterId, bool aIsCentral) | |
| { | |
| mAdapterId = aAdapterId; | |
| mIsCentral = aIsCentral; | |
| return CHIP_NO_ERROR; | |
| } | |
| void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) | |
| { | |
| switch (event->Type) | |
| { | |
| case DeviceEventType::kCHIPoBLESubscribe: | |
| HandleSubscribeReceived(event->CHIPoBLESubscribe.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); | |
| NotifyCHIPoBLEConnectionEstablished(); | |
| break; | |
| case DeviceEventType::kCHIPoBLEUnsubscribe: | |
| HandleUnsubscribeReceived(event->CHIPoBLEUnsubscribe.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); | |
| NotifyCHIPoBLEConnectionClosed(); | |
| break; | |
| case DeviceEventType::kCHIPoBLEWriteReceived: | |
| HandleWriteReceived(event->CHIPoBLEWriteReceived.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_1_UUID, | |
| PacketBufferHandle::Adopt(event->CHIPoBLEWriteReceived.Data)); | |
| break; | |
| case DeviceEventType::kCHIPoBLEIndicateConfirm: | |
| HandleIndicationConfirmation(event->CHIPoBLEIndicateConfirm.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); | |
| break; | |
| case DeviceEventType::kCHIPoBLEConnectionError: | |
| HandleConnectionError(event->CHIPoBLEConnectionError.ConId, event->CHIPoBLEConnectionError.Reason); | |
| break; | |
| case DeviceEventType::kServiceProvisioningChange: | |
| // Force the advertising configuration to be refreshed to reflect new provisioning state. | |
| mFlags.Clear(Flags::kAdvertisingConfigured); | |
| DriveBLEState(); | |
| break; | |
| default: | |
| HandlePlatformSpecificBLEEvent(event); | |
| break; | |
| } | |
| } | |
| void BLEManagerImpl::HandlePlatformSpecificBLEEvent(const ChipDeviceEvent * apEvent) | |
| { | |
| CHIP_ERROR err = CHIP_NO_ERROR; | |
| switch (apEvent->Type) | |
| { | |
| case DeviceEventType::kPlatformLinuxBLEAdapterAdded: | |
| ChipLogDetail(DeviceLayer, "BLE adapter added: id=%u address=%s", apEvent->Platform.BLEAdapter.mAdapterId, | |
| apEvent->Platform.BLEAdapter.mAdapterAddress); | |
| if (apEvent->Platform.BLEAdapter.mAdapterId == mAdapterId) | |
| { | |
| mServiceMode = ConnectivityManager::kCHIPoBLEServiceMode_Enabled; | |
| DriveBLEState(); | |
| } | |
| break; | |
| case DeviceEventType::kPlatformLinuxBLEAdapterRemoved: | |
| ChipLogDetail(DeviceLayer, "BLE adapter removed: id=%u address=%s", apEvent->Platform.BLEAdapter.mAdapterId, | |
| apEvent->Platform.BLEAdapter.mAdapterAddress); | |
| if (apEvent->Platform.BLEAdapter.mAdapterId == mAdapterId) | |
| { | |
| // Shutdown all BLE operations and release resources | |
| #if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONING_PROXY | |
| // As in _Shutdown: release proxy-scan ownership so proxy scanning can | |
| // recover once an adapter is available again. | |
| (void) StopProxyScan(); | |
| #endif | |
| mDeviceScanner.Shutdown(); | |
| mBLEAdvertisement.Shutdown(); | |
| mEndpoint.Shutdown(); | |
| // Drop reference to the adapter | |
| mAdapter.reset(); | |
| // Clear all flags related to BlueZ BLE operations | |
| mFlags.Clear(Flags::kBluezAdapterAvailable); | |
| mFlags.Clear(Flags::kBluezBLELayerInitialized); | |
| mFlags.Clear(Flags::kAdvertisingConfigured); | |
| mFlags.Clear(Flags::kAppRegistered); | |
| ClearAdvertisingFlag(); | |
| CleanScanConfig(); | |
| // Indicate that the adapter is no longer available | |
| err = BLE_ERROR_ADAPTER_UNAVAILABLE; | |
| } | |
| break; | |
| case DeviceEventType::kPlatformLinuxBLECentralConnected: { | |
| const bool accept = apEvent->Platform.BLECentralConnected.mRequestId == mScanRequestId && | |
| mBLEScanConfig.mBleScanState == BleScanState::kConnecting; | |
| if (auto * connection = mEndpoint.ResolvePendingConnection(apEvent->Platform.BLECentralConnected.mPendingTicket, accept)) | |
| { | |
| BleConnectionDelegate::OnConnectionComplete(mBLEScanConfig.mAppState, connection); | |
| CleanScanConfig(); | |
| } | |
| break; | |
| } | |
| case DeviceEventType::kPlatformLinuxBLECentralConnectFailed: | |
| if (apEvent->Platform.BLECentralConnectFailed.mRequestId == mScanRequestId && | |
| mBLEScanConfig.mBleScanState == BleScanState::kConnecting) | |
| { | |
| BleConnectionDelegate::OnConnectionError(mBLEScanConfig.mAppState, apEvent->Platform.BLECentralConnectFailed.mError); | |
| CleanScanConfig(); | |
| } | |
| break; | |
| case DeviceEventType::kPlatformLinuxBLEWriteComplete: | |
| HandleWriteConfirmation(apEvent->Platform.BLEWriteComplete.mConnection, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_1_UUID); | |
| break; | |
| case DeviceEventType::kPlatformLinuxBLESubscribeOpComplete: | |
| if (apEvent->Platform.BLESubscribeOpComplete.mIsSubscribed) | |
| HandleSubscribeComplete(apEvent->Platform.BLESubscribeOpComplete.mConnection, &CHIP_BLE_SVC_ID, | |
| &Ble::CHIP_BLE_CHAR_2_UUID); | |
| else | |
| HandleUnsubscribeComplete(apEvent->Platform.BLESubscribeOpComplete.mConnection, &CHIP_BLE_SVC_ID, | |
| &Ble::CHIP_BLE_CHAR_2_UUID); | |
| break; | |
| case DeviceEventType::kPlatformLinuxBLEIndicationReceived: | |
| HandleIndicationReceived(apEvent->Platform.BLEIndicationReceived.mConnection, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID, | |
| PacketBufferHandle::Adopt(apEvent->Platform.BLEIndicationReceived.mData)); | |
| break; | |
| case DeviceEventType::kPlatformLinuxBLEPeripheralAdvStartComplete: | |
| SuccessOrExit(err = apEvent->Platform.BLEPeripheralAdvStartComplete.mError); | |
| mFlags.Clear(Flags::kControlOpInProgress).Clear(Flags::kAdvertisingRefreshNeeded); | |
| // Do not restart the timer if it is still active. This is to avoid the timer from being restarted | |
| // if the advertising is stopped due to a premature release. | |
| if (!DeviceLayer::SystemLayer().IsTimerActive(HandleAdvertisingTimer, this)) | |
| { | |
| // Start a timer to make sure that the fast advertising is stopped after specified timeout. | |
| SuccessOrExit(err = DeviceLayer::SystemLayer().StartTimer(kFastAdvertiseTimeout, HandleAdvertisingTimer, this)); | |
| } | |
| mFlags.Set(Flags::kAdvertising); | |
| NotifyCHIPoBLEAdvertisingChange(kActivity_Started); | |
| break; | |
| case DeviceEventType::kPlatformLinuxBLEPeripheralAdvStopComplete: | |
| SuccessOrExit(err = apEvent->Platform.BLEPeripheralAdvStopComplete.mError); | |
| mFlags.Clear(Flags::kControlOpInProgress).Clear(Flags::kAdvertisingRefreshNeeded); | |
| DeviceLayer::SystemLayer().CancelTimer(HandleAdvertisingTimer, this); | |
| // Transition to the not Advertising state... | |
| ClearAdvertisingFlag(); | |
| break; | |
| case DeviceEventType::kPlatformLinuxBLEPeripheralAdvReleased: | |
| // If the advertising was stopped due to a premature release, check if it needs to be restarted. | |
| ClearAdvertisingFlag(); | |
| DriveBLEState(); | |
| break; | |
| case DeviceEventType::kPlatformLinuxBLEPeripheralRegisterAppComplete: | |
| SuccessOrExit(err = apEvent->Platform.BLEPeripheralRegisterAppComplete.mError); | |
| mFlags.Clear(Flags::kControlOpInProgress); | |
| mFlags.Set(Flags::kAppRegistered); | |
| DriveBLEState(); | |
| break; | |
| default: | |
| break; | |
| } | |
| exit: | |
| if (err != CHIP_NO_ERROR) | |
| { | |
| DisableBLEService(err); | |
| mFlags.Clear(Flags::kControlOpInProgress); | |
| } | |
| } | |
| uint16_t BLEManagerImpl::GetMTU(BLE_CONNECTION_OBJECT conId) const | |
| { | |
| uint16_t mtu = 0; | |
| VerifyOrExit(conId != BLE_CONNECTION_UNINITIALIZED, | |
| ChipLogError(DeviceLayer, "BLE connection is not initialized in %s", __func__)); | |
| mtu = conId->GetMTU(); | |
| exit: | |
| return mtu; | |
| } | |
| CHIP_ERROR BLEManagerImpl::SubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, | |
| const ChipBleUUID * charId) | |
| { | |
| CHIP_ERROR err = BLE_ERROR_GATT_SUBSCRIBE_FAILED; | |
| VerifyOrExit(conId != BLE_CONNECTION_UNINITIALIZED, | |
| ChipLogError(DeviceLayer, "BLE connection is not initialized in %s", __func__)); | |
| VerifyOrExit(Ble::UUIDsMatch(svcId, &CHIP_BLE_SVC_ID), | |
| ChipLogError(DeviceLayer, "SubscribeCharacteristic() called with invalid service ID")); | |
| VerifyOrExit(Ble::UUIDsMatch(charId, &Ble::CHIP_BLE_CHAR_2_UUID), | |
| ChipLogError(DeviceLayer, "SubscribeCharacteristic() called with invalid characteristic ID")); | |
| err = conId->SubscribeCharacteristic(); | |
| exit: | |
| return err; | |
| } | |
| CHIP_ERROR BLEManagerImpl::UnsubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, | |
| const ChipBleUUID * charId) | |
| { | |
| CHIP_ERROR err = BLE_ERROR_GATT_UNSUBSCRIBE_FAILED; | |
| VerifyOrExit(conId != BLE_CONNECTION_UNINITIALIZED, | |
| ChipLogError(DeviceLayer, "BLE connection is not initialized in %s", __func__)); | |
| VerifyOrExit(Ble::UUIDsMatch(svcId, &CHIP_BLE_SVC_ID), | |
| ChipLogError(DeviceLayer, "UnsubscribeCharacteristic() called with invalid service ID")); | |
| VerifyOrExit(Ble::UUIDsMatch(charId, &Ble::CHIP_BLE_CHAR_2_UUID), | |
| ChipLogError(DeviceLayer, "UnsubscribeCharacteristic() called with invalid characteristic ID")); | |
| err = conId->UnsubscribeCharacteristic(); | |
| exit: | |
| return err; | |
| } | |
| CHIP_ERROR BLEManagerImpl::CloseConnection(BLE_CONNECTION_OBJECT conId) | |
| { | |
| CHIP_ERROR err = CHIP_ERROR_INTERNAL; | |
| VerifyOrExit(conId != BLE_CONNECTION_UNINITIALIZED, | |
| ChipLogError(DeviceLayer, "BLE connection is not initialized in %s", __func__)); | |
| ChipLogProgress(DeviceLayer, "Closing BLE GATT connection (con %p)", conId); | |
| err = conId->CloseConnection(); | |
| exit: | |
| return err; | |
| } | |
| CHIP_ERROR BLEManagerImpl::SendIndication(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const Ble::ChipBleUUID * charId, | |
| chip::System::PacketBufferHandle pBuf) | |
| { | |
| CHIP_ERROR err = BLE_ERROR_GATT_INDICATE_FAILED; | |
| VerifyOrExit(conId != BLE_CONNECTION_UNINITIALIZED, | |
| ChipLogError(DeviceLayer, "BLE connection is not initialized in %s", __func__)); | |
| err = conId->SendIndication(std::move(pBuf)); | |
| exit: | |
| return err; | |
| } | |
| CHIP_ERROR BLEManagerImpl::SendWriteRequest(BLE_CONNECTION_OBJECT conId, const Ble::ChipBleUUID * svcId, | |
| const Ble::ChipBleUUID * charId, chip::System::PacketBufferHandle pBuf) | |
| { | |
| CHIP_ERROR err = BLE_ERROR_GATT_WRITE_FAILED; | |
| VerifyOrExit(conId != BLE_CONNECTION_UNINITIALIZED, | |
| ChipLogError(DeviceLayer, "BLE connection is not initialized in %s", __func__)); | |
| VerifyOrExit(Ble::UUIDsMatch(svcId, &CHIP_BLE_SVC_ID), | |
| ChipLogError(DeviceLayer, "SendWriteRequest() called with invalid service ID")); | |
| VerifyOrExit(Ble::UUIDsMatch(charId, &Ble::CHIP_BLE_CHAR_1_UUID), | |
| ChipLogError(DeviceLayer, "SendWriteRequest() called with invalid characteristic ID")); | |
| err = conId->SendWriteRequest(std::move(pBuf)); | |
| exit: | |
| return err; | |
| } | |
| void BLEManagerImpl::HandleNewConnection(uint64_t pendingTicket, uint64_t requestId) | |
| { | |
| if (sInstance.mIsCentral) | |
| { | |
| ChipDeviceEvent event{ .Type = DeviceEventType::kPlatformLinuxBLECentralConnected, | |
| .Platform = { | |
| .BLECentralConnected = { .mPendingTicket = pendingTicket, .mRequestId = requestId } } }; | |
| PlatformMgr().PostEventOrDie(&event); | |
| } | |
| } | |
| void BLEManagerImpl::HandleConnectFailed(CHIP_ERROR error) | |
| { | |
| HandleConnectFailed(error, sInstance.mScanRequestId.load()); | |
| } | |
| void BLEManagerImpl::HandleConnectFailed(CHIP_ERROR error, uint64_t requestId) | |
| { | |
| if (sInstance.mIsCentral) | |
| { | |
| ChipDeviceEvent event{ .Type = DeviceEventType::kPlatformLinuxBLECentralConnectFailed, | |
| .Platform = { .BLECentralConnectFailed = { .mError = error, .mRequestId = requestId } } }; | |
| PlatformMgr().PostEventOrDie(&event); | |
| } | |
| } | |
| void BLEManagerImpl::HandleWriteComplete(BLE_CONNECTION_OBJECT conId) | |
| { | |
| ChipDeviceEvent event{ .Type = DeviceEventType::kPlatformLinuxBLEWriteComplete, | |
| .Platform = { .BLEWriteComplete = { .mConnection = conId } } }; | |
| PlatformMgr().PostEventOrDie(&event); | |
| } | |
| void BLEManagerImpl::HandleSubscribeOpComplete(BLE_CONNECTION_OBJECT conId, bool subscribed) | |
| { | |
| ChipDeviceEvent event{ .Type = DeviceEventType::kPlatformLinuxBLESubscribeOpComplete, | |
| .Platform = { .BLESubscribeOpComplete = { .mConnection = conId, .mIsSubscribed = subscribed } } }; | |
| PlatformMgr().PostEventOrDie(&event); | |
| } | |
| void BLEManagerImpl::HandleTXCharChanged(BLE_CONNECTION_OBJECT conId, const uint8_t * value, size_t len) | |
| { | |
| System::PacketBufferHandle buf(System::PacketBufferHandle::NewWithData(value, len)); | |
| VerifyOrReturn(!buf.IsNull(), ChipLogError(DeviceLayer, "Failed to allocate packet buffer in %s", __func__)); | |
| ChipLogDetail(DeviceLayer, "Indication received: conn=%p", conId); | |
| ChipDeviceEvent event{ .Type = DeviceEventType::kPlatformLinuxBLEIndicationReceived, | |
| .Platform = { | |
| .BLEIndicationReceived = { .mConnection = conId, .mData = std::move(buf).UnsafeRelease() } } }; | |
| PlatformMgr().PostEventOrDie(&event); | |
| } | |
| void BLEManagerImpl::HandleRXCharWrite(BLE_CONNECTION_OBJECT conId, const uint8_t * value, size_t len) | |
| { | |
| // Copy the data to a packet buffer. | |
| System::PacketBufferHandle buf(System::PacketBufferHandle::NewWithData(value, len)); | |
| VerifyOrReturn(!buf.IsNull(), ChipLogError(DeviceLayer, "Failed to allocate packet buffer in %s", __func__)); | |
| ChipLogProgress(Ble, "Write request received: conn=%p", conId); | |
| // Post an event to the Chip queue to deliver the data into the Chip stack. | |
| ChipDeviceEvent event{ .Type = DeviceEventType::kCHIPoBLEWriteReceived, | |
| .CHIPoBLEWriteReceived = { .ConId = conId, .Data = std::move(buf).UnsafeRelease() } }; | |
| PlatformMgr().PostEventOrDie(&event); | |
| } | |
| void BLEManagerImpl::HandleConnectionClosed(BLE_CONNECTION_OBJECT conId) | |
| { | |
| // If this was a CHIPoBLE connection, post an event to deliver a connection error to the CHIPoBLE layer. | |
| ChipDeviceEvent event{ .Type = DeviceEventType::kCHIPoBLEConnectionError, | |
| .CHIPoBLEConnectionError = { .ConId = conId, .Reason = BLE_ERROR_REMOTE_DEVICE_DISCONNECTED } }; | |
| PlatformMgr().PostEventOrDie(&event); | |
| } | |
| void BLEManagerImpl::HandleTXCharCCCDWrite(BLE_CONNECTION_OBJECT conId) | |
| { | |
| VerifyOrReturn(conId != BLE_CONNECTION_UNINITIALIZED, | |
| ChipLogError(DeviceLayer, "BLE connection is not initialized in %s", __func__)); | |
| ChipLogProgress(DeviceLayer, "CHIPoBLE %s received", conId->IsNotifyAcquired() ? "subscribe" : "unsubscribe"); | |
| // Post an event to the Chip queue to process either a CHIPoBLE Subscribe or Unsubscribe based on | |
| // whether the client is enabling or disabling indications. | |
| ChipDeviceEvent event{ .Type = conId->IsNotifyAcquired() ? static_cast<uint16_t>(DeviceEventType::kCHIPoBLESubscribe) | |
| : static_cast<uint16_t>(DeviceEventType::kCHIPoBLEUnsubscribe), | |
| .CHIPoBLESubscribe = { .ConId = conId } }; | |
| PlatformMgr().PostEventOrDie(&event); | |
| } | |
| void BLEManagerImpl::HandleTXComplete(BLE_CONNECTION_OBJECT conId) | |
| { | |
| // Post an event to the Chip queue to process the indicate confirmation. | |
| ChipDeviceEvent event{ .Type = DeviceEventType::kCHIPoBLEIndicateConfirm, .CHIPoBLEIndicateConfirm = { .ConId = conId } }; | |
| PlatformMgr().PostEventOrDie(&event); | |
| } | |
| void BLEManagerImpl::DriveBLEState() | |
| { | |
| CHIP_ERROR err = CHIP_NO_ERROR; | |
| // Perform any initialization actions that must occur after the Chip task is running. | |
| if (!mFlags.Has(Flags::kAsyncInitCompleted)) | |
| { | |
| mFlags.Set(Flags::kAsyncInitCompleted); | |
| ExitNow(); | |
| } | |
| // If there's already a control operation in progress, wait until it completes. | |
| VerifyOrExit(!mFlags.Has(Flags::kControlOpInProgress), /* */); | |
| // Initializes the BlueZ BLE layer if needed. | |
| if (mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_Enabled) | |
| { | |
| if (!mFlags.Has(Flags::kBluezManagerInitialized)) | |
| { | |
| SuccessOrExit(err = mBluezObjectManager.Init()); | |
| mFlags.Set(Flags::kBluezManagerInitialized); | |
| } | |
| if (!mFlags.Has(Flags::kBluezAdapterAvailable)) | |
| { | |
| mAdapter.reset(mBluezObjectManager.GetAdapter(mAdapterId)); | |
| VerifyOrExit(mAdapter, err = BLE_ERROR_ADAPTER_UNAVAILABLE); | |
| mFlags.Set(Flags::kBluezAdapterAvailable); | |
| } | |
| if (!mFlags.Has(Flags::kBluezBLELayerInitialized)) | |
| { | |
| SuccessOrExit(err = mEndpoint.Init(mAdapter.get(), mIsCentral)); | |
| mFlags.Set(Flags::kBluezBLELayerInitialized); | |
| } | |
| } | |
| // Register the CHIPoBLE application with the Bluez BLE layer if needed. | |
| if (!mIsCentral && mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_Enabled && !mFlags.Has(Flags::kAppRegistered)) | |
| { | |
| SuccessOrExit(err = mEndpoint.RegisterGattApplication()); | |
| mFlags.Set(Flags::kControlOpInProgress); | |
| ExitNow(); | |
| } | |
| // If the application has enabled CHIPoBLE and BLE advertising... | |
| // (Skip when in central role — see spec note in _SetAdvertisingEnabled above.) | |
| if (mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_Enabled && mFlags.Has(Flags::kAdvertisingEnabled) && !mIsCentral) | |
| { | |
| // Start/re-start advertising if not already advertising, or if the advertising state of the | |
| // Bluez BLE layer needs to be refreshed. | |
| if (!mFlags.Has(Flags::kAdvertising) || mFlags.Has(Flags::kAdvertisingRefreshNeeded)) | |
| { | |
| mFlags.Clear(Flags::kAdvertisingRefreshNeeded); | |
| // Configure advertising data if it hasn't been done yet. | |
| if (!mFlags.Has(Flags::kAdvertisingConfigured)) | |
| { | |
| SuccessOrExit(err = mBLEAdvertisement.Init(mAdapter.get(), Ble::CHIP_BLE_SERVICE_SHORT_UUID_STR, mDeviceName)); | |
| mFlags.Set(Flags::kAdvertisingConfigured); | |
| } | |
| // Setup service data for advertising. | |
| auto serviceDataFlags = BluezAdvertisement::kServiceDataNone; | |
| #if CHIP_DEVICE_CONFIG_EXT_ADVERTISING | |
| if (mFlags.Has(Flags::kExtAdvertisingEnabled)) | |
| serviceDataFlags |= BluezAdvertisement::kServiceDataExtendedAnnouncement; | |
| #endif | |
| SuccessOrExit(err = mBLEAdvertisement.SetupServiceData(serviceDataFlags)); | |
| // Set or update the advertising intervals. | |
| SuccessOrExit(err = mBLEAdvertisement.SetIntervals(GetAdvertisingIntervals())); | |
| if (!mFlags.Has(Flags::kAdvertising)) | |
| { | |
| // Start advertising. This is an asynchronous step. BLE manager will be notified of | |
| // advertising start completion via a call to NotifyBLEPeripheralAdvStartComplete. | |
| SuccessOrExit(err = mBLEAdvertisement.Start()); | |
| mFlags.Set(Flags::kControlOpInProgress); | |
| ExitNow(); | |
| } | |
| } | |
| } | |
| // Otherwise stop advertising if needed... | |
| else | |
| { | |
| if (mFlags.Has(Flags::kAdvertising)) | |
| { | |
| SuccessOrExit(err = mBLEAdvertisement.Stop()); | |
| mFlags.Set(Flags::kControlOpInProgress); | |
| ExitNow(); | |
| } | |
| } | |
| exit: | |
| if (err != CHIP_NO_ERROR) | |
| { | |
| DisableBLEService(err); | |
| } | |
| } | |
| void BLEManagerImpl::DisableBLEService(CHIP_ERROR err) | |
| { | |
| ChipLogError(DeviceLayer, "Disabling CHIPoBLE service due to error: %" CHIP_ERROR_FORMAT, err.Format()); | |
| mServiceMode = ConnectivityManager::kCHIPoBLEServiceMode_Disabled; | |
| // Stop all timers if the error is other than BLE adapter unavailable. In case of BLE adapter | |
| // beeing unavailable, we will keep timers running, as the adapter might become available in | |
| // the nearest future (e.g. BlueZ restart due to crash). By doing that we will ensure that BLE | |
| // adapter reappearance will not extend timeouts for the ongoing operations. | |
| if (err != BLE_ERROR_ADAPTER_UNAVAILABLE) | |
| { | |
| DeviceLayer::SystemLayer().CancelTimer(HandleScanTimer, this); | |
| DeviceLayer::SystemLayer().CancelTimer(HandleAdvertisingTimer, this); | |
| DeviceLayer::SystemLayer().CancelTimer(HandleConnectTimer, this); | |
| } | |
| } | |
| void BLEManagerImpl::NotifyChipConnectionClosed(BLE_CONNECTION_OBJECT conId) | |
| { | |
| ChipLogProgress(Ble, "Got notification regarding chip connection closure"); | |
| #if CHIP_DEVICE_CONFIG_ENABLE_WPA && !CHIP_DEVICE_CONFIG_SUPPORTS_CONCURRENT_CONNECTION | |
| if (mState == kState_NotInitialized) | |
| { | |
| // Close BLE GATT connections to disconnect BlueZ | |
| CloseConnection(conId); | |
| // In Non-Concurrent mode start the Wi-Fi, as BLE has been stopped | |
| DeviceLayer::ConnectivityMgrImpl().StartNonConcurrentWiFiManagement(); | |
| } | |
| #endif // CHIP_DEVICE_CONFIG_SUPPORTS_CONCURRENT_CONNECTION | |
| } | |
| void BLEManagerImpl::CheckNonConcurrentBleClosing() | |
| { | |
| #if CHIP_DEVICE_CONFIG_ENABLE_WPA && !CHIP_DEVICE_CONFIG_SUPPORTS_CONCURRENT_CONNECTION | |
| if (mState == kState_Disconnecting) | |
| { | |
| DeviceLayer::DeviceControlServer::DeviceControlSvr().PostCloseAllBLEConnectionsToOperationalNetworkEvent(); | |
| } | |
| #endif | |
| } | |
| BluezAdvertisement::AdvertisingIntervals BLEManagerImpl::GetAdvertisingIntervals() const | |
| { | |
| if (mFlags.Has(Flags::kFastAdvertisingEnabled)) | |
| return { CHIP_DEVICE_CONFIG_BLE_FAST_ADVERTISING_INTERVAL_MIN, CHIP_DEVICE_CONFIG_BLE_FAST_ADVERTISING_INTERVAL_MAX }; | |
| #if CHIP_DEVICE_CONFIG_EXT_ADVERTISING | |
| if (mFlags.Has(Flags::kExtAdvertisingEnabled)) | |
| return { CHIP_DEVICE_CONFIG_BLE_EXT_ADVERTISING_INTERVAL_MIN, CHIP_DEVICE_CONFIG_BLE_EXT_ADVERTISING_INTERVAL_MAX }; | |
| #endif | |
| return { CHIP_DEVICE_CONFIG_BLE_SLOW_ADVERTISING_INTERVAL_MIN, CHIP_DEVICE_CONFIG_BLE_SLOW_ADVERTISING_INTERVAL_MAX }; | |
| } | |
| void BLEManagerImpl::HandleAdvertisingTimer(chip::System::Layer *, void * appState) | |
| { | |
| auto * self = static_cast<BLEManagerImpl *>(appState); | |
| if (self->mFlags.Has(Flags::kFastAdvertisingEnabled)) | |
| { | |
| ChipLogDetail(DeviceLayer, "bleAdv Timeout : Start slow advertisement"); | |
| TEMPORARY_RETURN_IGNORED self->_SetAdvertisingMode(BLEAdvertisingMode::kSlowAdvertising); | |
| #if CHIP_DEVICE_CONFIG_EXT_ADVERTISING | |
| self->mFlags.Clear(Flags::kExtAdvertisingEnabled); | |
| DeviceLayer::SystemLayer().StartTimer(kSlowAdvertiseTimeout, HandleAdvertisingTimer, self); | |
| } | |
| else | |
| { | |
| ChipLogDetail(DeviceLayer, "bleAdv Timeout : Start extended advertisement"); | |
| self->mFlags.Set(Flags::kExtAdvertisingEnabled); | |
| // This will trigger advertising intervals update in the DriveBLEState() function. | |
| self->_SetAdvertisingMode(BLEAdvertisingMode::kSlowAdvertising); | |
| #endif | |
| } | |
| } | |
| void BLEManagerImpl::InitiateScan(BleScanState scanType) | |
| { | |
| CHIP_ERROR err = CHIP_ERROR_INCORRECT_STATE; | |
| DriveBLEState(); | |
| VerifyOrExit(scanType != BleScanState::kNotScanning, | |
| ChipLogError(Ble, "Invalid scan type requested: %d", to_underlying(scanType))); | |
| VerifyOrExit(!mDeviceScanner.IsScanning(), ChipLogError(Ble, "BLE scan already in progress")); | |
| VerifyOrExit(mFlags.Has(Flags::kBluezAdapterAvailable), err = BLE_ERROR_ADAPTER_UNAVAILABLE); | |
| mBLEScanConfig.mBleScanState = scanType; | |
| err = mDeviceScanner.Init(mAdapter.get(), this); | |
| VerifyOrExit(err == CHIP_NO_ERROR, { | |
| mBLEScanConfig.mBleScanState = BleScanState::kNotScanning; | |
| ChipLogError(Ble, "Failed to create BLE device scanner: %" CHIP_ERROR_FORMAT, err.Format()); | |
| }); | |
| err = mDeviceScanner.StartScan(); | |
| VerifyOrExit(err == CHIP_NO_ERROR, { | |
| mBLEScanConfig.mBleScanState = BleScanState::kNotScanning; | |
| ChipLogError(Ble, "Failed to start BLE scan: %" CHIP_ERROR_FORMAT, err.Format()); | |
| }); | |
| err = DeviceLayer::SystemLayer().StartTimer(kNewConnectionScanTimeout, HandleScanTimer, this); | |
| VerifyOrExit(err == CHIP_NO_ERROR, { | |
| mBLEScanConfig.mBleScanState = BleScanState::kNotScanning; | |
| TEMPORARY_RETURN_IGNORED mDeviceScanner.StopScan(); | |
| ChipLogError(Ble, "Failed to start BLE scan timeout: %" CHIP_ERROR_FORMAT, err.Format()); | |
| }); | |
| exit: | |
| if (err != CHIP_NO_ERROR) | |
| { | |
| BleConnectionDelegate::OnConnectionError(mBLEScanConfig.mAppState, err); | |
| } | |
| } | |
| void BLEManagerImpl::HandleScanTimer(chip::System::Layer *, void * appState) | |
| { | |
| auto * manager = static_cast<BLEManagerImpl *>(appState); | |
| manager->OnScanError(CHIP_ERROR_TIMEOUT); | |
| TEMPORARY_RETURN_IGNORED manager->mDeviceScanner.StopScan(); | |
| } | |
| void BLEManagerImpl::CleanScanConfig() | |
| { | |
| if (mBLEScanConfig.mBleScanState == BleScanState::kConnecting) | |
| DeviceLayer::SystemLayer().CancelTimer(HandleConnectTimer, this); | |
| mBLEScanConfig.mBleScanState = BleScanState::kNotScanning; | |
| } | |
| void BLEManagerImpl::ClearAdvertisingFlag() | |
| { | |
| VerifyOrReturn(mFlags.Has(Flags::kAdvertising)); | |
| mFlags.Clear(Flags::kAdvertising); | |
| NotifyCHIPoBLEAdvertisingChange(kActivity_Stopped); | |
| ChipLogProgress(DeviceLayer, "CHIPoBLE advertising stopped"); | |
| } | |
| void BLEManagerImpl::NewConnection(BleLayer * bleLayer, void * appState, const SetupDiscriminator & connDiscriminator) | |
| { | |
| mBLEScanConfig.mDiscriminator = connDiscriminator; | |
| mBLEScanConfig.mAppState = appState; | |
| const auto requestId = ++mScanRequestId; | |
| // Scan initiation performed async, to ensure that the BLE subsystem is initialized. | |
| TEMPORARY_RETURN_IGNORED DeviceLayer::SystemLayer().ScheduleLambda([this, requestId] { | |
| if (requestId == mScanRequestId) | |
| { | |
| InitiateScan(BleScanState::kScanForDiscriminator); | |
| } | |
| }); | |
| } | |
| CHIP_ERROR BLEManagerImpl::CancelConnection() | |
| { | |
| if (mBLEScanConfig.mBleScanState == BleScanState::kConnecting) | |
| { | |
| mEndpoint.CancelConnect(); | |
| return CHIP_ERROR_BUSY; | |
| } | |
| // If in discovery mode, stop scan. | |
| if (mBLEScanConfig.mBleScanState != BleScanState::kNotScanning) | |
| { | |
| DeviceLayer::SystemLayer().CancelTimer(HandleScanTimer, this); | |
| CHIP_ERROR error = mDeviceScanner.StopScan(); | |
| VerifyOrReturnError(error == CHIP_NO_ERROR || !mDeviceScanner.IsScanning(), error); | |
| } | |
| ++mScanRequestId; | |
| CleanScanConfig(); | |
| return CHIP_NO_ERROR; | |
| } | |
| #if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONING_PROXY | |
| CHIP_ERROR BLEManagerImpl::SwitchToCentralMode() | |
| { | |
| VerifyOrReturnError(!mIsCentral, CHIP_NO_ERROR); | |
| // Refuse if any BLE connection is still active (e.g. the commissioning | |
| // session that brought the CP onto the fabric has not closed yet). Caller | |
| // can retry once the commissioner disconnects. | |
| if (mEndpoint.GetNumConnections() > 0) | |
| { | |
| ChipLogProgress(DeviceLayer, "SwitchToCentralMode: BLE connection still active, deferring"); | |
| return CHIP_ERROR_BUSY; | |
| } | |
| // Refuse if an advertising start/stop D-Bus call is in-flight. The async | |
| // completion callback (kPlatformLinuxBLEPeripheralAdvStartComplete) runs | |
| // unconditionally and re-arms kAdvertising=true after we clear it below, | |
| // which would cause DriveBLEState to call Stop() on an already-Shutdown() | |
| // BluezAdvertisement object and permanently disable BLE via DisableBLEService. | |
| if (mFlags.Has(Flags::kControlOpInProgress)) | |
| { | |
| ChipLogProgress(DeviceLayer, "SwitchToCentralMode: BLE control operation in progress, deferring"); | |
| return CHIP_ERROR_BUSY; | |
| } | |
| // Stop advertising and tear down advertising state so the radio is free for | |
| // central scans / connects. mBLEAdvertisement.Shutdown() also unregisters | |
| // the BlueZ LEAdvertisement1 D-Bus object. Shutting the advertisement down | |
| // directly bypasses the async stop whose completion event normally cancels the | |
| // advertising timer, so cancel it here: a timer left armed would fire into | |
| // _SetAdvertisingMode, set kAdvertisingRefreshNeeded and re-enter DriveBLEState | |
| // after the role switch (and with CHIP_DEVICE_CONFIG_EXT_ADVERTISING it re-arms | |
| // itself, so it would keep doing so for the life of the process). | |
| mBLEAdvertisement.Shutdown(); | |
| DeviceLayer::SystemLayer().CancelTimer(HandleAdvertisingTimer, this); | |
| mFlags.Clear(Flags::kAdvertisingEnabled); | |
| mFlags.Clear(Flags::kAdvertising); | |
| mFlags.Clear(Flags::kAdvertisingConfigured); | |
| // Lightweight role flip. The peripheral GATT server objects stay registered | |
| // (harmless — advertising is off so nothing will connect to them), but | |
| // BluezConnection::Init and BluezEndpoint::HandleNewDevice subsequently see | |
| // mIsCentral=true and take the central code path. After this returns, the | |
| // CP cannot be re-commissioned over BLE until the process restarts. | |
| mIsCentral = true; | |
| mEndpoint.SetCentralMode(true); | |
| ChipLogProgress(DeviceLayer, "SwitchToCentralMode: BLE switched to central role for proxy operations"); | |
| return CHIP_NO_ERROR; | |
| } | |
| CHIP_ERROR BLEManagerImpl::StartProxyScan(BleScanResultCallback cb, void * context) | |
| { | |
| VerifyOrReturnError(cb != nullptr, CHIP_ERROR_INVALID_ARGUMENT); | |
| VerifyOrReturnError(sProxyScanForwarder == nullptr, CHIP_ERROR_BUSY); | |
| VerifyOrReturnError(!mDeviceScanner.IsScanning(), CHIP_ERROR_BUSY); | |
| VerifyOrReturnError(mFlags.Has(Flags::kBluezAdapterAvailable), BLE_ERROR_ADAPTER_UNAVAILABLE); | |
| sProxyScanForwarder = new ProxyScanForwarder(cb, context, sProxyScanGeneration); | |
| CHIP_ERROR err = mDeviceScanner.Init(mAdapter.get(), sProxyScanForwarder); | |
| if (err != CHIP_NO_ERROR) | |
| { | |
| ReleaseProxyScanForwarder(); | |
| return err; | |
| } | |
| err = mDeviceScanner.StartScan(); | |
| if (err != CHIP_NO_ERROR) | |
| { | |
| // Restore BLEManagerImpl as the scanner's delegate so the next internal | |
| // scan (NewBleConnectionByDiscriminator) finds the expected callback target. | |
| // If this re-Init fails the scanner still holds the soon-to-be-freed | |
| // forwarder as its delegate, so abort rather than risk a use-after-free. | |
| CHIP_ERROR restoreErr = mDeviceScanner.Init(mAdapter.get(), this); | |
| VerifyOrDieWithMsg(restoreErr == CHIP_NO_ERROR, DeviceLayer, "ProxyScan rollback: scanner Init failed: %" CHIP_ERROR_FORMAT, | |
| restoreErr.Format()); | |
| ReleaseProxyScanForwarder(); | |
| } | |
| return err; | |
| } | |
| CHIP_ERROR BLEManagerImpl::StopProxyScan() | |
| { | |
| // No proxy scan of ours to stop: leave any internal scan and the scanner's | |
| // delegate alone. | |
| VerifyOrReturnError(sProxyScanForwarder != nullptr, CHIP_NO_ERROR); | |
| CHIP_ERROR err = CHIP_NO_ERROR; | |
| if (mDeviceScanner.IsScanning()) | |
| { | |
| err = mDeviceScanner.StopScan(); | |
| } | |
| // Restore BLEManagerImpl as the scanner's delegate before deleting the | |
| // forwarder, so any callback that fires after StopScan returns lands on a | |
| // live object (BLEManagerImpl) rather than freed memory. Skip the re-init | |
| // if the adapter has been removed (mAdapter is null in that path and the | |
| // scanner is already shut down by NotifyBLEAdapterRemoved). | |
| if (mFlags.Has(Flags::kBluezAdapterAvailable)) | |
| { | |
| CHIP_ERROR restoreErr = mDeviceScanner.Init(mAdapter.get(), this); | |
| VerifyOrDieWithMsg(restoreErr == CHIP_NO_ERROR, DeviceLayer, "StopProxyScan: scanner Init failed: %" CHIP_ERROR_FORMAT, | |
| restoreErr.Format()); | |
| } | |
| // Also invalidates any result this scan has already queued onto the event | |
| // loop, so it cannot be delivered to the next scan. | |
| ReleaseProxyScanForwarder(); | |
| return err; | |
| } | |
| #endif // CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONING_PROXY | |
| void BLEManagerImpl::NotifyBLEAdapterAdded(unsigned int aAdapterId, const char * aAdapterAddress) | |
| { | |
| ChipDeviceEvent event{ .Type = DeviceEventType::kPlatformLinuxBLEAdapterAdded, | |
| .Platform = { .BLEAdapter = { .mAdapterId = aAdapterId } } }; | |
| Platform::CopyString(event.Platform.BLEAdapter.mAdapterAddress, aAdapterAddress); | |
| PlatformMgr().PostEventOrDie(&event); | |
| } | |
| void BLEManagerImpl::NotifyBLEAdapterRemoved(unsigned int aAdapterId, const char * aAdapterAddress) | |
| { | |
| ChipDeviceEvent event{ .Type = DeviceEventType::kPlatformLinuxBLEAdapterRemoved, | |
| .Platform = { .BLEAdapter = { .mAdapterId = aAdapterId } } }; | |
| Platform::CopyString(event.Platform.BLEAdapter.mAdapterAddress, aAdapterAddress); | |
| PlatformMgr().PostEventOrDie(&event); | |
| } | |
| void BLEManagerImpl::NotifyBLEPeripheralRegisterAppComplete(CHIP_ERROR error) | |
| { | |
| ChipDeviceEvent event{ .Type = DeviceEventType::kPlatformLinuxBLEPeripheralRegisterAppComplete, | |
| .Platform = { .BLEPeripheralRegisterAppComplete = { .mError = error } } }; | |
| PlatformMgr().PostEventOrDie(&event); | |
| } | |
| void BLEManagerImpl::NotifyBLEPeripheralAdvStartComplete(CHIP_ERROR error) | |
| { | |
| ChipDeviceEvent event{ .Type = DeviceEventType::kPlatformLinuxBLEPeripheralAdvStartComplete, | |
| .Platform = { .BLEPeripheralAdvStartComplete = { .mError = error } } }; | |
| PlatformMgr().PostEventOrDie(&event); | |
| } | |
| void BLEManagerImpl::NotifyBLEPeripheralAdvStopComplete(CHIP_ERROR error) | |
| { | |
| ChipDeviceEvent event{ .Type = DeviceEventType::kPlatformLinuxBLEPeripheralAdvStopComplete, | |
| .Platform = { .BLEPeripheralAdvStopComplete = { .mError = error } } }; | |
| PlatformMgr().PostEventOrDie(&event); | |
| } | |
| void BLEManagerImpl::NotifyBLEPeripheralAdvReleased() | |
| { | |
| ChipDeviceEvent event{ .Type = DeviceEventType::kPlatformLinuxBLEPeripheralAdvReleased }; | |
| PlatformMgr().PostEventOrDie(&event); | |
| } | |
| void BLEManagerImpl::NotifyCHIPoBLEConnectionEstablished() | |
| { | |
| ChipDeviceEvent event{ .Type = DeviceEventType::kCHIPoBLEConnectionEstablished }; | |
| PlatformMgr().PostEventOrDie(&event); | |
| } | |
| void BLEManagerImpl::NotifyCHIPoBLEConnectionClosed() | |
| { | |
| ChipDeviceEvent event{ .Type = DeviceEventType::kCHIPoBLEConnectionClosed }; | |
| PlatformMgr().PostEventOrDie(&event); | |
| } | |
| void BLEManagerImpl::NotifyCHIPoBLEAdvertisingChange(enum ActivityChange change) | |
| { | |
| ChipDeviceEvent event{ .Type = DeviceEventType::kCHIPoBLEAdvertisingChange, .CHIPoBLEAdvertisingChange = { .Result = change } }; | |
| PlatformMgr().PostEventOrDie(&event); | |
| } | |
| void BLEManagerImpl::OnDeviceScanned(BluezDevice1 & device, const chip::Ble::ChipBLEDeviceIdentificationInfo & info) | |
| { | |
| struct ScannedDevice | |
| { | |
| GAutoPtr<BluezDevice1> device; | |
| chip::Ble::ChipBLEDeviceIdentificationInfo info; | |
| uint64_t requestId; | |
| }; | |
| auto * result = Platform::New<ScannedDevice>(); | |
| VerifyOrReturn(result != nullptr, ChipLogError(Ble, "Failed to allocate scanned device")); | |
| result->device.reset(BLUEZ_DEVICE1(g_object_ref(&device))); | |
| result->info = info; | |
| result->requestId = mScanRequestId.load(); | |
| CHIP_ERROR error = PlatformMgr().ScheduleWork( | |
| [](intptr_t context) { | |
| auto * scanned = reinterpret_cast<ScannedDevice *>(context); | |
| sInstance.HandleScannedDevice(*scanned->device, scanned->info, scanned->requestId); | |
| Platform::Delete(scanned); | |
| }, | |
| reinterpret_cast<intptr_t>(result)); | |
| if (error != CHIP_NO_ERROR) | |
| { | |
| Platform::Delete(result); | |
| ChipLogError(Ble, "Failed to queue scanned device: %" CHIP_ERROR_FORMAT, error.Format()); | |
| } | |
| } | |
| void BLEManagerImpl::HandleScannedDevice(BluezDevice1 & device, const chip::Ble::ChipBLEDeviceIdentificationInfo & info, | |
| uint64_t requestId) | |
| { | |
| VerifyOrReturn(requestId == mScanRequestId); | |
| const char * address = bluez_device1_get_address(&device); | |
| ChipLogProgress(Ble, "New device scanned: %s", address); | |
| if (mBLEScanConfig.mBleScanState == BleScanState::kScanForDiscriminator) | |
| { | |
| auto isMatch = mBLEScanConfig.mDiscriminator.MatchesLongDiscriminator(info.GetDeviceDiscriminator()); | |
| VerifyOrReturn( | |
| isMatch, | |
| ChipLogError(Ble, "Skip connection: Device discriminator does not match: %u != %u", info.GetDeviceDiscriminator(), | |
| mBLEScanConfig.mDiscriminator.IsShortDiscriminator() ? mBLEScanConfig.mDiscriminator.GetShortValue() | |
| : mBLEScanConfig.mDiscriminator.GetLongValue())); | |
| ChipLogProgress(Ble, "Device discriminator match. Attempting to connect."); | |
| } | |
| else if (mBLEScanConfig.mBleScanState == BleScanState::kScanForAddress) | |
| { | |
| auto isMatch = strcmp(address, mBLEScanConfig.mAddress.c_str()) == 0; | |
| VerifyOrReturn(isMatch, | |
| ChipLogError(Ble, "Skip connection: Device address does not match: %s != %s", address, | |
| mBLEScanConfig.mAddress.c_str())); | |
| ChipLogProgress(Ble, "Device address match. Attempting to connect."); | |
| } | |
| else | |
| { | |
| // Internal consistency error | |
| ChipLogError(Ble, "Unknown discovery type. Ignoring scanned device."); | |
| return; | |
| } | |
| CHIP_ERROR error = mDeviceScanner.StopScan(); | |
| VerifyOrReturn(error == CHIP_NO_ERROR || !mDeviceScanner.IsScanning(), | |
| ChipLogError(Ble, "Failed to stop BLE scan: %" CHIP_ERROR_FORMAT, error.Format())); | |
| DeviceLayer::SystemLayer().CancelTimer(HandleScanTimer, this); | |
| mEndpoint.PrepareConnect(); | |
| mBLEScanConfig.mBleScanState = BleScanState::kConnecting; | |
| error = DeviceLayer::SystemLayer().StartTimer(kConnectTimeout, HandleConnectTimer, this); | |
| if (error == CHIP_NO_ERROR) | |
| { | |
| error = mEndpoint.ScheduleConnect(device, requestId); | |
| } | |
| if (error != CHIP_NO_ERROR) | |
| { | |
| mEndpoint.CancelConnect(); | |
| HandleConnectFailed(error, requestId); | |
| } | |
| } | |
| void BLEManagerImpl::HandleConnectTimer(chip::System::Layer *, void * appState) | |
| { | |
| auto * manager = static_cast<BLEManagerImpl *>(appState); | |
| manager->mEndpoint.CancelConnect(); | |
| BLEManagerImpl::HandleConnectFailed(CHIP_ERROR_TIMEOUT); | |
| } | |
| void BLEManagerImpl::OnScanComplete() | |
| { | |
| switch (mBLEScanConfig.mBleScanState) | |
| { | |
| case BleScanState::kNotScanning: | |
| ChipLogProgress(Ble, "Scan complete notification without an active scan."); | |
| break; | |
| case BleScanState::kScanForAddress: | |
| case BleScanState::kScanForDiscriminator: | |
| mBLEScanConfig.mBleScanState = BleScanState::kNotScanning; | |
| ChipLogProgress(Ble, "Scan complete. No matching device found."); | |
| break; | |
| case BleScanState::kConnecting: | |
| break; | |
| } | |
| } | |
| void BLEManagerImpl::OnScanError(CHIP_ERROR err) | |
| { | |
| BleConnectionDelegate::OnConnectionError(mBLEScanConfig.mAppState, err); | |
| ChipLogError(Ble, "BLE scan error: %" CHIP_ERROR_FORMAT, err.Format()); | |
| } | |
| } // namespace Internal | |
| } // namespace DeviceLayer | |
| } // namespace chip |