Files
palemoon27/dom/bluetooth/common/webapi/BluetoothGattServer.cpp
T
roytam1 1dfd83ddde import changes from `dev' branch of rmottola/Arctic-Fox:
- Bug 1225603. Codegen ToJSValue overloads for Web IDL enums. r=smaug,jib (8c21e0b148)
- Bug 1194978 - Renable RequestSync tests in b2g, r=nsm (e99a2fb4f5)
- Bug 1182358 - patch 2 - RequestSyncService.jsm should not write debug messages (1fcc99d65c)
- Bug 1147804 - Facebook auto sync will not happen if you change the time 24 hours later. r=fabrice (936b25f586)
- Bug 1181489 - Enable debug for AlarmService.jsm. r=fabrice (a92673c2f4)
- Bug 1181489 - Adding sanity checks into the alarm service for preventing from the alarm works erroneously. r=fabrice (dd75f12425)
- Bug 1213169 - requestsync assumes all in-memory mozAlarms will never be purged (and these alarms get persisted anyways), but they are purged on timezone/clock changes, r=asuth (00924ed778)
- Bug 1147804 followup: Add missing 'override' annotation to AlarmHalService::Notify declaration. rs=ehsan (8e797f2a9a)
- Bug 1211469 - JavaScript error: resource://gre/modules/RequestSyncService.jsm, line 104: TypeError: this.addRegistration is not a function. r=baku (bbcefdb093)
- Bug 1216002 - "JavaScript error: resource://gre/modules/RequestSyncService.jsm, line 228: TypeError: 'continue' called on an object that does not implement interface IDBCursor." r=bz (153d8a610b)
- Bug 1226708 - part 1 - Use importInMainProcess in requestsync tests. r=baku (7638d77db3)
- Bug 1140275 - System messages shouldn't be sent to app pages not registered in manifests. r=fabrice (3e0d7ae440)
- var-let (e74f0b4a2c)
- Bug 1174683 - [Secure Element] Fix TypeError in UiccConnector.unregisterListener. r=allstars.chh (9dd333d909)
- Bug 1156710 - [Secure Element] Allow SE access without full ACE checks if certified apps debug is enabled. r=allstars.chh (f1d0b8d5b0)
- Bug 1216822 - Make sure that using an invalid Content-Type when constructing a Response object doesn't throw; r=bkelly (232af6f665)
- Bug 1227030 - Change log module to LazyLogModule with a more self-explantory name. r=seanlin (17f85691fb)
- Bug 1225873 - micro-optimize creating event target chains; r=smaug (a38d507a61)
- Bug 1194525 - Gecko should ignore |postResult| calls for WebActivities with no returnValue. r=fabrice,sicking (1549718723)
- Bug 1174071 - Remove 'required' keyword for Bluetooth*EventInit dictionary members. r=btian, r=bz (f8c02ed9e3)
- Bug 1181483: Implement GATT server characteristic notification; r=jocelyn, r=mrbkap (d5170b650e)
- Bug 1215525: Replace strings with Bluetooth addresses and UUIDs in GATT mid-layer, r=joliu (5949fa2a39)
- Bug 1223720: Support UUIDs and addresses for Bluetooth signal paths, r=joliu (1d98490eac)
- Bug 1217778 - Ensure sBluetoothGattService is not null before accessing GattInterface in GattManager. r=jocelyn (40c4cde2b3)
- Bug 1146355: Update Bluetooth backend interface for bluetooth2, r=brsun (f384d2f1dc)
- Bug 1211948: Introduce |enum BluetoothSetupServiceId|, r=brsun (2c96581c45)
- fix (3de8d6c033)
- Bug 1211948: Register Bluetooth GATT module in GATT manager, r=joliu (491d1e0408)
- Bug 1209469: Expose |BluetoothPropertyType| in Bluetooth backend interface, r=brsun (027a57df73)
- Bug 1209469: Replace |BluetoothNamedValue| with |BluetoothProperty| in Bluetooth backend, r=brsun (c14311d277)
- Bug 1207649: Convert Bluetooth AVRCP backend to |BluetoothAddress|, r=shuang (0acc2e7f51)
- Bug 1223806: Add Bluetooth Core interface, notification and result handler, r=btian (d6ca2c4beb)
- Bug 1209085: Replace simple init ops by |UnpackInitOp| in Bluetooth Core backend, r=joliu (a37e6cc579)
- Bug 1223806: Convert Bluetooth to |BluetoothCoreNotificationHandler|, r=btian (a85b9302f5)
- Bug 1220121: Convert IPDL of Bluetooth Core API to |BluetoothAddress|, r=brsun (d105f3eab0)
- Bug 1220121: Convert IPDL of Bluetooth Core API to |BluetoothPinCode|, r=brsun (c3a2b4f30a)
- Bug 1220121: Convert IPDL of Bluetooth OPP API to |BluetoothAddress|, r=btian (560c056efc)
- Bug 1220121: Convert IPDL of Bluetooth AVRCP API to |ControlPlayStatus|, r=shuang (0aaac4c9c8)
- Bug 1215525: Use strong typing in Bluetooth GATT mid-layer interfaces, r=joliu (7ad219094f)
- Bug 1223806: Convert Bluetooth to |BluetoothCoreResultHandler|, r=btian (e2c96b7f90)
- Bug 1220121: Convert IPDL of Bluetooth GATT API to |BluetoothAddress|, r=joliu (a426ffd63d)
- Bug 1220121: Convert IPDL of Bluetooth GATT API to |BluetoothUuid|, r=joliu (2343063b18)
- Bug 1225787: Fix wrong arguments of BluetoothGattInterface::AddCharacteristic; r=jocelyn (b19bb89fb3)
- Bug 1228519 - Fix RequestReadNotification for GATT Server API. r=brsun (25cc876d88)
- Bug 1225785: Fix WriteRequested mismatch; r=jocelyn (89d9b243a3)
- Bug 1223806: Add |BluetoothDaemonCoreInterface|, r=btian (c6b2cd9fba)
- Bug 1220121: Prepare IPDL support for additional Bluetooth types, r=brsun (8cb996570b)
- Bug 1211948: Register Bluetooth Handsfree module in Handsfree manager, r=btian (af91aa226d)
- Bug 1211435: Rename some internal classes of Bluetooth's A2DP manager, r=shuang (e834e2ee87)
- Bug 1211948: Register Bluetooth A2DP module in A2DP manager, r=brsun (f9fcb0115f)
- Bug 1211435: Rename some internal classes of Bluetooth's AVRCP manager, r=shuang (15a23ffe31)
- Bug 1211948: Register Bluetooth AVRCP module in AVRCP manager, r=brsun (68e51afcca)
- Bug 1223806: Convert Bluetooth to |BluetoothCoreInterface|, r=btian (7bff6267e1)
- Bug 1186840 - [MAP] Implement MessageUpdate function, r=btian (6439c7497b)
- Bug 1207998 - Convert nsCString to nsString for BluetoothVCardListingEvent.mSearchValue, r=shuang (37effbf4d2)
- cleanup (721fb92ec3)
- fix misspatch (5e94030fcd)
- Bug 1230066 - Add missing STATUS_AUTH_REJECTED into enum BluetoothStatus,r=tzimmermann (17b45140a5)
- Bug 1225340 - Refine nullity check macros in BluetoothServiceBluedroid, r=tzimmermann (5175c6eacf)
- Bug 1227440 - Reject pin reply by cancelling bond to trigger BondStateChangedNotification, in order to inform gaia setting app, r=shuang (772401f943)
- Bug 1209085: Replace simple init ops by |UnpackPDUInitOp| in Bluetooth GATT backend, r=joliu (392d81748c)
- Bug 1229290 - Pack/unpack UUIDs in a reverse order when adding characteristics and descriptors in GATT server API. r=brsun (850fb0eeb9)
- Bug 1197815: Add missing |BluetoothHfpManager::IsNrecEnabled|, r=shuang (968089bef0)
- Bug 1216179: Fix broken interface of fall-back Bluetooth HFP manager, r=btian (13b602a861)
- Bug 1166469 - Add HandleBackendError for hfp-fallback product, r=btian (309dd1a92b)
- Bug 1224240 - fix memory leak in Bluetooth*Manager::CompareHeaderTarget; r=btian (c6cfc95bac)
- Bug 1224166: Build BluetoothCommon.cpp unconditionally, r=shuang (8efa02b83d)
- Bug 1209085: Replace trivial init ops by |UnpackPDUInitOP| in Bluetooth A2DP backend, r=joliu (4ccaab6bd6)
- Bug 1142408 - Add data length parameter for Register Notification Response Command. r=tzimmermann (28706dcc16)
- Bug 1228521 - Fix PDU packing in |ServerSendResponseCmd| for GATT Server API. r=brsun (290c3739c3)
- Bug 1209085: Replace trivial init ops by |UnpackPDUInitOp| in Bluetooth AVRCP backend, r=joliu (639f5b6143)
- Bug 1199653 - Correctly set |sInShutdown| in BluetoothService for content processes. f=tzimmermann, r=shuang (5fed461709)
- Bug 1224166: Define Bluetooth debug flag in BluetoothCommon.cpp, r=shuang (9602455405)
2023-05-18 10:38:44 +08:00

953 lines
29 KiB
C++

/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "BluetoothGattServer.h"
#include "BluetoothReplyRunnable.h"
#include "BluetoothService.h"
#include "BluetoothUtils.h"
#include "mozilla/dom/BluetoothStatusChangedEvent.h"
#include "mozilla/dom/bluetooth/BluetoothGattAttributeEvent.h"
#include "mozilla/dom/bluetooth/BluetoothGattCharacteristic.h"
#include "mozilla/dom/bluetooth/BluetoothGattService.h"
#include "mozilla/dom/Promise.h"
using namespace mozilla;
using namespace mozilla::dom;
USING_BLUETOOTH_NAMESPACE
NS_IMPL_CYCLE_COLLECTION_CLASS(BluetoothGattServer)
NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(BluetoothGattServer,
DOMEventTargetHelper)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mOwner)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mServices)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mPendingService)
/**
* Unregister the bluetooth signal handler after unlinked.
*
* This is needed to avoid ending up with exposing a deleted object to JS or
* accessing deleted objects while receiving signals from parent process
* after unlinked. Please see Bug 1138267 for detail informations.
*/
UnregisterBluetoothSignalHandler(tmp->mAppUuid, tmp);
NS_IMPL_CYCLE_COLLECTION_UNLINK_END
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(BluetoothGattServer,
DOMEventTargetHelper)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mOwner)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mServices)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mPendingService)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(BluetoothGattServer)
NS_INTERFACE_MAP_END_INHERITING(DOMEventTargetHelper)
NS_IMPL_ADDREF_INHERITED(BluetoothGattServer, DOMEventTargetHelper)
NS_IMPL_RELEASE_INHERITED(BluetoothGattServer, DOMEventTargetHelper)
BluetoothGattServer::BluetoothGattServer(nsPIDOMWindow* aOwner)
: mOwner(aOwner)
, mServerIf(0)
, mValid(true)
{
if (NS_SUCCEEDED(GenerateUuid(mAppUuid)) && !mAppUuid.IsEmpty()) {
RegisterBluetoothSignalHandler(mAppUuid, this);
}
if (!mSignalRegistered) {
Invalidate();
}
}
BluetoothGattServer::~BluetoothGattServer()
{
Invalidate();
}
void BluetoothGattServer::HandleServerRegistered(const BluetoothValue& aValue)
{
MOZ_ASSERT(aValue.type() == BluetoothValue::Tuint32_t);
mServerIf = aValue.get_uint32_t();
}
void BluetoothGattServer::HandleServerUnregistered(const BluetoothValue& aValue)
{
mServerIf = 0;
}
void BluetoothGattServer::HandleConnectionStateChanged(
const BluetoothValue& aValue)
{
MOZ_ASSERT(aValue.type() == BluetoothValue::TArrayOfBluetoothNamedValue);
const InfallibleTArray<BluetoothNamedValue>& arr =
aValue.get_ArrayOfBluetoothNamedValue();
MOZ_ASSERT(arr.Length() == 2 &&
arr[0].value().type() == BluetoothValue::Tbool &&
arr[1].value().type() == BluetoothValue::TnsString);
BluetoothStatusChangedEventInit init;
init.mStatus = arr[0].value().get_bool();
init.mAddress = arr[1].value().get_nsString();
RefPtr<BluetoothStatusChangedEvent> event =
BluetoothStatusChangedEvent::Constructor(
this, NS_LITERAL_STRING(GATT_CONNECTION_STATE_CHANGED_ID), init);
DispatchTrustedEvent(event);
}
void
BluetoothGattServer::HandleServiceHandleUpdated(const BluetoothValue& aValue)
{
MOZ_ASSERT(aValue.type() == BluetoothValue::TArrayOfBluetoothNamedValue);
const InfallibleTArray<BluetoothNamedValue>& arr =
aValue.get_ArrayOfBluetoothNamedValue();
MOZ_ASSERT(arr.Length() == 2 &&
arr[0].value().type() == BluetoothValue::TBluetoothGattServiceId &&
arr[1].value().type() == BluetoothValue::TBluetoothAttributeHandle);
BluetoothGattServiceId serviceId =
arr[0].value().get_BluetoothGattServiceId();
BluetoothAttributeHandle serviceHandle =
arr[1].value().get_BluetoothAttributeHandle();
NS_ENSURE_TRUE_VOID(mPendingService);
NS_ENSURE_TRUE_VOID(mPendingService->GetServiceId() == serviceId);
mPendingService->AssignServiceHandle(serviceHandle);
}
void
BluetoothGattServer::HandleCharacteristicHandleUpdated(
const BluetoothValue& aValue)
{
MOZ_ASSERT(aValue.type() == BluetoothValue::TArrayOfBluetoothNamedValue);
const InfallibleTArray<BluetoothNamedValue>& arr =
aValue.get_ArrayOfBluetoothNamedValue();
MOZ_ASSERT(arr.Length() == 3 &&
arr[0].value().type() == BluetoothValue::TBluetoothUuid &&
arr[1].value().type() == BluetoothValue::TBluetoothAttributeHandle &&
arr[2].value().type() == BluetoothValue::TBluetoothAttributeHandle);
BluetoothUuid characteristicUuid =
arr[0].value().get_BluetoothUuid();
BluetoothAttributeHandle serviceHandle =
arr[1].value().get_BluetoothAttributeHandle();
BluetoothAttributeHandle characteristicHandle =
arr[2].value().get_BluetoothAttributeHandle();
NS_ENSURE_TRUE_VOID(mPendingService);
NS_ENSURE_TRUE_VOID(mPendingService->GetServiceHandle() == serviceHandle);
mPendingService->AssignCharacteristicHandle(characteristicUuid,
characteristicHandle);
}
void
BluetoothGattServer::HandleDescriptorHandleUpdated(
const BluetoothValue& aValue)
{
MOZ_ASSERT(aValue.type() == BluetoothValue::TArrayOfBluetoothNamedValue);
const InfallibleTArray<BluetoothNamedValue>& arr =
aValue.get_ArrayOfBluetoothNamedValue();
MOZ_ASSERT(arr.Length() == 4 &&
arr[0].value().type() == BluetoothValue::TBluetoothUuid &&
arr[1].value().type() == BluetoothValue::TBluetoothAttributeHandle &&
arr[2].value().type() == BluetoothValue::TBluetoothAttributeHandle &&
arr[3].value().type() == BluetoothValue::TBluetoothAttributeHandle);
BluetoothUuid descriptorUuid =
arr[0].value().get_BluetoothUuid();
BluetoothAttributeHandle serviceHandle =
arr[1].value().get_BluetoothAttributeHandle();
BluetoothAttributeHandle characteristicHandle =
arr[2].value().get_BluetoothAttributeHandle();
BluetoothAttributeHandle descriptorHandle =
arr[3].value().get_BluetoothAttributeHandle();
NS_ENSURE_TRUE_VOID(mPendingService);
NS_ENSURE_TRUE_VOID(mPendingService->GetServiceHandle() == serviceHandle);
mPendingService->AssignDescriptorHandle(descriptorUuid,
characteristicHandle,
descriptorHandle);
}
void
BluetoothGattServer::HandleReadWriteRequest(const BluetoothValue& aValue,
const nsAString& aEventName)
{
MOZ_ASSERT(aValue.type() == BluetoothValue::TArrayOfBluetoothNamedValue);
const InfallibleTArray<BluetoothNamedValue>& arr =
aValue.get_ArrayOfBluetoothNamedValue();
MOZ_ASSERT(arr.Length() == 5 &&
arr[0].value().type() == BluetoothValue::Tint32_t &&
arr[1].value().type() == BluetoothValue::TBluetoothAttributeHandle &&
arr[2].value().type() == BluetoothValue::TnsString &&
arr[3].value().type() == BluetoothValue::Tbool &&
arr[4].value().type() == BluetoothValue::TArrayOfuint8_t);
int32_t requestId = arr[0].value().get_int32_t();
BluetoothAttributeHandle handle =
arr[1].value().get_BluetoothAttributeHandle();
nsString address = arr[2].value().get_nsString();
bool needResponse = arr[3].value().get_bool();
nsTArray<uint8_t> value;
value = arr[4].value().get_ArrayOfuint8_t();
// Find the target characteristic or descriptor from the given handle
RefPtr<BluetoothGattCharacteristic> characteristic = nullptr;
RefPtr<BluetoothGattDescriptor> descriptor = nullptr;
for (uint32_t i = 0; i < mServices.Length(); i++) {
for (uint32_t j = 0; j < mServices[i]->mCharacteristics.Length(); j++) {
RefPtr<BluetoothGattCharacteristic> currentChar =
mServices[i]->mCharacteristics[j];
if (handle == currentChar->GetCharacteristicHandle()) {
characteristic = currentChar;
break;
}
size_t index = currentChar->mDescriptors.IndexOf(handle);
if (index != currentChar->mDescriptors.NoIndex) {
descriptor = currentChar->mDescriptors[index];
break;
}
}
}
if (!(characteristic || descriptor)) {
BT_WARNING("Wrong handle: no matched characteristic or descriptor");
return;
}
// Save the request information for sending the response later
RequestData data(handle,
characteristic,
descriptor);
mRequestMap.Put(requestId, &data);
RefPtr<BluetoothGattAttributeEvent> event =
BluetoothGattAttributeEvent::Constructor(
this, aEventName, address, requestId, characteristic, descriptor,
&value, needResponse, false /* Bubble */, false /* Cancelable*/);
DispatchTrustedEvent(event);
}
void
BluetoothGattServer::Notify(const BluetoothSignal& aData)
{
BT_LOGD("[GattServer] %s", NS_ConvertUTF16toUTF8(aData.name()).get());
NS_ENSURE_TRUE_VOID(mSignalRegistered);
BluetoothValue v = aData.value();
if (aData.name().EqualsLiteral("ServerRegistered")) {
HandleServerRegistered(v);
} else if (aData.name().EqualsLiteral("ServerUnregistered")) {
HandleServerUnregistered(v);
} else if (aData.name().EqualsLiteral(GATT_CONNECTION_STATE_CHANGED_ID)) {
HandleConnectionStateChanged(v);
} else if (aData.name().EqualsLiteral("ServiceHandleUpdated")) {
HandleServiceHandleUpdated(v);
} else if (aData.name().EqualsLiteral("CharacteristicHandleUpdated")) {
HandleCharacteristicHandleUpdated(v);
} else if (aData.name().EqualsLiteral("DescriptorHandleUpdated")) {
HandleDescriptorHandleUpdated(v);
} else if (aData.name().EqualsLiteral("ReadRequested")) {
HandleReadWriteRequest(v, NS_LITERAL_STRING(ATTRIBUTE_READ_REQUEST));
} else if (aData.name().EqualsLiteral("WriteRequested")) {
HandleReadWriteRequest(v, NS_LITERAL_STRING(ATTRIBUTE_WRITE_REQUEST));
} else {
BT_WARNING("Not handling GATT signal: %s",
NS_ConvertUTF16toUTF8(aData.name()).get());
}
}
JSObject*
BluetoothGattServer::WrapObject(JSContext* aContext,
JS::Handle<JSObject*> aGivenProto)
{
return BluetoothGattServerBinding::Wrap(aContext, this, aGivenProto);
}
void
BluetoothGattServer::DisconnectFromOwner()
{
DOMEventTargetHelper::DisconnectFromOwner();
Invalidate();
}
void
BluetoothGattServer::Invalidate()
{
mValid = false;
mPendingService = nullptr;
mServices.Clear();
mRequestMap.Clear();
BluetoothService* bs = BluetoothService::Get();
NS_ENSURE_TRUE_VOID(bs);
if (mServerIf > 0) {
bs->UnregisterGattServerInternal(mServerIf,
new BluetoothVoidReplyRunnable(nullptr,
nullptr));
}
if (!mAppUuid.IsEmpty() && mSignalRegistered) {
UnregisterBluetoothSignalHandler(mAppUuid, this);
}
}
already_AddRefed<Promise>
BluetoothGattServer::Connect(const nsAString& aAddress, ErrorResult& aRv)
{
nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(GetParentObject());
if (!global) {
aRv.Throw(NS_ERROR_FAILURE);
return nullptr;
}
RefPtr<Promise> promise = Promise::Create(global, aRv);
NS_ENSURE_TRUE(!aRv.Failed(), nullptr);
BluetoothUuid appUuid;
BT_ENSURE_TRUE_REJECT(NS_SUCCEEDED(StringToUuid(mAppUuid, appUuid)),
promise,
NS_ERROR_DOM_OPERATION_ERR);
BluetoothAddress address;
BT_ENSURE_TRUE_REJECT(
NS_SUCCEEDED(StringToAddress(aAddress, address)),
promise,
NS_ERROR_INVALID_ARG);
BT_ENSURE_TRUE_REJECT(mValid, promise, NS_ERROR_NOT_AVAILABLE);
BluetoothService* bs = BluetoothService::Get();
BT_ENSURE_TRUE_REJECT(bs, promise, NS_ERROR_NOT_AVAILABLE);
bs->GattServerConnectPeripheralInternal(
appUuid, address, new BluetoothVoidReplyRunnable(nullptr, promise));
return promise.forget();
}
already_AddRefed<Promise>
BluetoothGattServer::Disconnect(const nsAString& aAddress, ErrorResult& aRv)
{
nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(GetParentObject());
if (!global) {
aRv.Throw(NS_ERROR_FAILURE);
return nullptr;
}
RefPtr<Promise> promise = Promise::Create(global, aRv);
NS_ENSURE_TRUE(!aRv.Failed(), nullptr);
BluetoothUuid appUuid;
BT_ENSURE_TRUE_REJECT(NS_SUCCEEDED(StringToUuid(mAppUuid, appUuid)),
promise,
NS_ERROR_DOM_OPERATION_ERR);
BluetoothAddress address;
BT_ENSURE_TRUE_REJECT(
NS_SUCCEEDED(StringToAddress(aAddress, address)),
promise,
NS_ERROR_INVALID_ARG);
BT_ENSURE_TRUE_REJECT(mValid, promise, NS_ERROR_NOT_AVAILABLE);
BluetoothService* bs = BluetoothService::Get();
BT_ENSURE_TRUE_REJECT(bs, promise, NS_ERROR_NOT_AVAILABLE);
bs->GattServerDisconnectPeripheralInternal(
appUuid, address, new BluetoothVoidReplyRunnable(nullptr, promise));
return promise.forget();
}
class BluetoothGattServer::AddIncludedServiceTask final
: public BluetoothReplyTaskQueue::SubTask
{
public:
AddIncludedServiceTask(BluetoothReplyTaskQueue* aRootQueue,
BluetoothGattServer* aServer,
BluetoothGattService* aService,
BluetoothGattService* aIncludedService)
: BluetoothReplyTaskQueue::SubTask(aRootQueue, nullptr)
, mServer(aServer)
, mService(aService)
, mIncludedService(aIncludedService)
{ }
bool Execute() override
{
BluetoothService* bs = BluetoothService::Get();
if (NS_WARN_IF(!bs)) {
return false;
}
BluetoothUuid appUuid;
if (NS_FAILED(StringToUuid(mServer->mAppUuid, appUuid))) {
return false;
}
bs->GattServerAddIncludedServiceInternal(
appUuid,
mService->GetServiceHandle(),
mIncludedService->GetServiceHandle(),
GetReply());
return true;
}
private:
RefPtr<BluetoothGattServer> mServer;
RefPtr<BluetoothGattService> mService;
RefPtr<BluetoothGattService> mIncludedService;
};
class BluetoothGattServer::AddCharacteristicTask final
: public BluetoothReplyTaskQueue::SubTask
{
public:
AddCharacteristicTask(BluetoothReplyTaskQueue* aRootQueue,
BluetoothGattServer* aServer,
BluetoothGattService* aService,
BluetoothGattCharacteristic* aCharacteristic)
: BluetoothReplyTaskQueue::SubTask(aRootQueue, nullptr)
, mServer(aServer)
, mService(aService)
, mCharacteristic(aCharacteristic)
{ }
bool Execute() override
{
BluetoothService* bs = BluetoothService::Get();
if (NS_WARN_IF(!bs)) {
return false;
}
BluetoothUuid appUuid;
if (NS_FAILED(StringToUuid(mServer->mAppUuid, appUuid))) {
return false;
}
BluetoothUuid uuid;
mCharacteristic->GetUuid(uuid);
bs->GattServerAddCharacteristicInternal(
appUuid,
mService->GetServiceHandle(),
uuid,
mCharacteristic->GetPermissions(),
mCharacteristic->GetProperties(),
GetReply());
return true;
}
private:
RefPtr<BluetoothGattServer> mServer;
RefPtr<BluetoothGattService> mService;
RefPtr<BluetoothGattCharacteristic> mCharacteristic;
};
class BluetoothGattServer::AddDescriptorTask final
: public BluetoothReplyTaskQueue::SubTask
{
public:
AddDescriptorTask(BluetoothReplyTaskQueue* aRootQueue,
BluetoothGattServer* aServer,
BluetoothGattService* aService,
BluetoothGattCharacteristic* aCharacteristic,
BluetoothGattDescriptor* aDescriptor)
: BluetoothReplyTaskQueue::SubTask(aRootQueue, nullptr)
, mServer(aServer)
, mService(aService)
, mCharacteristic(aCharacteristic)
, mDescriptor(aDescriptor)
{ }
bool Execute() override
{
BluetoothService* bs = BluetoothService::Get();
if (NS_WARN_IF(!bs)) {
return false;
}
BluetoothUuid appUuid;
if (NS_FAILED(StringToUuid(mServer->mAppUuid, appUuid))) {
return false;
}
BluetoothUuid uuid;
mDescriptor->GetUuid(uuid);
bs->GattServerAddDescriptorInternal(
appUuid,
mService->GetServiceHandle(),
mCharacteristic->GetCharacteristicHandle(),
uuid,
mDescriptor->GetPermissions(),
GetReply());
return true;
}
private:
RefPtr<BluetoothGattServer> mServer;
RefPtr<BluetoothGattService> mService;
RefPtr<BluetoothGattCharacteristic> mCharacteristic;
RefPtr<BluetoothGattDescriptor> mDescriptor;
};
class BluetoothGattServer::StartServiceTask final
: public BluetoothReplyTaskQueue::SubTask
{
public:
StartServiceTask(BluetoothReplyTaskQueue* aRootQueue,
BluetoothGattServer* aServer,
BluetoothGattService* aService)
: BluetoothReplyTaskQueue::SubTask(aRootQueue, nullptr)
, mServer(aServer)
, mService(aService)
{ }
bool Execute() override
{
BluetoothService* bs = BluetoothService::Get();
if (NS_WARN_IF(!bs)) {
return false;
}
BluetoothUuid appUuid;
if (NS_FAILED(StringToUuid(mServer->mAppUuid, appUuid))) {
return false;
}
bs->GattServerStartServiceInternal(
appUuid,
mService->GetServiceHandle(),
GetReply());
return true;
}
private:
RefPtr<BluetoothGattServer> mServer;
RefPtr<BluetoothGattService> mService;
};
/*
* CancelAddServiceTask is used when failing to completely add a service. No
* matter CancelAddServiceTask executes successfully or not, the promose should
* be rejected because we fail to adding the service eventually.
*/
class BluetoothGattServer::CancelAddServiceTask final
: public BluetoothVoidReplyRunnable
{
public:
CancelAddServiceTask(BluetoothGattServer* aServer,
BluetoothGattService* aService,
Promise* aPromise)
: BluetoothVoidReplyRunnable(nullptr, nullptr)
/* aPromise is not managed by BluetoothVoidReplyRunnable. It would be
* rejected after this task has been executed anyway. */
, mServer(aServer)
, mService(aService)
, mPromise(aPromise)
{
MOZ_ASSERT(mPromise);
}
void ReleaseMembers() override
{
BluetoothVoidReplyRunnable::ReleaseMembers();
mServer = nullptr;
mService = nullptr;
mPromise = nullptr;
}
private:
void OnSuccessFired() override
{
mServer->mPendingService = nullptr;
mPromise->MaybeReject(NS_ERROR_FAILURE);
}
void OnErrorFired() override
{
mServer->mPendingService = nullptr;
mPromise->MaybeReject(NS_ERROR_FAILURE);
}
RefPtr<BluetoothGattServer> mServer;
RefPtr<BluetoothGattService> mService;
RefPtr<Promise> mPromise;
};
class BluetoothGattServer::AddServiceTaskQueue final
: public BluetoothReplyTaskQueue
{
public:
AddServiceTaskQueue(BluetoothGattServer* aServer,
BluetoothGattService* aService,
Promise* aPromise)
: BluetoothReplyTaskQueue(nullptr)
, mServer(aServer)
, mService(aService)
, mPromise(aPromise)
{
/* add included services */
nsTArray<RefPtr<BluetoothGattService>> includedServices;
mService->GetIncludedServices(includedServices);
for (size_t i = 0; i < includedServices.Length(); ++i) {
RefPtr<SubTask> includedServiceTask =
new AddIncludedServiceTask(this, mServer, mService, includedServices[i]);
AppendTask(includedServiceTask.forget());
}
/* add characteristics */
nsTArray<RefPtr<BluetoothGattCharacteristic>> characteristics;
mService->GetCharacteristics(characteristics);
for (size_t i = 0; i < characteristics.Length(); ++i) {
RefPtr<SubTask> characteristicTask =
new AddCharacteristicTask(this, mServer, mService, characteristics[i]);
AppendTask(characteristicTask.forget());
/* add descriptors */
nsTArray<RefPtr<BluetoothGattDescriptor>> descriptors;
characteristics[i]->GetDescriptors(descriptors);
for (size_t j = 0; j < descriptors.Length(); ++j) {
RefPtr<SubTask> descriptorTask =
new AddDescriptorTask(this,
mServer,
mService,
characteristics[i],
descriptors[j]);
AppendTask(descriptorTask.forget());
}
}
/* start service */
RefPtr<SubTask> startTask = new StartServiceTask(this, mServer, mService);
AppendTask(startTask.forget());
}
protected:
virtual ~AddServiceTaskQueue()
{ }
private:
void OnSuccessFired() override
{
mServer->mPendingService = nullptr;
mServer->mServices.AppendElement(mService);
mPromise->MaybeResolve(JS::UndefinedHandleValue);
}
void OnErrorFired() override
{
BluetoothService* bs = BluetoothService::Get();
BT_ENSURE_TRUE_REJECT_VOID(bs, mPromise, NS_ERROR_NOT_AVAILABLE);
BluetoothUuid appUuid;
BT_ENSURE_TRUE_REJECT_VOID(NS_SUCCEEDED(StringToUuid(mServer->mAppUuid,
appUuid)),
mPromise,
NS_ERROR_DOM_OPERATION_ERR);
bs->GattServerRemoveServiceInternal(
appUuid,
mService->GetServiceHandle(),
new CancelAddServiceTask(mServer, mService, mPromise));
}
RefPtr<BluetoothGattServer> mServer;
RefPtr<BluetoothGattService> mService;
RefPtr<Promise> mPromise;
};
class BluetoothGattServer::AddServiceTask final
: public BluetoothVoidReplyRunnable
{
public:
AddServiceTask(BluetoothGattServer* aServer,
BluetoothGattService* aService,
Promise* aPromise)
: BluetoothVoidReplyRunnable(nullptr, nullptr)
/* aPromise is not managed by BluetoothVoidReplyRunnable. It would be
* passed to other tasks after this task executes successfully. */
, mServer(aServer)
, mService(aService)
, mPromise(aPromise)
{
MOZ_ASSERT(mServer);
MOZ_ASSERT(mService);
MOZ_ASSERT(mPromise);
}
void ReleaseMembers() override
{
BluetoothReplyRunnable::ReleaseMembers();
mServer = nullptr;
mService = nullptr;
mPromise = nullptr;
}
private:
virtual void OnSuccessFired() override
{
mService->AssignAppUuid(mServer->mAppUuid);
RefPtr<nsRunnable> runnable = new AddServiceTaskQueue(mServer,
mService,
mPromise);
nsresult rv = NS_DispatchToMainThread(runnable.forget());
if (NS_WARN_IF(NS_FAILED(rv))) {
mServer->mPendingService = nullptr;
mPromise->MaybeReject(NS_ERROR_NOT_AVAILABLE);
}
}
virtual void OnErrorFired() override
{
mServer->mPendingService = nullptr;
mPromise->MaybeReject(NS_ERROR_NOT_AVAILABLE);
}
RefPtr<BluetoothGattServer> mServer;
RefPtr<BluetoothGattService> mService;
RefPtr<Promise> mPromise;
};
already_AddRefed<Promise>
BluetoothGattServer::AddService(BluetoothGattService& aService,
ErrorResult& aRv)
{
nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(GetParentObject());
if (!global) {
aRv.Throw(NS_ERROR_FAILURE);
return nullptr;
}
RefPtr<Promise> promise = Promise::Create(global, aRv);
NS_ENSURE_TRUE(!aRv.Failed(), nullptr);
BT_ENSURE_TRUE_REJECT(mValid, promise, NS_ERROR_NOT_AVAILABLE);
BT_ENSURE_TRUE_REJECT(!aService.IsActivated(),
promise,
NS_ERROR_INVALID_ARG);
BluetoothService* bs = BluetoothService::Get();
BT_ENSURE_TRUE_REJECT(bs, promise, NS_ERROR_NOT_AVAILABLE);
mPendingService = &aService;
BluetoothUuid appUuid;
if (NS_FAILED(StringToUuid(mAppUuid, appUuid))) {
return false;
}
bs->GattServerAddServiceInternal(appUuid,
mPendingService->GetServiceId(),
mPendingService->GetHandleCount(),
new AddServiceTask(this,
mPendingService,
promise));
return promise.forget();
}
class BluetoothGattServer::RemoveServiceTask final
: public BluetoothReplyRunnable
{
public:
RemoveServiceTask(BluetoothGattServer* aServer,
BluetoothGattService* aService,
Promise* aPromise)
: BluetoothReplyRunnable(nullptr, aPromise)
, mServer(aServer)
, mService(aService)
{
MOZ_ASSERT(mServer);
MOZ_ASSERT(mService);
}
void ReleaseMembers() override
{
BluetoothReplyRunnable::ReleaseMembers();
mServer = nullptr;
mService = nullptr;
}
protected:
bool ParseSuccessfulReply(JS::MutableHandle<JS::Value> aValue) override
{
aValue.setUndefined();
mServer->mServices.RemoveElement(mService);
return true;
}
private:
RefPtr<BluetoothGattServer> mServer;
RefPtr<BluetoothGattService> mService;
};
already_AddRefed<Promise>
BluetoothGattServer::RemoveService(BluetoothGattService& aService,
ErrorResult& aRv)
{
nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(GetParentObject());
if (!global) {
aRv.Throw(NS_ERROR_FAILURE);
return nullptr;
}
RefPtr<Promise> promise = Promise::Create(global, aRv);
NS_ENSURE_TRUE(!aRv.Failed(), nullptr);
BT_ENSURE_TRUE_REJECT(mValid, promise, NS_ERROR_NOT_AVAILABLE);
BT_ENSURE_TRUE_REJECT(mServices.Contains(&aService),
promise,
NS_ERROR_INVALID_ARG);
BluetoothService* bs = BluetoothService::Get();
BT_ENSURE_TRUE_REJECT(bs, promise, NS_ERROR_NOT_AVAILABLE);
BluetoothUuid appUuid;
BT_ENSURE_TRUE_REJECT(NS_SUCCEEDED(StringToUuid(mAppUuid, appUuid)),
promise,
NS_ERROR_DOM_OPERATION_ERR);
bs->GattServerRemoveServiceInternal(
appUuid, aService.GetServiceHandle(), new RemoveServiceTask(this,
&aService,
promise));
return promise.forget();
}
already_AddRefed<Promise>
BluetoothGattServer::NotifyCharacteristicChanged(
const nsAString& aAddress,
BluetoothGattCharacteristic& aCharacteristic,
bool aConfirm,
ErrorResult& aRv)
{
nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(GetParentObject());
if (!global) {
aRv.Throw(NS_ERROR_FAILURE);
return nullptr;
}
RefPtr<Promise> promise = Promise::Create(global, aRv);
NS_ENSURE_TRUE(!aRv.Failed(), nullptr);
BT_ENSURE_TRUE_REJECT(mValid, promise, NS_ERROR_NOT_AVAILABLE);
BluetoothUuid appUuid;
BT_ENSURE_TRUE_REJECT(NS_SUCCEEDED(StringToUuid(mAppUuid, appUuid)),
promise,
NS_ERROR_DOM_OPERATION_ERR);
BluetoothAddress address;
BT_ENSURE_TRUE_REJECT(
NS_SUCCEEDED(StringToAddress(aAddress, address)),
promise,
NS_ERROR_INVALID_ARG);
BluetoothService* bs = BluetoothService::Get();
BT_ENSURE_TRUE_REJECT(bs, promise, NS_ERROR_NOT_AVAILABLE);
RefPtr<BluetoothGattService> service = aCharacteristic.Service();
BT_ENSURE_TRUE_REJECT(service, promise, NS_ERROR_NOT_AVAILABLE);
BT_ENSURE_TRUE_REJECT(mServices.Contains(service),
promise,
NS_ERROR_NOT_AVAILABLE);
bs->GattServerSendIndicationInternal(
appUuid, address, aCharacteristic.GetCharacteristicHandle(), aConfirm,
aCharacteristic.GetValue(),
new BluetoothVoidReplyRunnable(nullptr, promise));
return promise.forget();
}
already_AddRefed<Promise>
BluetoothGattServer::SendResponse(const nsAString& aAddress,
uint16_t aStatus,
int32_t aRequestId,
ErrorResult& aRv)
{
nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(GetParentObject());
if (!global) {
aRv.Throw(NS_ERROR_FAILURE);
return nullptr;
}
RefPtr<Promise> promise = Promise::Create(global, aRv);
NS_ENSURE_TRUE(!aRv.Failed(), nullptr);
BluetoothUuid appUuid;
BT_ENSURE_TRUE_REJECT(NS_SUCCEEDED(StringToUuid(mAppUuid, appUuid)),
promise,
NS_ERROR_DOM_OPERATION_ERR);
BluetoothAddress address;
BT_ENSURE_TRUE_REJECT(
NS_SUCCEEDED(StringToAddress(aAddress, address)),
promise,
NS_ERROR_INVALID_ARG);
BT_ENSURE_TRUE_REJECT(mValid, promise, NS_ERROR_NOT_AVAILABLE);
RequestData* requestData;
mRequestMap.Get(aRequestId, &requestData);
BT_ENSURE_TRUE_REJECT(requestData, promise, NS_ERROR_UNEXPECTED);
BluetoothGattResponse response;
memset(&response, 0, sizeof(response));
response.mHandle = requestData->mHandle;
if (requestData->mCharacteristic) {
const nsTArray<uint8_t>& value = requestData->mCharacteristic->GetValue();
response.mLength = value.Length();
memcpy(&response.mValue, value.Elements(), response.mLength);
} else if (requestData->mDescriptor) {
const nsTArray<uint8_t>& value = requestData->mDescriptor->GetValue();
response.mLength = value.Length();
memcpy(&response.mValue, value.Elements(), response.mLength);
} else {
MOZ_ASSERT_UNREACHABLE(
"There should be at least one characteristic or descriptor in the "
"request data.");
promise->MaybeReject(NS_ERROR_INVALID_ARG);
return promise.forget();
}
BluetoothService* bs = BluetoothService::Get();
BT_ENSURE_TRUE_REJECT(bs, promise, NS_ERROR_NOT_AVAILABLE);
bs->GattServerSendResponseInternal(
appUuid,
address,
aStatus,
aRequestId,
response,
new BluetoothVoidReplyRunnable(nullptr, promise));
return promise.forget();
}