Files
palemoon27/dom/bluetooth/common/webapi/BluetoothGattServer.cpp
T
roytam1 3f625686df import changes from `dev' branch of rmottola/Arctic-Fox:
- Bug 1157064 - implementation of font-display. r=heycam,khuey (43fe566f45)
- Bug 1235186 - fix small userfont logging nit. r=m_kato (d40bead913)
- Bug 1188802 - only rebuild local webfont rules when needed. r=heycam (f74200aeb2)
- Backout unrelated code landed in dee3e26cc1c0 by mistake. (5d254b78b6)
- Bug 1236506: Add support for "-webkit-filter" as an alias for CSS property "filter". r=heycam (1e7ac6554a)
- Bug 1230426 - Remove support for -webkit-border-image longhand CSS property aliases. r=dholbert (a1a2d5e82a)
- Bug 1246101 - Restore some auto-completion for the align-/justify-* properties. r=dholbert (a33dd2e7c2)
- Bug 1195142 patch 1 - Set CSS_PROPERTY_CREATES_STACKING_CONTEXT for the opacity property. r=BenWa (e547f7b420)
- Bug 1195142 patch 2 - Add reftests for will-change creating a stacking context. r=BenWa (3bb9dc17b9)
- Bug 1195142 patch 3 - Link to correct specification URLs so the CSSWG test suite system is happy. (a8121cdcf0)
- Bug 1234966 - nsStylePosition::MaxDifference should include nsChangeHint_NeutralChange because CalcDiffrence returns it. r=heycam (aa0bf89e54)
- Bug 1244166: Don't ignore stroke/fill properties in high-contrast mode, since doing so can produce icons that are invisible or whose colors are unrelated to the user's chosen high-contrast colors. r=longsonr (6448b05118)
- Bug 1157057 - Rewrite the handling of the nsITimer object in nrappkitTimerCallback; r=ekr (7cc88409b0)
- Bug 1117984: added proxy connection state enum. r=bwc (0c643ff34a)
- Bug 1231971 - Refactor the NAT simulator to use e10s sockets when appropriate. r=drno (c0722c431b)
- Bug 1231973 - Allow NAT simulator to be enabled with the pref system. r=drno (c92ca4fefa)
- Bug 1201209 - Extend the timeout on socket readiness in test_nr_socket_unittest. r=drno (e9e5400902)
- Bug 1216815 - fix memory leaks in test TCP STUN server. r=mjf (11219f41fc)
- Bug 1194385 - Add new unit tests which demonstrate the current behavior. r=bwc (900c621491)
- crashreporte (2ac99868b6)
- Bug 1150966: Check whether |streams_| is null on stats methods in NrIceMediaStream. r=drno (130a9ac2da)
- Bug 1241690: reduce logging output for unconnected PCs. r=bwc (aa236d7184)
- Bug 1224845 - close sockets on errors and don't connect to IPv4 TURN TCP from IPv6 sockets. r=jesup (f128a67692)
- Bug 1189961 - added DNS AAAA convertion to nICEr transport addr. r=bwc (30c14fe7dd)
- Bug 1247536 - Fix -Wunreachable-code warning in media/mtransport/. r=drno (f6768f8539)
- Bug 1194259: nsresult != NS_IMETHODIMP rs=bustage (3a922e6e14)
- Bug 1237909 part 1 - Remove unused TransportLayer::RunOnThread function. r=bwc (d2d219d63a)
- Bug 1237909 part 2 - Do not return value from task for sync dispatch. r=froydnj (c5ec2aecfc)
- Bug 1245035 - Move LOCAL_INCLUDES to moz.build in media/omx-plugin/lib/ics/libvideoeditorplayer. r=mshal (54c363c9f7)
- Bug 1232069 - Check box sizes before alloc&copy. r=jya (86cfe660e7)
- Bug 1234778: Mark all audio frames as keyframes. r=kentuckyfriedtakahe (5e4f1b54d5)
- Bug 1231169 - report rust mp4parse track status in telemetry. r=kinetik,vladan (260d0fed99)
- Bug 1238420 - Update mp4parse-rust invocations in MP4Metadata to match CAPI changes. r=rillian (64c5d6a1ef)
- Bug 1238420 - Report mp4parse-rust errors via Telemetry. r=rillian,vladan (ff72f8dead)
- Bug 1219452 - Update script for rust mp4parser. r=kinetik (9abc268b60)
- Bug 1220754 - Update rust mp4parse import script for v0.1.3. r=kinetik (7185657598)
- Bug 1224785, Part 1 - Implement alert favicons backend. r=wchen (665c44b0cb)
- Bug 1224785, Part 2 - Show the site favicon in OS X notifications. r=mstange (814ff022ba)
- Bug 1224785, Part 3 - Don't include ShowWith{Icon}Backend on Android. r=me (fe323c2960)
- Bug 1243418 - Fix up incorrect 'aOverwrite' usage and impl in GLUploadHelpers r=jgilbert (67677b4921)
- clarify comment (88003aaf96)
- Bug 1204284: Show paper size options in OS X print dialog. r=smichaud (8bb40b4349)
- Bug 1214511 - Show copies, page range selection, and more on the expanded OSX print dialog. r=mstange (301d5cdccc)
- Bug 1216478 - prefer tooltiptext on a XUL element over title attribute on a containing toolbaritem when determining accessible name, r=surkov (ec1dfcad37)
- Bug 1248838 - ARIA owns change may fail, r=yzen (d183be3f3c)
- Bug 1222531 - turn off -Wextra-tokens on clang-cl in accessible/ directories; r=tbsaunde (6dd4dcae20)
- bug 1241453 - add DocAccessibleParent::GetXPCAccessible() r=davidb (f243398399)
- Bug 1087608 - eliminating a pref observer leak and fixing test timeout overflow that cause intermittents. r=eeejay (413354c349)
- Bug 1238368 - Re-introduce workaround for Android tap gesture. r=yzen (04bb9cea5a)
- Bug 1233863 - ARM64: Disable tests that require ion.enable = 1. r=jimb (b268c03c22)
- Bug 1191976 - Intentionally crash if we hit an IPC FatalError in the  parent process. r=billm (b6e9d90d34)
- Bug 1194721: Add |DaemonRunnable8|, r=shuang (0b293cb8a5)
- Bug 1194721: Add PDU_ prefix to daemon PDU constants, r=shuang (834240b14b)
- Bug 1228546 - Implement peripheral mode support for GATT API. r=brsun, r=mrbkap (01a711cac6)
- Bug 1194721: Add helpers for Gonk sensors daemon, r=gsvelto (524d1d6792)
2024-01-02 22:59:35 +08:00

1143 lines
34 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::TBluetoothAddress);
BluetoothStatusChangedEventInit init;
init.mStatus = arr[0].value().get_bool();
AddressToString(arr[1].value().get_BluetoothAddress(), init.mAddress);
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::TBluetoothAddress &&
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;
AddressToString(arr[2].value().get_BluetoothAddress(), address);
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::StartAdvertisingTask final
: public BluetoothVoidReplyRunnable
{
public:
StartAdvertisingTask(BluetoothGattServer* aServer, Promise* aPromise)
: BluetoothVoidReplyRunnable(nullptr, aPromise)
, mServer(aServer)
{
MOZ_ASSERT(aServer);
MOZ_ASSERT(aPromise);
}
virtual void
ReleaseMembers() override
{
BluetoothReplyRunnable::ReleaseMembers();
mServer = nullptr;
}
protected:
virtual void OnErrorFired() override
{
mServer->mAdvertisingAppUuid.Clear();
}
private:
RefPtr<BluetoothGattServer> mServer;
};
class BluetoothGattServer::RegisterServerAndStartAdvertisingTask final
: public BluetoothVoidReplyRunnable
{
public:
RegisterServerAndStartAdvertisingTask(
BluetoothGattServer* aServer,
const BluetoothGattAdvertisingData& aAdvData,
Promise* aPromise)
: BluetoothVoidReplyRunnable(nullptr, nullptr)
/**
* aPromise is not managed by BluetoothVoidReplyRunnable. It would be
* passed to |StartAdvertisingTask| after this one executes successfully.
*/
, mServer(aServer)
, mAdvData(aAdvData)
, mPromise(aPromise)
{
MOZ_ASSERT(mServer);
MOZ_ASSERT(mPromise);
}
void ReleaseMembers() override
{
BluetoothReplyRunnable::ReleaseMembers();
mServer = nullptr;
mPromise = nullptr;
}
private:
virtual void OnSuccessFired() override
{
BluetoothService* bs = BluetoothService::Get();
if (NS_WARN_IF(!bs)) {
mPromise->MaybeReject(NS_ERROR_NOT_AVAILABLE);
}
if (NS_WARN_IF(mServer->mAdvertisingAppUuid.IsCleared())) {
mPromise->MaybeReject(NS_ERROR_DOM_INVALID_STATE_ERR);
}
bs->StartAdvertisingInternal(
mServer->mAdvertisingAppUuid, mAdvData,
new StartAdvertisingTask(mServer, mPromise));
}
virtual void OnErrorFired() override
{
mServer->mAdvertisingAppUuid.Clear();
mPromise->MaybeReject(NS_ERROR_DOM_OPERATION_ERR);
}
RefPtr<BluetoothGattServer> mServer;
BluetoothGattAdvertisingData mAdvData;
RefPtr<Promise> mPromise;
};
already_AddRefed<Promise>
BluetoothGattServer::StartAdvertising(const BluetoothAdvertisingData& aAdvData,
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(mAdvertisingAppUuid.IsCleared(),
promise,
NS_ERROR_DOM_INVALID_STATE_ERR);
nsresult rv = GenerateUuid(mAdvertisingAppUuid);
BT_ENSURE_TRUE_REJECT(NS_SUCCEEDED(rv) && !mAdvertisingAppUuid.IsCleared(),
promise,
NS_ERROR_DOM_OPERATION_ERR);
BluetoothService* bs = BluetoothService::Get();
BT_ENSURE_TRUE_REJECT(bs, promise, NS_ERROR_NOT_AVAILABLE);
BluetoothGattAdvertisingData data;
rv = AdvertisingDataToGattAdvertisingData(aAdvData, data);
BT_ENSURE_TRUE_REJECT(NS_SUCCEEDED(rv), promise, rv);
BluetoothUuid appUuid;
rv = StringToUuid(mAppUuid, appUuid);
BT_ENSURE_TRUE_REJECT(NS_SUCCEEDED(rv), promise, rv);
bs->GattServerRegisterInternal(
appUuid,
new RegisterServerAndStartAdvertisingTask(this, data, promise));
return promise.forget();
}
class BluetoothGattServer::StopAdvertisingTask final
: public BluetoothVoidReplyRunnable
{
public:
StopAdvertisingTask(BluetoothGattServer* aServer, Promise* aPromise)
: BluetoothVoidReplyRunnable(nullptr, aPromise)
, mServer(aServer)
{
MOZ_ASSERT(aPromise);
MOZ_ASSERT(aServer);
}
virtual void
ReleaseMembers() override
{
BluetoothReplyRunnable::ReleaseMembers();
mServer = nullptr;
}
protected:
virtual void OnSuccessFired() override
{
mServer->mAdvertisingAppUuid.Clear();
}
virtual void OnErrorFired() override
{
mServer->mAdvertisingAppUuid.Clear();
}
private:
RefPtr<BluetoothGattServer> mServer;
};
already_AddRefed<Promise>
BluetoothGattServer::StopAdvertising(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);
if (mAdvertisingAppUuid.IsCleared()) {
promise->MaybeResolve(JS::UndefinedHandleValue);
return promise.forget();
}
BluetoothService* bs = BluetoothService::Get();
BT_ENSURE_TRUE_REJECT(bs, promise, NS_ERROR_NOT_AVAILABLE);
bs->StopAdvertisingInternal(mAdvertisingAppUuid,
new StopAdvertisingTask(this, 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();
}