Skip to content

Commit

Permalink
[Tizen] Run single thread for processing all GLib sources (#25762)
Browse files Browse the repository at this point in the history
* Remove unused timeout in MainLoop::AsyncRequest()

* Create dedicated glib thread during Matter stack initialization

* Use GLibMatterContextInvoke in BLE manager

* Use GLibMatterContextInvoke in device scanner

* Use GLibMatterContextInvoke in DNS-SD manager

* Use GLibMatterContextInvoke in WiFi manager

* Remove MainLoop class

* Use better name for synchronous invoke

* Verify that thread default glib context is set

* Type safety for GLibMatterContextInvokeSynchronous

* Cleanup

* Align sync function name with convention

* Wait for Matter glib event loop to start running
  • Loading branch information
arkq authored and pull[bot] committed Aug 9, 2023
1 parent ce53168 commit 5349674
Show file tree
Hide file tree
Showing 13 changed files with 251 additions and 464 deletions.
49 changes: 18 additions & 31 deletions src/platform/Tizen/BLEManagerImpl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,6 @@

#include "CHIPDevicePlatformEvent.h"
#include "ChipDeviceScanner.h"
#include "MainLoop.h"

namespace chip {
namespace DeviceLayer {
Expand Down Expand Up @@ -118,14 +117,14 @@ void BLEManagerImpl::GattConnectionStateChangedCb(int result, bool connected, co
}
}

gboolean BLEManagerImpl::_BleInitialize(void * userData)
CHIP_ERROR BLEManagerImpl::_BleInitialize(void * userData)
{
int ret;

if (sInstance.mFlags.Has(Flags::kTizenBLELayerInitialized))
{
ChipLogProgress(DeviceLayer, "BLE Already Initialized");
return true;
return CHIP_NO_ERROR;
}

ret = bt_initialize();
Expand All @@ -144,11 +143,10 @@ gboolean BLEManagerImpl::_BleInitialize(void * userData)

sInstance.mFlags.Set(Flags::kTizenBLELayerInitialized);
ChipLogProgress(DeviceLayer, "BLE Initialized");
sInstance.mMainContext = g_main_context_get_thread_default();
return true;
return CHIP_NO_ERROR;

exit:
return false;
return CHIP_ERROR_INTERNAL;
}

static int __GetAttInfo(bt_gatt_h gattHandle, char ** uuid, bt_gatt_type_e * type)
Expand Down Expand Up @@ -447,37 +445,27 @@ void BLEManagerImpl::HandleConnectionTimeout(System::Layer * layer, void * data)
sInstance.NotifyHandleConnectFailed(CHIP_ERROR_TIMEOUT);
}

gboolean BLEManagerImpl::ConnectChipThing(gpointer userData)
CHIP_ERROR BLEManagerImpl::ConnectChipThing(const char * address)
{
int ret = BT_ERROR_NONE;
CHIP_ERROR err = CHIP_NO_ERROR;
int ret;

char * address = reinterpret_cast<char *>(userData);
ChipLogProgress(DeviceLayer, "ConnectRequest: Addr [%s]", StringOrNullMarker(address));

ret = bt_gatt_client_create(address, &sInstance.mGattClient);
VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "Failed to create GATT client. ret [%d]", ret));
VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "Failed to create GATT client. ret [%d]", ret);
err = CHIP_ERROR_INTERNAL);

ret = bt_gatt_connect(address, false);
VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "Failed to issue GATT connect request. ret [%d]", ret));
VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "Failed to issue GATT connect request. ret [%d]", ret);
err = CHIP_ERROR_INTERNAL);

ChipLogProgress(DeviceLayer, "GATT Connect Issued");
exit:
if (ret != BT_ERROR_NONE)
sInstance.NotifyHandleConnectFailed(CHIP_ERROR_INTERNAL);

g_free(address);
return G_SOURCE_REMOVE;
}

void BLEManagerImpl::ConnectHandler(const char * address)
{
GSource * idleSource;

idleSource = g_idle_source_new();
g_source_set_callback(idleSource, ConnectChipThing, g_strdup(address), nullptr);
g_source_set_priority(idleSource, G_PRIORITY_HIGH_IDLE);
g_source_attach(idleSource, sInstance.mMainContext);
g_source_unref(idleSource);
exit:
if (err != CHIP_NO_ERROR)
sInstance.NotifyHandleConnectFailed(err);
return err;
}

void BLEManagerImpl::OnChipDeviceScanned(void * device, const Ble::ChipBLEDeviceIdentificationInfo & info)
Expand Down Expand Up @@ -515,7 +503,7 @@ void BLEManagerImpl::OnChipDeviceScanned(void * device, const Ble::ChipBLEDevice
mDeviceScanner->StopChipScan();

/* Initiate Connect */
ConnectHandler(deviceInfo->remote_address);
PlatformMgrImpl().GLibMatterContextInvokeSync(ConnectChipThing, const_cast<const char *>(deviceInfo->remote_address));
}

void BLEManagerImpl::OnScanComplete()
Expand Down Expand Up @@ -960,16 +948,15 @@ void BLEManagerImpl::DriveBLEState(intptr_t arg)
CHIP_ERROR BLEManagerImpl::_Init()
{
CHIP_ERROR err;
bool ret;

err = BleLayer::Init(this, this, this, &DeviceLayer::SystemLayer());
SuccessOrExit(err);

mServiceMode = ConnectivityManager::kCHIPoBLEServiceMode_Enabled;

ChipLogProgress(DeviceLayer, "Initialize BLE");
ret = MainLoop::Instance().Init(_BleInitialize);
VerifyOrExit(ret != false, err = CHIP_ERROR_INTERNAL);
err = PlatformMgrImpl().GLibMatterContextInvokeSync(_BleInitialize, static_cast<void *>(nullptr));
SuccessOrExit(err);

PlatformMgr().ScheduleWork(DriveBLEState, 0);

Expand Down
6 changes: 2 additions & 4 deletions src/platform/Tizen/BLEManagerImpl.h
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ class BLEManagerImpl final : public BLEManager,
kAdvertisingRefreshNeeded = 0x0200, /**< The advertising configuration/state in BLE layer needs to be updated. */
};

static gboolean _BleInitialize(void * userData);
static CHIP_ERROR _BleInitialize(void * userData);
void DriveBLEState();
static void DriveBLEState(intptr_t arg);

Expand Down Expand Up @@ -207,8 +207,7 @@ class BLEManagerImpl final : public BLEManager,
void NotifyBLEWriteReceived(System::PacketBufferHandle & buf, BLE_CONNECTION_OBJECT conId);

// ==== Connection.
void ConnectHandler(const char * address);
static gboolean ConnectChipThing(gpointer userData);
static CHIP_ERROR ConnectChipThing(const char * userData);
void NotifyBLEConnectionEstablished(BLE_CONNECTION_OBJECT conId, CHIP_ERROR error);
void NotifyBLEDisconnection(BLE_CONNECTION_OBJECT conId, CHIP_ERROR error);
void NotifyHandleNewConnection(BLE_CONNECTION_OBJECT conId);
Expand All @@ -235,7 +234,6 @@ class BLEManagerImpl final : public BLEManager,

BLEScanConfig mBLEScanConfig;
std::unique_ptr<ChipDeviceScanner> mDeviceScanner;
GMainContext * mMainContext = nullptr;
bt_gatt_client_h mGattClient = nullptr;
};

Expand Down
2 changes: 0 additions & 2 deletions src/platform/Tizen/BUILD.gn
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,6 @@ static_library("Tizen") {
"KeyValueStoreManagerImpl.cpp",
"KeyValueStoreManagerImpl.h",
"Logging.cpp",
"MainLoop.cpp",
"MainLoop.h",
"NetworkCommissioningDriver.h",
"NetworkCommissioningEthernetDriver.cpp",
"PlatformManagerImpl.cpp",
Expand Down
39 changes: 15 additions & 24 deletions src/platform/Tizen/ChipDeviceScanner.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,7 @@
#include <lib/support/CodeUtils.h>
#include <lib/support/Span.h>
#include <lib/support/logging/CHIPLogging.h>

#include "MainLoop.h"
#include <platform/PlatformManager.h>

namespace chip {
namespace DeviceLayer {
Expand Down Expand Up @@ -144,29 +143,27 @@ gboolean ChipDeviceScanner::TimerExpiredCb(gpointer userData)
return G_SOURCE_REMOVE;
}

gboolean ChipDeviceScanner::TriggerScan(GMainLoop * mainLoop, gpointer userData)
CHIP_ERROR ChipDeviceScanner::TriggerScan(ChipDeviceScanner * self)
{
auto self = reinterpret_cast<ChipDeviceScanner *>(userData);
int ret = BT_ERROR_NONE;
CHIP_ERROR err = CHIP_NO_ERROR;
GSource * idleSource;
int ret;

self->mAsyncLoop = mainLoop;

// All set, trigger LE Scan
ret = bt_adapter_le_start_scan(LeScanResultCb, userData);
VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_adapter_le_start_scan() failed: %s", get_error_message(ret)));
ChipLogProgress(DeviceLayer, "Scan started");
// Trigger LE Scan
ret = bt_adapter_le_start_scan(LeScanResultCb, self);
VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_adapter_le_start_scan() failed: %s", get_error_message(ret));
err = CHIP_ERROR_INTERNAL);
self->mIsScanning = true;

// Start Timer
// Setup timer for scan timeout
idleSource = g_timeout_source_new(self->mScanTimeoutMs);
g_source_set_callback(idleSource, TimerExpiredCb, userData, nullptr);
g_source_set_callback(idleSource, TimerExpiredCb, self, nullptr);
g_source_set_priority(idleSource, G_PRIORITY_HIGH_IDLE);
g_source_attach(idleSource, g_main_loop_get_context(self->mAsyncLoop));
g_source_attach(idleSource, g_main_context_get_thread_default());
g_source_unref(idleSource);
return true;

exit:
return false;
return err;
}

static bool __IsScanFilterSupported()
Expand Down Expand Up @@ -212,14 +209,9 @@ CHIP_ERROR ChipDeviceScanner::StartChipScan(System::Clock::Timeout timeout, Scan

// All set to trigger LE Scan
ChipLogProgress(DeviceLayer, "Start CHIP BLE scan: timeout=%ums", mScanTimeoutMs);
if (MainLoop::Instance().AsyncRequest(TriggerScan, this) == false)
{
ChipLogError(DeviceLayer, "Failed to trigger Scan...");
err = CHIP_ERROR_INTERNAL;
goto exit;
}
err = PlatformMgrImpl().GLibMatterContextInvokeSync(TriggerScan, this);
SuccessOrExit(err);

mIsScanning = true; // optimistic, to allow all callbacks to check this
return CHIP_NO_ERROR;

exit:
Expand All @@ -240,7 +232,6 @@ CHIP_ERROR ChipDeviceScanner::StopChipScan()
ChipLogError(DeviceLayer, "bt_adapter_le_stop_scan() failed: %s", get_error_message(ret));
}

g_main_loop_quit(mAsyncLoop);
ChipLogProgress(DeviceLayer, "CHIP Scanner Async Thread Quit Done..Wait for Thread Windup...!");

UnRegisterScanFilter();
Expand Down
5 changes: 2 additions & 3 deletions src/platform/Tizen/ChipDeviceScanner.h
Original file line number Diff line number Diff line change
Expand Up @@ -96,18 +96,17 @@ class ChipDeviceScanner
static std::unique_ptr<ChipDeviceScanner> Create(ChipDeviceScannerDelegate * delegate);

private:
static gboolean TriggerScan(GMainLoop * mainLoop, gpointer userData);
static void LeScanResultCb(int result, bt_adapter_le_device_scan_result_info_s * info, void * userData);
static gboolean TimerExpiredCb(gpointer user_data);
static CHIP_ERROR TriggerScan(ChipDeviceScanner * userData);
void CheckScanFilter(ScanFilterType filterType, ScanFilterData & filterData);
int RegisterScanFilter(ScanFilterType filterType, ScanFilterData & filterData);
void UnRegisterScanFilter(void);
int CreateLEScanFilter(ScanFilterType filterType, ScanFilterData & filterData);
static gboolean TimerExpiredCb(gpointer user_data);

ChipDeviceScannerDelegate * mDelegate = nullptr;
bool mIsScanning = false;
bool mIsStopping = false;
GMainLoop * mAsyncLoop = nullptr;
unsigned int mScanTimeoutMs = 10000;
bt_scan_filter_h mScanFilter = nullptr;
};
Expand Down
Loading

0 comments on commit 5349674

Please sign in to comment.