diff --git a/dom/activities/ActivityRequestHandler.js b/dom/activities/ActivityRequestHandler.js index ffe1504eb5..3598652cf4 100644 --- a/dom/activities/ActivityRequestHandler.js +++ b/dom/activities/ActivityRequestHandler.js @@ -36,9 +36,10 @@ ActivityRequestHandler.prototype = { this._window = aWindow; }, - __init: function arh___init(aId, aOptions) { + __init: function arh___init(aId, aOptions, aReturnValue) { this._id = aId; this._options = aOptions; + this._returnValue = aReturnValue; }, get source() { @@ -49,11 +50,16 @@ ActivityRequestHandler.prototype = { }, postResult: function arh_postResult(aResult) { - cpmm.sendAsyncMessage("Activity:PostResult", { - "id": this._id, - "result": aResult - }); - Services.obs.notifyObservers(null, "activity-success", this._id); + if (this._returnValue) { + cpmm.sendAsyncMessage("Activity:PostResult", { + "id": this._id, + "result": aResult + }); + Services.obs.notifyObservers(null, "activity-success", this._id); + } else { + Cu.reportError("postResult() can't be called when 'returnValue': 'true' isn't declared in manifest.webapp"); + throw new Error("postResult() can't be called when 'returnValue': 'true' isn't declared in manifest.webapp"); + } }, postError: function arh_postError(aError) { diff --git a/dom/activities/ActivityWrapper.js b/dom/activities/ActivityWrapper.js index a9e81c428f..34427fddcd 100644 --- a/dom/activities/ActivityWrapper.js +++ b/dom/activities/ActivityWrapper.js @@ -37,7 +37,10 @@ ActivityWrapper.prototype = { // Activity workflow. cpmm.sendAsyncMessage("Activity:Ready", { id: aMessage.id }); - let handler = new aWindow.ActivityRequestHandler(aMessage.id, aMessage.payload); + // Gecko should ignore |postResult| calls for WebActivities with no returnValue + // We need to pass returnValue to ActivityRequestHandler constructor to then properly + // decide if should call postResult or not + let handler = new aWindow.ActivityRequestHandler(aMessage.id, aMessage.payload, aMessage.target.returnValue); // When the activity window is closed, fire an error to notify the activity // caller of the situation. diff --git a/dom/alarm/AlarmHalService.cpp b/dom/alarm/AlarmHalService.cpp index d5eee2fe15..3394c031e7 100644 --- a/dom/alarm/AlarmHalService.cpp +++ b/dom/alarm/AlarmHalService.cpp @@ -22,13 +22,15 @@ AlarmHalService::Init() return; } RegisterSystemTimezoneChangeObserver(this); + RegisterSystemClockChangeObserver(this); } -/* virtual */ AlarmHalService::~AlarmHalService() +/* virtual */ AlarmHalService::~AlarmHalService() { if (mAlarmEnabled) { UnregisterTheOneAlarmObserver(); UnregisterSystemTimezoneChangeObserver(this); + UnregisterSystemClockChangeObserver(this); } } @@ -39,7 +41,7 @@ AlarmHalService::GetInstance() { if (!sSingleton) { sSingleton = new AlarmHalService(); - sSingleton->Init(); + sSingleton->Init(); ClearOnShutdown(&sSingleton); } @@ -77,6 +79,14 @@ AlarmHalService::SetTimezoneChangedCb(nsITimezoneChangedCb* aTimeZoneChangedCb) return NS_OK; } +NS_IMETHODIMP +AlarmHalService::SetSystemClockChangedCb( + nsISystemClockChangedCb* aSystemClockChangedCb) +{ + mSystemClockChangedCb = aSystemClockChangedCb; + return NS_OK; +} + void AlarmHalService::Notify(const void_t& aVoid) { @@ -97,6 +107,15 @@ AlarmHalService::Notify( aSystemTimezoneChangeInfo.newTimezoneOffsetMinutes()); } +void +AlarmHalService::Notify(const int64_t& aClockDeltaMS) +{ + if (!mSystemClockChangedCb) { + return; + } + mSystemClockChangedCb->OnSystemClockChanged(aClockDeltaMS); +} + } // namespace alarm } // namespace dom } // namespace mozilla diff --git a/dom/alarm/AlarmHalService.h b/dom/alarm/AlarmHalService.h index 923f8712e1..dcb62e0ccc 100644 --- a/dom/alarm/AlarmHalService.h +++ b/dom/alarm/AlarmHalService.h @@ -3,7 +3,7 @@ /* 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/. */ - + #ifndef mozilla_dom_alarm_AlarmHalService_h #define mozilla_dom_alarm_AlarmHalService_h @@ -19,13 +19,15 @@ namespace mozilla { namespace dom { namespace alarm { - + typedef Observer AlarmObserver; typedef Observer SystemTimezoneChangeObserver; +typedef Observer SystemClockChangeObserver; -class AlarmHalService : public nsIAlarmHalService, +class AlarmHalService : public nsIAlarmHalService, public AlarmObserver, - public SystemTimezoneChangeObserver + public SystemTimezoneChangeObserver, + public SystemClockChangeObserver { public: NS_DECL_ISUPPORTS @@ -41,6 +43,9 @@ public: // Implementing hal::SystemTimezoneChangeObserver void Notify(const hal::SystemTimezoneChangeInformation& aSystemTimezoneChangeInfo) override; + // Implementing hal::SystemClockChangeObserver + void Notify(const int64_t& aClockDeltaMS) override; + private: virtual ~AlarmHalService(); @@ -49,6 +54,7 @@ private: nsCOMPtr mAlarmFiredCb; nsCOMPtr mTimezoneChangedCb; + nsCOMPtr mSystemClockChangedCb; }; } // namespace alarm diff --git a/dom/alarm/AlarmService.jsm b/dom/alarm/AlarmService.jsm index 2cc80d21ff..7af0a910ec 100644 --- a/dom/alarm/AlarmService.jsm +++ b/dom/alarm/AlarmService.jsm @@ -5,11 +5,10 @@ "use strict"; /* static functions */ -const DEBUG = false; +const DEBUG = true; function debug(aStr) { - if (DEBUG) - dump("AlarmService: " + aStr + "\n"); + DEBUG && dump("AlarmService: " + aStr + "\n"); } const { classes: Cc, interfaces: Ci, utils: Cu, results: Cr } = Components; @@ -50,6 +49,8 @@ XPCOMUtils.defineLazyGetter(this, "powerManagerService", function() { */ this.AlarmService = { + lastChromeId: 0, + init: function init() { debug("init()"); @@ -63,6 +64,8 @@ this.AlarmService = { alarmHalService.setAlarmFiredCb(this._onAlarmFired.bind(this)); alarmHalService.setTimezoneChangedCb(this._onTimezoneChanged.bind(this)); + alarmHalService.setSystemClockChangedCb( + this._onSystemClockChanged.bind(this)); // Add the messages to be listened to. this._messages = ["AlarmsManager:GetAll", @@ -204,6 +207,12 @@ this.AlarmService = { }; } + // Is this a chrome alarm? + if (aId < 0) { + aRemoveSuccessCb(); + return; + } + this._db.remove(aId, aManifestURL, aRemoveSuccessCb, function removeErrorCb(aErrorMsg) { throw Components.results.NS_ERROR_NOT_IMPLEMENTED; @@ -240,20 +249,44 @@ this.AlarmService = { _notifyAlarmObserver: function _notifyAlarmObserver(aAlarm) { debug("_notifyAlarmObserver()"); - if (aAlarm.manifestURL) { - this._fireSystemMessage(aAlarm); - } else if (typeof aAlarm.alarmFiredCb === "function") { - aAlarm.alarmFiredCb(this._publicAlarm(aAlarm)); - } + let wakeLock = powerManagerService.newWakeLock("cpu"); + + let timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer); + timer.initWithCallback(() => { + debug("_notifyAlarmObserver - timeout()"); + if (aAlarm.manifestURL) { + this._fireSystemMessage(aAlarm); + } else if (typeof aAlarm.alarmFiredCb === "function") { + aAlarm.alarmFiredCb(this._publicAlarm(aAlarm)); + } + + wakeLock.unlock(); + }, 0, Ci.nsITimer.TYPE_ONE_SHOT); }, _onAlarmFired: function _onAlarmFired() { debug("_onAlarmFired()"); if (this._currentAlarm) { + let currentAlarmTime = this._getAlarmTime(this._currentAlarm); + + // If a alarm fired before the actual time that the current + // alarm should occur, we reset this current alarm. + if (currentAlarmTime > Date.now()) { + let currentAlarm = this._currentAlarm; + this._currentAlarm = currentAlarm; + + this._debugCurrentAlarm(); + return; + } + this._removeAlarmFromDb(this._currentAlarm.id, null); - this._notifyAlarmObserver(this._currentAlarm); + // We need to clear the current alarm before notifying because chrome + // alarms may add a new alarm during their callback, and we do not want + // to clobber it. + let firingAlarm = this._currentAlarm; this._currentAlarm = null; + this._notifyAlarmObserver(firingAlarm); } // Reset the next alarm from the queue. @@ -283,6 +316,11 @@ this.AlarmService = { this._restoreAlarmsFromDb(); }, + _onSystemClockChanged: function _onSystemClockChanged(aClockDeltaMS) { + debug("_onSystemClockChanged"); + this._restoreAlarmsFromDb(); + }, + _restoreAlarmsFromDb: function _restoreAlarmsFromDb() { debug("_restoreAlarmsFromDb()"); @@ -291,15 +329,25 @@ this.AlarmService = { debug("Callback after getting alarms from database: " + JSON.stringify(aAlarms)); - // Clear any alarms set or queued in the cache. + // Clear any alarms set or queued in the cache if coming from db. let alarmQueue = this._alarmQueue; - alarmQueue.length = 0; - this._currentAlarm = null; + if (this._currentAlarm) { + alarmQueue.unshift(this._currentAlarm); + this._currentAlarm = null; + } + for (let i = 0; i < alarmQueue.length;) { + if (alarmQueue[i]['id'] < 0) { + ++i; + continue; + } + alarmQueue.splice(i, 1); + } // Only restore the alarm that's not yet expired; otherwise, remove it // from the database and notify the observer. aAlarms.forEach(function addAlarm(aAlarm) { - if (this._getAlarmTime(aAlarm) > Date.now()) { + if ("manifestURL" in aAlarm && aAlarm.manifestURL && + this._getAlarmTime(aAlarm) > Date.now()) { alarmQueue.push(aAlarm); } else { this._removeAlarmFromDb(aAlarm.id, null); @@ -398,46 +446,65 @@ this.AlarmService = { aNewAlarm['timezoneOffset'] = this._currentTimezoneOffset; - this._db.add(aNewAlarm, - function addSuccessCb(aNewId) { - debug("Callback after adding alarm in database."); + if ("manifestURL" in aNewAlarm) { + this._db.add(aNewAlarm, + function addSuccessCb(aNewId) { + debug("Callback after adding alarm in database."); + this.processNewAlarm(aNewAlarm, aNewId, aAlarmFiredCb, aSuccessCb); + }.bind(this), + function addErrorCb(aErrorMsg) { + aErrorCb(aErrorMsg); + }.bind(this)); + } else { + // alarms without manifests are managed by chrome code. For them we use + // negative IDs. + this.processNewAlarm(aNewAlarm, --this.lastChromeId, aAlarmFiredCb, + aSuccessCb); + } + }, - aNewAlarm['id'] = aNewId; + processNewAlarm: function(aNewAlarm, aNewId, aAlarmFiredCb, aSuccessCb) { + aNewAlarm['id'] = aNewId; - // Now that the alarm has been added to the database, we can tack on - // the non-serializable callback to the in-memory object. - aNewAlarm['alarmFiredCb'] = aAlarmFiredCb; + // Now that the alarm has been added to the database, we can tack on + // the non-serializable callback to the in-memory object. + aNewAlarm['alarmFiredCb'] = aAlarmFiredCb; - // If there is no alarm being set in system, set the new alarm. - if (this._currentAlarm == null) { - this._currentAlarm = aNewAlarm; - this._debugCurrentAlarm(); - aSuccessCb(aNewId); - return; - } + // If the new alarm already expired at this moment, we directly + // notify this alarm + let newAlarmTime = this._getAlarmTime(aNewAlarm); + if (newAlarmTime < Date.now()) { + aSuccessCb(aNewId); + this._removeAlarmFromDb(aNewAlarm.id, null); + this._notifyAlarmObserver(aNewAlarm); + return; + } - // If the new alarm is earlier than the current alarm, swap them and - // push the previous alarm back to the queue. - let alarmQueue = this._alarmQueue; - let aNewAlarmTime = this._getAlarmTime(aNewAlarm); - let currentAlarmTime = this._getAlarmTime(this._currentAlarm); - if (aNewAlarmTime < currentAlarmTime) { - alarmQueue.unshift(this._currentAlarm); - this._currentAlarm = aNewAlarm; - this._debugCurrentAlarm(); - aSuccessCb(aNewId); - return; - } + // If there is no alarm being set in system, set the new alarm. + if (this._currentAlarm == null) { + this._currentAlarm = aNewAlarm; + this._debugCurrentAlarm(); + aSuccessCb(aNewId); + return; + } - // Push the new alarm in the queue. - alarmQueue.push(aNewAlarm); - alarmQueue.sort(this._sortAlarmByTimeStamps.bind(this)); - this._debugCurrentAlarm(); - aSuccessCb(aNewId); - }.bind(this), - function addErrorCb(aErrorMsg) { - aErrorCb(aErrorMsg); - }.bind(this)); + // If the new alarm is earlier than the current alarm, swap them and + // push the previous alarm back to the queue. + let alarmQueue = this._alarmQueue; + let currentAlarmTime = this._getAlarmTime(this._currentAlarm); + if (newAlarmTime < currentAlarmTime) { + alarmQueue.unshift(this._currentAlarm); + this._currentAlarm = aNewAlarm; + this._debugCurrentAlarm(); + aSuccessCb(aNewId); + return; + } + + // Push the new alarm in the queue. + alarmQueue.push(aNewAlarm); + alarmQueue.sort(this._sortAlarmByTimeStamps.bind(this)); + this._debugCurrentAlarm(); + aSuccessCb(aNewId); }, /* diff --git a/dom/alarm/moz.build b/dom/alarm/moz.build index ae7d9f58b9..5632c12ece 100644 --- a/dom/alarm/moz.build +++ b/dom/alarm/moz.build @@ -33,3 +33,5 @@ include('/ipc/chromium/chromium-config.mozbuild') FINAL_LIBRARY = 'xul' MOCHITEST_MANIFESTS += ['test/mochitest.ini'] + +XPCSHELL_TESTS_MANIFESTS += ['test/xpcshell.ini'] diff --git a/dom/alarm/nsIAlarmHalService.idl b/dom/alarm/nsIAlarmHalService.idl index 70d31ce379..d70986c37f 100644 --- a/dom/alarm/nsIAlarmHalService.idl +++ b/dom/alarm/nsIAlarmHalService.idl @@ -4,29 +4,36 @@ #include "nsISupports.idl" -[scriptable, function, uuid(9f3ed2c0-aed9-11e1-8c3d-5310bd393466)] -interface nsIAlarmFiredCb : nsISupports +[scriptable, function, uuid(53dec7f9-bb51-4c3a-98ab-80d5d750c9dd)] +interface nsIAlarmFiredCb : nsISupports { void onAlarmFired(); }; -[scriptable, function, uuid(0ca52e84-ba8f-11e1-87e8-63235527db9e)] -interface nsITimezoneChangedCb : nsISupports +[scriptable, function, uuid(e6662911-c066-4358-9388-8661065c65a2)] +interface nsITimezoneChangedCb : nsISupports { void onTimezoneChanged(in int32_t aTimezoneOffset); }; +[scriptable, function, uuid(46ece987-a3ec-4124-906f-d99c83296ac6)] +interface nsISystemClockChangedCb : nsISupports +{ + void onSystemClockChanged(in int32_t aClockDeltaMS); +}; + %{C++ #define NS_ALARMHALSERVICE_CID { 0x7dafea4c, 0x7163, 0x4b70, { 0x95, 0x4e, 0x5a, 0xd4, 0x09, 0x94, 0x83, 0xd7 } } #define ALARMHALSERVICE_CONTRACTID "@mozilla.org/alarmHalService;1" %} -[scriptable, uuid(057b1ee4-f696-486d-bd55-205e21e88fab)] +[scriptable, uuid(35074214-f50d-4f9a-b173-8d564dfa657d)] interface nsIAlarmHalService : nsISupports { bool setAlarm(in int32_t aSeconds, in int32_t aNanoseconds); void setAlarmFiredCb(in nsIAlarmFiredCb aAlarmFiredCb); void setTimezoneChangedCb(in nsITimezoneChangedCb aTimezoneChangedCb); + void setSystemClockChangedCb(in nsISystemClockChangedCb aSystemClockChangedCb); }; diff --git a/dom/alarm/test/mochitest.ini b/dom/alarm/test/mochitest.ini index 2c8960f566..96a06e0365 100644 --- a/dom/alarm/test/mochitest.ini +++ b/dom/alarm/test/mochitest.ini @@ -1,6 +1,7 @@ [DEFAULT] support-files = file_empty.html + system_message_chrome_script.js [test_alarm_add_data.html] skip-if = ((buildapp == 'mulet' || buildapp == 'b2g') && toolkit != 'gonk') #Bug 931116, b2g desktop specific, initial triage diff --git a/dom/alarm/test/system_message_chrome_script.js b/dom/alarm/test/system_message_chrome_script.js new file mode 100644 index 0000000000..4d6358f517 --- /dev/null +++ b/dom/alarm/test/system_message_chrome_script.js @@ -0,0 +1,18 @@ +/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ +'use strict'; + +const { classes: Cc, interfaces: Ci } = Components; + +const systemMessenger = Cc["@mozilla.org/system-message-internal;1"] + .getService(Ci.nsISystemMessagesInternal); +const ioService = Cc["@mozilla.org/network/io-service;1"] + .getService(Ci.nsIIOService); + +addMessageListener("trigger-register-page", function(aData) { + systemMessenger.registerPage(aData.type, + ioService.newURI(aData.pageURL, null, null), + ioService.newURI(aData.manifestURL, null, null)); + sendAsyncMessage("page-registered"); +}); diff --git a/dom/alarm/test/test_alarm_change_system_clock.js b/dom/alarm/test/test_alarm_change_system_clock.js new file mode 100644 index 0000000000..0444e64481 --- /dev/null +++ b/dom/alarm/test/test_alarm_change_system_clock.js @@ -0,0 +1,70 @@ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +Components.utils.import("resource://gre/modules/AlarmService.jsm"); +Components.utils.import("resource://gre/modules/Services.jsm"); +Components.utils.import("resource://gre/modules/XPCOMUtils.jsm"); + +XPCOMUtils.defineLazyServiceGetter(this, "gTimeService", + "@mozilla.org/time/timeservice;1", + "nsITimeService"); + +const ALARM_OFFSET = 10000; // 10 seconds. +const CLOCK_OFFSET = 20000; // 20 seconds. +const MANIFEST_URL = "http://dummyurl.com/manifest.webapp"; + +let alarmDate; +let alarmFired; +function alarmCb() { + alarmFired = true; +}; + +function run_test() { + do_get_profile(); + Services.prefs.setBoolPref("dom.mozAlarms.enabled", true); + run_next_test(); +} + +/* Tests */ + +add_test(function test_getAll() { + do_print("= There should not be any alarm ="); + AlarmService._db.getAll(MANIFEST_URL, (aAlarms) => { + do_check_eq(aAlarms.length, 0); + run_next_test(); + }); +}); + +add_test(function test_addAlarm() { + do_print("= Set alarm ="); + alarmDate = Date.now() + ALARM_OFFSET; + AlarmService.add({ + date: alarmDate, + manifestURL: MANIFEST_URL + }, alarmCb, run_next_test, do_throw); +}); + +add_test(function test_alarmNotFired() { + do_print("= The alarm should be in the DB and pending ="); + AlarmService._db.getAll(MANIFEST_URL, aAlarms => { + do_check_eq(aAlarms.length, 1, "The alarm is in the DB"); + run_next_test(); + }); +}); + +add_test(function test_changeSystemClock() { + do_print("= Change system clock ="); + gTimeService.set(Date.now() + CLOCK_OFFSET); + run_next_test(); +}); + +add_test(function test_alarmFired() { + do_print("= The alarm should have been fired and removed from the DB ="); + do_check_true(alarmFired, "The alarm was fired"); + AlarmService._db.getAll(MANIFEST_URL, aAlarms => { + do_check_eq(aAlarms.length, 0, "No alarms in the DB"); + run_next_test(); + }); +}); diff --git a/dom/alarm/test/test_bug1037079.html b/dom/alarm/test/test_bug1037079.html index 3912f7a1a6..425c4ce505 100644 --- a/dom/alarm/test/test_bug1037079.html +++ b/dom/alarm/test/test_bug1037079.html @@ -14,6 +14,20 @@ "use strict"; + function registerPage() { + var gScript = SpecialPowers.loadChromeScript(SimpleTest.getTestFileURL('system_message_chrome_script.js')); + gScript.addMessageListener("page-registered", function pageRegisteredHandler() { + gScript.removeMessageListener("page-registered", pageRegisteredHandler); + gScript.destroy(); + testFireTimeAlert(); + }); + + gScript.sendAsyncMessage("trigger-register-page", + { type: "alarm", + manifestURL: window.location.origin + "/manifest.webapp", + pageURL: window.location.href }); + } + function testFireTimeAlert() { var secondsLater = new Date(); secondsLater.setSeconds(secondsLater.getSeconds() + 10); @@ -27,7 +41,7 @@ }); domRequest = navigator.mozAlarms.add(secondsLater, "honorTimezone", - {type: "timer"}); + {type: "timer"}); } catch (e) { ok(false, "Unexpected exception trying to set time alert."); @@ -62,7 +76,7 @@ if (isAllowedToTest) { ok(true, "Start to test..."); - testFireTimeAlert(); + registerPage(); } else { // A sanity check to make sure we must run tests on Firefox OS (B2G). if (navigator.userAgent.indexOf("Mobile") != -1 && diff --git a/dom/alarm/test/test_bug1090896.html b/dom/alarm/test/test_bug1090896.html index ea3c6c5ef5..f74912c7c7 100644 --- a/dom/alarm/test/test_bug1090896.html +++ b/dom/alarm/test/test_bug1090896.html @@ -14,6 +14,20 @@ "use strict"; + function registerPage() { + var gScript = SpecialPowers.loadChromeScript(SimpleTest.getTestFileURL('system_message_chrome_script.js')); + gScript.addMessageListener("page-registered", function pageRegisteredHandler() { + gScript.removeMessageListener("page-registered", pageRegisteredHandler); + gScript.destroy(); + testFireTimeAlertWithNoData(); + }); + + gScript.sendAsyncMessage("trigger-register-page", + { type: "alarm", + manifestURL: window.location.origin + "/manifest.webapp", + pageURL: window.location.href }); + } + function testFireTimeAlertWithNoData() { var secondsLater = new Date(); secondsLater.setSeconds(secondsLater.getSeconds() + 1); @@ -61,7 +75,7 @@ if (isAllowedToTest) { ok(true, "Start to test..."); - testFireTimeAlertWithNoData(); + registerPage(); } else { // A sanity check to make sure we must run tests on Firefox OS (B2G). if (navigator.userAgent.indexOf("Mobile") != -1 && diff --git a/dom/alarm/test/xpcshell.ini b/dom/alarm/test/xpcshell.ini new file mode 100644 index 0000000000..0561fa2e8c --- /dev/null +++ b/dom/alarm/test/xpcshell.ini @@ -0,0 +1,7 @@ +[DEFAULT] +head = +tail = + +[test_alarm_change_system_clock.js] +# This test fails on the ICS emulator. We can enable it once bug 1090359 is fixed. +skip-if = 1 diff --git a/dom/bindings/Codegen.py b/dom/bindings/Codegen.py index edd45d9326..275f170cf5 100644 --- a/dom/bindings/Codegen.py +++ b/dom/bindings/Codegen.py @@ -6403,21 +6403,14 @@ def getWrapTemplateForType(type, descriptorProvider, result, successCode, resultLoc = result conversion = fill( """ - { - // Scope for resultStr - MOZ_ASSERT(uint32_t(${result}) < ArrayLength(${strings})); - JSString* resultStr = JS_NewStringCopyN(cx, ${strings}[uint32_t(${result})].value, ${strings}[uint32_t(${result})].length); - if (!resultStr) { - $*{exceptionCode} - } - $*{setResultStr} + if (!ToJSValue(cx, ${result}, $${jsvalHandle})) { + $*{exceptionCode} } + $*{successCode} """, result=resultLoc, - strings=(type.unroll().inner.identifier.name + "Values::" + - ENUM_ENTRY_VARIABLE_NAME), exceptionCode=exceptionCode, - setResultStr=setString("resultStr")) + successCode=successCode) if type.nullable(): conversion = CGIfElseWrapper( @@ -9218,11 +9211,53 @@ def getEnumValueName(value): ' rename our internal EndGuard_ to something else') return nativeName +class CGEnumToJSValue(CGAbstractMethod): + def __init__(self, enum): + enumType = enum.identifier.name + self.stringsArray = enumType + "Values::" + ENUM_ENTRY_VARIABLE_NAME + CGAbstractMethod.__init__(self, None, "ToJSValue", "bool", + [Argument("JSContext*", "aCx"), + Argument(enumType, "aArgument"), + Argument("JS::MutableHandle", + "aValue")]) + + def definition_body(self): + return fill( + """ + MOZ_ASSERT(uint32_t(aArgument) < ArrayLength(${strings})); + JSString* resultStr = + JS_NewStringCopyN(aCx, ${strings}[uint32_t(aArgument)].value, + ${strings}[uint32_t(aArgument)].length); + if (!resultStr) { + return false; + } + aValue.setString(resultStr); + return true; + """, + strings=self.stringsArray) + class CGEnum(CGThing): def __init__(self, enum): CGThing.__init__(self) self.enum = enum + strings = CGNamespace( + self.stringsNamespace(), + CGGeneric(declare=("extern const EnumEntry %s[%d];\n" % + (ENUM_ENTRY_VARIABLE_NAME, self.nEnumStrings())), + define=fill( + """ + extern const EnumEntry ${name}[${count}] = { + $*{entries} + { nullptr, 0 } + }; + """, + name=ENUM_ENTRY_VARIABLE_NAME, + count=self.nEnumStrings(), + entries=''.join('{"%s", %d},\n' % (val, len(val)) + for val in self.enum.values())))) + toJSValue = CGEnumToJSValue(enum) + self.cgThings = CGList([strings, toJSValue], "\n") def stringsNamespace(self): return self.enum.identifier.name + "Values" @@ -9243,22 +9278,10 @@ class CGEnum(CGThing): strings = CGNamespace(self.stringsNamespace(), CGGeneric(declare="extern const EnumEntry %s[%d];\n" % (ENUM_ENTRY_VARIABLE_NAME, self.nEnumStrings()))) - return decl + "\n" + strings.declare() + return decl + "\n" + self.cgThings.declare() def define(self): - strings = fill( - """ - extern const EnumEntry ${name}[${count}] = { - $*{entries} - { nullptr, 0 } - }; - """, - name=ENUM_ENTRY_VARIABLE_NAME, - count=self.nEnumStrings(), - entries=''.join('{"%s", %d},\n' % (val, len(val)) - for val in self.enum.values())) - return CGNamespace(self.stringsNamespace(), - CGGeneric(define=indent(strings))).define() + return self.cgThings.define() def deps(self): return self.enum.getDeps() @@ -13178,6 +13201,11 @@ class CGBindingRoot(CGThing): bindingHeaders["mozilla/dom/DOMJSClass.h"] = descriptors bindingHeaders["mozilla/dom/ScriptSettings.h"] = dictionaries # AutoJSAPI bindingHeaders["xpcpublic.h"] = dictionaries # xpc::UnprivilegedJunkScope + # Ensure we see our enums in the generated .cpp file, for the ToJSValue + # method body. Also ensure that we see jsapi.h. + if enums: + bindingHeaders[CGHeaders.getDeclarationFilename(enums[0])] = True + bindingHeaders["jsapi.h"] = True # For things that have [UseCounter] def descriptorRequiresTelemetry(desc): diff --git a/dom/bluetooth/bluedroid/BluetoothA2dpManager.cpp b/dom/bluetooth/bluedroid/BluetoothA2dpManager.cpp index 33a719bc92..068e0e2efb 100644 --- a/dom/bluetooth/bluedroid/BluetoothA2dpManager.cpp +++ b/dom/bluetooth/bluedroid/BluetoothA2dpManager.cpp @@ -35,6 +35,8 @@ namespace { static BluetoothA2dpInterface* sBtA2dpInterface; } // namespace +const int BluetoothA2dpManager::MAX_NUM_CLIENTS = 1; + NS_IMETHODIMP BluetoothA2dpManager::Observe(nsISupports* aSubject, const char* aTopic, @@ -86,40 +88,52 @@ AvStatusToSinkString(BluetoothA2dpConnectionState aState, nsAString& aString) } } -class BluetoothA2dpManager::InitA2dpResultHandler final - : public BluetoothA2dpResultHandler +class BluetoothA2dpManager::RegisterModuleResultHandler final + : public BluetoothSetupResultHandler { public: - InitA2dpResultHandler(BluetoothProfileResultHandler* aRes) - : mRes(aRes) + RegisterModuleResultHandler(BluetoothA2dpInterface* aInterface, + BluetoothProfileResultHandler* aRes) + : mInterface(aInterface) + , mRes(aRes) { } void OnError(BluetoothStatus aStatus) override { - BT_WARNING("BluetoothA2dpInterface::Init failed: %d", + MOZ_ASSERT(NS_IsMainThread()); + + BT_WARNING("BluetoothSetupInterface::RegisterModule failed for A2DP: %d", (int)aStatus); + + mInterface->SetNotificationHandler(nullptr); + if (mRes) { mRes->OnError(NS_ERROR_FAILURE); } } - void Init() override + void RegisterModule() override { + MOZ_ASSERT(NS_IsMainThread()); + + sBtA2dpInterface = mInterface; + if (mRes) { mRes->Init(); } } private: + BluetoothA2dpInterface* mInterface; RefPtr mRes; }; -class BluetoothA2dpManager::OnErrorProfileResultHandlerRunnable final +class BluetoothA2dpManager::InitProfileResultHandlerRunnable final : public nsRunnable { public: - OnErrorProfileResultHandlerRunnable(BluetoothProfileResultHandler* aRes, - nsresult aRv) + InitProfileResultHandlerRunnable(BluetoothProfileResultHandler* aRes, + nsresult aRv) : mRes(aRes) , mRv(aRv) { @@ -128,7 +142,13 @@ public: NS_IMETHOD Run() override { - mRes->OnError(mRv); + MOZ_ASSERT(NS_IsMainThread()); + + if (NS_SUCCEEDED(mRv)) { + mRes->Init(); + } else { + mRes->OnError(mRv); + } return NS_OK; } @@ -147,32 +167,64 @@ private: void BluetoothA2dpManager::InitA2dpInterface(BluetoothProfileResultHandler* aRes) { - BluetoothInterface* btInf = BluetoothInterface::GetInstance(); + MOZ_ASSERT(NS_IsMainThread()); + + if (sBtA2dpInterface) { + BT_LOGR("Bluetooth A2DP interface is already initalized."); + RefPtr r = + new InitProfileResultHandlerRunnable(aRes, NS_OK); + if (NS_FAILED(NS_DispatchToMainThread(r))) { + BT_LOGR("Failed to dispatch A2DP Init runnable"); + } + return; + } + + auto btInf = BluetoothInterface::GetInstance(); + if (NS_WARN_IF(!btInf)) { - // If there's no HFP interface, we dispatch a runnable + // If there's no Bluetooth interface, we dispatch a runnable // that calls the profile result handler. RefPtr r = - new OnErrorProfileResultHandlerRunnable(aRes, NS_ERROR_FAILURE); + new InitProfileResultHandlerRunnable(aRes, NS_ERROR_FAILURE); if (NS_FAILED(NS_DispatchToMainThread(r))) { - BT_LOGR("Failed to dispatch HFP OnError runnable"); + BT_LOGR("Failed to dispatch A2DP OnError runnable"); } return; } - sBtA2dpInterface = btInf->GetBluetoothA2dpInterface(); - if (NS_WARN_IF(!sBtA2dpInterface)) { - // If there's no HFP interface, we dispatch a runnable + auto setupInterface = btInf->GetBluetoothSetupInterface(); + + if (NS_WARN_IF(!setupInterface)) { + // If there's no Setup interface, we dispatch a runnable // that calls the profile result handler. RefPtr r = - new OnErrorProfileResultHandlerRunnable(aRes, NS_ERROR_FAILURE); + new InitProfileResultHandlerRunnable(aRes, NS_ERROR_FAILURE); if (NS_FAILED(NS_DispatchToMainThread(r))) { - BT_LOGR("Failed to dispatch HFP OnError runnable"); + BT_LOGR("Failed to dispatch A2DP OnError runnable"); } return; } - BluetoothA2dpManager* a2dpManager = BluetoothA2dpManager::Get(); - sBtA2dpInterface->Init(a2dpManager, new InitA2dpResultHandler(aRes)); + auto a2dpInterface = btInf->GetBluetoothA2dpInterface(); + + if (NS_WARN_IF(!a2dpInterface)) { + // If there's no A2DP interface, we dispatch a runnable + // that calls the profile result handler. + RefPtr r = + new InitProfileResultHandlerRunnable(aRes, NS_ERROR_FAILURE); + if (NS_FAILED(NS_DispatchToMainThread(r))) { + BT_LOGR("Failed to dispatch A2DP OnError runnable"); + } + return; + } + + // Set notification handler _before_ registering the module. It could + // happen that we receive notifications, before the result handler runs. + a2dpInterface->SetNotificationHandler(BluetoothA2dpManager::Get()); + + setupInterface->RegisterModule( + SETUP_SERVICE_ID_A2DP, 0, MAX_NUM_CLIENTS, + new RegisterModuleResultHandler(a2dpInterface, aRes)); } BluetoothA2dpManager::~BluetoothA2dpManager() @@ -227,19 +279,22 @@ BluetoothA2dpManager::Get() return sBluetoothA2dpManager; } -class BluetoothA2dpManager::CleanupA2dpResultHandler final - : public BluetoothA2dpResultHandler +class BluetoothA2dpManager::UnregisterModuleResultHandler final + : public BluetoothSetupResultHandler { public: - CleanupA2dpResultHandler(BluetoothProfileResultHandler* aRes) + UnregisterModuleResultHandler(BluetoothProfileResultHandler* aRes) : mRes(aRes) { } void OnError(BluetoothStatus aStatus) override { - BT_WARNING("BluetoothA2dpInterface::Cleanup failed: %d", + MOZ_ASSERT(NS_IsMainThread()); + + BT_WARNING("BluetoothSetupInterface::UnregisterModule failed for A2DP: %d", (int)aStatus); + sBtA2dpInterface->SetNotificationHandler(nullptr); sBtA2dpInterface = nullptr; if (mRes) { @@ -247,8 +302,11 @@ public: } } - void Cleanup() override + void UnregisterModule() override { + MOZ_ASSERT(NS_IsMainThread()); + + sBtA2dpInterface->SetNotificationHandler(nullptr); sBtA2dpInterface = nullptr; if (mRes) { @@ -260,26 +318,33 @@ private: RefPtr mRes; }; -class BluetoothA2dpManager::CleanupA2dpResultHandlerRunnable final +class BluetoothA2dpManager::DeinitProfileResultHandlerRunnable final : public nsRunnable { public: - CleanupA2dpResultHandlerRunnable(BluetoothProfileResultHandler* aRes) + DeinitProfileResultHandlerRunnable(BluetoothProfileResultHandler* aRes, + nsresult aRv) : mRes(aRes) - { } + , mRv(aRv) + { + MOZ_ASSERT(mRes); + } NS_IMETHOD Run() override { - sBtA2dpInterface = nullptr; + MOZ_ASSERT(NS_IsMainThread()); - if (mRes) { + if (NS_SUCCEEDED(mRv)) { mRes->Deinit(); + } else { + mRes->OnError(mRv); } return NS_OK; } private: RefPtr mRes; + nsresult mRv; }; // static @@ -288,16 +353,45 @@ BluetoothA2dpManager::DeinitA2dpInterface(BluetoothProfileResultHandler* aRes) { MOZ_ASSERT(NS_IsMainThread()); - if (sBtA2dpInterface) { - sBtA2dpInterface->Cleanup(new CleanupA2dpResultHandler(aRes)); - } else if (aRes) { - // We dispatch a runnable here to make the profile resource handler - // behave as if A2DP was initialized. - RefPtr r = new CleanupA2dpResultHandlerRunnable(aRes); + if (!sBtA2dpInterface) { + BT_LOGR("Bluetooth A2DP interface has not been initalized."); + RefPtr r = + new DeinitProfileResultHandlerRunnable(aRes, NS_OK); if (NS_FAILED(NS_DispatchToMainThread(r))) { - BT_LOGR("Failed to dispatch cleanup-result-handler runnable"); + BT_LOGR("Failed to dispatch A2DP Deinit runnable"); } + return; } + + auto btInf = BluetoothInterface::GetInstance(); + + if (NS_WARN_IF(!btInf)) { + // If there's no backend interface, we dispatch a runnable + // that calls the profile result handler. + RefPtr r = + new DeinitProfileResultHandlerRunnable(aRes, NS_ERROR_FAILURE); + if (NS_FAILED(NS_DispatchToMainThread(r))) { + BT_LOGR("Failed to dispatch A2DP OnError runnable"); + } + return; + } + + auto setupInterface = btInf->GetBluetoothSetupInterface(); + + if (NS_WARN_IF(!setupInterface)) { + // If there's no Setup interface, we dispatch a runnable + // that calls the profile result handler. + RefPtr r = + new DeinitProfileResultHandlerRunnable(aRes, NS_ERROR_FAILURE); + if (NS_FAILED(NS_DispatchToMainThread(r))) { + BT_LOGR("Failed to dispatch A2DP OnError runnable"); + } + return; + } + + setupInterface->UnregisterModule( + SETUP_SERVICE_ID_A2DP, + new UnregisterModuleResultHandler(aRes)); } void diff --git a/dom/bluetooth/bluedroid/BluetoothA2dpManager.h b/dom/bluetooth/bluedroid/BluetoothA2dpManager.h index 344010dd17..dda282654b 100644 --- a/dom/bluetooth/bluedroid/BluetoothA2dpManager.h +++ b/dom/bluetooth/bluedroid/BluetoothA2dpManager.h @@ -17,6 +17,8 @@ class BluetoothA2dpManager : public BluetoothProfileManagerBase , public BluetoothA2dpNotificationHandler { public: + static const int MAX_NUM_CLIENTS; + BT_DECL_PROFILE_MGR_BASE virtual void GetName(nsACString& aName) { @@ -47,12 +49,12 @@ protected: virtual ~BluetoothA2dpManager(); private: - class CleanupA2dpResultHandler; - class CleanupA2dpResultHandlerRunnable; class ConnectResultHandler; + class DeinitProfileResultHandlerRunnable; class DisconnectResultHandler; - class InitA2dpResultHandler; - class OnErrorProfileResultHandlerRunnable; + class InitProfileResultHandlerRunnable; + class RegisterModuleResultHandler; + class UnregisterModuleResultHandler; BluetoothA2dpManager(); diff --git a/dom/bluetooth/bluedroid/BluetoothAvrcpManager.cpp b/dom/bluetooth/bluedroid/BluetoothAvrcpManager.cpp index 1ef9c06ad2..df8c104d27 100644 --- a/dom/bluetooth/bluedroid/BluetoothAvrcpManager.cpp +++ b/dom/bluetooth/bluedroid/BluetoothAvrcpManager.cpp @@ -35,6 +35,8 @@ namespace { static BluetoothAvrcpInterface* sBtAvrcpInterface; } // namespace +const int BluetoothAvrcpManager::MAX_NUM_CLIENTS = 1; + /* * This function maps attribute id and returns corresponding values */ @@ -118,18 +120,27 @@ BluetoothAvrcpManager::Reset() mPlayStatus = ControlPlayStatus::PLAYSTATUS_STOPPED; } -class BluetoothAvrcpManager::InitAvrcpResultHandler final - : public BluetoothAvrcpResultHandler +class BluetoothAvrcpManager::RegisterModuleResultHandler final + : public BluetoothSetupResultHandler { public: - InitAvrcpResultHandler(BluetoothProfileResultHandler* aRes) - : mRes(aRes) - { } + RegisterModuleResultHandler(BluetoothAvrcpInterface* aInterface, + BluetoothProfileResultHandler* aRes) + : mInterface(aInterface) + , mRes(aRes) + { + MOZ_ASSERT(mInterface); + } void OnError(BluetoothStatus aStatus) override { - BT_WARNING("BluetoothAvrcpInterface::Init failed: %d", + MOZ_ASSERT(NS_IsMainThread()); + + BT_WARNING("BluetoothSetupInterface::RegisterModule failed for AVRCP: %d", (int)aStatus); + + mInterface->SetNotificationHandler(nullptr); + if (mRes) { if (aStatus == STATUS_UNSUPPORTED) { /* Not all versions of Bluedroid support AVRCP. So if the @@ -143,23 +154,28 @@ public: } } - void Init() override + void RegisterModule() override { + MOZ_ASSERT(NS_IsMainThread()); + + sBtAvrcpInterface = mInterface; + if (mRes) { mRes->Init(); } } private: + BluetoothAvrcpInterface* mInterface; RefPtr mRes; }; -class BluetoothAvrcpManager::OnErrorProfileResultHandlerRunnable final +class BluetoothAvrcpManager::InitProfileResultHandlerRunnable final : public nsRunnable { public: - OnErrorProfileResultHandlerRunnable(BluetoothProfileResultHandler* aRes, - nsresult aRv) + InitProfileResultHandlerRunnable(BluetoothProfileResultHandler* aRes, + nsresult aRv) : mRes(aRes) , mRv(aRv) { @@ -168,7 +184,13 @@ public: NS_IMETHOD Run() override { - mRes->OnError(mRv); + MOZ_ASSERT(NS_IsMainThread()); + + if (NS_SUCCEEDED(mRv)) { + mRes->Init(); + } else { + mRes->OnError(mRv); + } return NS_OK; } @@ -184,32 +206,64 @@ private: void BluetoothAvrcpManager::InitAvrcpInterface(BluetoothProfileResultHandler* aRes) { - BluetoothInterface* btInf = BluetoothInterface::GetInstance(); - if (NS_WARN_IF(!btInf)) { - // If there's no HFP interface, we dispatch a runnable - // that calls the profile result handler. + MOZ_ASSERT(NS_IsMainThread()); + + if (sBtAvrcpInterface) { + BT_LOGR("Bluetooth AVRCP interface is already initalized."); RefPtr r = - new OnErrorProfileResultHandlerRunnable(aRes, NS_ERROR_FAILURE); + new InitProfileResultHandlerRunnable(aRes, NS_OK); if (NS_FAILED(NS_DispatchToMainThread(r))) { - BT_LOGR("Failed to dispatch HFP OnError runnable"); + BT_LOGR("Failed to dispatch AVRCP Init runnable"); } return; } - sBtAvrcpInterface = btInf->GetBluetoothAvrcpInterface(); - if (NS_WARN_IF(!sBtAvrcpInterface)) { + auto btInf = BluetoothInterface::GetInstance(); + + if (NS_WARN_IF(!btInf)) { + // If there's no Bluetooth interface, we dispatch a runnable + // that calls the profile result handler. + RefPtr r = + new InitProfileResultHandlerRunnable(aRes, NS_ERROR_FAILURE); + if (NS_FAILED(NS_DispatchToMainThread(r))) { + BT_LOGR("Failed to dispatch AVRCP OnError runnable"); + } + return; + } + + auto setupInterface = btInf->GetBluetoothSetupInterface(); + + if (NS_WARN_IF(!setupInterface)) { + // If there's no Setup interface, we dispatch a runnable + // that calls the profile result handler. + RefPtr r = + new InitProfileResultHandlerRunnable(aRes, NS_ERROR_FAILURE); + if (NS_FAILED(NS_DispatchToMainThread(r))) { + BT_LOGR("Failed to dispatch AVRCP OnError runnable"); + } + return; + } + + auto avrcpInterface = btInf->GetBluetoothAvrcpInterface(); + + if (NS_WARN_IF(!avrcpInterface)) { // If there's no AVRCP interface, we dispatch a runnable // that calls the profile result handler. RefPtr r = - new OnErrorProfileResultHandlerRunnable(aRes, NS_ERROR_FAILURE); + new InitProfileResultHandlerRunnable(aRes, NS_ERROR_FAILURE); if (NS_FAILED(NS_DispatchToMainThread(r))) { - BT_LOGR("Failed to dispatch HFP OnError runnable"); + BT_LOGR("Failed to dispatch AVRCP OnError runnable"); } return; } - BluetoothAvrcpManager* avrcpManager = BluetoothAvrcpManager::Get(); - sBtAvrcpInterface->Init(avrcpManager, new InitAvrcpResultHandler(aRes)); + // Set notification handler _before_ registering the module. It could + // happen that we receive notifications, before the result handler runs. + avrcpInterface->SetNotificationHandler(BluetoothAvrcpManager::Get()); + + setupInterface->RegisterModule( + SETUP_SERVICE_ID_AVRCP, 0, MAX_NUM_CLIENTS, + new RegisterModuleResultHandler(avrcpInterface, aRes)); } BluetoothAvrcpManager::~BluetoothAvrcpManager() @@ -245,37 +299,36 @@ BluetoothAvrcpManager::Get() return sBluetoothAvrcpManager; } -class BluetoothAvrcpManager::CleanupAvrcpResultHandler final - : public BluetoothAvrcpResultHandler +class BluetoothAvrcpManager::UnregisterModuleResultHandler final + : public BluetoothSetupResultHandler { public: - CleanupAvrcpResultHandler(BluetoothProfileResultHandler* aRes) + UnregisterModuleResultHandler(BluetoothProfileResultHandler* aRes) : mRes(aRes) { } void OnError(BluetoothStatus aStatus) override { - BT_WARNING("BluetoothAvrcpInterface::Cleanup failed: %d", + MOZ_ASSERT(NS_IsMainThread()); + + BT_WARNING("BluetoothSetupInterface::UnregisterModule failed for AVRCP: %d", (int)aStatus); + sBtAvrcpInterface->SetNotificationHandler(nullptr); sBtAvrcpInterface = nullptr; if (mRes) { - if (aStatus == STATUS_UNSUPPORTED) { - /* Not all versions of Bluedroid support AVRCP. So if the - * cleanup fails with STATUS_UNSUPPORTED, we still signal - * success. - */ - mRes->Deinit(); - } else { - mRes->OnError(NS_ERROR_FAILURE); - } + mRes->OnError(NS_ERROR_FAILURE); } } - void Cleanup() override + void UnregisterModule() override { + MOZ_ASSERT(NS_IsMainThread()); + + sBtAvrcpInterface->SetNotificationHandler(nullptr); sBtAvrcpInterface = nullptr; + if (mRes) { mRes->Deinit(); } @@ -285,31 +338,33 @@ private: RefPtr mRes; }; -class BluetoothAvrcpManager::CleanupAvrcpResultHandlerRunnable final +class BluetoothAvrcpManager::DeinitProfileResultHandlerRunnable final : public nsRunnable { public: - CleanupAvrcpResultHandlerRunnable(BluetoothProfileResultHandler* aRes) + DeinitProfileResultHandlerRunnable(BluetoothProfileResultHandler* aRes, + nsresult aRv) : mRes(aRes) - { } + , mRv(aRv) + { + MOZ_ASSERT(mRes); + } NS_IMETHOD Run() override { - sBtAvrcpInterface = nullptr; - if (sBtAvrcpInterface) { - sBtAvrcpInterface->Cleanup(new CleanupAvrcpResultHandler(mRes)); - } else if (mRes) { - /* Not all backends support AVRCP. If it's not available - * we signal success from here. - */ - mRes->Deinit(); - } + MOZ_ASSERT(NS_IsMainThread()); + if (NS_SUCCEEDED(mRv)) { + mRes->Deinit(); + } else { + mRes->OnError(mRv); + } return NS_OK; } private: RefPtr mRes; + nsresult mRv; }; // static @@ -318,16 +373,45 @@ BluetoothAvrcpManager::DeinitAvrcpInterface(BluetoothProfileResultHandler* aRes) { MOZ_ASSERT(NS_IsMainThread()); - if (sBtAvrcpInterface) { - sBtAvrcpInterface->Cleanup(new CleanupAvrcpResultHandler(aRes)); - } else if (aRes) { - // We dispatch a runnable here to make the profile resource handler - // behave as if A2DP was initialized. - RefPtr r = new CleanupAvrcpResultHandlerRunnable(aRes); + if (!sBtAvrcpInterface) { + BT_LOGR("Bluetooth AVRCP interface has not been initalized."); + RefPtr r = + new DeinitProfileResultHandlerRunnable(aRes, NS_OK); if (NS_FAILED(NS_DispatchToMainThread(r))) { - BT_LOGR("Failed to dispatch cleanup-result-handler runnable"); + BT_LOGR("Failed to dispatch AVRCP Deinit runnable"); } + return; } + + auto btInf = BluetoothInterface::GetInstance(); + + if (NS_WARN_IF(!btInf)) { + // If there's no backend interface, we dispatch a runnable + // that calls the profile result handler. + RefPtr r = + new DeinitProfileResultHandlerRunnable(aRes, NS_ERROR_FAILURE); + if (NS_FAILED(NS_DispatchToMainThread(r))) { + BT_LOGR("Failed to dispatch AVRCP OnError runnable"); + } + return; + } + + auto setupInterface = btInf->GetBluetoothSetupInterface(); + + if (NS_WARN_IF(!setupInterface)) { + // If there's no Setup interface, we dispatch a runnable + // that calls the profile result handler. + RefPtr r = + new DeinitProfileResultHandlerRunnable(aRes, NS_ERROR_FAILURE); + if (NS_FAILED(NS_DispatchToMainThread(r))) { + BT_LOGR("Failed to dispatch AVRCP OnError runnable"); + } + return; + } + + setupInterface->UnregisterModule( + SETUP_SERVICE_ID_AVRCP, + new UnregisterModuleResultHandler(aRes)); } void @@ -799,7 +883,7 @@ BluetoothAvrcpManager::RegisterNotificationNotification( */ void BluetoothAvrcpManager::RemoteFeatureNotification( - const nsAString& aBdAddr, unsigned long aFeatures) + const BluetoothAddress& aBdAddr, unsigned long aFeatures) { MOZ_ASSERT(NS_IsMainThread()); @@ -811,7 +895,7 @@ BluetoothAvrcpManager::RemoteFeatureNotification( */ void BluetoothAvrcpManager::VolumeChangeNotification(uint8_t aVolume, - uint8_t aCType) + uint8_t aCType) { MOZ_ASSERT(NS_IsMainThread()); diff --git a/dom/bluetooth/bluedroid/BluetoothAvrcpManager.h b/dom/bluetooth/bluedroid/BluetoothAvrcpManager.h index 7a9d99783d..926d48f720 100644 --- a/dom/bluetooth/bluedroid/BluetoothAvrcpManager.h +++ b/dom/bluetooth/bluedroid/BluetoothAvrcpManager.h @@ -17,6 +17,8 @@ class BluetoothAvrcpManager : public BluetoothProfileManagerBase , public BluetoothAvrcpNotificationHandler { public: + static const int MAX_NUM_CLIENTS; + BT_DECL_PROFILE_MGR_BASE virtual void GetName(nsACString& aName) { @@ -60,12 +62,12 @@ protected: virtual ~BluetoothAvrcpManager(); private: - class CleanupAvrcpResultHandler; - class CleanupAvrcpResultHandlerRunnable; class ConnectRunnable; + class DeinitProfileResultHandlerRunnable; class DisconnectRunnable; - class InitAvrcpResultHandler; - class OnErrorProfileResultHandlerRunnable; + class InitProfileResultHandlerRunnable; + class RegisterModuleResultHandler; + class UnregisterModuleResultHandler; BluetoothAvrcpManager(); @@ -101,7 +103,7 @@ private: BluetoothAvrcpEvent aEvent, uint32_t aParam) override; void RemoteFeatureNotification( - const nsAString& aBdAddr, unsigned long aFeatures) override; + const BluetoothAddress& aBdAddr, unsigned long aFeatures) override; void VolumeChangeNotification(uint8_t aVolume, uint8_t aCType) override; diff --git a/dom/bluetooth/bluedroid/BluetoothDaemonA2dpInterface.cpp b/dom/bluetooth/bluedroid/BluetoothDaemonA2dpInterface.cpp index a9fab08f19..858fc76a57 100644 --- a/dom/bluetooth/bluedroid/BluetoothDaemonA2dpInterface.cpp +++ b/dom/bluetooth/bluedroid/BluetoothDaemonA2dpInterface.cpp @@ -15,8 +15,6 @@ using namespace mozilla::ipc; // A2DP module // -const int BluetoothDaemonA2dpModule::MAX_NUM_CLIENTS = 1; - BluetoothA2dpNotificationHandler* BluetoothDaemonA2dpModule::sNotificationHandler; @@ -170,129 +168,31 @@ public: } }; -// Init operator class for ConnectionStateNotification -class BluetoothDaemonA2dpModule::ConnectionStateInitOp final - : private PDUInitOp -{ -public: - ConnectionStateInitOp(DaemonSocketPDU& aPDU) - : PDUInitOp(aPDU) - { } - - nsresult - operator () (BluetoothA2dpConnectionState& aArg1, - BluetoothAddress& aArg2) const - { - DaemonSocketPDU& pdu = GetPDU(); - - /* Read state */ - nsresult rv = UnpackPDU(pdu, aArg1); - if (NS_FAILED(rv)) { - return rv; - } - - /* Read address */ - rv = UnpackPDU(pdu, aArg2); - if (NS_FAILED(rv)) { - return rv; - } - WarnAboutTrailingData(); - return NS_OK; - } -}; - void BluetoothDaemonA2dpModule::ConnectionStateNtf( const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU) { ConnectionStateNotification::Dispatch( &BluetoothA2dpNotificationHandler::ConnectionStateNotification, - ConnectionStateInitOp(aPDU)); + UnpackPDUInitOp(aPDU)); } -// Init operator class for AudioStateNotification -class BluetoothDaemonA2dpModule::AudioStateInitOp final - : private PDUInitOp -{ -public: - AudioStateInitOp(DaemonSocketPDU& aPDU) - : PDUInitOp(aPDU) - { } - - nsresult - operator () (BluetoothA2dpAudioState& aArg1, - BluetoothAddress& aArg2) const - { - DaemonSocketPDU& pdu = GetPDU(); - - /* Read state */ - nsresult rv = UnpackPDU(pdu, aArg1); - if (NS_FAILED(rv)) { - return rv; - } - - /* Read address */ - rv = UnpackPDU(pdu, aArg2); - if (NS_FAILED(rv)) { - return rv; - } - WarnAboutTrailingData(); - return NS_OK; - } -}; - void BluetoothDaemonA2dpModule::AudioStateNtf( const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU) { AudioStateNotification::Dispatch( &BluetoothA2dpNotificationHandler::AudioStateNotification, - AudioStateInitOp(aPDU)); + UnpackPDUInitOp(aPDU)); } -// Init operator class for AudioConfigNotification -class BluetoothDaemonA2dpModule::AudioConfigInitOp final - : private PDUInitOp -{ -public: - AudioConfigInitOp(DaemonSocketPDU& aPDU) - : PDUInitOp(aPDU) - { } - - nsresult - operator () (BluetoothAddress& aArg1, uint32_t aArg2, uint8_t aArg3) const - { - DaemonSocketPDU& pdu = GetPDU(); - - /* Read address */ - nsresult rv = UnpackPDU(pdu, aArg1); - if (NS_FAILED(rv)) { - return rv; - } - - /* Read sample rate */ - rv = UnpackPDU(pdu, aArg2); - if (NS_FAILED(rv)) { - return rv; - } - - /* Read channel count */ - rv = UnpackPDU(pdu, aArg3); - if (NS_FAILED(rv)) { - return rv; - } - WarnAboutTrailingData(); - return NS_OK; - } -}; - void BluetoothDaemonA2dpModule::AudioConfigNtf( const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU) { AudioConfigNotification::Dispatch( &BluetoothA2dpNotificationHandler::AudioConfigNotification, - AudioConfigInitOp(aPDU)); + UnpackPDUInitOp(aPDU)); } void @@ -333,109 +233,13 @@ BluetoothDaemonA2dpInterface::BluetoothDaemonA2dpInterface( BluetoothDaemonA2dpInterface::~BluetoothDaemonA2dpInterface() { } -class BluetoothDaemonA2dpInterface::InitResultHandler final - : public BluetoothSetupResultHandler -{ -public: - InitResultHandler(BluetoothA2dpResultHandler* aRes) - : mRes(aRes) - { - MOZ_ASSERT(mRes); - } - - void OnError(BluetoothStatus aStatus) override - { - MOZ_ASSERT(NS_IsMainThread()); - - mRes->OnError(aStatus); - } - - void RegisterModule() override - { - MOZ_ASSERT(NS_IsMainThread()); - - mRes->Init(); - } - -private: - RefPtr mRes; -}; - void -BluetoothDaemonA2dpInterface::Init( - BluetoothA2dpNotificationHandler* aNotificationHandler, - BluetoothA2dpResultHandler* aRes) +BluetoothDaemonA2dpInterface::SetNotificationHandler( + BluetoothA2dpNotificationHandler* aNotificationHandler) { - // Set notification handler _before_ registering the module. It could - // happen that we receive notifications, before the result handler runs. + MOZ_ASSERT(mModule); + mModule->SetNotificationHandler(aNotificationHandler); - - InitResultHandler* res; - - if (aRes) { - res = new InitResultHandler(aRes); - } else { - // We don't need a result handler if the caller is not interested. - res = nullptr; - } - - nsresult rv = mModule->RegisterModule(BluetoothDaemonA2dpModule::SERVICE_ID, - 0x00, BluetoothDaemonA2dpModule::MAX_NUM_CLIENTS, res); - if (NS_FAILED(rv) && aRes) { - DispatchError(aRes, rv); - } -} - -class BluetoothDaemonA2dpInterface::CleanupResultHandler final - : public BluetoothSetupResultHandler -{ -public: - CleanupResultHandler(BluetoothDaemonA2dpModule* aModule, - BluetoothA2dpResultHandler* aRes) - : mModule(aModule) - , mRes(aRes) - { - MOZ_ASSERT(mModule); - } - - void OnError(BluetoothStatus aStatus) override - { - MOZ_ASSERT(NS_IsMainThread()); - - if (mRes) { - mRes->OnError(aStatus); - } - } - - void UnregisterModule() override - { - MOZ_ASSERT(NS_IsMainThread()); - - // Clear notification handler _after_ module has been - // unregistered. While unregistering the module, we might - // still receive notifications. - mModule->SetNotificationHandler(nullptr); - - if (mRes) { - mRes->Cleanup(); - } - } - -private: - BluetoothDaemonA2dpModule* mModule; - RefPtr mRes; -}; - -void -BluetoothDaemonA2dpInterface::Cleanup( - BluetoothA2dpResultHandler* aRes) -{ - nsresult rv = mModule->UnregisterModule( - BluetoothDaemonA2dpModule::SERVICE_ID, - new CleanupResultHandler(mModule, aRes)); - if (NS_FAILED(rv)) { - DispatchError(aRes, rv); - } } /* Connect / Disconnect */ diff --git a/dom/bluetooth/bluedroid/BluetoothDaemonA2dpInterface.h b/dom/bluetooth/bluedroid/BluetoothDaemonA2dpInterface.h index e1e1d648f7..a9d263824d 100644 --- a/dom/bluetooth/bluedroid/BluetoothDaemonA2dpInterface.h +++ b/dom/bluetooth/bluedroid/BluetoothDaemonA2dpInterface.h @@ -30,18 +30,9 @@ public: OPCODE_DISCONNECT = 0x02 }; - static const int MAX_NUM_CLIENTS; - virtual nsresult Send(DaemonSocketPDU* aPDU, DaemonSocketResultHandler* aRes) = 0; - virtual nsresult RegisterModule(uint8_t aId, uint8_t aMode, - uint32_t aMaxNumClients, - BluetoothSetupResultHandler* aRes) = 0; - - virtual nsresult UnregisterModule(uint8_t aId, - BluetoothSetupResultHandler* aRes) = 0; - void SetNotificationHandler( BluetoothA2dpNotificationHandler* aNotificationHandler); @@ -110,10 +101,6 @@ protected: const BluetoothAddress&, uint32_t, uint8_t> AudioConfigNotification; - class ConnectionStateInitOp; - class AudioStateInitOp; - class AudioConfigInitOp; - void ConnectionStateNtf(const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU); @@ -133,17 +120,12 @@ protected: class BluetoothDaemonA2dpInterface final : public BluetoothA2dpInterface { - class CleanupResultHandler; - class InitResultHandler; - public: BluetoothDaemonA2dpInterface(BluetoothDaemonA2dpModule* aModule); ~BluetoothDaemonA2dpInterface(); - void Init( - BluetoothA2dpNotificationHandler* aNotificationHandler, - BluetoothA2dpResultHandler* aRes) override; - void Cleanup(BluetoothA2dpResultHandler* aRes) override; + void SetNotificationHandler( + BluetoothA2dpNotificationHandler* aNotificationHandler) override; /* Connect / Disconnect */ diff --git a/dom/bluetooth/bluedroid/BluetoothDaemonAvrcpInterface.cpp b/dom/bluetooth/bluedroid/BluetoothDaemonAvrcpInterface.cpp index 93de980588..442bd9ecbf 100644 --- a/dom/bluetooth/bluedroid/BluetoothDaemonAvrcpInterface.cpp +++ b/dom/bluetooth/bluedroid/BluetoothDaemonAvrcpInterface.cpp @@ -15,8 +15,6 @@ using namespace mozilla::ipc; // AVRCP module // -const int BluetoothDaemonAvrcpModule::MAX_NUM_CLIENTS = 1; - BluetoothAvrcpNotificationHandler* BluetoothDaemonAvrcpModule::sNotificationHandler; @@ -258,8 +256,9 @@ BluetoothDaemonAvrcpModule::RegisterNotificationRspCmd( 1 + // Data length 256)); // Maximum data length - nsresult rv = PackPDU(aEvent, aType, - BluetoothAvrcpEventParamPair(aEvent, aParam), *pdu); + BluetoothAvrcpEventParamPair data(aEvent, aParam); + nsresult rv = PackPDU(aEvent, aType, static_cast(data.GetLength()), + data, *pdu); if (NS_FAILED(rv)) { return rv; } @@ -482,13 +481,12 @@ public: { } nsresult - operator () (nsString& aArg1, unsigned long& aArg2) const + operator () (BluetoothAddress& aArg1, unsigned long& aArg2) const { DaemonSocketPDU& pdu = GetPDU(); /* Read address */ - nsresult rv = UnpackPDU( - pdu, UnpackConversion(aArg1)); + nsresult rv = UnpackPDU(pdu, aArg1); if (NS_FAILED(rv)) { return rv; } @@ -738,40 +736,13 @@ BluetoothDaemonAvrcpModule::VolumeChangeNtf( UnpackPDUInitOp(aPDU)); } -// Init operator class for PassthroughCmdNotification -class BluetoothDaemonAvrcpModule::PassthroughCmdInitOp final - : private PDUInitOp -{ -public: - PassthroughCmdInitOp(DaemonSocketPDU& aPDU) - : PDUInitOp(aPDU) - { } - - nsresult - operator () (int& aArg1, int& aArg2) const - { - DaemonSocketPDU& pdu = GetPDU(); - - nsresult rv = UnpackPDU(pdu, UnpackConversion(aArg1)); - if (NS_FAILED(rv)) { - return rv; - } - rv = UnpackPDU(pdu, UnpackConversion(aArg2)); - if (NS_FAILED(rv)) { - return rv; - } - WarnAboutTrailingData(); - return NS_OK; - } -}; - void BluetoothDaemonAvrcpModule::PassthroughCmdNtf( const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU) { PassthroughCmdNotification::Dispatch( &BluetoothAvrcpNotificationHandler::PassthroughCmdNotification, - PassthroughCmdInitOp(aPDU)); + UnpackPDUInitOp(aPDU)); } #endif @@ -832,115 +803,13 @@ BluetoothDaemonAvrcpInterface::BluetoothDaemonAvrcpInterface( BluetoothDaemonAvrcpInterface::~BluetoothDaemonAvrcpInterface() { } -class BluetoothDaemonAvrcpInterface::InitResultHandler final - : public BluetoothSetupResultHandler -{ -public: - InitResultHandler(BluetoothAvrcpResultHandler* aRes) - : mRes(aRes) - { - MOZ_ASSERT(mRes); - } - - void OnError(BluetoothStatus aStatus) override - { - MOZ_ASSERT(NS_IsMainThread()); - - mRes->OnError(aStatus); - } - - void RegisterModule() override - { - MOZ_ASSERT(NS_IsMainThread()); - - mRes->Init(); - } - -private: - RefPtr mRes; -}; - void -BluetoothDaemonAvrcpInterface::Init( - BluetoothAvrcpNotificationHandler* aNotificationHandler, - BluetoothAvrcpResultHandler* aRes) +BluetoothDaemonAvrcpInterface::SetNotificationHandler( + BluetoothAvrcpNotificationHandler* aNotificationHandler) { MOZ_ASSERT(mModule); - // Set notification handler _before_ registering the module. It could - // happen that we receive notifications, before the result handler runs. mModule->SetNotificationHandler(aNotificationHandler); - - InitResultHandler* res; - - if (aRes) { - res = new InitResultHandler(aRes); - } else { - // We don't need a result handler if the caller is not interested. - res = nullptr; - } - - nsresult rv = mModule->RegisterModule( - BluetoothDaemonAvrcpModule::SERVICE_ID, - BluetoothDaemonAvrcpModule::MAX_NUM_CLIENTS, 0x00, res); - - if (NS_FAILED(rv) && aRes) { - DispatchError(aRes, rv); - } -} - -class BluetoothDaemonAvrcpInterface::CleanupResultHandler final - : public BluetoothSetupResultHandler -{ -public: - CleanupResultHandler(BluetoothDaemonAvrcpModule* aModule, - BluetoothAvrcpResultHandler* aRes) - : mModule(aModule) - , mRes(aRes) - { - MOZ_ASSERT(mModule); - } - - void OnError(BluetoothStatus aStatus) override - { - MOZ_ASSERT(NS_IsMainThread()); - - if (mRes) { - mRes->OnError(aStatus); - } - } - - void UnregisterModule() override - { - MOZ_ASSERT(NS_IsMainThread()); - - // Clear notification handler _after_ module has been - // unregistered. While unregistering the module, we might - // still receive notifications. - mModule->SetNotificationHandler(nullptr); - - if (mRes) { - mRes->Cleanup(); - } - } - -private: - BluetoothDaemonAvrcpModule* mModule; - RefPtr mRes; -}; - -void -BluetoothDaemonAvrcpInterface::Cleanup( - BluetoothAvrcpResultHandler* aRes) -{ - MOZ_ASSERT(mModule); - - nsresult rv = mModule->UnregisterModule( - BluetoothDaemonAvrcpModule::SERVICE_ID, - new CleanupResultHandler(mModule, aRes)); - if (NS_FAILED(rv)) { - DispatchError(aRes, rv); - } } void diff --git a/dom/bluetooth/bluedroid/BluetoothDaemonAvrcpInterface.h b/dom/bluetooth/bluedroid/BluetoothDaemonAvrcpInterface.h index 5ad9fb7e66..c70f663c35 100644 --- a/dom/bluetooth/bluedroid/BluetoothDaemonAvrcpInterface.h +++ b/dom/bluetooth/bluedroid/BluetoothDaemonAvrcpInterface.h @@ -62,18 +62,9 @@ public: #endif }; - static const int MAX_NUM_CLIENTS; - virtual nsresult Send(DaemonSocketPDU* aPDU, DaemonSocketResultHandler* aRes) = 0; - virtual nsresult RegisterModule(uint8_t aId, uint8_t aMode, - uint32_t aMaxNumClients, - BluetoothSetupResultHandler* aRes) = 0; - - virtual nsresult UnregisterModule(uint8_t aId, - BluetoothSetupResultHandler* aRes) = 0; - void SetNotificationHandler( BluetoothAvrcpNotificationHandler* aNotificationHandler); @@ -189,8 +180,9 @@ protected: class NotificationHandlerWrapper; typedef mozilla::ipc::DaemonNotificationRunnable2< - NotificationHandlerWrapper, void, nsString, unsigned long, - const nsAString&> + NotificationHandlerWrapper, void, + BluetoothAddress, unsigned long, + const BluetoothAddress&> RemoteFeatureNotification; typedef mozilla::ipc::DaemonNotificationRunnable0< @@ -242,14 +234,13 @@ protected: VolumeChangeNotification; typedef mozilla::ipc::DaemonNotificationRunnable2< - NotificationHandlerWrapper, void, int, int> + NotificationHandlerWrapper, void, uint8_t, uint8_t, int, int> PassthroughCmdNotification; class GetElementAttrInitOp; class GetPlayerAppAttrsTextInitOp; class GetPlayerAppValueInitOp; class GetPlayerAppValuesTextInitOp; - class PassthroughCmdInitOp; class RemoteFeatureInitOp; void RemoteFeatureNtf(const DaemonSocketPDUHeader& aHeader, @@ -305,10 +296,8 @@ public: BluetoothDaemonAvrcpInterface(BluetoothDaemonAvrcpModule* aModule); ~BluetoothDaemonAvrcpInterface(); - void Init(BluetoothAvrcpNotificationHandler* aNotificationHandler, - BluetoothAvrcpResultHandler* aRes) override; - - void Cleanup(BluetoothAvrcpResultHandler* aRes) override; + void SetNotificationHandler( + BluetoothAvrcpNotificationHandler* aNotificationHandler) override; void GetPlayStatusRsp(ControlPlayStatus aPlayStatus, uint32_t aSongLen, uint32_t aSongPos, diff --git a/dom/bluetooth/bluedroid/BluetoothDaemonCoreInterface.cpp b/dom/bluetooth/bluedroid/BluetoothDaemonCoreInterface.cpp index 6f8d09fd2e..cd397d3c97 100644 --- a/dom/bluetooth/bluedroid/BluetoothDaemonCoreInterface.cpp +++ b/dom/bluetooth/bluedroid/BluetoothDaemonCoreInterface.cpp @@ -17,21 +17,16 @@ using namespace mozilla::ipc; const int BluetoothDaemonCoreModule::MAX_NUM_CLIENTS = 1; -BluetoothNotificationHandler* BluetoothDaemonCoreModule::sNotificationHandler; +BluetoothCoreNotificationHandler* + BluetoothDaemonCoreModule::sNotificationHandler; void BluetoothDaemonCoreModule::SetNotificationHandler( - BluetoothNotificationHandler* aNotificationHandler) + BluetoothCoreNotificationHandler* aNotificationHandler) { sNotificationHandler = aNotificationHandler; } -BluetoothNotificationHandler* -BluetoothDaemonCoreModule::GetNotificationHandler() -{ - return sNotificationHandler; -} - void BluetoothDaemonCoreModule::HandleSvc(const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU, @@ -53,7 +48,7 @@ BluetoothDaemonCoreModule::HandleSvc(const DaemonSocketPDUHeader& aHeader, // nsresult -BluetoothDaemonCoreModule::EnableCmd(BluetoothResultHandler* aRes) +BluetoothDaemonCoreModule::EnableCmd(BluetoothCoreResultHandler* aRes) { MOZ_ASSERT(NS_IsMainThread()); @@ -70,7 +65,7 @@ BluetoothDaemonCoreModule::EnableCmd(BluetoothResultHandler* aRes) } nsresult -BluetoothDaemonCoreModule::DisableCmd(BluetoothResultHandler* aRes) +BluetoothDaemonCoreModule::DisableCmd(BluetoothCoreResultHandler* aRes) { MOZ_ASSERT(NS_IsMainThread()); @@ -88,7 +83,7 @@ BluetoothDaemonCoreModule::DisableCmd(BluetoothResultHandler* aRes) nsresult BluetoothDaemonCoreModule::GetAdapterPropertiesCmd( - BluetoothResultHandler* aRes) + BluetoothCoreResultHandler* aRes) { MOZ_ASSERT(NS_IsMainThread()); @@ -105,8 +100,8 @@ BluetoothDaemonCoreModule::GetAdapterPropertiesCmd( } nsresult -BluetoothDaemonCoreModule::GetAdapterPropertyCmd(const nsAString& aName, - BluetoothResultHandler* aRes) +BluetoothDaemonCoreModule::GetAdapterPropertyCmd( + BluetoothPropertyType aType, BluetoothCoreResultHandler* aRes) { MOZ_ASSERT(NS_IsMainThread()); @@ -114,8 +109,7 @@ BluetoothDaemonCoreModule::GetAdapterPropertyCmd(const nsAString& aName, new DaemonSocketPDU(SERVICE_ID, OPCODE_GET_ADAPTER_PROPERTY, 0)); - nsresult rv = PackPDU( - PackConversion(aName), *pdu); + nsresult rv = PackPDU(aType, *pdu); if (NS_FAILED(rv)) { return rv; } @@ -129,7 +123,7 @@ BluetoothDaemonCoreModule::GetAdapterPropertyCmd(const nsAString& aName, nsresult BluetoothDaemonCoreModule::SetAdapterPropertyCmd( - const BluetoothNamedValue& aProperty, BluetoothResultHandler* aRes) + const BluetoothProperty& aProperty, BluetoothCoreResultHandler* aRes) { MOZ_ASSERT(NS_IsMainThread()); @@ -151,7 +145,7 @@ BluetoothDaemonCoreModule::SetAdapterPropertyCmd( nsresult BluetoothDaemonCoreModule::GetRemoteDevicePropertiesCmd( - const BluetoothAddress& aRemoteAddr, BluetoothResultHandler* aRes) + const BluetoothAddress& aRemoteAddr, BluetoothCoreResultHandler* aRes) { MOZ_ASSERT(NS_IsMainThread()); @@ -174,8 +168,8 @@ BluetoothDaemonCoreModule::GetRemoteDevicePropertiesCmd( nsresult BluetoothDaemonCoreModule::GetRemoteDevicePropertyCmd( const BluetoothAddress& aRemoteAddr, - const nsAString& aName, - BluetoothResultHandler* aRes) + BluetoothPropertyType aType, + BluetoothCoreResultHandler* aRes) { MOZ_ASSERT(NS_IsMainThread()); @@ -183,9 +177,7 @@ BluetoothDaemonCoreModule::GetRemoteDevicePropertyCmd( new DaemonSocketPDU(SERVICE_ID, OPCODE_GET_REMOTE_DEVICE_PROPERTY, 0)); - nsresult rv = PackPDU( - aRemoteAddr, - PackConversion(aName), *pdu); + nsresult rv = PackPDU(aRemoteAddr, aType, *pdu); if (NS_FAILED(rv)) { return rv; } @@ -200,8 +192,8 @@ BluetoothDaemonCoreModule::GetRemoteDevicePropertyCmd( nsresult BluetoothDaemonCoreModule::SetRemoteDevicePropertyCmd( const BluetoothAddress& aRemoteAddr, - const BluetoothNamedValue& aProperty, - BluetoothResultHandler* aRes) + const BluetoothProperty& aProperty, + BluetoothCoreResultHandler* aRes) { MOZ_ASSERT(NS_IsMainThread()); @@ -224,7 +216,7 @@ BluetoothDaemonCoreModule::SetRemoteDevicePropertyCmd( nsresult BluetoothDaemonCoreModule::GetRemoteServiceRecordCmd( const BluetoothAddress& aRemoteAddr, const BluetoothUuid& aUuid, - BluetoothResultHandler* aRes) + BluetoothCoreResultHandler* aRes) { MOZ_ASSERT(NS_IsMainThread()); @@ -246,7 +238,7 @@ BluetoothDaemonCoreModule::GetRemoteServiceRecordCmd( nsresult BluetoothDaemonCoreModule::GetRemoteServicesCmd( - const BluetoothAddress& aRemoteAddr, BluetoothResultHandler* aRes) + const BluetoothAddress& aRemoteAddr, BluetoothCoreResultHandler* aRes) { MOZ_ASSERT(NS_IsMainThread()); @@ -266,7 +258,7 @@ BluetoothDaemonCoreModule::GetRemoteServicesCmd( } nsresult -BluetoothDaemonCoreModule::StartDiscoveryCmd(BluetoothResultHandler* aRes) +BluetoothDaemonCoreModule::StartDiscoveryCmd(BluetoothCoreResultHandler* aRes) { MOZ_ASSERT(NS_IsMainThread()); @@ -283,7 +275,7 @@ BluetoothDaemonCoreModule::StartDiscoveryCmd(BluetoothResultHandler* aRes) } nsresult -BluetoothDaemonCoreModule::CancelDiscoveryCmd(BluetoothResultHandler* aRes) +BluetoothDaemonCoreModule::CancelDiscoveryCmd(BluetoothCoreResultHandler* aRes) { MOZ_ASSERT(NS_IsMainThread()); @@ -302,7 +294,7 @@ BluetoothDaemonCoreModule::CancelDiscoveryCmd(BluetoothResultHandler* aRes) nsresult BluetoothDaemonCoreModule::CreateBondCmd(const BluetoothAddress& aBdAddr, BluetoothTransport aTransport, - BluetoothResultHandler* aRes) + BluetoothCoreResultHandler* aRes) { MOZ_ASSERT(NS_IsMainThread()); @@ -328,7 +320,7 @@ BluetoothDaemonCoreModule::CreateBondCmd(const BluetoothAddress& aBdAddr, nsresult BluetoothDaemonCoreModule::RemoveBondCmd(const BluetoothAddress& aBdAddr, - BluetoothResultHandler* aRes) + BluetoothCoreResultHandler* aRes) { MOZ_ASSERT(NS_IsMainThread()); @@ -350,7 +342,7 @@ BluetoothDaemonCoreModule::RemoveBondCmd(const BluetoothAddress& aBdAddr, nsresult BluetoothDaemonCoreModule::CancelBondCmd(const BluetoothAddress& aBdAddr, - BluetoothResultHandler* aRes) + BluetoothCoreResultHandler* aRes) { MOZ_ASSERT(NS_IsMainThread()); @@ -374,7 +366,7 @@ nsresult BluetoothDaemonCoreModule::PinReplyCmd(const BluetoothAddress& aBdAddr, bool aAccept, const BluetoothPinCode& aPinCode, - BluetoothResultHandler* aRes) + BluetoothCoreResultHandler* aRes) { MOZ_ASSERT(NS_IsMainThread()); @@ -398,7 +390,7 @@ nsresult BluetoothDaemonCoreModule::SspReplyCmd(const BluetoothAddress& aBdAddr, BluetoothSspVariant aVariant, bool aAccept, uint32_t aPasskey, - BluetoothResultHandler* aRes) + BluetoothCoreResultHandler* aRes) { MOZ_ASSERT(NS_IsMainThread()); @@ -419,8 +411,8 @@ BluetoothDaemonCoreModule::SspReplyCmd(const BluetoothAddress& aBdAddr, } nsresult -BluetoothDaemonCoreModule::DutModeConfigureCmd(bool aEnable, - BluetoothResultHandler* aRes) +BluetoothDaemonCoreModule::DutModeConfigureCmd( + bool aEnable, BluetoothCoreResultHandler* aRes) { MOZ_ASSERT(NS_IsMainThread()); @@ -443,7 +435,7 @@ BluetoothDaemonCoreModule::DutModeConfigureCmd(bool aEnable, nsresult BluetoothDaemonCoreModule::DutModeSendCmd(uint16_t aOpcode, uint8_t* aBuf, uint8_t aLen, - BluetoothResultHandler* aRes) + BluetoothCoreResultHandler* aRes) { MOZ_ASSERT(NS_IsMainThread()); @@ -467,7 +459,7 @@ BluetoothDaemonCoreModule::DutModeSendCmd(uint16_t aOpcode, nsresult BluetoothDaemonCoreModule::LeTestModeCmd(uint16_t aOpcode, uint8_t* aBuf, uint8_t aLen, - BluetoothResultHandler* aRes) + BluetoothCoreResultHandler* aRes) { MOZ_ASSERT(NS_IsMainThread()); @@ -494,207 +486,207 @@ BluetoothDaemonCoreModule::LeTestModeCmd(uint16_t aOpcode, void BluetoothDaemonCoreModule::ErrorRsp(const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU, - BluetoothResultHandler* aRes) + BluetoothCoreResultHandler* aRes) { ErrorRunnable::Dispatch( - aRes, &BluetoothResultHandler::OnError, UnpackPDUInitOp(aPDU)); + aRes, &BluetoothCoreResultHandler::OnError, UnpackPDUInitOp(aPDU)); } void BluetoothDaemonCoreModule::EnableRsp(const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU, - BluetoothResultHandler* aRes) + BluetoothCoreResultHandler* aRes) { ResultRunnable::Dispatch( - aRes, &BluetoothResultHandler::Enable, UnpackPDUInitOp(aPDU)); + aRes, &BluetoothCoreResultHandler::Enable, UnpackPDUInitOp(aPDU)); } void BluetoothDaemonCoreModule::DisableRsp(const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU, - BluetoothResultHandler* aRes) + BluetoothCoreResultHandler* aRes) { ResultRunnable::Dispatch( - aRes, &BluetoothResultHandler::Disable, UnpackPDUInitOp(aPDU)); + aRes, &BluetoothCoreResultHandler::Disable, UnpackPDUInitOp(aPDU)); } void BluetoothDaemonCoreModule::GetAdapterPropertiesRsp( const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU, - BluetoothResultHandler* aRes) + BluetoothCoreResultHandler* aRes) { ResultRunnable::Dispatch( - aRes, &BluetoothResultHandler::GetAdapterProperties, + aRes, &BluetoothCoreResultHandler::GetAdapterProperties, UnpackPDUInitOp(aPDU)); } void BluetoothDaemonCoreModule::GetAdapterPropertyRsp( const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU, - BluetoothResultHandler* aRes) + BluetoothCoreResultHandler* aRes) { ResultRunnable::Dispatch( - aRes, &BluetoothResultHandler::GetAdapterProperty, + aRes, &BluetoothCoreResultHandler::GetAdapterProperty, UnpackPDUInitOp(aPDU)); } void BluetoothDaemonCoreModule::SetAdapterPropertyRsp( const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU, - BluetoothResultHandler* aRes) + BluetoothCoreResultHandler* aRes) { ResultRunnable::Dispatch( - aRes, &BluetoothResultHandler::SetAdapterProperty, + aRes, &BluetoothCoreResultHandler::SetAdapterProperty, UnpackPDUInitOp(aPDU)); } void BluetoothDaemonCoreModule::GetRemoteDevicePropertiesRsp( const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU, - BluetoothResultHandler* aRes) + BluetoothCoreResultHandler* aRes) { ResultRunnable::Dispatch( - aRes, &BluetoothResultHandler::GetRemoteDeviceProperties, + aRes, &BluetoothCoreResultHandler::GetRemoteDeviceProperties, UnpackPDUInitOp(aPDU)); } void BluetoothDaemonCoreModule::GetRemoteDevicePropertyRsp( const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU, - BluetoothResultHandler* aRes) + BluetoothCoreResultHandler* aRes) { ResultRunnable::Dispatch( - aRes, &BluetoothResultHandler::GetRemoteDeviceProperty, + aRes, &BluetoothCoreResultHandler::GetRemoteDeviceProperty, UnpackPDUInitOp(aPDU)); } void BluetoothDaemonCoreModule::SetRemoteDevicePropertyRsp( const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU, - BluetoothResultHandler* aRes) + BluetoothCoreResultHandler* aRes) { ResultRunnable::Dispatch( - aRes, &BluetoothResultHandler::SetRemoteDeviceProperty, + aRes, &BluetoothCoreResultHandler::SetRemoteDeviceProperty, UnpackPDUInitOp(aPDU)); } void BluetoothDaemonCoreModule::GetRemoteServiceRecordRsp( const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU, - BluetoothResultHandler* aRes) + BluetoothCoreResultHandler* aRes) { ResultRunnable::Dispatch( - aRes, &BluetoothResultHandler::GetRemoteServiceRecord, + aRes, &BluetoothCoreResultHandler::GetRemoteServiceRecord, UnpackPDUInitOp(aPDU)); } void BluetoothDaemonCoreModule::GetRemoteServicesRsp( const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU, - BluetoothResultHandler* aRes) + BluetoothCoreResultHandler* aRes) { ResultRunnable::Dispatch( - aRes, &BluetoothResultHandler::GetRemoteServices, + aRes, &BluetoothCoreResultHandler::GetRemoteServices, UnpackPDUInitOp(aPDU)); } void BluetoothDaemonCoreModule::StartDiscoveryRsp( const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU, - BluetoothResultHandler* aRes) + BluetoothCoreResultHandler* aRes) { ResultRunnable::Dispatch( - aRes, &BluetoothResultHandler::StartDiscovery, + aRes, &BluetoothCoreResultHandler::StartDiscovery, UnpackPDUInitOp(aPDU)); } void BluetoothDaemonCoreModule::CancelDiscoveryRsp( const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU, - BluetoothResultHandler* aRes) + BluetoothCoreResultHandler* aRes) { ResultRunnable::Dispatch( - aRes, &BluetoothResultHandler::CancelDiscovery, + aRes, &BluetoothCoreResultHandler::CancelDiscovery, UnpackPDUInitOp(aPDU)); } void BluetoothDaemonCoreModule::CreateBondRsp( const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU, - BluetoothResultHandler* aRes) + BluetoothCoreResultHandler* aRes) { ResultRunnable::Dispatch( - aRes, &BluetoothResultHandler::CreateBond, + aRes, &BluetoothCoreResultHandler::CreateBond, UnpackPDUInitOp(aPDU)); } void BluetoothDaemonCoreModule::RemoveBondRsp( const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU, - BluetoothResultHandler* aRes) + BluetoothCoreResultHandler* aRes) { ResultRunnable::Dispatch( - aRes, &BluetoothResultHandler::RemoveBond, + aRes, &BluetoothCoreResultHandler::RemoveBond, UnpackPDUInitOp(aPDU)); } void BluetoothDaemonCoreModule::CancelBondRsp( const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU, - BluetoothResultHandler* aRes) + BluetoothCoreResultHandler* aRes) { ResultRunnable::Dispatch( - aRes, &BluetoothResultHandler::CancelBond, + aRes, &BluetoothCoreResultHandler::CancelBond, UnpackPDUInitOp(aPDU)); } void BluetoothDaemonCoreModule::PinReplyRsp( const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU, - BluetoothResultHandler* aRes) + BluetoothCoreResultHandler* aRes) { ResultRunnable::Dispatch( - aRes, &BluetoothResultHandler::PinReply, + aRes, &BluetoothCoreResultHandler::PinReply, UnpackPDUInitOp(aPDU)); } void BluetoothDaemonCoreModule::SspReplyRsp( const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU, - BluetoothResultHandler* aRes) + BluetoothCoreResultHandler* aRes) { ResultRunnable::Dispatch( - aRes, &BluetoothResultHandler::SspReply, + aRes, &BluetoothCoreResultHandler::SspReply, UnpackPDUInitOp(aPDU)); } void BluetoothDaemonCoreModule::DutModeConfigureRsp( const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU, - BluetoothResultHandler* aRes) + BluetoothCoreResultHandler* aRes) { ResultRunnable::Dispatch( - aRes, &BluetoothResultHandler::DutModeConfigure, + aRes, &BluetoothCoreResultHandler::DutModeConfigure, UnpackPDUInitOp(aPDU)); } void BluetoothDaemonCoreModule::DutModeSendRsp( const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU, - BluetoothResultHandler* aRes) + BluetoothCoreResultHandler* aRes) { ResultRunnable::Dispatch( - aRes, &BluetoothResultHandler::DutModeSend, + aRes, &BluetoothCoreResultHandler::DutModeSend, UnpackPDUInitOp(aPDU)); } void BluetoothDaemonCoreModule::LeTestModeRsp( const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU, - BluetoothResultHandler* aRes) + BluetoothCoreResultHandler* aRes) { ResultRunnable::Dispatch( - aRes, &BluetoothResultHandler::LeTestMode, + aRes, &BluetoothCoreResultHandler::LeTestMode, UnpackPDUInitOp(aPDU)); } @@ -706,7 +698,7 @@ BluetoothDaemonCoreModule::HandleRsp( static void (BluetoothDaemonCoreModule::* const HandleRsp[])( const DaemonSocketPDUHeader&, DaemonSocketPDU&, - BluetoothResultHandler*) = { + BluetoothCoreResultHandler*) = { [OPCODE_ERROR] = &BluetoothDaemonCoreModule::ErrorRsp, [OPCODE_ENABLE] = @@ -758,8 +750,8 @@ BluetoothDaemonCoreModule::HandleRsp( return; } - RefPtr res = - static_cast(aRes); + RefPtr res = + static_cast(aRes); if (!res) { return; // Return early if no result handler has been set for response @@ -774,7 +766,7 @@ BluetoothDaemonCoreModule::HandleRsp( class BluetoothDaemonCoreModule::NotificationHandlerWrapper final { public: - typedef BluetoothNotificationHandler ObjectType; + typedef BluetoothCoreNotificationHandler ObjectType; static ObjectType* GetInstance() { @@ -789,7 +781,7 @@ BluetoothDaemonCoreModule::AdapterStateChangedNtf( const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU) { AdapterStateChangedNotification::Dispatch( - &BluetoothNotificationHandler::AdapterStateChangedNotification, + &BluetoothCoreNotificationHandler::AdapterStateChangedNotification, UnpackPDUInitOp(aPDU)); } @@ -838,7 +830,7 @@ BluetoothDaemonCoreModule::AdapterPropertiesNtf( const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU) { AdapterPropertiesNotification::Dispatch( - &BluetoothNotificationHandler::AdapterPropertiesNotification, + &BluetoothCoreNotificationHandler::AdapterPropertiesNotification, AdapterPropertiesInitOp(aPDU)); } @@ -893,7 +885,7 @@ BluetoothDaemonCoreModule::RemoteDevicePropertiesNtf( const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU) { RemoteDevicePropertiesNotification::Dispatch( - &BluetoothNotificationHandler::RemoteDevicePropertiesNotification, + &BluetoothCoreNotificationHandler::RemoteDevicePropertiesNotification, RemoteDevicePropertiesInitOp(aPDU)); } @@ -935,7 +927,7 @@ BluetoothDaemonCoreModule::DeviceFoundNtf( const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU) { DeviceFoundNotification::Dispatch( - &BluetoothNotificationHandler::DeviceFoundNotification, + &BluetoothCoreNotificationHandler::DeviceFoundNotification, DeviceFoundInitOp(aPDU)); } @@ -944,205 +936,44 @@ BluetoothDaemonCoreModule::DiscoveryStateChangedNtf( const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU) { DiscoveryStateChangedNotification::Dispatch( - &BluetoothNotificationHandler::DiscoveryStateChangedNotification, + &BluetoothCoreNotificationHandler::DiscoveryStateChangedNotification, UnpackPDUInitOp(aPDU)); } -// Init operator class for PinRequestNotification -class BluetoothDaemonCoreModule::PinRequestInitOp final - : private PDUInitOp -{ -public: - PinRequestInitOp(DaemonSocketPDU& aPDU) - : PDUInitOp(aPDU) - { } - - nsresult - operator () (BluetoothAddress& aArg1, BluetoothRemoteName& aArg2, - uint32_t& aArg3) const - { - DaemonSocketPDU& pdu = GetPDU(); - - /* Read remote address */ - nsresult rv = UnpackPDU(pdu, aArg1); - if (NS_FAILED(rv)) { - return rv; - } - - /* Read remote name */ - rv = UnpackPDU(pdu, aArg2); - if (NS_FAILED(rv)) { - return rv; - } - - /* Read CoD */ - rv = UnpackPDU(pdu, aArg3); - if (NS_FAILED(rv)) { - return rv; - } - WarnAboutTrailingData(); - return NS_OK; - } -}; - void BluetoothDaemonCoreModule::PinRequestNtf( const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU) { PinRequestNotification::Dispatch( - &BluetoothNotificationHandler::PinRequestNotification, - PinRequestInitOp(aPDU)); + &BluetoothCoreNotificationHandler::PinRequestNotification, + UnpackPDUInitOp(aPDU)); } -// Init operator class for SspRequestNotification -class BluetoothDaemonCoreModule::SspRequestInitOp final - : private PDUInitOp -{ -public: - SspRequestInitOp(DaemonSocketPDU& aPDU) - : PDUInitOp(aPDU) - { } - - nsresult - operator () (BluetoothAddress& aArg1, BluetoothRemoteName& aArg2, - uint32_t& aArg3, BluetoothSspVariant& aArg4, - uint32_t& aArg5) const - { - DaemonSocketPDU& pdu = GetPDU(); - - /* Read remote address */ - nsresult rv = UnpackPDU(pdu, aArg1); - if (NS_FAILED(rv)) { - return rv; - } - - /* Read remote name */ - rv = UnpackPDU(pdu, aArg2); - if (NS_FAILED(rv)) { - return rv; - } - - /* Read CoD */ - rv = UnpackPDU(pdu, aArg3); - if (NS_FAILED(rv)) { - return rv; - } - - /* Read pairing variant */ - rv = UnpackPDU(pdu, aArg4); - if (NS_FAILED(rv)) { - return rv; - } - - /* Read passkey */ - rv = UnpackPDU(pdu, aArg5); - if (NS_FAILED(rv)) { - return rv; - } - WarnAboutTrailingData(); - return NS_OK; - } -}; - void BluetoothDaemonCoreModule::SspRequestNtf( const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU) { SspRequestNotification::Dispatch( - &BluetoothNotificationHandler::SspRequestNotification, - SspRequestInitOp(aPDU)); + &BluetoothCoreNotificationHandler::SspRequestNotification, + UnpackPDUInitOp(aPDU)); } -// Init operator class for BondStateChangedNotification -class BluetoothDaemonCoreModule::BondStateChangedInitOp final - : private PDUInitOp -{ -public: - BondStateChangedInitOp(DaemonSocketPDU& aPDU) - : PDUInitOp(aPDU) - { } - - nsresult - operator () (BluetoothStatus& aArg1, BluetoothAddress& aArg2, - BluetoothBondState& aArg3) const - { - DaemonSocketPDU& pdu = GetPDU(); - - /* Read status */ - nsresult rv = UnpackPDU(pdu, aArg1); - if (NS_FAILED(rv)) { - return rv; - } - - /* Read remote address */ - rv = UnpackPDU(pdu, aArg2); - if (NS_FAILED(rv)) { - return rv; - } - - /* Read bond state */ - rv = UnpackPDU(pdu, aArg3); - if (NS_FAILED(rv)) { - return rv; - } - WarnAboutTrailingData(); - return NS_OK; - } -}; - void BluetoothDaemonCoreModule::BondStateChangedNtf( const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU) { BondStateChangedNotification::Dispatch( - &BluetoothNotificationHandler::BondStateChangedNotification, - BondStateChangedInitOp(aPDU)); + &BluetoothCoreNotificationHandler::BondStateChangedNotification, + UnpackPDUInitOp(aPDU)); } -// Init operator class for AclStateChangedNotification -class BluetoothDaemonCoreModule::AclStateChangedInitOp final - : private PDUInitOp -{ -public: - AclStateChangedInitOp(DaemonSocketPDU& aPDU) - : PDUInitOp(aPDU) - { } - - nsresult - operator () (BluetoothStatus& aArg1, BluetoothAddress& aArg2, - BluetoothAclState& aArg3) const - { - DaemonSocketPDU& pdu = GetPDU(); - - /* Read status */ - nsresult rv = UnpackPDU(pdu, aArg1); - if (NS_FAILED(rv)) { - return rv; - } - - /* Read remote address */ - rv = UnpackPDU(pdu, aArg2); - if (NS_FAILED(rv)) { - return rv; - } - - /* Read ACL state */ - rv = UnpackPDU(pdu, aArg3); - if (NS_FAILED(rv)) { - return rv; - } - WarnAboutTrailingData(); - return NS_OK; - } -}; - void BluetoothDaemonCoreModule::AclStateChangedNtf( const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU) { AclStateChangedNotification::Dispatch( - &BluetoothNotificationHandler::AclStateChangedNotification, - AclStateChangedInitOp(aPDU)); + &BluetoothCoreNotificationHandler::AclStateChangedNotification, + UnpackPDUInitOp(aPDU)); } // Init operator class for DutModeRecvNotification @@ -1187,7 +1018,7 @@ BluetoothDaemonCoreModule::DutModeRecvNtf( const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU) { DutModeRecvNotification::Dispatch( - &BluetoothNotificationHandler::DutModeRecvNotification, + &BluetoothCoreNotificationHandler::DutModeRecvNotification, DutModeRecvInitOp(aPDU)); } @@ -1196,7 +1027,7 @@ BluetoothDaemonCoreModule::LeTestModeNtf( const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU) { LeTestModeNotification::Dispatch( - &BluetoothNotificationHandler::LeTestModeNotification, + &BluetoothCoreNotificationHandler::LeTestModeNotification, UnpackPDUInitOp(aPDU)); } @@ -1232,4 +1063,294 @@ BluetoothDaemonCoreModule::HandleNtf( (this->*(HandleNtf[index]))(aHeader, aPDU); } +// +// Core interface +// + +BluetoothDaemonCoreInterface::BluetoothDaemonCoreInterface( + BluetoothDaemonCoreModule* aModule) + : mModule(aModule) +{ } + +BluetoothDaemonCoreInterface::~BluetoothDaemonCoreInterface() +{ } + +void +BluetoothDaemonCoreInterface::SetNotificationHandler( + BluetoothCoreNotificationHandler* aNotificationHandler) +{ + MOZ_ASSERT(mModule); + + mModule->SetNotificationHandler(aNotificationHandler); +} + +/* Enable / Disable */ + +void +BluetoothDaemonCoreInterface::Enable(BluetoothCoreResultHandler* aRes) +{ + nsresult rv = mModule->EnableCmd(aRes); + if (NS_FAILED(rv)) { + DispatchError(aRes, rv); + } +} + +void +BluetoothDaemonCoreInterface::Disable(BluetoothCoreResultHandler* aRes) +{ + nsresult rv = mModule->DisableCmd(aRes); + if (NS_FAILED(rv)) { + DispatchError(aRes, rv); + } +} + +/* Adapter Properties */ + +void +BluetoothDaemonCoreInterface::GetAdapterProperties( + BluetoothCoreResultHandler* aRes) +{ + nsresult rv = mModule->GetAdapterPropertiesCmd(aRes); + if (NS_FAILED(rv)) { + DispatchError(aRes, rv); + } +} + +void +BluetoothDaemonCoreInterface::GetAdapterProperty( + BluetoothPropertyType aType, BluetoothCoreResultHandler* aRes) +{ + nsresult rv = mModule->GetAdapterPropertyCmd(aType, aRes); + if (NS_FAILED(rv)) { + DispatchError(aRes, rv); + } +} + +void +BluetoothDaemonCoreInterface::SetAdapterProperty( + const BluetoothProperty& aProperty, BluetoothCoreResultHandler* aRes) +{ + nsresult rv = mModule->SetAdapterPropertyCmd(aProperty, aRes); + if (NS_FAILED(rv)) { + DispatchError(aRes, rv); + } +} + +/* Remote Device Properties */ + +void +BluetoothDaemonCoreInterface::GetRemoteDeviceProperties( + const BluetoothAddress& aRemoteAddr, BluetoothCoreResultHandler* aRes) +{ + nsresult rv = mModule->GetRemoteDevicePropertiesCmd(aRemoteAddr, aRes); + if (NS_FAILED(rv)) { + DispatchError(aRes, rv); + } +} + +void +BluetoothDaemonCoreInterface::GetRemoteDeviceProperty( + const BluetoothAddress& aRemoteAddr, BluetoothPropertyType aType, + BluetoothCoreResultHandler* aRes) +{ + nsresult rv = mModule->GetRemoteDevicePropertyCmd(aRemoteAddr, aType, aRes); + if (NS_FAILED(rv)) { + DispatchError(aRes, rv); + } +} + +void +BluetoothDaemonCoreInterface::SetRemoteDeviceProperty( + const BluetoothAddress& aRemoteAddr, const BluetoothProperty& aProperty, + BluetoothCoreResultHandler* aRes) +{ + nsresult rv = mModule->SetRemoteDevicePropertyCmd(aRemoteAddr, + aProperty, + aRes); + if (NS_FAILED(rv)) { + DispatchError(aRes, rv); + } +} + +/* Remote Services */ + +void +BluetoothDaemonCoreInterface::GetRemoteServiceRecord( + const BluetoothAddress& aRemoteAddr, const BluetoothUuid& aUuid, + BluetoothCoreResultHandler* aRes) +{ + nsresult rv = mModule->GetRemoteServiceRecordCmd(aRemoteAddr, aUuid, aRes); + if (NS_FAILED(rv)) { + DispatchError(aRes, rv); + } +} + +void +BluetoothDaemonCoreInterface::GetRemoteServices( + const BluetoothAddress& aRemoteAddr, BluetoothCoreResultHandler* aRes) +{ + nsresult rv = mModule->GetRemoteServicesCmd(aRemoteAddr, aRes); + if (NS_FAILED(rv)) { + DispatchError(aRes, rv); + } +} + +/* Discovery */ + +void +BluetoothDaemonCoreInterface::StartDiscovery(BluetoothCoreResultHandler* aRes) +{ + nsresult rv = mModule->StartDiscoveryCmd(aRes); + if (NS_FAILED(rv)) { + DispatchError(aRes, rv); + } +} + +void +BluetoothDaemonCoreInterface::CancelDiscovery(BluetoothCoreResultHandler* aRes) +{ + nsresult rv = mModule->CancelDiscoveryCmd(aRes); + if (NS_FAILED(rv)) { + DispatchError(aRes, rv); + } +} + +/* Bonds */ + +void +BluetoothDaemonCoreInterface::CreateBond(const BluetoothAddress& aBdAddr, + BluetoothTransport aTransport, + BluetoothCoreResultHandler* aRes) +{ + nsresult rv = mModule->CreateBondCmd(aBdAddr, aTransport, aRes); + if (NS_FAILED(rv)) { + DispatchError(aRes, rv); + } +} + +void +BluetoothDaemonCoreInterface::RemoveBond(const BluetoothAddress& aBdAddr, + BluetoothCoreResultHandler* aRes) +{ + nsresult rv = mModule->RemoveBondCmd(aBdAddr, aRes); + if (NS_FAILED(rv)) { + DispatchError(aRes, rv); + } +} + +void +BluetoothDaemonCoreInterface::CancelBond( + const BluetoothAddress& aBdAddr, BluetoothCoreResultHandler* aRes) +{ + nsresult rv = mModule->CancelBondCmd(aBdAddr, aRes); + if (NS_FAILED(rv)) { + DispatchError(aRes, rv); + } +} + +/* Connection */ + +void +BluetoothDaemonCoreInterface::GetConnectionState( + const BluetoothAddress& aBdAddr, BluetoothCoreResultHandler* aRes) +{ + // NO-OP: no corresponding interface of current BlueZ +} + +/* Authentication */ + +void +BluetoothDaemonCoreInterface::PinReply(const BluetoothAddress& aBdAddr, + bool aAccept, + const BluetoothPinCode& aPinCode, + BluetoothCoreResultHandler* aRes) +{ + nsresult rv = mModule->PinReplyCmd(aBdAddr, aAccept, aPinCode, aRes); + if (NS_FAILED(rv)) { + DispatchError(aRes, rv); + } +} + +void +BluetoothDaemonCoreInterface::SspReply(const BluetoothAddress& aBdAddr, + BluetoothSspVariant aVariant, + bool aAccept, uint32_t aPasskey, + BluetoothCoreResultHandler* aRes) +{ + nsresult rv = mModule->SspReplyCmd(aBdAddr, aVariant, aAccept, aPasskey, + aRes); + if (NS_FAILED(rv)) { + DispatchError(aRes, rv); + } +} + +/* DUT Mode */ + +void +BluetoothDaemonCoreInterface::DutModeConfigure( + bool aEnable, BluetoothCoreResultHandler* aRes) +{ + nsresult rv = mModule->DutModeConfigureCmd(aEnable, aRes); + if (NS_FAILED(rv)) { + DispatchError(aRes, rv); + } +} + +void +BluetoothDaemonCoreInterface::DutModeSend(uint16_t aOpcode, + uint8_t* aBuf, + uint8_t aLen, + BluetoothCoreResultHandler* aRes) +{ + nsresult rv = mModule->DutModeSendCmd(aOpcode, aBuf, aLen, aRes); + if (NS_FAILED(rv)) { + DispatchError(aRes, rv); + } +} + +/* LE Mode */ + +void +BluetoothDaemonCoreInterface::LeTestMode(uint16_t aOpcode, + uint8_t* aBuf, + uint8_t aLen, + BluetoothCoreResultHandler* aRes) +{ + nsresult rv = mModule->LeTestModeCmd(aOpcode, aBuf, aLen, aRes); + if (NS_FAILED(rv)) { + DispatchError(aRes, rv); + } +} + +/* Energy Information */ + +void +BluetoothDaemonCoreInterface::ReadEnergyInfo(BluetoothCoreResultHandler* aRes) +{ + // NO-OP: no corresponding interface of current BlueZ +} + +void +BluetoothDaemonCoreInterface::DispatchError(BluetoothCoreResultHandler* aRes, + BluetoothStatus aStatus) +{ + DaemonResultRunnable1< + BluetoothCoreResultHandler, void, + BluetoothStatus, BluetoothStatus>::Dispatch( + aRes, &BluetoothCoreResultHandler::OnError, + ConstantInitOp1(aStatus)); +} + +void +BluetoothDaemonCoreInterface::DispatchError(BluetoothCoreResultHandler* aRes, + nsresult aRv) +{ + BluetoothStatus status; + + if (NS_WARN_IF(NS_FAILED(Convert(aRv, status)))) { + status = STATUS_FAIL; + } + DispatchError(aRes, status); +} + END_BLUETOOTH_NAMESPACE diff --git a/dom/bluetooth/bluedroid/BluetoothDaemonCoreInterface.h b/dom/bluetooth/bluedroid/BluetoothDaemonCoreInterface.h index f955330c1d..0d6f03d47e 100644 --- a/dom/bluetooth/bluedroid/BluetoothDaemonCoreInterface.h +++ b/dom/bluetooth/bluedroid/BluetoothDaemonCoreInterface.h @@ -65,74 +65,73 @@ public: DaemonSocketResultHandler* aRes) = 0; void SetNotificationHandler( - BluetoothNotificationHandler* aNotificationHandler); - - BluetoothNotificationHandler* GetNotificationHandler(); + BluetoothCoreNotificationHandler* aNotificationHandler); // // Commands // - nsresult EnableCmd(BluetoothResultHandler* aRes); + nsresult EnableCmd(BluetoothCoreResultHandler* aRes); - nsresult DisableCmd(BluetoothResultHandler* aRes); + nsresult DisableCmd(BluetoothCoreResultHandler* aRes); - nsresult GetAdapterPropertiesCmd(BluetoothResultHandler* aRes); + nsresult GetAdapterPropertiesCmd(BluetoothCoreResultHandler* aRes); - nsresult GetAdapterPropertyCmd(const nsAString& aName, - BluetoothResultHandler* aRes); + nsresult GetAdapterPropertyCmd(BluetoothPropertyType aType, + BluetoothCoreResultHandler* aRes); - nsresult SetAdapterPropertyCmd(const BluetoothNamedValue& aProperty, - BluetoothResultHandler* aRes); + nsresult SetAdapterPropertyCmd(const BluetoothProperty& aProperty, + BluetoothCoreResultHandler* aRes); nsresult GetRemoteDevicePropertiesCmd(const BluetoothAddress& aRemoteAddr, - BluetoothResultHandler* aRes); + BluetoothCoreResultHandler* aRes); nsresult GetRemoteDevicePropertyCmd(const BluetoothAddress& aRemoteAddr, - const nsAString& aName, - BluetoothResultHandler* aRes); + BluetoothPropertyType aType, + BluetoothCoreResultHandler* aRes); nsresult SetRemoteDevicePropertyCmd(const BluetoothAddress& aRemoteAddr, - const BluetoothNamedValue& aProperty, - BluetoothResultHandler* aRes); + const BluetoothProperty& aProperty, + BluetoothCoreResultHandler* aRes); nsresult GetRemoteServiceRecordCmd(const BluetoothAddress& aRemoteAddr, const BluetoothUuid& aUuid, - BluetoothResultHandler* aRes); + BluetoothCoreResultHandler* aRes); nsresult GetRemoteServicesCmd(const BluetoothAddress& aRemoteAddr, - BluetoothResultHandler* aRes); + BluetoothCoreResultHandler* aRes); - nsresult StartDiscoveryCmd(BluetoothResultHandler* aRes); + nsresult StartDiscoveryCmd(BluetoothCoreResultHandler* aRes); - nsresult CancelDiscoveryCmd(BluetoothResultHandler* aRes); + nsresult CancelDiscoveryCmd(BluetoothCoreResultHandler* aRes); nsresult CreateBondCmd(const BluetoothAddress& aBdAddr, BluetoothTransport aTransport, - BluetoothResultHandler* aRes); + BluetoothCoreResultHandler* aRes); nsresult RemoveBondCmd(const BluetoothAddress& aBdAddr, - BluetoothResultHandler* aRes); + BluetoothCoreResultHandler* aRes); nsresult CancelBondCmd(const BluetoothAddress& aBdAddr, - BluetoothResultHandler* aRes); + BluetoothCoreResultHandler* aRes); nsresult PinReplyCmd(const BluetoothAddress& aBdAddr, bool aAccept, const BluetoothPinCode& aPinCode, - BluetoothResultHandler* aRes); + BluetoothCoreResultHandler* aRes); nsresult SspReplyCmd(const BluetoothAddress& aBdAddr, BluetoothSspVariant aVariant, bool aAccept, uint32_t aPasskey, - BluetoothResultHandler* aRes); + BluetoothCoreResultHandler* aRes); - nsresult DutModeConfigureCmd(bool aEnable, BluetoothResultHandler* aRes); + nsresult DutModeConfigureCmd(bool aEnable, + BluetoothCoreResultHandler* aRes); nsresult DutModeSendCmd(uint16_t aOpcode, uint8_t* aBuf, uint8_t aLen, - BluetoothResultHandler* aRes); + BluetoothCoreResultHandler* aRes); nsresult LeTestModeCmd(uint16_t aOpcode, uint8_t* aBuf, uint8_t aLen, - BluetoothResultHandler* aRes); + BluetoothCoreResultHandler* aRes); protected: void HandleSvc(const DaemonSocketPDUHeader& aHeader, @@ -145,91 +144,90 @@ private: // typedef mozilla::ipc::DaemonResultRunnable0< - BluetoothResultHandler, void> + BluetoothCoreResultHandler, void> ResultRunnable; typedef mozilla::ipc::DaemonResultRunnable1< - BluetoothResultHandler, void, BluetoothStatus, BluetoothStatus> + BluetoothCoreResultHandler, void, BluetoothStatus, BluetoothStatus> ErrorRunnable; void ErrorRsp(const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU, - BluetoothResultHandler* aRes); + BluetoothCoreResultHandler* aRes); void EnableRsp(const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU, - BluetoothResultHandler* aRes); + BluetoothCoreResultHandler* aRes); void DisableRsp(const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU, - BluetoothResultHandler* aRes); + BluetoothCoreResultHandler* aRes); void GetAdapterPropertiesRsp(const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU, - BluetoothResultHandler* aRes); + BluetoothCoreResultHandler* aRes); void GetAdapterPropertyRsp(const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU, - BluetoothResultHandler* aRes); + BluetoothCoreResultHandler* aRes); void SetAdapterPropertyRsp(const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU, - BluetoothResultHandler* aRes); + BluetoothCoreResultHandler* aRes); void GetRemoteDevicePropertiesRsp(const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU, - BluetoothResultHandler* aRes); + BluetoothCoreResultHandler* aRes); - void - GetRemoteDevicePropertyRsp(const DaemonSocketPDUHeader& aHeader, - DaemonSocketPDU& aPDU, - BluetoothResultHandler* aRes); + void GetRemoteDevicePropertyRsp(const DaemonSocketPDUHeader& aHeader, + DaemonSocketPDU& aPDU, + BluetoothCoreResultHandler* aRes); void SetRemoteDevicePropertyRsp(const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU, - BluetoothResultHandler* aRes); + BluetoothCoreResultHandler* aRes); void GetRemoteServiceRecordRsp(const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU, - BluetoothResultHandler* aRes); + BluetoothCoreResultHandler* aRes); void GetRemoteServicesRsp(const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU, - BluetoothResultHandler* aRes); + BluetoothCoreResultHandler* aRes); void StartDiscoveryRsp(const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU, - BluetoothResultHandler* aRes); + BluetoothCoreResultHandler* aRes); void CancelDiscoveryRsp(const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU, - BluetoothResultHandler* aRes); + BluetoothCoreResultHandler* aRes); void CreateBondRsp(const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU, - BluetoothResultHandler* aRes); + BluetoothCoreResultHandler* aRes); void RemoveBondRsp(const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU, - BluetoothResultHandler* aRes); + BluetoothCoreResultHandler* aRes); void CancelBondRsp(const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU, - BluetoothResultHandler* aRes); + BluetoothCoreResultHandler* aRes); void PinReplyRsp(const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU, - BluetoothResultHandler* aRes); + BluetoothCoreResultHandler* aRes); void SspReplyRsp(const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU, - BluetoothResultHandler* aRes); + BluetoothCoreResultHandler* aRes); void DutModeConfigureRsp(const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU, - BluetoothResultHandler* aRes); + BluetoothCoreResultHandler* aRes); void DutModeSendRsp(const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU, - BluetoothResultHandler* aRes); + BluetoothCoreResultHandler* aRes); void LeTestModeRsp(const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU, - BluetoothResultHandler* aRes); + BluetoothCoreResultHandler* aRes); void HandleRsp(const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU, DaemonSocketResultHandler* aRes); @@ -298,14 +296,10 @@ private: NotificationHandlerWrapper, void, BluetoothStatus, uint16_t> LeTestModeNotification; - class AclStateChangedInitOp; class AdapterPropertiesInitOp; - class BondStateChangedInitOp; class DeviceFoundInitOp; class DutModeRecvInitOp; - class PinRequestInitOp; class RemoteDevicePropertiesInitOp; - class SspRequestInitOp; void AdapterStateChangedNtf(const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU); @@ -343,7 +337,104 @@ private: void HandleNtf(const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU, DaemonSocketResultHandler* aRes); - static BluetoothNotificationHandler* sNotificationHandler; + static BluetoothCoreNotificationHandler* sNotificationHandler; +}; + +class BluetoothDaemonCoreInterface final + : public BluetoothCoreInterface +{ +public: + BluetoothDaemonCoreInterface(BluetoothDaemonCoreModule* aModule); + ~BluetoothDaemonCoreInterface(); + + void SetNotificationHandler( + BluetoothCoreNotificationHandler* aNotificationHandler) override; + + /* Enable / Disable */ + + void Enable(BluetoothCoreResultHandler* aRes) override; + void Disable(BluetoothCoreResultHandler* aRes) override; + + /* Adapter Properties */ + + void GetAdapterProperties(BluetoothCoreResultHandler* aRes) override; + void GetAdapterProperty(BluetoothPropertyType aType, + BluetoothCoreResultHandler* aRes) override; + void SetAdapterProperty(const BluetoothProperty& aProperty, + BluetoothCoreResultHandler* aRes) override; + + /* Remote Device Properties */ + + void GetRemoteDeviceProperties(const BluetoothAddress& aRemoteAddr, + BluetoothCoreResultHandler* aRes) override; + void GetRemoteDeviceProperty(const BluetoothAddress& aRemoteAddr, + BluetoothPropertyType aType, + BluetoothCoreResultHandler* aRes) override; + void SetRemoteDeviceProperty(const BluetoothAddress& aRemoteAddr, + const BluetoothProperty& aProperty, + BluetoothCoreResultHandler* aRes) override; + + /* Remote Services */ + + void GetRemoteServiceRecord(const BluetoothAddress& aRemoteAddr, + const BluetoothUuid& aUuid, + BluetoothCoreResultHandler* aRes) override; + void GetRemoteServices(const BluetoothAddress& aRemoteAddr, + BluetoothCoreResultHandler* aRes) override; + + /* Discovery */ + + void StartDiscovery(BluetoothCoreResultHandler* aRes) override; + void CancelDiscovery(BluetoothCoreResultHandler* aRes) override; + + /* Bonds */ + + void CreateBond(const BluetoothAddress& aBdAddr, + BluetoothTransport aTransport, + BluetoothCoreResultHandler* aRes) override; + void RemoveBond(const BluetoothAddress& aBdAddr, + BluetoothCoreResultHandler* aRes) override; + void CancelBond(const BluetoothAddress& aBdAddr, + BluetoothCoreResultHandler* aRes) override; + + /* Connection */ + + void GetConnectionState(const BluetoothAddress& aBdAddr, + BluetoothCoreResultHandler* aRes) override; + + /* Authentication */ + + void PinReply(const BluetoothAddress& aBdAddr, bool aAccept, + const BluetoothPinCode& aPinCode, + BluetoothCoreResultHandler* aRes) override; + + void SspReply(const BluetoothAddress& aBdAddr, + BluetoothSspVariant aVariant, + bool aAccept, uint32_t aPasskey, + BluetoothCoreResultHandler* aRes) override; + + /* DUT Mode */ + + void DutModeConfigure(bool aEnable, BluetoothCoreResultHandler* aRes); + void DutModeSend(uint16_t aOpcode, uint8_t* aBuf, uint8_t aLen, + BluetoothCoreResultHandler* aRes) override; + + /* LE Mode */ + + void LeTestMode(uint16_t aOpcode, uint8_t* aBuf, uint8_t aLen, + BluetoothCoreResultHandler* aRes) override; + + /* Energy Information */ + + void ReadEnergyInfo(BluetoothCoreResultHandler* aRes) override; + +private: + void DispatchError(BluetoothCoreResultHandler* aRes, + BluetoothStatus aStatus); + void DispatchError(BluetoothCoreResultHandler* aRes, + nsresult aRv); + + BluetoothDaemonCoreModule* mModule; }; END_BLUETOOTH_NAMESPACE diff --git a/dom/bluetooth/bluedroid/BluetoothDaemonGattInterface.cpp b/dom/bluetooth/bluedroid/BluetoothDaemonGattInterface.cpp index 31dca9f2fb..ff19d7225f 100644 --- a/dom/bluetooth/bluedroid/BluetoothDaemonGattInterface.cpp +++ b/dom/bluetooth/bluedroid/BluetoothDaemonGattInterface.cpp @@ -15,8 +15,6 @@ using namespace mozilla::ipc; // GATT module // -const int BluetoothDaemonGattModule::MAX_NUM_CLIENTS = 1; - BluetoothGattNotificationHandler* BluetoothDaemonGattModule::sNotificationHandler; @@ -827,7 +825,8 @@ BluetoothDaemonGattModule::ServerAddCharacteristicCmd( 4)); // Permissions nsresult rv = PackPDU( - PackConversion(aServerIf), aServiceHandle, aUuid, + PackConversion(aServerIf), aServiceHandle, + PackReversed(aUuid), PackConversion(aProperties), PackConversion(aPermissions), *pdu); if (NS_FAILED(rv)) { @@ -857,7 +856,8 @@ BluetoothDaemonGattModule::ServerAddDescriptorCmd( 4)); // Permissions nsresult rv = PackPDU( - PackConversion(aServerIf), aServiceHandle, aUuid, + PackConversion(aServerIf), aServiceHandle, + PackReversed(aUuid), PackConversion(aPermissions), *pdu); if (NS_FAILED(rv)) { return rv; @@ -949,7 +949,8 @@ BluetoothDaemonGattModule::ServerDeleteServiceCmd( nsresult BluetoothDaemonGattModule::ServerSendIndicationCmd( - int aServerIf, int aAttributeHandle, int aConnId, int aLength, bool aConfirm, + int aServerIf, const BluetoothAttributeHandle& aCharacteristicHandle, + int aConnId, int aLength, bool aConfirm, uint8_t* aValue, BluetoothGattResultHandler* aRes) { MOZ_ASSERT(NS_IsMainThread()); @@ -959,7 +960,7 @@ BluetoothDaemonGattModule::ServerSendIndicationCmd( 0)); nsresult rv = PackPDU(PackConversion(aServerIf), - PackConversion(aAttributeHandle), + aCharacteristicHandle, PackConversion(aConnId), PackConversion(aLength), PackConversion(aConfirm), @@ -990,7 +991,7 @@ BluetoothDaemonGattModule::ServerSendResponseCmd( nsresult rv = PackPDU( PackConversion(aConnId), PackConversion(aTransId), - aResponse.mHandle, + PackConversion(aResponse.mHandle), aResponse.mOffset, PackConversion(aResponse.mAuthReq), PackConversion(aStatus), @@ -1567,56 +1568,13 @@ BluetoothDaemonGattModule::ClientScanResultNtf( ClientScanResultInitOp(aPDU)); } -// Init operator class for ClientConnect/DisconnectNotification -class BluetoothDaemonGattModule::ClientConnectDisconnectInitOp final - : private PDUInitOp -{ -public: - ClientConnectDisconnectInitOp(DaemonSocketPDU& aPDU) - : PDUInitOp(aPDU) - { } - - nsresult - operator () (int& aArg1, - BluetoothGattStatus& aArg2, - int& aArg3, - BluetoothAddress& aArg4) const - { - DaemonSocketPDU& pdu = GetPDU(); - - /* Read connection ID */ - nsresult rv = UnpackPDU(pdu, aArg1); - if (NS_FAILED(rv)) { - return rv; - } - /* Read status */ - rv = UnpackPDU(pdu, aArg2); - if (NS_FAILED(rv)) { - return rv; - } - /* Read client interface */ - rv = UnpackPDU(pdu, aArg3); - if (NS_FAILED(rv)) { - return rv; - } - /* Read address */ - rv = UnpackPDU(pdu, aArg4); - if (NS_FAILED(rv)) { - return rv; - } - - WarnAboutTrailingData(); - return NS_OK; - } -}; - void BluetoothDaemonGattModule::ClientConnectNtf( const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU) { ClientConnectNotification::Dispatch( &BluetoothGattNotificationHandler::ConnectNotification, - ClientConnectDisconnectInitOp(aPDU)); + UnpackPDUInitOp(aPDU)); } void @@ -1625,7 +1583,7 @@ BluetoothDaemonGattModule::ClientDisconnectNtf( { ClientDisconnectNotification::Dispatch( &BluetoothGattNotificationHandler::DisconnectNotification, - ClientConnectDisconnectInitOp(aPDU)); + UnpackPDUInitOp(aPDU)); } void @@ -1736,56 +1694,13 @@ BluetoothDaemonGattModule::ClientExecuteWriteNtf( UnpackPDUInitOp(aPDU)); } -// Init operator class for ClientReadRemoteRssiNotification -class BluetoothDaemonGattModule::ClientReadRemoteRssiInitOp final - : private PDUInitOp -{ -public: - ClientReadRemoteRssiInitOp(DaemonSocketPDU& aPDU) - : PDUInitOp(aPDU) - { } - - nsresult - operator () (int& aArg1, - BluetoothAddress& aArg2, - int& aArg3, - BluetoothGattStatus& aArg4) const - { - DaemonSocketPDU& pdu = GetPDU(); - - /* Read client interface */ - nsresult rv = UnpackPDU(pdu, aArg1); - if (NS_FAILED(rv)) { - return rv; - } - /* Read address */ - rv = UnpackPDU(pdu, aArg2); - if (NS_FAILED(rv)) { - return rv; - } - /* Read RSSI */ - rv = UnpackPDU(pdu, aArg3); - if (NS_FAILED(rv)) { - return rv; - } - /* Read status */ - rv = UnpackPDU(pdu, aArg4); - if (NS_FAILED(rv)) { - return rv; - } - - WarnAboutTrailingData(); - return NS_OK; - } -}; - void BluetoothDaemonGattModule::ClientReadRemoteRssiNtf( const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU) { ClientReadRemoteRssiNotification::Dispatch( &BluetoothGattNotificationHandler::ReadRemoteRssiNotification, - ClientReadRemoteRssiInitOp(aPDU)); + UnpackPDUInitOp(aPDU)); } void @@ -1876,22 +1791,119 @@ BluetoothDaemonGattModule::ServerIncludedServiceAddedNtf( UnpackPDUInitOp(aPDU)); } +// Init operator class for ServerCharacteristicAddedNotification +class BluetoothDaemonGattModule::ServerCharacteristicAddedInitOp final + : private PDUInitOp +{ +public: + ServerCharacteristicAddedInitOp(DaemonSocketPDU& aPDU) + : PDUInitOp(aPDU) + { } + + nsresult + operator () (BluetoothGattStatus& aArg1, + int& aArg2, + BluetoothUuid& aArg3, + BluetoothAttributeHandle& aArg4, + BluetoothAttributeHandle& aArg5) const + { + DaemonSocketPDU& pdu = GetPDU(); + + /* Read GATT status */ + nsresult rv = UnpackPDU(pdu, aArg1); + if (NS_FAILED(rv)) { + return rv; + } + /* Read server interface */ + rv = UnpackPDU(pdu, aArg2); + if (NS_FAILED(rv)) { + return rv; + } + /* Read characteristic UUID */ + rv = UnpackPDU(pdu, UnpackReversed(aArg3)); + if (NS_FAILED(rv)) { + return rv; + } + /* Read service handle */ + rv = UnpackPDU(pdu, aArg4); + if (NS_FAILED(rv)) { + return rv; + } + /* Read characteristic handle */ + rv = UnpackPDU(pdu, aArg5); + if (NS_FAILED(rv)) { + return rv; + } + + WarnAboutTrailingData(); + return NS_OK; + } +}; + void BluetoothDaemonGattModule::ServerCharacteristicAddedNtf( const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU) { ServerCharacteristicAddedNotification::Dispatch( &BluetoothGattNotificationHandler::CharacteristicAddedNotification, - UnpackPDUInitOp(aPDU)); + ServerCharacteristicAddedInitOp(aPDU)); } +// Init operator class for ServerDescriptorAddedNotification +class BluetoothDaemonGattModule::ServerDescriptorAddedInitOp final + : private PDUInitOp +{ +public: + ServerDescriptorAddedInitOp(DaemonSocketPDU& aPDU) + : PDUInitOp(aPDU) + { } + + nsresult + operator () (BluetoothGattStatus& aArg1, + int& aArg2, + BluetoothUuid& aArg3, + BluetoothAttributeHandle& aArg4, + BluetoothAttributeHandle& aArg5) const + { + DaemonSocketPDU& pdu = GetPDU(); + + /* Read GATT status */ + nsresult rv = UnpackPDU(pdu, aArg1); + if (NS_FAILED(rv)) { + return rv; + } + /* Read server interface */ + rv = UnpackPDU(pdu, aArg2); + if (NS_FAILED(rv)) { + return rv; + } + /* Read characteristic UUID */ + rv = UnpackPDU(pdu, UnpackReversed(aArg3)); + if (NS_FAILED(rv)) { + return rv; + } + /* Read service handle */ + rv = UnpackPDU(pdu, aArg4); + if (NS_FAILED(rv)) { + return rv; + } + /* Read descriptor handle */ + rv = UnpackPDU(pdu, aArg5); + if (NS_FAILED(rv)) { + return rv; + } + + WarnAboutTrailingData(); + return NS_OK; + } +}; void BluetoothDaemonGattModule::ServerDescriptorAddedNtf( const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU) { ServerDescriptorAddedNotification::Dispatch( &BluetoothGattNotificationHandler::DescriptorAddedNotification, - UnpackPDUInitOp(aPDU)); + ServerDescriptorAddedInitOp(aPDU)); } void @@ -1921,68 +1933,13 @@ BluetoothDaemonGattModule::ServerServiceDeletedNtf( UnpackPDUInitOp(aPDU)); } -// Init operator class for ServerRequestReadNotification -class BluetoothDaemonGattModule::ServerRequestReadInitOp final - : private PDUInitOp -{ -public: - ServerRequestReadInitOp(DaemonSocketPDU& aPDU) - : PDUInitOp(aPDU) - { } - - nsresult - operator () (int& aArg1, - int& aArg2, - BluetoothAddress& aArg3, - BluetoothAttributeHandle& aArg4, - int& aArg5, - bool& aArg6) const - { - DaemonSocketPDU& pdu = GetPDU(); - - /* Read connection ID */ - nsresult rv = UnpackPDU(pdu, aArg1); - if (NS_FAILED(rv)) { - return rv; - } - /* Read trans ID */ - rv = UnpackPDU(pdu, aArg2); - if (NS_FAILED(rv)) { - return rv; - } - /* Read address */ - rv = UnpackPDU(pdu, aArg3); - if (NS_FAILED(rv)) { - return rv; - } - /* Read attribute handle */ - rv = UnpackPDU(pdu, aArg4); - if (NS_FAILED(rv)) { - return rv; - } - /* Read offset */ - rv = UnpackPDU(pdu, aArg5); - if (NS_FAILED(rv)) { - return rv; - } - /* Read isLong */ - rv = UnpackPDU(pdu, aArg6); - if (NS_FAILED(rv)) { - return rv; - } - - WarnAboutTrailingData(); - return NS_OK; - } -}; - void BluetoothDaemonGattModule::ServerRequestReadNtf( const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU) { ServerRequestReadNotification::Dispatch( &BluetoothGattNotificationHandler::RequestReadNotification, - ServerRequestReadInitOp(aPDU)); + UnpackPDUInitOp(aPDU)); } // Init operator class for ServerRequestWriteNotification @@ -2068,56 +2025,13 @@ BluetoothDaemonGattModule::ServerRequestWriteNtf( ServerRequestWriteInitOp(aPDU)); } -// Init operator class for ServerRequestExecuteWriteNotification -class BluetoothDaemonGattModule::ServerRequestExecuteWriteInitOp final - : private PDUInitOp -{ -public: - ServerRequestExecuteWriteInitOp(DaemonSocketPDU& aPDU) - : PDUInitOp(aPDU) - { } - - nsresult - operator () (int& aArg1, - int& aArg2, - BluetoothAddress& aArg3, - bool& aArg4) const - { - DaemonSocketPDU& pdu = GetPDU(); - - /* Read connection ID */ - nsresult rv = UnpackPDU(pdu, aArg1); - if (NS_FAILED(rv)) { - return rv; - } - /* Read trans ID */ - rv = UnpackPDU(pdu, aArg2); - if (NS_FAILED(rv)) { - return rv; - } - /* Read address */ - rv = UnpackPDU(pdu, aArg3); - if (NS_FAILED(rv)) { - return rv; - } - /* Read execute write */ - rv = UnpackPDU(pdu, aArg4); - if (NS_FAILED(rv)) { - return rv; - } - - WarnAboutTrailingData(); - return NS_OK; - } -}; - void BluetoothDaemonGattModule::ServerRequestExecuteWriteNtf( const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU) { ServerRequestExecuteWriteNotification::Dispatch( &BluetoothGattNotificationHandler::RequestExecuteWriteNotification, - ServerRequestExecuteWriteInitOp(aPDU)); + UnpackPDUInitOp(aPDU)); } void @@ -2193,6 +2107,7 @@ BluetoothDaemonGattInterface::BluetoothDaemonGattInterface( BluetoothDaemonGattInterface::~BluetoothDaemonGattInterface() { } +#if 0 class BluetoothDaemonGattInterface::InitResultHandler final : public BluetoothSetupResultHandler { @@ -2240,8 +2155,8 @@ BluetoothDaemonGattInterface::Init( } nsresult rv = mModule->RegisterModule( - BluetoothDaemonGattModule::SERVICE_ID, 0x00, - BluetoothDaemonGattModule::MAX_NUM_CLIENTS, res); + SETUP_SERVICE_ID_GATT, 0x00, BluetoothDaemonGattModule::MAX_NUM_CLIENTS, + res); if (NS_FAILED(rv) && aRes) { DispatchError(aRes, rv); @@ -2293,12 +2208,21 @@ BluetoothDaemonGattInterface::Cleanup( BluetoothGattResultHandler* aRes) { nsresult rv = mModule->UnregisterModule( - BluetoothDaemonGattModule::SERVICE_ID, - new CleanupResultHandler(mModule, aRes)); + SETUP_SERVICE_ID_GATT, new CleanupResultHandler(mModule, aRes)); if (NS_FAILED(rv)) { DispatchError(aRes, rv); } } +#endif + +void +BluetoothDaemonGattInterface::SetNotificationHandler( + BluetoothGattNotificationHandler* aNotificationHandler) +{ + MOZ_ASSERT(mModule); + + mModule->SetNotificationHandler(aNotificationHandler); +} /* Register / Unregister */ void @@ -2798,14 +2722,14 @@ BluetoothDaemonGattInterface::DeleteService( void BluetoothDaemonGattInterface::SendIndication( - int aServerIf, int aAttributeHandle, int aConnId, - const nsTArray& aValue, bool aConfirm, + int aServerIf, const BluetoothAttributeHandle& aCharacteristicHandle, + int aConnId, const nsTArray& aValue, bool aConfirm, BluetoothGattResultHandler* aRes) { MOZ_ASSERT(mModule); nsresult rv = mModule->ServerSendIndicationCmd( - aServerIf, aAttributeHandle, aConnId, + aServerIf, aCharacteristicHandle, aConnId, aValue.Length() * sizeof(uint8_t), aConfirm, const_cast(aValue.Elements()), aRes); diff --git a/dom/bluetooth/bluedroid/BluetoothDaemonGattInterface.h b/dom/bluetooth/bluedroid/BluetoothDaemonGattInterface.h index af2eabeac3..98e7e45379 100644 --- a/dom/bluetooth/bluedroid/BluetoothDaemonGattInterface.h +++ b/dom/bluetooth/bluedroid/BluetoothDaemonGattInterface.h @@ -64,18 +64,9 @@ public: // TODO: Add L support }; - static const int MAX_NUM_CLIENTS; - virtual nsresult Send(DaemonSocketPDU* aPDU, DaemonSocketResultHandler* aRes) = 0; - virtual nsresult RegisterModule(uint8_t aId, uint8_t aMode, - uint32_t aMaxNumClients, - BluetoothSetupResultHandler* aRes) = 0; - - virtual nsresult UnregisterModule(uint8_t aId, - BluetoothSetupResultHandler* aRes) = 0; - void SetNotificationHandler( BluetoothGattNotificationHandler* aNotificationHandler); @@ -287,13 +278,14 @@ public: BluetoothGattResultHandler* aRes); /* Send an indication or a notification */ - nsresult ServerSendIndicationCmd(int aServerIf, - int aAttributeHandle, - int aConnId, - int aLength, - bool aConfirm, - uint8_t* aValue, - BluetoothGattResultHandler* aRes); + nsresult ServerSendIndicationCmd( + int aServerIf, + const BluetoothAttributeHandle& aCharacteristicHandle, + int aConnId, + int aLength, + bool aConfirm, + uint8_t* aValue, + BluetoothGattResultHandler* aRes); /* Send a response for an incoming indication */ nsresult ServerSendResponseCmd(int aConnId, @@ -680,14 +672,12 @@ protected: BluetoothGattStatus, int> ServerResponseConfirmationNotification; - class ClientScanResultInitOp; - class ClientConnectDisconnectInitOp; - class ClientReadRemoteRssiInitOp; class ClientGetDeviceTypeInitOp; + class ClientScanResultInitOp; class ServerConnectionInitOp; - class ServerRequestReadInitOp; class ServerRequestWriteInitOp; - class ServerRequestExecuteWriteInitOp; + class ServerCharacteristicAddedInitOp; + class ServerDescriptorAddedInitOp; void ClientRegisterNtf(const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU); @@ -801,9 +791,8 @@ public: BluetoothDaemonGattInterface(BluetoothDaemonGattModule* aModule); ~BluetoothDaemonGattInterface(); - void Init(BluetoothGattNotificationHandler* aNotificationHandler, - BluetoothGattResultHandler* aRes) override; - void Cleanup(BluetoothGattResultHandler* aRes) override; + void SetNotificationHandler( + BluetoothGattNotificationHandler* aNotificationHandler) override; /* Register / Unregister */ void RegisterClient(const BluetoothUuid& aUuid, @@ -981,7 +970,7 @@ public: /* Send an indication or a notification */ void SendIndication( int aServerIf, - int aAttributeHandle, + const BluetoothAttributeHandle& aCharacteristicHandle, int aConnId, const nsTArray& aValue, bool aConfirm, /* true: indication, false: notification */ diff --git a/dom/bluetooth/bluedroid/BluetoothDaemonHandsfreeInterface.cpp b/dom/bluetooth/bluedroid/BluetoothDaemonHandsfreeInterface.cpp index 3b7eae62a8..de923a1bba 100644 --- a/dom/bluetooth/bluedroid/BluetoothDaemonHandsfreeInterface.cpp +++ b/dom/bluetooth/bluedroid/BluetoothDaemonHandsfreeInterface.cpp @@ -1471,115 +1471,12 @@ BluetoothDaemonHandsfreeInterface::BluetoothDaemonHandsfreeInterface( BluetoothDaemonHandsfreeInterface::~BluetoothDaemonHandsfreeInterface() { } -class BluetoothDaemonHandsfreeInterface::InitResultHandler final - : public BluetoothSetupResultHandler +void BluetoothDaemonHandsfreeInterface::SetNotificationHandler( + BluetoothHandsfreeNotificationHandler* aNotificationHandler) { -public: - InitResultHandler(BluetoothHandsfreeResultHandler* aRes) - : mRes(aRes) - { - MOZ_ASSERT(mRes); - } + MOZ_ASSERT(mModule); - void OnError(BluetoothStatus aStatus) override - { - MOZ_ASSERT(NS_IsMainThread()); - - mRes->OnError(aStatus); - } - - void RegisterModule() override - { - MOZ_ASSERT(NS_IsMainThread()); - - mRes->Init(); - } - -private: - RefPtr mRes; -}; - -void -BluetoothDaemonHandsfreeInterface::Init( - BluetoothHandsfreeNotificationHandler* aNotificationHandler, - int aMaxNumClients, BluetoothHandsfreeResultHandler* aRes) -{ - // Set notification handler _before_ registering the module. It could - // happen that we receive notifications, before the result handler runs. mModule->SetNotificationHandler(aNotificationHandler); - - InitResultHandler* res; - - if (aRes) { - res = new InitResultHandler(aRes); - } else { - // We don't need a result handler if the caller is not interested. - res = nullptr; - } - - nsresult rv = mModule->RegisterModule( - BluetoothDaemonHandsfreeModule::SERVICE_ID, MODE_NARROWBAND_SPEECH, - aMaxNumClients, res); - - if (NS_FAILED(rv) && aRes) { - DispatchError(aRes, rv); - } -} - -class BluetoothDaemonHandsfreeInterface::CleanupResultHandler final - : public BluetoothSetupResultHandler -{ -public: - CleanupResultHandler(BluetoothDaemonHandsfreeModule* aModule, - BluetoothHandsfreeResultHandler* aRes) - : mModule(aModule) - , mRes(aRes) - { - MOZ_ASSERT(mModule); - } - - void OnError(BluetoothStatus aStatus) override - { - MOZ_ASSERT(NS_IsMainThread()); - - BT_LOGR("%s:%d", __func__, __LINE__); - if (mRes) { - mRes->OnError(aStatus); - } - } - - void UnregisterModule() override - { - MOZ_ASSERT(NS_IsMainThread()); - - BT_LOGR("%s:%d", __func__, __LINE__); - // Clear notification handler _after_ module has been - // unregistered. While unregistering the module, we might - // still receive notifications. - mModule->SetNotificationHandler(nullptr); - - if (mRes) { - mRes->Cleanup(); - } - } - -private: - BluetoothDaemonHandsfreeModule* mModule; - RefPtr mRes; -}; - -void -BluetoothDaemonHandsfreeInterface::Cleanup( - BluetoothHandsfreeResultHandler* aRes) -{ - BT_LOGR("%s:%d", __func__, __LINE__); - nsresult rv = mModule->UnregisterModule( - BluetoothDaemonHandsfreeModule::SERVICE_ID, - new CleanupResultHandler(mModule, aRes)); - BT_LOGR("%s:%d", __func__, __LINE__); - if (NS_FAILED(rv)) { - DispatchError(aRes, rv); - } } /* Connect / Disconnect */ diff --git a/dom/bluetooth/bluedroid/BluetoothDaemonHandsfreeInterface.h b/dom/bluetooth/bluedroid/BluetoothDaemonHandsfreeInterface.h index 83f9d32e2f..8f6efd6c1e 100644 --- a/dom/bluetooth/bluedroid/BluetoothDaemonHandsfreeInterface.h +++ b/dom/bluetooth/bluedroid/BluetoothDaemonHandsfreeInterface.h @@ -46,13 +46,6 @@ public: virtual nsresult Send(DaemonSocketPDU* aPDU, DaemonSocketResultHandler* aRes) = 0; - virtual nsresult RegisterModule(uint8_t aId, uint8_t aMode, - uint32_t aMaxNumClients, - BluetoothSetupResultHandler* aRes) = 0; - - virtual nsresult UnregisterModule(uint8_t aId, - BluetoothSetupResultHandler* aRes) = 0; - void SetNotificationHandler( BluetoothHandsfreeNotificationHandler* aNotificationHandler); @@ -402,23 +395,12 @@ protected: class BluetoothDaemonHandsfreeInterface final : public BluetoothHandsfreeInterface { - class CleanupResultHandler; - class InitResultHandler; - - enum { - MODE_HEADSET = 0x00, - MODE_NARROWBAND_SPEECH = 0x01, - MODE_NARRAWBAND_WIDEBAND_SPEECH = 0x02 - }; - public: BluetoothDaemonHandsfreeInterface(BluetoothDaemonHandsfreeModule* aModule); ~BluetoothDaemonHandsfreeInterface(); - void Init( - BluetoothHandsfreeNotificationHandler* aNotificationHandler, - int aMaxNumClients, BluetoothHandsfreeResultHandler* aRes) override; - void Cleanup(BluetoothHandsfreeResultHandler* aRes) override; + void SetNotificationHandler( + BluetoothHandsfreeNotificationHandler* aNotificationHandler) override; /* Connect / Disconnect */ diff --git a/dom/bluetooth/bluedroid/BluetoothDaemonHelpers.cpp b/dom/bluetooth/bluedroid/BluetoothDaemonHelpers.cpp index 5513c90297..fb3e7463dd 100644 --- a/dom/bluetooth/bluedroid/BluetoothDaemonHelpers.cpp +++ b/dom/bluetooth/bluedroid/BluetoothDaemonHelpers.cpp @@ -456,7 +456,8 @@ Convert(uint8_t aIn, BluetoothStatus& aOut) [0x07] = STATUS_PARM_INVALID, [0x08] = STATUS_UNHANDLED, [0x09] = STATUS_AUTH_FAILURE, - [0x0a] = STATUS_RMT_DEV_DOWN + [0x0a] = STATUS_RMT_DEV_DOWN, + [0x0b] = STATUS_AUTH_REJECTED }; if (MOZ_HAL_IPC_CONVERT_WARN_IF( aIn >= MOZ_ARRAY_LENGTH(sStatus), uint8_t, BluetoothStatus)) { @@ -513,24 +514,6 @@ Convert(int32_t aIn, BluetoothGattStatus& aOut) return NS_OK; } -nsresult -Convert(const nsAString& aIn, BluetoothPropertyType& aOut) -{ - if (aIn.EqualsLiteral("Name")) { - aOut = PROPERTY_BDNAME; - } else if (aIn.EqualsLiteral("Discoverable")) { - aOut = PROPERTY_ADAPTER_SCAN_MODE; - } else if (aIn.EqualsLiteral("DiscoverableTimeout")) { - aOut = PROPERTY_ADAPTER_DISCOVERY_TIMEOUT; - } else if (MOZ_HAL_IPC_CONVERT_WARN_IF( - false, nsAString, BluetoothPropertyType)) { - BT_LOGR("Invalid property name: %s", NS_ConvertUTF16toUTF8(aIn).get()); - aOut = static_cast(0); // silences compiler warning - return NS_ERROR_ILLEGAL_VALUE; - } - return NS_OK; -} - nsresult Convert(nsresult aIn, BluetoothStatus& aOut) { @@ -551,6 +534,14 @@ Convert(const BluetoothAttributeHandle& aIn, int32_t& aOut) return NS_OK; } +nsresult +Convert(const BluetoothAttributeHandle& aIn, uint16_t& aOut) +{ + aOut = aIn.mHandle; + return NS_OK; +} + + nsresult Convert(BluetoothAvrcpEvent aIn, uint8_t& aOut) { @@ -859,6 +850,35 @@ Convert(BluetoothScanMode aIn, int32_t& aOut) return NS_OK; } +nsresult +Convert(BluetoothSetupServiceId aIn, uint8_t& aOut) +{ + static const uint8_t sServiceId[] = { + [SETUP_SERVICE_ID_SETUP] = 0x00, + [SETUP_SERVICE_ID_CORE] = 0x01, + [SETUP_SERVICE_ID_SOCKET] = 0x02, + [SETUP_SERVICE_ID_HID] = 0x03, + [SETUP_SERVICE_ID_PAN] = 0x04, + [SETUP_SERVICE_ID_HANDSFREE] = 0x05, + [SETUP_SERVICE_ID_A2DP] = 0x06, + [SETUP_SERVICE_ID_HEALTH] = 0x07, + [SETUP_SERVICE_ID_AVRCP] = 0x08, + [SETUP_SERVICE_ID_GATT] = 0x09, + [SETUP_SERVICE_ID_HANDSFREE_CLIENT] = 0x0a, + [SETUP_SERVICE_ID_MAP_CLIENT] = 0x0b, + [SETUP_SERVICE_ID_AVRCP_CONTROLLER] = 0x0c, + [SETUP_SERVICE_ID_A2DP_SINK] = 0x0d + }; + if (MOZ_HAL_IPC_CONVERT_WARN_IF( + aIn >= MOZ_ARRAY_LENGTH(sServiceId), + BluetoothServiceSetupId, uint8_t)) { + aOut = 0; // silences compiler warning + return NS_ERROR_ILLEGAL_VALUE; + } + aOut = sServiceId[aIn]; + return NS_OK; +} + nsresult Convert(BluetoothSspVariant aIn, uint8_t& aOut) { @@ -922,6 +942,26 @@ Convert(BluetoothGattAuthReq aIn, int32_t& aOut) return NS_OK; } +nsresult +Convert(BluetoothGattAuthReq aIn, uint8_t& aOut) +{ + static const uint8_t sGattAuthReq[] = { + [GATT_AUTH_REQ_NONE] = 0x00, + [GATT_AUTH_REQ_NO_MITM] = 0x01, + [GATT_AUTH_REQ_MITM] = 0x02, + [GATT_AUTH_REQ_SIGNED_NO_MITM] = 0x03, + [GATT_AUTH_REQ_SIGNED_MITM] = 0x04 + }; + if (MOZ_HAL_IPC_CONVERT_WARN_IF( + aIn >= MOZ_ARRAY_LENGTH(sGattAuthReq), BluetoothGattAuthReq, + uint8_t)) { + aOut = GATT_AUTH_REQ_NONE; // silences compiler warning + return NS_ERROR_ILLEGAL_VALUE; + } + aOut = sGattAuthReq[aIn]; + return NS_OK; +} + nsresult Convert(BluetoothGattWriteType aIn, int32_t& aOut) { @@ -1219,37 +1259,42 @@ PackPDU(const BluetoothHandsfreeWbsConfig& aIn, DaemonSocketPDU& aPDU) } nsresult -PackPDU(const BluetoothNamedValue& aIn, DaemonSocketPDU& aPDU) +PackPDU(const BluetoothProperty& aIn, DaemonSocketPDU& aPDU) { - nsresult rv = PackPDU( - PackConversion(aIn.name()), aPDU); + nsresult rv = PackPDU(aIn.mType, aPDU); if (NS_FAILED(rv)) { return rv; } - if (aIn.value().type() == BluetoothValue::Tuint32_t) { - // Set discoverable timeout - rv = PackPDU(static_cast(sizeof(uint32_t)), - aIn.value().get_uint32_t(), aPDU); - } else if (aIn.value().type() == BluetoothValue::TnsString) { - // Set name - const nsCString value = - NS_ConvertUTF16toUTF8(aIn.value().get_nsString()); + switch (aIn.mType) { + case PROPERTY_BDNAME: + /* fall through */ + case PROPERTY_REMOTE_FRIENDLY_NAME: { + NS_ConvertUTF16toUTF8 stringUTF8(aIn.mString); - rv = PackPDU(PackConversion(value.Length()), - PackArray( - reinterpret_cast(value.get()), - value.Length()), - aPDU); - } else if (aIn.value().type() == BluetoothValue::Tbool) { - // Set scan mode - bool value = aIn.value().get_bool(); - - rv = PackPDU(static_cast(sizeof(int32_t)), - PackConversion(value), aPDU); - } else if (MOZ_HAL_IPC_PACK_WARN_IF(true, BluetoothNamedValue)) { - BT_LOGR("Invalid property value type"); - rv = NS_ERROR_ILLEGAL_VALUE; + rv = PackPDU(PackConversion(stringUTF8.Length()), + PackArray( + reinterpret_cast(stringUTF8.get()), + stringUTF8.Length()), + aPDU); + } + break; + case PROPERTY_CLASS_OF_DEVICE: + /* fall through */ + case PROPERTY_ADAPTER_DISCOVERY_TIMEOUT: + rv = PackPDU(PackConversion(sizeof(aIn.mUint32)), + aIn.mUint32, + aPDU); + break; + case PROPERTY_ADAPTER_SCAN_MODE: + /* |mScanMode| is sent as signed int of 4 bytes */ + rv = PackPDU(PackConversion(sizeof(int32_t)), + aIn.mScanMode, + aPDU); + break; + default: + NS_NOTREACHED("Invalid property for packing"); + return NS_ERROR_ILLEGAL_VALUE; } return rv; } @@ -1280,6 +1325,12 @@ PackPDU(BluetoothScanMode aIn, DaemonSocketPDU& aPDU) return PackPDU(PackConversion(aIn), aPDU); } +nsresult +PackPDU(BluetoothSetupServiceId aIn, DaemonSocketPDU& aPDU) +{ + return PackPDU(PackConversion(aIn), aPDU); +} + nsresult PackPDU(const BluetoothServiceName& aIn, DaemonSocketPDU& aPDU) { diff --git a/dom/bluetooth/bluedroid/BluetoothDaemonHelpers.h b/dom/bluetooth/bluedroid/BluetoothDaemonHelpers.h index f52e47cee7..7dfbddd586 100644 --- a/dom/bluetooth/bluedroid/BluetoothDaemonHelpers.h +++ b/dom/bluetooth/bluedroid/BluetoothDaemonHelpers.h @@ -62,6 +62,37 @@ struct BluetoothAvrcpEventParamPair { , mParam(aParam) { } + size_t GetLength() + { + size_t size; + + switch(mEvent) { + case AVRCP_EVENT_PLAY_STATUS_CHANGED: + /* PackPDU casts ControlPlayStatus to uint8_t */ + size = sizeof(static_cast(mParam.mPlayStatus)); + break; + case AVRCP_EVENT_TRACK_CHANGE: + size = sizeof(mParam.mTrack); + break; + case AVRCP_EVENT_TRACK_REACHED_END: + case AVRCP_EVENT_TRACK_REACHED_START: + /* no data to pack */ + size = 0; + break; + case AVRCP_EVENT_PLAY_POS_CHANGED: + size = sizeof(mParam.mSongPos); + break; + case AVRCP_EVENT_APP_SETTINGS_CHANGED: + size = (sizeof(mParam.mIds[0]) + sizeof(mParam.mValues[0])) * mParam.mNumAttr; + break; + default: + size = 0; + break; + } + + return size; + } + BluetoothAvrcpEvent mEvent; const BluetoothAvrcpNotificationParam& mParam; }; @@ -146,10 +177,10 @@ nsresult Convert(int32_t aIn, BluetoothGattStatus& aOut); nsresult -Convert(const nsAString& aIn, BluetoothPropertyType& aOut); +Convert(const BluetoothAttributeHandle& aIn, int32_t& aOut); nsresult -Convert(const BluetoothAttributeHandle& aIn, int32_t& aOut); +Convert(const BluetoothAttributeHandle& aIn, uint16_t& aOut); nsresult Convert(BluetoothAvrcpEvent aIn, uint8_t& aOut); @@ -202,6 +233,9 @@ Convert(BluetoothPropertyType aIn, uint8_t& aOut); nsresult Convert(BluetoothScanMode aIn, uint8_t& aOut); +nsresult +Convert(BluetoothSetupServiceId aIn, uint8_t& aOut); + nsresult Convert(BluetoothSocketType aIn, uint8_t& aOut); @@ -214,6 +248,9 @@ Convert(ControlPlayStatus aIn, uint8_t& aOut); nsresult Convert(BluetoothGattAuthReq aIn, int32_t& aOut); +nsresult +Convert(BluetoothGattAuthReq aIn, uint8_t& aOut); + nsresult Convert(BluetoothGattWriteType aIn, int32_t& aOut); @@ -290,7 +327,7 @@ nsresult PackPDU(const BluetoothHandsfreeWbsConfig& aIn, DaemonSocketPDU& aPDU); nsresult -PackPDU(const BluetoothNamedValue& aIn, DaemonSocketPDU& aPDU); +PackPDU(const BluetoothProperty& aIn, DaemonSocketPDU& aPDU); nsresult PackPDU(const BluetoothPinCode& aIn, DaemonSocketPDU& aPDU); @@ -301,6 +338,9 @@ PackPDU(BluetoothPropertyType aIn, DaemonSocketPDU& aPDU); nsresult PackPDU(const BluetoothServiceName& aIn, DaemonSocketPDU& aPDU); +nsresult +PackPDU(BluetoothSetupServiceId aIn, DaemonSocketPDU& aPDU); + nsresult PackPDU(BluetoothSocketType aIn, DaemonSocketPDU& aPDU); diff --git a/dom/bluetooth/bluedroid/BluetoothDaemonInterface.cpp b/dom/bluetooth/bluedroid/BluetoothDaemonInterface.cpp index 9230f4a32e..8cbb29c0e5 100644 --- a/dom/bluetooth/bluedroid/BluetoothDaemonInterface.cpp +++ b/dom/bluetooth/bluedroid/BluetoothDaemonInterface.cpp @@ -28,6 +28,9 @@ using namespace mozilla::ipc; static const int sRetryInterval = 100; // ms +BluetoothNotificationHandler* + BluetoothDaemonInterface::sNotificationHandler; + // // Protocol handling // @@ -95,11 +98,12 @@ public: void SetConnection(DaemonSocket* aConnection); - nsresult RegisterModule(uint8_t aId, uint8_t aMode, uint32_t aMaxNumClients, - BluetoothSetupResultHandler* aRes) override; + nsresult RegisterModule(BluetoothSetupServiceId aId, + uint8_t aMode, uint32_t aMaxNumClients, + BluetoothSetupResultHandler* aRes); - nsresult UnregisterModule(uint8_t aId, - BluetoothSetupResultHandler* aRes) override; + nsresult UnregisterModule(BluetoothSetupServiceId aId, + BluetoothSetupResultHandler* aRes); // Outgoing PDUs // @@ -154,8 +158,8 @@ BluetoothDaemonProtocol::SetConnection(DaemonSocket* aConnection) } nsresult -BluetoothDaemonProtocol::RegisterModule(uint8_t aId, uint8_t aMode, - uint32_t aMaxNumClients, +BluetoothDaemonProtocol::RegisterModule(BluetoothSetupServiceId aId, + uint8_t aMode, uint32_t aMaxNumClients, BluetoothSetupResultHandler* aRes) { return BluetoothDaemonSetupModule::RegisterModuleCmd(aId, aMode, @@ -163,7 +167,7 @@ BluetoothDaemonProtocol::RegisterModule(uint8_t aId, uint8_t aMode, } nsresult -BluetoothDaemonProtocol::UnregisterModule(uint8_t aId, +BluetoothDaemonProtocol::UnregisterModule(BluetoothSetupServiceId aId, BluetoothSetupResultHandler* aRes) { return BluetoothDaemonSetupModule::UnregisterModuleCmd(aId, aRes); @@ -422,7 +426,9 @@ public: if (!mRegisteredSocketModule) { mRegisteredSocketModule = true; // Init, step 5: Register Socket module - mInterface->mProtocol->RegisterModuleCmd(0x02, 0x00, + mInterface->mProtocol->RegisterModuleCmd( + SETUP_SERVICE_ID_SOCKET, + 0x00, BluetoothDaemonSocketModule::MAX_NUM_CLIENTS, this); } else if (mRes) { // Init, step 6: Signal success to caller @@ -474,6 +480,10 @@ BluetoothDaemonInterface::Init( #define BASE_SOCKET_NAME "bluetoothd" static unsigned long POSTFIX_LENGTH = 16; + // First of all, we set the notification handler. Backend crashes + // will be reported this way. + sNotificationHandler = aNotificationHandler; + // If we could not cleanup properly before and an old // instance of the daemon is still running, we kill it // here. @@ -484,8 +494,6 @@ BluetoothDaemonInterface::Init( if (!mProtocol) { mProtocol = new BluetoothDaemonProtocol(); } - static_cast(mProtocol)->SetNotificationHandler( - aNotificationHandler); if (!mListenSocket) { mListenSocket = new ListenSocket(this, LISTEN_SOCKET); @@ -556,7 +564,7 @@ private: if (!mUnregisteredCoreModule) { mUnregisteredCoreModule = true; // Cleanup, step 2: Unregister Core module - mInterface->mProtocol->UnregisterModuleCmd(0x01, this); + mInterface->mProtocol->UnregisterModuleCmd(SETUP_SERVICE_ID_CORE, this); } else { // Cleanup, step 3: Close command channel mInterface->mCmdChannel->Close(); @@ -595,12 +603,11 @@ private: void BluetoothDaemonInterface::Cleanup(BluetoothResultHandler* aRes) { - static_cast(mProtocol)->SetNotificationHandler( - nullptr); + sNotificationHandler = nullptr; // Cleanup, step 1: Unregister Socket module nsresult rv = mProtocol->UnregisterModuleCmd( - 0x02, new CleanupResultHandler(this)); + SETUP_SERVICE_ID_SOCKET, new CleanupResultHandler(this)); if (NS_FAILED(rv)) { DispatchError(aRes, rv); return; @@ -609,264 +616,6 @@ BluetoothDaemonInterface::Cleanup(BluetoothResultHandler* aRes) mResultHandlerQ.AppendElement(aRes); } -void -BluetoothDaemonInterface::Enable(BluetoothResultHandler* aRes) -{ - nsresult rv = - static_cast(mProtocol)->EnableCmd(aRes); - if (NS_FAILED(rv)) { - DispatchError(aRes, rv); - } -} - -void -BluetoothDaemonInterface::Disable(BluetoothResultHandler* aRes) -{ - nsresult rv = - static_cast(mProtocol)->DisableCmd(aRes); - if (NS_FAILED(rv)) { - DispatchError(aRes, rv); - } -} - -/* Adapter Properties */ - -void -BluetoothDaemonInterface::GetAdapterProperties(BluetoothResultHandler* aRes) -{ - nsresult rv = static_cast - (mProtocol)->GetAdapterPropertiesCmd(aRes); - if (NS_FAILED(rv)) { - DispatchError(aRes, rv); - } -} - -void -BluetoothDaemonInterface::GetAdapterProperty(const nsAString& aName, - BluetoothResultHandler* aRes) -{ - nsresult rv = static_cast - (mProtocol)->GetAdapterPropertyCmd(aName, aRes); - if (NS_FAILED(rv)) { - DispatchError(aRes, rv); - } -} - -void -BluetoothDaemonInterface::SetAdapterProperty( - const BluetoothNamedValue& aProperty, BluetoothResultHandler* aRes) -{ - nsresult rv = static_cast - (mProtocol)->SetAdapterPropertyCmd(aProperty, aRes); - if (NS_FAILED(rv)) { - DispatchError(aRes, rv); - } -} - -/* Remote Device Properties */ - -void -BluetoothDaemonInterface::GetRemoteDeviceProperties( - const BluetoothAddress& aRemoteAddr, BluetoothResultHandler* aRes) -{ - nsresult rv = static_cast - (mProtocol)->GetRemoteDevicePropertiesCmd(aRemoteAddr, aRes); - if (NS_FAILED(rv)) { - DispatchError(aRes, rv); - } -} - -void -BluetoothDaemonInterface::GetRemoteDeviceProperty( - const BluetoothAddress& aRemoteAddr, const nsAString& aName, - BluetoothResultHandler* aRes) -{ - nsresult rv = static_cast - (mProtocol)->GetRemoteDevicePropertyCmd(aRemoteAddr, aName, aRes); - if (NS_FAILED(rv)) { - DispatchError(aRes, rv); - } -} - -void -BluetoothDaemonInterface::SetRemoteDeviceProperty( - const BluetoothAddress& aRemoteAddr, const BluetoothNamedValue& aProperty, - BluetoothResultHandler* aRes) -{ - nsresult rv = static_cast - (mProtocol)->SetRemoteDevicePropertyCmd(aRemoteAddr, aProperty, aRes); - if (NS_FAILED(rv)) { - DispatchError(aRes, rv); - } -} - -/* Remote Services */ - -void -BluetoothDaemonInterface::GetRemoteServiceRecord( - const BluetoothAddress& aRemoteAddr, const BluetoothUuid& aUuid, - BluetoothResultHandler* aRes) -{ - nsresult rv = static_cast - (mProtocol)->GetRemoteServiceRecordCmd(aRemoteAddr, aUuid, aRes); - if (NS_FAILED(rv)) { - DispatchError(aRes, rv); - } -} - -void -BluetoothDaemonInterface::GetRemoteServices( - const BluetoothAddress& aRemoteAddr, BluetoothResultHandler* aRes) -{ - nsresult rv = static_cast - (mProtocol)->GetRemoteServicesCmd(aRemoteAddr, aRes); - if (NS_FAILED(rv)) { - DispatchError(aRes, rv); - } -} - -/* Discovery */ - -void -BluetoothDaemonInterface::StartDiscovery(BluetoothResultHandler* aRes) -{ - nsresult rv = static_cast - (mProtocol)->StartDiscoveryCmd(aRes); - if (NS_FAILED(rv)) { - DispatchError(aRes, rv); - } -} - -void -BluetoothDaemonInterface::CancelDiscovery(BluetoothResultHandler* aRes) -{ - nsresult rv = static_cast - (mProtocol)->CancelDiscoveryCmd(aRes); - if (NS_FAILED(rv)) { - DispatchError(aRes, rv); - } -} - -/* Bonds */ - -void -BluetoothDaemonInterface::CreateBond(const BluetoothAddress& aBdAddr, - BluetoothTransport aTransport, - BluetoothResultHandler* aRes) -{ - nsresult rv = static_cast - (mProtocol)->CreateBondCmd(aBdAddr, aTransport, aRes); - if (NS_FAILED(rv)) { - DispatchError(aRes, rv); - } -} - -void -BluetoothDaemonInterface::RemoveBond(const BluetoothAddress& aBdAddr, - BluetoothResultHandler* aRes) -{ - nsresult rv = static_cast - (mProtocol)->RemoveBondCmd(aBdAddr, aRes); - if (NS_FAILED(rv)) { - DispatchError(aRes, rv); - } -} - -void -BluetoothDaemonInterface::CancelBond(const BluetoothAddress& aBdAddr, - BluetoothResultHandler* aRes) -{ - nsresult rv = static_cast - (mProtocol)->CancelBondCmd(aBdAddr, aRes); - if (NS_FAILED(rv)) { - DispatchError(aRes, rv); - } -} - -/* Connection */ - -void -BluetoothDaemonInterface::GetConnectionState(const BluetoothAddress& aBdAddr, - BluetoothResultHandler* aRes) -{ - // NO-OP: no corresponding interface of current BlueZ -} - -/* Authentication */ - -void -BluetoothDaemonInterface::PinReply(const BluetoothAddress& aBdAddr, - bool aAccept, - const BluetoothPinCode& aPinCode, - BluetoothResultHandler* aRes) -{ - nsresult rv = static_cast - (mProtocol)->PinReplyCmd(aBdAddr, aAccept, aPinCode, aRes); - if (NS_FAILED(rv)) { - DispatchError(aRes, rv); - } -} - -void -BluetoothDaemonInterface::SspReply(const BluetoothAddress& aBdAddr, - BluetoothSspVariant aVariant, - bool aAccept, uint32_t aPasskey, - BluetoothResultHandler* aRes) -{ - nsresult rv = static_cast - (mProtocol)->SspReplyCmd(aBdAddr, aVariant, aAccept, aPasskey, aRes); - if (NS_FAILED(rv)) { - DispatchError(aRes, rv); - } -} - -/* DUT Mode */ - -void -BluetoothDaemonInterface::DutModeConfigure(bool aEnable, - BluetoothResultHandler* aRes) -{ - nsresult rv = static_cast - (mProtocol)->DutModeConfigureCmd(aEnable, aRes); - if (NS_FAILED(rv)) { - DispatchError(aRes, rv); - } -} - -void -BluetoothDaemonInterface::DutModeSend(uint16_t aOpcode, uint8_t* aBuf, - uint8_t aLen, - BluetoothResultHandler* aRes) -{ - nsresult rv = static_cast - (mProtocol)->DutModeSendCmd(aOpcode, aBuf, aLen, aRes); - if (NS_FAILED(rv)) { - DispatchError(aRes, rv); - } -} - -/* LE Mode */ - -void -BluetoothDaemonInterface::LeTestMode(uint16_t aOpcode, uint8_t* aBuf, - uint8_t aLen, - BluetoothResultHandler* aRes) -{ - nsresult rv = static_cast - (mProtocol)->LeTestModeCmd(aOpcode, aBuf, aLen, aRes); - if (NS_FAILED(rv)) { - DispatchError(aRes, rv); - } -} - -/* Energy Information */ - -void -BluetoothDaemonInterface::ReadEnergyInfo(BluetoothResultHandler* aRes) -{ - // NO-OP: no corresponding interface of current BlueZ -} - void BluetoothDaemonInterface::DispatchError(BluetoothResultHandler* aRes, BluetoothStatus aStatus) @@ -904,6 +653,18 @@ BluetoothDaemonInterface::GetBluetoothSetupInterface() return mSetupInterface; } +BluetoothCoreInterface* +BluetoothDaemonInterface::GetBluetoothCoreInterface() +{ + if (mCoreInterface) { + return mCoreInterface; + } + + mCoreInterface = new BluetoothDaemonCoreInterface(mProtocol); + + return mCoreInterface; +} + BluetoothSocketInterface* BluetoothDaemonInterface::GetBluetoothSocketInterface() { @@ -1014,7 +775,9 @@ BluetoothDaemonInterface::OnConnectSuccess(int aIndex) // Init, step 4: Register Core module nsresult rv = mProtocol->RegisterModuleCmd( - 0x01, 0x00, BluetoothDaemonCoreModule::MAX_NUM_CLIENTS, + SETUP_SERVICE_ID_CORE, + 0x00, + BluetoothDaemonCoreModule::MAX_NUM_CLIENTS, new InitResultHandler(this, res)); if (NS_FAILED(rv) && res) { DispatchError(res, STATUS_FAIL); @@ -1094,22 +857,17 @@ BluetoothDaemonInterface::OnDisconnect(int aIndex) break; } - BluetoothNotificationHandler* notificationHandler = - static_cast(mProtocol)-> - GetNotificationHandler(); - /* For recovery make sure all sockets disconnected, in order to avoid * the remaining disconnects interfere with the restart procedure. */ - if (notificationHandler && mResultHandlerQ.IsEmpty()) { + if (sNotificationHandler && mResultHandlerQ.IsEmpty()) { if (mListenSocket->GetConnectionStatus() == SOCKET_DISCONNECTED && mCmdChannel->GetConnectionStatus() == SOCKET_DISCONNECTED && mNtfChannel->GetConnectionStatus() == SOCKET_DISCONNECTED) { // Assume daemon crashed during regular service; notify // BluetoothServiceBluedroid to prepare restart-daemon procedure - notificationHandler->BackendErrorNotification(true); - static_cast(mProtocol)-> - SetNotificationHandler(nullptr); + sNotificationHandler->BackendErrorNotification(true); + sNotificationHandler = nullptr; } } } diff --git a/dom/bluetooth/bluedroid/BluetoothDaemonInterface.h b/dom/bluetooth/bluedroid/BluetoothDaemonInterface.h index 5e55e88371..a2609724f6 100644 --- a/dom/bluetooth/bluedroid/BluetoothDaemonInterface.h +++ b/dom/bluetooth/bluedroid/BluetoothDaemonInterface.h @@ -24,6 +24,7 @@ BEGIN_BLUETOOTH_NAMESPACE class BluetoothDaemonA2dpInterface; class BluetoothDaemonAvrcpInterface; +class BluetoothDaemonCoreInterface; class BluetoothDaemonGattInterface; class BluetoothDaemonHandsfreeInterface; class BluetoothDaemonProtocol; @@ -50,85 +51,10 @@ public: BluetoothResultHandler* aRes) override; void Cleanup(BluetoothResultHandler* aRes) override; - void Enable(BluetoothResultHandler* aRes) override; - void Disable(BluetoothResultHandler* aRes) override; - - /* Adapter Properties */ - - void GetAdapterProperties(BluetoothResultHandler* aRes) override; - void GetAdapterProperty(const nsAString& aName, - BluetoothResultHandler* aRes) override; - void SetAdapterProperty(const BluetoothNamedValue& aProperty, - BluetoothResultHandler* aRes) override; - - /* Remote Device Properties */ - - void GetRemoteDeviceProperties(const BluetoothAddress& aRemoteAddr, - BluetoothResultHandler* aRes) override; - void GetRemoteDeviceProperty(const BluetoothAddress& aRemoteAddr, - const nsAString& aName, - BluetoothResultHandler* aRes) override; - void SetRemoteDeviceProperty(const BluetoothAddress& aRemoteAddr, - const BluetoothNamedValue& aProperty, - BluetoothResultHandler* aRes) override; - - /* Remote Services */ - - void GetRemoteServiceRecord(const BluetoothAddress& aRemoteAddr, - const BluetoothUuid& aUuid, - BluetoothResultHandler* aRes) override; - void GetRemoteServices(const BluetoothAddress& aRemoteAddr, - BluetoothResultHandler* aRes) override; - - /* Discovery */ - - void StartDiscovery(BluetoothResultHandler* aRes) override; - void CancelDiscovery(BluetoothResultHandler* aRes) override; - - /* Bonds */ - - void CreateBond(const BluetoothAddress& aBdAddr, - BluetoothTransport aTransport, - BluetoothResultHandler* aRes) override; - void RemoveBond(const BluetoothAddress& aBdAddr, - BluetoothResultHandler* aRes) override; - void CancelBond(const BluetoothAddress& aBdAddr, - BluetoothResultHandler* aRes) override; - - /* Connection */ - - void GetConnectionState(const BluetoothAddress& aBdAddr, - BluetoothResultHandler* aRes) override; - - /* Authentication */ - - void PinReply(const BluetoothAddress& aBdAddr, bool aAccept, - const BluetoothPinCode& aPinCode, - BluetoothResultHandler* aRes) override; - - void SspReply(const BluetoothAddress& aBdAddr, - BluetoothSspVariant aVariant, - bool aAccept, uint32_t aPasskey, - BluetoothResultHandler* aRes) override; - - /* DUT Mode */ - - void DutModeConfigure(bool aEnable, BluetoothResultHandler* aRes); - void DutModeSend(uint16_t aOpcode, uint8_t* aBuf, uint8_t aLen, - BluetoothResultHandler* aRes) override; - - /* LE Mode */ - - void LeTestMode(uint16_t aOpcode, uint8_t* aBuf, uint8_t aLen, - BluetoothResultHandler* aRes) override; - - /* Energy Information */ - - void ReadEnergyInfo(BluetoothResultHandler* aRes) override; - /* Service Interfaces */ BluetoothSetupInterface* GetBluetoothSetupInterface() override; + BluetoothCoreInterface* GetBluetoothCoreInterface() override; BluetoothSocketInterface* GetBluetoothSocketInterface() override; BluetoothHandsfreeInterface* GetBluetoothHandsfreeInterface() override; BluetoothA2dpInterface* GetBluetoothA2dpInterface() override; @@ -156,6 +82,8 @@ private: void DispatchError(BluetoothResultHandler* aRes, BluetoothStatus aStatus); void DispatchError(BluetoothResultHandler* aRes, nsresult aRv); + static BluetoothNotificationHandler* sNotificationHandler; + nsCString mListenSocketName; RefPtr mListenSocket; RefPtr mCmdChannel; @@ -165,6 +93,7 @@ private: nsTArray > mResultHandlerQ; nsAutoPtr mSetupInterface; + nsAutoPtr mCoreInterface; nsAutoPtr mSocketInterface; nsAutoPtr mHandsfreeInterface; nsAutoPtr mA2dpInterface; diff --git a/dom/bluetooth/bluedroid/BluetoothDaemonSetupInterface.cpp b/dom/bluetooth/bluedroid/BluetoothDaemonSetupInterface.cpp index fcde736429..60e6f1f5ca 100644 --- a/dom/bluetooth/bluedroid/BluetoothDaemonSetupInterface.cpp +++ b/dom/bluetooth/bluedroid/BluetoothDaemonSetupInterface.cpp @@ -56,7 +56,7 @@ BluetoothDaemonSetupModule::HandleSvc(const DaemonSocketPDUHeader& aHeader, nsresult BluetoothDaemonSetupModule::RegisterModuleCmd( - uint8_t aId, uint8_t aMode, uint32_t aMaxNumClients, + BluetoothSetupServiceId aId, uint8_t aMode, uint32_t aMaxNumClients, BluetoothSetupResultHandler* aRes) { MOZ_ASSERT(NS_IsMainThread()); @@ -83,7 +83,7 @@ BluetoothDaemonSetupModule::RegisterModuleCmd( nsresult BluetoothDaemonSetupModule::UnregisterModuleCmd( - uint8_t aId, BluetoothSetupResultHandler* aRes) + BluetoothSetupServiceId aId, BluetoothSetupResultHandler* aRes) { MOZ_ASSERT(NS_IsMainThread()); @@ -183,7 +183,7 @@ BluetoothDaemonSetupInterface::~BluetoothDaemonSetupInterface() void BluetoothDaemonSetupInterface::RegisterModule( - uint8_t aId, uint8_t aMode, uint32_t aMaxNumClients, + BluetoothSetupServiceId aId, uint8_t aMode, uint32_t aMaxNumClients, BluetoothSetupResultHandler* aRes) { MOZ_ASSERT(mModule); @@ -196,7 +196,7 @@ BluetoothDaemonSetupInterface::RegisterModule( void BluetoothDaemonSetupInterface::UnregisterModule( - uint8_t aId, + BluetoothSetupServiceId aId, BluetoothSetupResultHandler* aRes) { MOZ_ASSERT(mModule); diff --git a/dom/bluetooth/bluedroid/BluetoothDaemonSetupInterface.h b/dom/bluetooth/bluedroid/BluetoothDaemonSetupInterface.h index ccd62c634e..1068eebc28 100644 --- a/dom/bluetooth/bluedroid/BluetoothDaemonSetupInterface.h +++ b/dom/bluetooth/bluedroid/BluetoothDaemonSetupInterface.h @@ -37,11 +37,11 @@ public: // Commands // - nsresult RegisterModuleCmd(uint8_t aId, uint8_t aMode, + nsresult RegisterModuleCmd(BluetoothSetupServiceId aId, uint8_t aMode, uint32_t aMaxNumClients, BluetoothSetupResultHandler* aRes); - nsresult UnregisterModuleCmd(uint8_t aId, + nsresult UnregisterModuleCmd(BluetoothSetupServiceId aId, BluetoothSetupResultHandler* aRes); nsresult ConfigurationCmd(const BluetoothConfigurationParameter* aParam, @@ -93,11 +93,11 @@ public: BluetoothDaemonSetupInterface(BluetoothDaemonSetupModule* aModule); ~BluetoothDaemonSetupInterface(); - void RegisterModule(uint8_t aId, uint8_t aMode, + void RegisterModule(BluetoothSetupServiceId aId, uint8_t aMode, uint32_t aMaxNumClients, BluetoothSetupResultHandler* aRes) override; - void UnregisterModule(uint8_t aId, + void UnregisterModule(BluetoothSetupServiceId aId, BluetoothSetupResultHandler* aRes) override; void Configuration(const BluetoothConfigurationParameter* aParam, diff --git a/dom/bluetooth/bluedroid/BluetoothGattManager.cpp b/dom/bluetooth/bluedroid/BluetoothGattManager.cpp index ce2c2ebd90..18c770f445 100644 --- a/dom/bluetooth/bluedroid/BluetoothGattManager.cpp +++ b/dom/bluetooth/bluedroid/BluetoothGattManager.cpp @@ -6,6 +6,7 @@ #include "BluetoothGattManager.h" +#include "BluetoothHashKeys.h" #include "BluetoothInterface.h" #include "BluetoothReplyRunnable.h" #include "BluetoothService.h" @@ -20,9 +21,18 @@ #define ENSURE_GATT_INTF_IS_READY_VOID(runnable) \ do { \ - if (!sBluetoothGattInterface) { \ + if (NS_WARN_IF(!sBluetoothGattInterface)) { \ DispatchReplyError(runnable, \ NS_LITERAL_STRING("BluetoothGattInterface is not ready")); \ + runnable = nullptr; \ + return; \ + } \ + } while(0) + +#define ENSURE_GATT_INTF_IN_ATTR_DISCOVER(client) \ + do { \ + if (NS_WARN_IF(!sBluetoothGattInterface)) { \ + client->NotifyDiscoverCompleted(false); \ return; \ } \ } while(0) @@ -37,6 +47,8 @@ namespace { static BluetoothGattInterface* sBluetoothGattInterface; } // namespace +const int BluetoothGattManager::MAX_NUM_CLIENTS = 1; + bool BluetoothGattManager::mInShutdown = false; static StaticAutoPtr > > sClients; @@ -135,16 +147,17 @@ class mozilla::dom::bluetooth::BluetoothGattClient final : public nsISupports public: NS_DECL_ISUPPORTS - BluetoothGattClient(const nsAString& aAppUuid, const nsAString& aDeviceAddr) - : mAppUuid(aAppUuid) - , mDeviceAddr(aDeviceAddr) - , mClientIf(0) - , mConnId(0) + BluetoothGattClient(const BluetoothUuid& aAppUuid, + const BluetoothAddress& aDeviceAddr) + : mAppUuid(aAppUuid) + , mDeviceAddr(aDeviceAddr) + , mClientIf(0) + , mConnId(0) { } void NotifyDiscoverCompleted(bool aSuccess) { - MOZ_ASSERT(!mAppUuid.IsEmpty()); + MOZ_ASSERT(!mAppUuid.IsCleared()); MOZ_ASSERT(mDiscoverRunnable); BluetoothService* bs = BluetoothService::Get(); @@ -172,8 +185,8 @@ public: mDiscoverRunnable = nullptr; } - nsString mAppUuid; - nsString mDeviceAddr; + BluetoothUuid mAppUuid; + BluetoothAddress mDeviceAddr; int mClientIf; int mConnId; RefPtr mStartLeScanRunnable; @@ -251,7 +264,7 @@ struct BluetoothGattServerAddDescriptorState { memset(&mServiceHandle, 0, sizeof(mServiceHandle)); memset(&mCharacteristicHandle, 0, sizeof(mCharacteristicHandle)); - memset(&mDescriptorUuid, 0, sizeof(mDescriptorUuid)); + mDescriptorUuid.Clear(); mRunnable = nullptr; } }; @@ -261,13 +274,13 @@ class BluetoothGattServer final : public nsISupports public: NS_DECL_ISUPPORTS - BluetoothGattServer(const nsAString& aAppUuid) - : mAppUuid(aAppUuid) - , mServerIf(0) - , mIsRegistering(false) + BluetoothGattServer(const BluetoothUuid& aAppUuid) + : mAppUuid(aAppUuid) + , mServerIf(0) + , mIsRegistering(false) { } - nsString mAppUuid; + BluetoothUuid mAppUuid; int mServerIf; /* @@ -292,9 +305,10 @@ public: RefPtr mStartServiceRunnable; RefPtr mStopServiceRunnable; RefPtr mSendResponseRunnable; + RefPtr mSendIndicationRunnable; // Map connection id from device address - nsDataHashtable mConnectionMap; + nsDataHashtable mConnectionMap; private: ~BluetoothGattServer() { } @@ -306,15 +320,15 @@ class UuidComparator { public: bool Equals(const RefPtr& aClient, - const nsAString& aAppUuid) const + const BluetoothUuid& aAppUuid) const { - return aClient->mAppUuid.Equals(aAppUuid); + return aClient->mAppUuid == aAppUuid; } bool Equals(const RefPtr& aServer, - const nsAString& aAppUuid) const + const BluetoothUuid& aAppUuid) const { - return aServer->mAppUuid.Equals(aAppUuid); + return aServer->mAppUuid == aAppUuid; } }; @@ -375,52 +389,126 @@ BluetoothGattManager::Get() return sBluetoothGattManager; } -class BluetoothGattManager::InitGattResultHandler final - : public BluetoothGattResultHandler +class BluetoothGattManager::RegisterModuleResultHandler final + : public BluetoothSetupResultHandler { public: - InitGattResultHandler(BluetoothProfileResultHandler* aRes) - : mRes(aRes) + RegisterModuleResultHandler(BluetoothGattInterface* aInterface, + BluetoothProfileResultHandler* aRes) + : mInterface(aInterface) + , mRes(aRes) { } void OnError(BluetoothStatus aStatus) override { - BT_WARNING("BluetoothGattInterface::Init failed: %d", + MOZ_ASSERT(NS_IsMainThread()); + + BT_WARNING("BluetoothSetupInterface::RegisterModule failed for GATT: %d", (int)aStatus); + + mInterface->SetNotificationHandler(nullptr); + if (mRes) { mRes->OnError(NS_ERROR_FAILURE); } } - void Init() override + void RegisterModule() override { + MOZ_ASSERT(NS_IsMainThread()); + + sBluetoothGattInterface = mInterface; + if (mRes) { mRes->Init(); } } private: + BluetoothGattInterface* mInterface; RefPtr mRes; }; +class BluetoothGattManager::InitProfileResultHandlerRunnable final + : public nsRunnable +{ +public: + InitProfileResultHandlerRunnable(BluetoothProfileResultHandler* aRes, + nsresult aRv) + : mRes(aRes) + , mRv(aRv) + { + MOZ_ASSERT(mRes); + } + + NS_IMETHOD Run() override + { + MOZ_ASSERT(NS_IsMainThread()); + + if (NS_SUCCEEDED(mRv)) { + mRes->Init(); + } else { + mRes->OnError(mRv); + } + return NS_OK; + } + +private: + RefPtr mRes; + nsresult mRv; +}; + // static void BluetoothGattManager::InitGattInterface(BluetoothProfileResultHandler* aRes) { - BluetoothInterface* btInf = BluetoothInterface::GetInstance(); - if (!btInf) { - BT_LOGR("Error: Bluetooth interface not available"); - if (aRes) { - aRes->OnError(NS_ERROR_FAILURE); + MOZ_ASSERT(NS_IsMainThread()); + + if (sBluetoothGattInterface) { + BT_LOGR("Bluetooth GATT interface is already initalized."); + RefPtr r = + new InitProfileResultHandlerRunnable(aRes, NS_OK); + if (NS_FAILED(NS_DispatchToMainThread(r))) { + BT_LOGR("Failed to dispatch GATT Init runnable"); } return; } - sBluetoothGattInterface = btInf->GetBluetoothGattInterface(); - if (!sBluetoothGattInterface) { - BT_LOGR("Error: Bluetooth GATT interface not available"); - if (aRes) { - aRes->OnError(NS_ERROR_FAILURE); + auto btInf = BluetoothInterface::GetInstance(); + + if (NS_WARN_IF(!btInf)) { + // If there's no Bluetooth interface, we dispatch a runnable + // that calls the profile result handler. + RefPtr r = + new InitProfileResultHandlerRunnable(aRes, NS_ERROR_FAILURE); + if (NS_FAILED(NS_DispatchToMainThread(r))) { + BT_LOGR("Failed to dispatch GATT OnError runnable"); + } + return; + } + + auto setupInterface = btInf->GetBluetoothSetupInterface(); + + if (NS_WARN_IF(!setupInterface)) { + // If there's no Setup interface, we dispatch a runnable + // that calls the profile result handler. + RefPtr r = + new InitProfileResultHandlerRunnable(aRes, NS_ERROR_FAILURE); + if (NS_FAILED(NS_DispatchToMainThread(r))) { + BT_LOGR("Failed to dispatch GATT OnError runnable"); + } + return; + } + + auto gattInterface = btInf->GetBluetoothGattInterface(); + + if (NS_WARN_IF(!gattInterface)) { + // If there's no GATT interface, we dispatch a runnable + // that calls the profile result handler. + RefPtr r = + new InitProfileResultHandlerRunnable(aRes, NS_ERROR_FAILURE); + if (NS_FAILED(NS_DispatchToMainThread(r))) { + BT_LOGR("Failed to dispatch GATT OnError runnable"); } return; } @@ -433,30 +521,43 @@ BluetoothGattManager::InitGattInterface(BluetoothProfileResultHandler* aRes) sServers = new nsTArray >; } - BluetoothGattManager* gattManager = BluetoothGattManager::Get(); - sBluetoothGattInterface->Init(gattManager, - new InitGattResultHandler(aRes)); + // Set notification handler _before_ registering the module. It could + // happen that we receive notifications, before the result handler runs. + gattInterface->SetNotificationHandler(BluetoothGattManager::Get()); + + setupInterface->RegisterModule( + SETUP_SERVICE_ID_GATT, 0, MAX_NUM_CLIENTS, + new RegisterModuleResultHandler(gattInterface, aRes)); } -class BluetoothGattManager::CleanupResultHandler final - : public BluetoothGattResultHandler +class BluetoothGattManager::UnregisterModuleResultHandler final + : public BluetoothSetupResultHandler { public: - CleanupResultHandler(BluetoothProfileResultHandler* aRes) - : mRes(aRes) + UnregisterModuleResultHandler(BluetoothProfileResultHandler* aRes) + : mRes(aRes) { } void OnError(BluetoothStatus aStatus) override { - BT_WARNING("BluetoothGattInterface::Cleanup failed: %d", + MOZ_ASSERT(NS_IsMainThread()); + + BT_WARNING("BluetoothSetupInterface::UnregisterModule failed for GATT: %d", (int)aStatus); + + sBluetoothGattInterface->SetNotificationHandler(nullptr); + sBluetoothGattInterface = nullptr; + if (mRes) { mRes->OnError(NS_ERROR_FAILURE); } } - void Cleanup() override + void UnregisterModule() override { + MOZ_ASSERT(NS_IsMainThread()); + + sBluetoothGattInterface->SetNotificationHandler(nullptr); sBluetoothGattInterface = nullptr; sClients = nullptr; sServers = nullptr; @@ -470,24 +571,33 @@ private: RefPtr mRes; }; -class BluetoothGattManager::CleanupResultHandlerRunnable final +class BluetoothGattManager::DeinitProfileResultHandlerRunnable final : public nsRunnable { public: - CleanupResultHandlerRunnable(BluetoothProfileResultHandler* aRes) - : mRes(aRes) + DeinitProfileResultHandlerRunnable(BluetoothProfileResultHandler* aRes, + nsresult aRv) + : mRes(aRes) + , mRv(aRv) { MOZ_ASSERT(mRes); } NS_IMETHOD Run() override { - mRes->Deinit(); + MOZ_ASSERT(NS_IsMainThread()); + + if (NS_SUCCEEDED(mRv)) { + mRes->Deinit(); + } else { + mRes->OnError(mRv); + } return NS_OK; } private: RefPtr mRes; + nsresult mRv; }; // static @@ -496,16 +606,45 @@ BluetoothGattManager::DeinitGattInterface(BluetoothProfileResultHandler* aRes) { MOZ_ASSERT(NS_IsMainThread()); - if (sBluetoothGattInterface) { - sBluetoothGattInterface->Cleanup(new CleanupResultHandler(aRes)); - } else if (aRes) { - // We dispatch a runnable here to make the profile resource handler - // behave as if GATT was initialized. - RefPtr r = new CleanupResultHandlerRunnable(aRes); + if (!sBluetoothGattInterface) { + BT_LOGR("Bluetooth GATT interface has not been initalized."); + RefPtr r = + new DeinitProfileResultHandlerRunnable(aRes, NS_OK); if (NS_FAILED(NS_DispatchToMainThread(r))) { - BT_LOGR("Failed to dispatch cleanup-result-handler runnable"); + BT_LOGR("Failed to dispatch GATT Deinit runnable"); } + return; } + + auto btInf = BluetoothInterface::GetInstance(); + + if (NS_WARN_IF(!btInf)) { + // If there's no backend interface, we dispatch a runnable + // that calls the profile result handler. + RefPtr r = + new DeinitProfileResultHandlerRunnable(aRes, NS_ERROR_FAILURE); + if (NS_FAILED(NS_DispatchToMainThread(r))) { + BT_LOGR("Failed to dispatch GATT OnError runnable"); + } + return; + } + + auto setupInterface = btInf->GetBluetoothSetupInterface(); + + if (NS_WARN_IF(!setupInterface)) { + // If there's no Setup interface, we dispatch a runnable + // that calls the profile result handler. + RefPtr r = + new DeinitProfileResultHandlerRunnable(aRes, NS_ERROR_FAILURE); + if (NS_FAILED(NS_DispatchToMainThread(r))) { + BT_LOGR("Failed to dispatch GATT OnError runnable"); + } + return; + } + + setupInterface->UnregisterModule( + SETUP_SERVICE_ID_GATT, + new UnregisterModuleResultHandler(aRes)); } class BluetoothGattManager::RegisterClientResultHandler final @@ -690,7 +829,7 @@ private: }; void -BluetoothGattManager::StartLeScan(const nsTArray& aServiceUuids, +BluetoothGattManager::StartLeScan(const nsTArray& aServiceUuids, BluetoothReplyRunnable* aRunnable) { MOZ_ASSERT(NS_IsMainThread()); @@ -698,14 +837,14 @@ BluetoothGattManager::StartLeScan(const nsTArray& aServiceUuids, ENSURE_GATT_INTF_IS_READY_VOID(aRunnable); - nsString appUuidStr; - if (NS_WARN_IF(NS_FAILED(GenerateUuid(appUuidStr))) || appUuidStr.IsEmpty()) { + BluetoothUuid appUuid; + if (NS_WARN_IF(NS_FAILED(GenerateUuid(appUuid)))) { DispatchReplyError(aRunnable, NS_LITERAL_STRING("start LE scan failed")); return; } - size_t index = sClients->IndexOf(appUuidStr, 0 /* Start */, UuidComparator()); + size_t index = sClients->IndexOf(appUuid, 0 /* Start */, UuidComparator()); // Reject the startLeScan request if the clientIf is being used. if (NS_WARN_IF(index != sClients->NoIndex)) { @@ -715,20 +854,18 @@ BluetoothGattManager::StartLeScan(const nsTArray& aServiceUuids, } index = sClients->Length(); - sClients->AppendElement(new BluetoothGattClient(appUuidStr, EmptyString())); + sClients->AppendElement(new BluetoothGattClient(appUuid, + BluetoothAddress::ANY)); RefPtr client = sClients->ElementAt(index); client->mStartLeScanRunnable = aRunnable; - BluetoothUuid appUuid; - StringToUuid(appUuidStr, appUuid); - // 'startLeScan' will be proceeded after client registered sBluetoothGattInterface->RegisterClient( appUuid, new RegisterClientResultHandler(client)); } void -BluetoothGattManager::StopLeScan(const nsAString& aScanUuid, +BluetoothGattManager::StopLeScan(const BluetoothUuid& aScanUuid, BluetoothReplyRunnable* aRunnable) { MOZ_ASSERT(NS_IsMainThread()); @@ -786,8 +923,8 @@ private: }; void -BluetoothGattManager::Connect(const nsAString& aAppUuid, - const nsAString& aDeviceAddr, +BluetoothGattManager::Connect(const BluetoothUuid& aAppUuid, + const BluetoothAddress& aDeviceAddr, BluetoothReplyRunnable* aRunnable) { MOZ_ASSERT(NS_IsMainThread()); @@ -795,23 +932,6 @@ BluetoothGattManager::Connect(const nsAString& aAppUuid, ENSURE_GATT_INTF_IS_READY_VOID(aRunnable); - BluetoothAddress deviceAddr; - nsresult rv = StringToAddress(aDeviceAddr, deviceAddr); - if (NS_FAILED(rv)) { - BluetoothService* bs = BluetoothService::Get(); - NS_ENSURE_TRUE_VOID(bs); - - // Notify BluetoothGatt for client disconnected - bs->DistributeSignal( - NS_LITERAL_STRING(GATT_CONNECTION_STATE_CHANGED_ID), - aAppUuid, - BluetoothValue(false)); // Disconnected - - // Reject the connect request - DispatchReplyError(aRunnable, STATUS_PARM_INVALID); - return; - } - size_t index = sClients->IndexOf(aAppUuid, 0 /* Start */, UuidComparator()); if (index == sClients->NoIndex) { index = sClients->Length(); @@ -823,17 +943,14 @@ BluetoothGattManager::Connect(const nsAString& aAppUuid, if (client->mClientIf > 0) { sBluetoothGattInterface->Connect(client->mClientIf, - deviceAddr, + aDeviceAddr, true, // direct connect TRANSPORT_AUTO, new ConnectResultHandler(client)); } else { - BluetoothUuid uuid; - StringToUuid(aAppUuid, uuid); - // connect will be proceeded after client registered sBluetoothGattInterface->RegisterClient( - uuid, new RegisterClientResultHandler(client)); + aAppUuid, new RegisterClientResultHandler(client)); } } @@ -873,8 +990,8 @@ private: }; void -BluetoothGattManager::Disconnect(const nsAString& aAppUuid, - const nsAString& aDeviceAddr, +BluetoothGattManager::Disconnect(const BluetoothUuid& aAppUuid, + const BluetoothAddress& aDeviceAddr, BluetoothReplyRunnable* aRunnable) { MOZ_ASSERT(NS_IsMainThread()); @@ -882,23 +999,6 @@ BluetoothGattManager::Disconnect(const nsAString& aAppUuid, ENSURE_GATT_INTF_IS_READY_VOID(aRunnable); - BluetoothAddress deviceAddr; - nsresult rv = StringToAddress(aDeviceAddr, deviceAddr); - if (NS_FAILED(rv)) { - BluetoothService* bs = BluetoothService::Get(); - NS_ENSURE_TRUE_VOID(bs); - - // Notify BluetoothGatt that client remains connected - bs->DistributeSignal( - NS_LITERAL_STRING(GATT_CONNECTION_STATE_CHANGED_ID), - aAppUuid, - BluetoothValue(true)); // Connected - - // Reject the Disconnect request - DispatchReplyError(aRunnable, STATUS_PARM_INVALID); - return; - } - size_t index = sClients->IndexOf(aAppUuid, 0 /* Start */, UuidComparator()); if (NS_WARN_IF(index == sClients->NoIndex)) { DispatchReplyError(aRunnable, STATUS_PARM_INVALID); @@ -910,7 +1010,7 @@ BluetoothGattManager::Disconnect(const nsAString& aAppUuid, sBluetoothGattInterface->Disconnect( client->mClientIf, - deviceAddr, + aDeviceAddr, client->mConnId, new DisconnectResultHandler(client)); } @@ -938,7 +1038,7 @@ private: }; void -BluetoothGattManager::Discover(const nsAString& aAppUuid, +BluetoothGattManager::Discover(const BluetoothUuid& aAppUuid, BluetoothReplyRunnable* aRunnable) { MOZ_ASSERT(NS_IsMainThread()); @@ -1006,7 +1106,7 @@ private: void BluetoothGattManager::ReadRemoteRssi(int aClientIf, - const nsAString& aDeviceAddr, + const BluetoothAddress& aDeviceAddr, BluetoothReplyRunnable* aRunnable) { MOZ_ASSERT(NS_IsMainThread()); @@ -1014,13 +1114,6 @@ BluetoothGattManager::ReadRemoteRssi(int aClientIf, ENSURE_GATT_INTF_IS_READY_VOID(aRunnable); - BluetoothAddress deviceAddr; - nsresult rv = StringToAddress(aDeviceAddr, deviceAddr); - if (NS_FAILED(rv)) { - DispatchReplyError(aRunnable, STATUS_PARM_INVALID); - return; - } - size_t index = sClients->IndexOf(aClientIf, 0 /* Start */, InterfaceIdComparator()); if (NS_WARN_IF(index == sClients->NoIndex)) { @@ -1032,7 +1125,7 @@ BluetoothGattManager::ReadRemoteRssi(int aClientIf, client->mReadRemoteRssiRunnable = aRunnable; sBluetoothGattInterface->ReadRemoteRssi( - aClientIf, deviceAddr, + aClientIf, aDeviceAddr, new ReadRemoteRssiResultHandler(client)); } @@ -1081,7 +1174,7 @@ private: void BluetoothGattManager::RegisterNotifications( - const nsAString& aAppUuid, const BluetoothGattServiceId& aServId, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServId, const BluetoothGattId& aCharId, BluetoothReplyRunnable* aRunnable) { MOZ_ASSERT(NS_IsMainThread()); @@ -1105,17 +1198,10 @@ BluetoothGattManager::RegisterNotifications( return; } - BluetoothAddress deviceAddr; - nsresult rv = StringToAddress(client->mDeviceAddr, deviceAddr); - if (NS_FAILED(rv)) { - DispatchReplyError(aRunnable, STATUS_PARM_INVALID); - return; - } - client->mRegisterNotificationsRunnable = aRunnable; sBluetoothGattInterface->RegisterNotification( - client->mClientIf, deviceAddr, aServId, aCharId, + client->mClientIf, client->mDeviceAddr, aServId, aCharId, new RegisterNotificationsResultHandler(client)); } @@ -1164,7 +1250,7 @@ private: void BluetoothGattManager::DeregisterNotifications( - const nsAString& aAppUuid, const BluetoothGattServiceId& aServId, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServId, const BluetoothGattId& aCharId, BluetoothReplyRunnable* aRunnable) { MOZ_ASSERT(NS_IsMainThread()); @@ -1187,17 +1273,10 @@ BluetoothGattManager::DeregisterNotifications( return; } - BluetoothAddress deviceAddr; - nsresult rv = StringToAddress(client->mDeviceAddr, deviceAddr); - if (NS_FAILED(rv)) { - DispatchReplyError(aRunnable, STATUS_PARM_INVALID); - return; - } - client->mDeregisterNotificationsRunnable = aRunnable; sBluetoothGattInterface->DeregisterNotification( - client->mClientIf, deviceAddr, aServId, aCharId, + client->mClientIf, client->mDeviceAddr, aServId, aCharId, new DeregisterNotificationsResultHandler(client)); } @@ -1232,7 +1311,7 @@ private: void BluetoothGattManager::ReadCharacteristicValue( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServiceId, const BluetoothGattId& aCharacteristicId, BluetoothReplyRunnable* aRunnable) @@ -1310,7 +1389,7 @@ private: void BluetoothGattManager::WriteCharacteristicValue( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServiceId, const BluetoothGattId& aCharacteristicId, const BluetoothGattWriteType& aWriteType, @@ -1393,7 +1472,7 @@ private: void BluetoothGattManager::ReadDescriptorValue( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServiceId, const BluetoothGattId& aCharacteristicId, const BluetoothGattId& aDescriptorId, @@ -1473,7 +1552,7 @@ private: void BluetoothGattManager::WriteDescriptorValue( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServiceId, const BluetoothGattId& aCharacteristicId, const BluetoothGattId& aDescriptorId, @@ -1590,13 +1669,10 @@ public: (int)aStatus); MOZ_ASSERT(mServer->mConnectPeripheralRunnable); - nsAutoString addressStr; - AddressToString(mDeviceAddr, addressStr); - DispatchReplyError(mServer->mConnectPeripheralRunnable, NS_LITERAL_STRING("ConnectPeripheral failed")); mServer->mConnectPeripheralRunnable = nullptr; - mServer->mConnectionMap.Remove(addressStr); + mServer->mConnectionMap.Remove(mDeviceAddr); } private: @@ -1606,8 +1682,8 @@ private: void BluetoothGattManager::ConnectPeripheral( - const nsAString& aAppUuid, - const nsAString& aAddress, + const BluetoothUuid& aAppUuid, + const BluetoothAddress& aAddress, BluetoothReplyRunnable* aRunnable) { MOZ_ASSERT(NS_IsMainThread()); @@ -1615,13 +1691,6 @@ BluetoothGattManager::ConnectPeripheral( ENSURE_GATT_INTF_IS_READY_VOID(aRunnable); - BluetoothAddress address; - nsresult rv = StringToAddress(aAddress, address); - if (NS_FAILED(rv)) { - DispatchReplyError(aRunnable, STATUS_PARM_INVALID); - return; - } - size_t index = sServers->IndexOf(aAppUuid, 0 /* Start */, UuidComparator()); if (index == sServers->NoIndex) { index = sServers->Length(); @@ -1660,19 +1729,16 @@ BluetoothGattManager::ConnectPeripheral( if (server->mServerIf > 0) { sBluetoothGattInterface->ConnectPeripheral( server->mServerIf, - address, + aAddress, true, // direct connect TRANSPORT_AUTO, - new ConnectPeripheralResultHandler(server, address)); + new ConnectPeripheralResultHandler(server, aAddress)); } else if (!server->mIsRegistering) { /* avoid triggering another registration * procedure if there is an on-going one * already */ - BluetoothUuid uuid; - StringToUuid(aAppUuid, uuid); - // connect will be proceeded after server registered sBluetoothGattInterface->RegisterServer( - uuid, new RegisterServerResultHandler(server)); + aAppUuid, new RegisterServerResultHandler(server)); } } @@ -1704,8 +1770,8 @@ private: void BluetoothGattManager::DisconnectPeripheral( - const nsAString& aAppUuid, - const nsAString& aAddress, + const BluetoothUuid& aAppUuid, + const BluetoothAddress& aAddress, BluetoothReplyRunnable* aRunnable) { MOZ_ASSERT(NS_IsMainThread()); @@ -1713,13 +1779,6 @@ BluetoothGattManager::DisconnectPeripheral( ENSURE_GATT_INTF_IS_READY_VOID(aRunnable); - BluetoothAddress address; - nsresult rv = StringToAddress(aAddress, address); - if (NS_FAILED(rv)) { - DispatchReplyError(aRunnable, STATUS_PARM_INVALID); - return; - } - size_t index = sServers->IndexOf(aAppUuid, 0 /* Start */, UuidComparator()); if (NS_WARN_IF(index == sServers->NoIndex)) { DispatchReplyError(aRunnable, STATUS_PARM_INVALID); @@ -1751,7 +1810,7 @@ BluetoothGattManager::DisconnectPeripheral( sBluetoothGattInterface->DisconnectPeripheral( server->mServerIf, - address, + aAddress, connId, new DisconnectPeripheralResultHandler(server)); } @@ -1851,7 +1910,7 @@ private: void BluetoothGattManager::ServerAddService( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServiceId, uint16_t aHandleCount, BluetoothReplyRunnable* aRunnable) @@ -1885,12 +1944,9 @@ BluetoothGattManager::ServerAddService( } else if (!server->mIsRegistering) { /* avoid triggering another registration * procedure if there is an on-going one * already */ - BluetoothUuid uuid; - StringToUuid(aAppUuid, uuid); - // add service will be proceeded after server registered sBluetoothGattInterface->RegisterServer( - uuid, new RegisterServerResultHandler(server)); + aAppUuid, new RegisterServerResultHandler(server)); } } @@ -1923,7 +1979,7 @@ private: void BluetoothGattManager::ServerAddIncludedService( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothAttributeHandle& aServiceHandle, const BluetoothAttributeHandle& aIncludedServiceHandle, BluetoothReplyRunnable* aRunnable) @@ -1989,7 +2045,7 @@ private: void BluetoothGattManager::ServerAddCharacteristic( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothAttributeHandle& aServiceHandle, const BluetoothUuid& aCharacteristicUuid, BluetoothGattAttrPerm aPermissions, @@ -2025,8 +2081,8 @@ BluetoothGattManager::ServerAddCharacteristic( server->mServerIf, aServiceHandle, aCharacteristicUuid, - aPermissions, aProperties, + aPermissions, new ServerAddCharacteristicResultHandler(server)); } @@ -2059,7 +2115,7 @@ private: void BluetoothGattManager::ServerAddDescriptor( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothAttributeHandle& aServiceHandle, const BluetoothAttributeHandle& aCharacteristicHandle, const BluetoothUuid& aDescriptorUuid, @@ -2131,7 +2187,7 @@ private: void BluetoothGattManager::ServerRemoveService( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothAttributeHandle& aServiceHandle, BluetoothReplyRunnable* aRunnable) { @@ -2195,7 +2251,7 @@ private: void BluetoothGattManager::ServerStartService( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothAttributeHandle& aServiceHandle, BluetoothReplyRunnable* aRunnable) { @@ -2260,7 +2316,7 @@ private: void BluetoothGattManager::ServerStopService( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothAttributeHandle& aServiceHandle, BluetoothReplyRunnable* aRunnable) { @@ -2331,8 +2387,8 @@ private: }; void -BluetoothGattManager::ServerSendResponse(const nsAString& aAppUuid, - const nsAString& aAddress, +BluetoothGattManager::ServerSendResponse(const BluetoothUuid& aAppUuid, + const BluetoothAddress& aAddress, uint16_t aStatus, int aRequestId, const BluetoothGattResponse& aRsp, @@ -2370,6 +2426,96 @@ BluetoothGattManager::ServerSendResponse(const nsAString& aAppUuid, new ServerSendResponseResultHandler(server)); } +class BluetoothGattManager::ServerSendIndicationResultHandler final + : public BluetoothGattResultHandler +{ +public: + ServerSendIndicationResultHandler(BluetoothGattServer* aServer) + : mServer(aServer) + { + MOZ_ASSERT(mServer); + } + + void SendIndication() override + { + if (mServer->mSendIndicationRunnable) { + DispatchReplySuccess(mServer->mSendIndicationRunnable); + mServer->mSendIndicationRunnable = nullptr; + } + } + + void OnError(BluetoothStatus aStatus) override + { + BT_WARNING("BluetoothGattServerInterface::NotifyCharacteristicChanged" + "failed: %d", (int)aStatus); + + // Reject the send indication request + if (mServer->mSendIndicationRunnable) { + DispatchReplyError(mServer->mSendIndicationRunnable, + NS_LITERAL_STRING("Send GATT indication failed")); + mServer->mSendIndicationRunnable = nullptr; + } + } + +private: + RefPtr mServer; +}; + +void +BluetoothGattManager::ServerSendIndication( + const BluetoothUuid& aAppUuid, + const BluetoothAddress& aAddress, + const BluetoothAttributeHandle& aCharacteristicHandle, + bool aConfirm, + const nsTArray& aValue, + BluetoothReplyRunnable* aRunnable) +{ + MOZ_ASSERT(NS_IsMainThread()); + MOZ_ASSERT(aRunnable); + + ENSURE_GATT_INTF_IS_READY_VOID(aRunnable); + + size_t index = sServers->IndexOf(aAppUuid, 0 /* Start */, UuidComparator()); + // Reject the request if the server has not been registered yet. + if (index == sServers->NoIndex) { + DispatchReplyError(aRunnable, STATUS_NOT_READY); + return; + } + RefPtr server = sServers->ElementAt(index); + + // Reject the request if the server has not been registered successfully. + if (!server->mServerIf) { + DispatchReplyError(aRunnable, STATUS_NOT_READY); + return; + } + // Reject the request if there is an ongoing send indication request. + if (server->mSendIndicationRunnable) { + DispatchReplyError(aRunnable, STATUS_BUSY); + return; + } + + int connId = 0; + if (!server->mConnectionMap.Get(aAddress, &connId)) { + DispatchReplyError(aRunnable, STATUS_PARM_INVALID); + return; + } + + if (!connId) { + DispatchReplyError(aRunnable, STATUS_NOT_READY); + return; + } + + server->mSendIndicationRunnable = aRunnable; + + sBluetoothGattInterface->SendIndication( + server->mServerIf, + aCharacteristicHandle, + connId, + aValue, + aConfirm, + new ServerSendIndicationResultHandler(server)); +} + // // Notification Handlers // @@ -2380,10 +2526,7 @@ BluetoothGattManager::RegisterClientNotification(BluetoothGattStatus aStatus, { MOZ_ASSERT(NS_IsMainThread()); - nsString uuid; - UuidToString(aAppUuid, uuid); - - size_t index = sClients->IndexOf(uuid, 0 /* Start */, UuidComparator()); + size_t index = sClients->IndexOf(aAppUuid, 0 /* Start */, UuidComparator()); NS_ENSURE_TRUE_VOID(index != sClients->NoIndex); RefPtr client = sClients->ElementAt(index); @@ -2392,13 +2535,16 @@ BluetoothGattManager::RegisterClientNotification(BluetoothGattStatus aStatus, NS_ENSURE_TRUE_VOID(bs); if (aStatus != GATT_STATUS_SUCCESS) { + nsAutoString appUuidStr; + UuidToString(aAppUuid, appUuidStr); + BT_LOGD("RegisterClient failed: clientIf = %d, status = %d, appUuid = %s", - aClientIf, aStatus, NS_ConvertUTF16toUTF8(uuid).get()); + aClientIf, aStatus, NS_ConvertUTF16toUTF8(appUuidStr).get()); // Notify BluetoothGatt for client disconnected bs->DistributeSignal( NS_LITERAL_STRING(GATT_CONNECTION_STATE_CHANGED_ID), - uuid, BluetoothValue(false)); // Disconnected + aAppUuid, BluetoothValue(false)); // Disconnected if (client->mStartLeScanRunnable) { // Reject the LE scan request @@ -2423,33 +2569,19 @@ BluetoothGattManager::RegisterClientNotification(BluetoothGattStatus aStatus, // Notify BluetoothGatt to update the clientIf bs->DistributeSignal( NS_LITERAL_STRING("ClientRegistered"), - uuid, BluetoothValue(uint32_t(aClientIf))); + aAppUuid, BluetoothValue(uint32_t(aClientIf))); if (client->mStartLeScanRunnable) { // Client just registered, proceed remaining startLeScan request. + ENSURE_GATT_INTF_IS_READY_VOID(client->mStartLeScanRunnable); sBluetoothGattInterface->Scan( aClientIf, true /* start */, new StartLeScanResultHandler(client)); } else if (client->mConnectRunnable) { // Client just registered, proceed remaining connect request. - BluetoothAddress address; - nsresult rv = StringToAddress(client->mDeviceAddr, address); - if (NS_FAILED(rv)) { - // Notify BluetoothGatt for client disconnected - bs->DistributeSignal( - NS_LITERAL_STRING(GATT_CONNECTION_STATE_CHANGED_ID), - client->mAppUuid, - BluetoothValue(false)); // Disconnected - - // Reject the connect request - DispatchReplyError(client->mConnectRunnable, - NS_LITERAL_STRING("Connect failed")); - client->mConnectRunnable = nullptr; - return; - } - + ENSURE_GATT_INTF_IS_READY_VOID(client->mConnectRunnable); sBluetoothGattInterface->Connect( - aClientIf, address, true /* direct connect */, + aClientIf, client->mDeviceAddr, true /* direct connect */, TRANSPORT_AUTO, new ConnectResultHandler(client)); } @@ -2652,6 +2784,7 @@ BluetoothGattManager::SearchCompleteNotification(int aConnId, // All services are discovered, continue to search included services of each // service if existed, otherwise, notify application that discover completed if (!client->mServices.IsEmpty()) { + ENSURE_GATT_INTF_IN_ATTR_DISCOVER(client); sBluetoothGattInterface->GetIncludedService( aConnId, client->mServices[0], // start from first service @@ -2711,6 +2844,7 @@ BluetoothGattManager::GetCharacteristicNotification( client->mCharacteristics.AppendElement(attribute); // Get next characteristic of this service + ENSURE_GATT_INTF_IN_ATTR_DISCOVER(client); sBluetoothGattInterface->GetCharacteristic( aConnId, aServiceId, @@ -2756,6 +2890,7 @@ BluetoothGattManager::GetDescriptorNotification( client->mDescriptors.AppendElement(aDescriptorId); // Get next descriptor of this characteristic + ENSURE_GATT_INTF_IN_ATTR_DISCOVER(client); sBluetoothGattInterface->GetDescriptor( aConnId, aServiceId, @@ -2798,6 +2933,7 @@ BluetoothGattManager::GetIncludedServiceNotification( RefPtr client = sClients->ElementAt(index); MOZ_ASSERT(client->mDiscoverRunnable); + ENSURE_GATT_INTF_IN_ATTR_DISCOVER(client); if (aStatus == GATT_STATUS_SUCCESS) { // Save to mIncludedServices for distributing to applications client->mIncludedServices.AppendElement(aIncludedServId); @@ -2941,6 +3077,14 @@ BluetoothGattManager::ReadCharacteristicNotification( } else if (!client->mReadCharacteristicState.mAuthRetry && (aStatus == GATT_STATUS_INSUFFICIENT_AUTHENTICATION || aStatus == GATT_STATUS_INSUFFICIENT_ENCRYPTION)) { + if (NS_WARN_IF(!sBluetoothGattInterface)) { + client->mReadCharacteristicState.Reset(); + // Reject the promise + DispatchReplyError(runnable, + NS_LITERAL_STRING("ReadCharacteristicValue failed")); + return; + } + client->mReadCharacteristicState.mAuthRetry = true; // Retry with another authentication requirement sBluetoothGattInterface->ReadCharacteristic( @@ -2980,6 +3124,14 @@ BluetoothGattManager::WriteCharacteristicNotification( } else if (!client->mWriteCharacteristicState.mAuthRetry && (aStatus == GATT_STATUS_INSUFFICIENT_AUTHENTICATION || aStatus == GATT_STATUS_INSUFFICIENT_ENCRYPTION)) { + if (NS_WARN_IF(!sBluetoothGattInterface)) { + client->mWriteCharacteristicState.Reset(); + // Reject the promise + DispatchReplyError(runnable, + NS_LITERAL_STRING("WriteCharacteristicValue failed")); + return; + } + client->mWriteCharacteristicState.mAuthRetry = true; // Retry with another authentication requirement sBluetoothGattInterface->WriteCharacteristic( @@ -3035,6 +3187,14 @@ BluetoothGattManager::ReadDescriptorNotification( } else if (!client->mReadDescriptorState.mAuthRetry && (aStatus == GATT_STATUS_INSUFFICIENT_AUTHENTICATION || aStatus == GATT_STATUS_INSUFFICIENT_ENCRYPTION)) { + if (NS_WARN_IF(!sBluetoothGattInterface)) { + client->mReadDescriptorState.Reset(); + // Reject the promise + DispatchReplyError(runnable, + NS_LITERAL_STRING("ReadDescriptorValue failed")); + return; + } + client->mReadDescriptorState.mAuthRetry = true; // Retry with another authentication requirement sBluetoothGattInterface->ReadDescriptor( @@ -3075,6 +3235,14 @@ BluetoothGattManager::WriteDescriptorNotification( } else if (!client->mWriteDescriptorState.mAuthRetry && (aStatus == GATT_STATUS_INSUFFICIENT_AUTHENTICATION || aStatus == GATT_STATUS_INSUFFICIENT_ENCRYPTION)) { + if (NS_WARN_IF(!sBluetoothGattInterface)) { + client->mWriteDescriptorState.Reset(); + // Reject the promise + DispatchReplyError(runnable, + NS_LITERAL_STRING("WriteDescriptorValue failed")); + return; + } + client->mWriteDescriptorState.mAuthRetry = true; // Retry with another authentication requirement sBluetoothGattInterface->WriteDescriptor( @@ -3157,10 +3325,7 @@ BluetoothGattManager::RegisterServerNotification(BluetoothGattStatus aStatus, { MOZ_ASSERT(NS_IsMainThread()); - nsString uuid; - UuidToString(aAppUuid, uuid); - - size_t index = sServers->IndexOf(uuid, 0 /* Start */, UuidComparator()); + size_t index = sServers->IndexOf(aAppUuid, 0 /* Start */, UuidComparator()); NS_ENSURE_TRUE_VOID(index != sServers->NoIndex); RefPtr server = (*sServers)[index]; @@ -3168,9 +3333,12 @@ BluetoothGattManager::RegisterServerNotification(BluetoothGattStatus aStatus, server->mIsRegistering = false; BluetoothService* bs = BluetoothService::Get(); - if (!bs || aStatus != GATT_STATUS_SUCCESS) { + if (!bs || aStatus != GATT_STATUS_SUCCESS || !sBluetoothGattInterface) { + nsAutoString appUuidStr; + UuidToString(aAppUuid, appUuidStr); + BT_LOGD("RegisterServer failed: serverIf = %d, status = %d, appUuid = %s", - aServerIf, aStatus, NS_ConvertUTF16toUTF8(uuid).get()); + aServerIf, aStatus, NS_ConvertUTF16toUTF8(appUuidStr).get()); if (server->mConnectPeripheralRunnable) { // Reject the connect peripheral request @@ -3199,19 +3367,11 @@ BluetoothGattManager::RegisterServerNotification(BluetoothGattStatus aStatus, // Notify BluetoothGattServer to update the serverIf bs->DistributeSignal( NS_LITERAL_STRING("ServerRegistered"), - uuid, BluetoothValue(uint32_t(aServerIf))); + aAppUuid, BluetoothValue(uint32_t(aServerIf))); if (server->mConnectPeripheralRunnable) { // Only one entry exists in the map during first connect peripheral request - BluetoothAddress deviceAddr; - nsresult rv = StringToAddress(server->mConnectionMap.Iter().Key(), deviceAddr); - if (NS_FAILED(rv)) { - DispatchReplyError(server->mConnectPeripheralRunnable, - NS_LITERAL_STRING("ConnectPeripheral failed")); - server->mConnectPeripheralRunnable = nullptr; - server->mConnectionMap.Remove(server->mConnectionMap.Iter().Key()); - return; - } + const BluetoothAddress& deviceAddr = server->mConnectionMap.Iter().Key(); sBluetoothGattInterface->ConnectPeripheral( aServerIf, deviceAddr, true /* direct connect */, TRANSPORT_AUTO, @@ -3244,20 +3404,20 @@ BluetoothGattManager::ConnectionNotification(int aConnId, RefPtr server = (*sServers)[index]; - nsAutoString addressStr; - AddressToString(aBdAddr, addressStr); - // Update the connection map based on the connection status if (aConnected) { - server->mConnectionMap.Put(addressStr, aConnId); + server->mConnectionMap.Put(aBdAddr, aConnId); } else { - server->mConnectionMap.Remove(addressStr); + server->mConnectionMap.Remove(aBdAddr); } + nsAutoString bdAddrStr; + AddressToString(aBdAddr, bdAddrStr); + // Notify BluetoothGattServer that connection status changed InfallibleTArray props; AppendNamedValue(props, "Connected", aConnected); - AppendNamedValue(props, "Address", addressStr); + AppendNamedValue(props, "Address", bdAddrStr); bs->DistributeSignal( NS_LITERAL_STRING(GATT_CONNECTION_STATE_CHANGED_ID), server->mAppUuid, @@ -3542,6 +3702,7 @@ BluetoothGattManager::RequestReadNotification( MOZ_ASSERT(NS_IsMainThread()); NS_ENSURE_TRUE_VOID(aConnId); + NS_ENSURE_TRUE_VOID(sBluetoothGattInterface); BluetoothService* bs = BluetoothService::Get(); NS_ENSURE_TRUE_VOID(bs); @@ -3564,17 +3725,17 @@ BluetoothGattManager::RequestReadNotification( return; } - nsAutoString addressStr; - AddressToString(aBdAddr, addressStr); + nsAutoString bdAddrStr; + AddressToString(aBdAddr, bdAddrStr); // Distribute a signal to gattServer InfallibleTArray properties; AppendNamedValue(properties, "TransId", aTransId); AppendNamedValue(properties, "AttrHandle", aAttributeHandle); - AppendNamedValue(properties, "Address", addressStr); + AppendNamedValue(properties, "Address", bdAddrStr); AppendNamedValue(properties, "NeedResponse", true); - AppendNamedValue(properties, "Value", new nsTArray()); + AppendNamedValue(properties, "Value", nsTArray()); bs->DistributeSignal(NS_LITERAL_STRING("ReadRequested"), server->mAppUuid, @@ -3596,6 +3757,7 @@ BluetoothGattManager::RequestWriteNotification( MOZ_ASSERT(NS_IsMainThread()); NS_ENSURE_TRUE_VOID(aConnId); + NS_ENSURE_TRUE_VOID(sBluetoothGattInterface); BluetoothService* bs = BluetoothService::Get(); NS_ENSURE_TRUE_VOID(bs); @@ -3620,22 +3782,22 @@ BluetoothGattManager::RequestWriteNotification( return; } - nsAutoString addressStr; - AddressToString(aBdAddr, addressStr); + nsAutoString bdAddrStr; + AddressToString(aBdAddr, bdAddrStr); // Distribute a signal to gattServer InfallibleTArray properties; AppendNamedValue(properties, "TransId", aTransId); AppendNamedValue(properties, "AttrHandle", aAttributeHandle); - AppendNamedValue(properties, "Address", addressStr); + AppendNamedValue(properties, "Address", bdAddrStr); AppendNamedValue(properties, "NeedResponse", aNeedResponse); nsTArray value; value.AppendElements(aValue, aLength); AppendNamedValue(properties, "Value", value); - bs->DistributeSignal(NS_LITERAL_STRING("WrtieRequested"), + bs->DistributeSignal(NS_LITERAL_STRING("WriteRequested"), server->mAppUuid, properties); } @@ -3697,6 +3859,9 @@ BluetoothGattManager::ProceedDiscoverProcess( * 3) Both arrays are already empty: * Discover is done, notify application. */ + MOZ_ASSERT(aClient->mDiscoverRunnable); + ENSURE_GATT_INTF_IN_ATTR_DISCOVER(aClient); + if (!aClient->mCharacteristics.IsEmpty()) { sBluetoothGattInterface->GetDescriptor( aClient->mConnId, diff --git a/dom/bluetooth/bluedroid/BluetoothGattManager.h b/dom/bluetooth/bluedroid/BluetoothGattManager.h index 47d5601c17..daede969df 100644 --- a/dom/bluetooth/bluedroid/BluetoothGattManager.h +++ b/dom/bluetooth/bluedroid/BluetoothGattManager.h @@ -20,6 +20,8 @@ class BluetoothGattManager final : public nsIObserver , public BluetoothGattNotificationHandler { public: + static const int MAX_NUM_CLIENTS; + NS_DECL_ISUPPORTS NS_DECL_NSIOBSERVER @@ -27,48 +29,48 @@ public: static void InitGattInterface(BluetoothProfileResultHandler* aRes); static void DeinitGattInterface(BluetoothProfileResultHandler* aRes); - void StartLeScan(const nsTArray& aServiceUuids, + void StartLeScan(const nsTArray& aServiceUuids, BluetoothReplyRunnable* aRunnable); - void StopLeScan(const nsAString& aScanUuid, + void StopLeScan(const BluetoothUuid& aScanUuid, BluetoothReplyRunnable* aRunnable); - void Connect(const nsAString& aAppUuid, - const nsAString& aDeviceAddr, + void Connect(const BluetoothUuid& aAppUuid, + const BluetoothAddress& aDeviceAddr, BluetoothReplyRunnable* aRunnable); - void Disconnect(const nsAString& aAppUuid, - const nsAString& aDeviceAddr, + void Disconnect(const BluetoothUuid& aAppUuid, + const BluetoothAddress& aDeviceAddr, BluetoothReplyRunnable* aRunnable); - void Discover(const nsAString& aAppUuid, + void Discover(const BluetoothUuid& aAppUuid, BluetoothReplyRunnable* aRunnable); void UnregisterClient(int aClientIf, BluetoothReplyRunnable* aRunnable); void ReadRemoteRssi(int aClientIf, - const nsAString& aDeviceAddr, + const BluetoothAddress& aDeviceAddr, BluetoothReplyRunnable* aRunnable); - void RegisterNotifications(const nsAString& aAppUuid, + void RegisterNotifications(const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServId, const BluetoothGattId& aCharId, BluetoothReplyRunnable* aRunnable); - void DeregisterNotifications(const nsAString& aAppUuid, + void DeregisterNotifications(const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServId, const BluetoothGattId& aCharId, BluetoothReplyRunnable* aRunnable); void ReadCharacteristicValue( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServiceId, const BluetoothGattId& aCharacteristicId, BluetoothReplyRunnable* aRunnable); void WriteCharacteristicValue( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServiceId, const BluetoothGattId& aCharacteristicId, const BluetoothGattWriteType& aWriteType, @@ -76,14 +78,14 @@ public: BluetoothReplyRunnable* aRunnable); void ReadDescriptorValue( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServiceId, const BluetoothGattId& aCharacteristicId, const BluetoothGattId& aDescriptorId, BluetoothReplyRunnable* aRunnable); void WriteDescriptorValue( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServiceId, const BluetoothGattId& aCharacteristicId, const BluetoothGattId& aDescriptorId, @@ -91,32 +93,32 @@ public: BluetoothReplyRunnable* aRunnable); void ConnectPeripheral( - const nsAString& aAppUuid, - const nsAString& aAddress, + const BluetoothUuid& aAppUuid, + const BluetoothAddress& aAddress, BluetoothReplyRunnable* aRunnable); void DisconnectPeripheral( - const nsAString& aAppUuid, - const nsAString& aAddress, + const BluetoothUuid& aAppUuid, + const BluetoothAddress& aAddress, BluetoothReplyRunnable* aRunnable); void UnregisterServer(int aServerIf, BluetoothReplyRunnable* aRunnable); void ServerAddService( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServiceId, uint16_t aHandleCount, BluetoothReplyRunnable* aRunnable); void ServerAddIncludedService( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothAttributeHandle& aServiceHandle, const BluetoothAttributeHandle& aIncludedServiceHandle, BluetoothReplyRunnable* aRunnable); void ServerAddCharacteristic( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothAttributeHandle& aServiceHandle, const BluetoothUuid& aCharacteristicUuid, BluetoothGattAttrPerm aPermissions, @@ -124,7 +126,7 @@ public: BluetoothReplyRunnable* aRunnable); void ServerAddDescriptor( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothAttributeHandle& aServiceHandle, const BluetoothAttributeHandle& aCharacteristicHandle, const BluetoothUuid& aDescriptorUuid, @@ -132,34 +134,44 @@ public: BluetoothReplyRunnable* aRunnable); void ServerRemoveService( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothAttributeHandle& aServiceHandle, BluetoothReplyRunnable* aRunnable); void ServerStartService( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothAttributeHandle& aServiceHandle, BluetoothReplyRunnable* aRunnable); void ServerStopService( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothAttributeHandle& aServiceHandle, BluetoothReplyRunnable* aRunnable); void ServerSendResponse( - const nsAString& aAppUuid, - const nsAString& aAddress, + const BluetoothUuid& aAppUuid, + const BluetoothAddress& aAddress, uint16_t aStatus, int32_t aRequestId, const BluetoothGattResponse& aRsp, BluetoothReplyRunnable* aRunnable); + void ServerSendIndication( + const BluetoothUuid& aAppUuid, + const BluetoothAddress& aAddress, + const BluetoothAttributeHandle& aCharacteristicHandle, + bool aConfirm, + const nsTArray& aValue, + BluetoothReplyRunnable* aRunnable); + private: ~BluetoothGattManager(); - class CleanupResultHandler; - class CleanupResultHandlerRunnable; - class InitGattResultHandler; + class DeinitProfileResultHandlerRunnable; + class InitProfileResultHandlerRunnable; + class RegisterModuleResultHandler; + class UnregisterModuleResultHandler; + class RegisterClientResultHandler; class UnregisterClientResultHandler; class StartLeScanResultHandler; @@ -188,6 +200,7 @@ private: class ServerStartServiceResultHandler; class ServerStopServiceResultHandler; class ServerSendResponseResultHandler; + class ServerSendIndicationResultHandler; BluetoothGattManager(); diff --git a/dom/bluetooth/bluedroid/BluetoothMapSmsManager.cpp b/dom/bluetooth/bluedroid/BluetoothMapSmsManager.cpp index f6eb863cee..4f21f5fb22 100644 --- a/dom/bluetooth/bluedroid/BluetoothMapSmsManager.cpp +++ b/dom/bluetooth/bluedroid/BluetoothMapSmsManager.cpp @@ -324,20 +324,33 @@ BluetoothMapSmsManager::MasDataHandler(UnixSocketBuffer* aMessage) return; } - if (pktHeaders.Has(ObexHeaderId::Type)) { - pktHeaders.GetContentType(type); - BT_LOGR("Type: %s", NS_ConvertUTF16toUTF8(type).get()); - ReplyToPut(); + // Multi-packet PUT request (0x02) may not contain Type header + if (!pktHeaders.Has(ObexHeaderId::Type)) { + BT_LOGR("Missing OBEX PUT request Type header"); + SendReply(ObexResponseCode::BadRequest); + return; + } - if (type.EqualsLiteral("x-bt/MAP-NotificationRegistration")) { - HandleNotificationRegistration(pktHeaders); - } else if (type.EqualsLiteral("x-bt/MAP-event-report")) { - HandleEventReport(pktHeaders); - } else if (type.EqualsLiteral("x-bt/messageStatus")) { - HandleSetMessageStatus(pktHeaders); - } else if (type.EqualsLiteral("x-bt/message")) { - HandleSmsMmsPushMessage(pktHeaders); - } + pktHeaders.GetContentType(type); + BT_LOGR("Type: %s", NS_ConvertUTF16toUTF8(type).get()); + + if (type.EqualsLiteral("x-bt/MAP-NotificationRegistration")) { + HandleNotificationRegistration(pktHeaders); + ReplyToPut(); + } else if (type.EqualsLiteral("x-bt/messageStatus")) { + HandleSetMessageStatus(pktHeaders); + } else if (type.EqualsLiteral("x-bt/message")) { + HandleSmsMmsPushMessage(pktHeaders); + } else if (type.EqualsLiteral("x-bt/MAP-messageUpdate")) { + /* MAP 5.9, There is no concept for Sms/Mms to update inbox. If the + * MSE does NOT allowed the polling of its mailbox it shall answer + * with a 'Not implemented' error response. + */ + SendReply(ObexResponseCode::NotImplemented); + } else { + BT_LOGR("Unknown MAP PUT request type: %s", + NS_ConvertUTF16toUTF8(type).get()); + SendReply(ObexResponseCode::NotImplemented); } break; case ObexRequestCode::Get: @@ -363,6 +376,12 @@ BluetoothMapSmsManager::MasDataHandler(UnixSocketBuffer* aMessage) return; } + if (!pktHeaders.Has(ObexHeaderId::Type)) { + BT_LOGR("Missing OBEX GET request Type header"); + SendReply(ObexResponseCode::BadRequest); + return; + } + pktHeaders.GetContentType(type); if (type.EqualsLiteral("x-obex/folder-listing")) { HandleSmsMmsFolderListing(pktHeaders); @@ -371,8 +390,9 @@ BluetoothMapSmsManager::MasDataHandler(UnixSocketBuffer* aMessage) } else if (type.EqualsLiteral("x-bt/message")) { HandleSmsMmsGetMessage(pktHeaders); } else { - BT_LOGR("Unknown MAP request type: %s", + BT_LOGR("Unknown MAP GET request type: %s", NS_ConvertUTF16toUTF8(type).get()); + SendReply(ObexResponseCode::NotImplemented); } break; } @@ -400,24 +420,22 @@ BluetoothMapSmsManager::ReceiveSocketData(BluetoothSocket* aSocket, bool BluetoothMapSmsManager::CompareHeaderTarget(const ObexHeaderSet& aHeader) { - if (!aHeader.Has(ObexHeaderId::Target)) { + const ObexHeader* header = aHeader.GetHeader(ObexHeaderId::Target); + + if (!header) { BT_LOGR("No ObexHeaderId::Target in header"); return false; } - uint8_t* targetPtr; - int targetLength; - aHeader.GetTarget(&targetPtr, &targetLength); - - if (targetLength != sizeof(BluetoothUuid)) { - BT_LOGR("Length mismatch: %d != 16", targetLength); + if (header->mDataLength != sizeof(BluetoothUuid)) { + BT_LOGR("Length mismatch: %d != 16", header->mDataLength); return false; } for (uint8_t i = 0; i < sizeof(BluetoothUuid); i++) { - if (targetPtr[i] != kMapMasObexTarget.mUuid[i]) { + if (header->mData[i] != kMapMasObexTarget.mUuid[i]) { BT_LOGR("UUID mismatch: received target[%d]=0x%x != 0x%x", - i, targetPtr[i], kMapMasObexTarget.mUuid[i]); + i, header->mData[i], kMapMasObexTarget.mUuid[i]); return false; } } @@ -648,10 +666,9 @@ BluetoothMapSmsManager::ReplyToPut() // Section 3.3.3.2 "PutResponse", IrOBEX 1.2 // [opcode:1][length:2][Headers:var] - uint8_t req[255]; - int index = 3; + uint8_t req[kObexRespHeaderSize]; - SendMasObexData(req, ObexResponseCode::Success, index); + SendMasObexData(req, ObexResponseCode::Success, kObexRespHeaderSize); } bool @@ -1317,12 +1334,6 @@ BluetoothMapSmsManager::HandleNotificationRegistration( } } -void -BluetoothMapSmsManager::HandleEventReport(const ObexHeaderSet& aHeader) -{ - // TODO: Handle event report in Bug 1211769 -} - void BluetoothMapSmsManager::HandleSetMessageStatus(const ObexHeaderSet& aHeader) { @@ -1400,7 +1411,7 @@ BluetoothMapSmsManager::HandleSmsMmsPushMessage(const ObexHeaderSet& aHeader) nsCString subject; bmsg->GetBody(subject); // It's possible that subject is empty, send it anyway - AppendNamedValue(data, "subject", subject); + AppendNamedValue(data, "messageBody", subject); nsTArray> recipients; bmsg->GetRecipients(recipients); @@ -1412,7 +1423,7 @@ BluetoothMapSmsManager::HandleSmsMmsPushMessage(const ObexHeaderSet& aHeader) AppendNamedValue(data, "recipient", recipient); } - bs->DistributeSignal(NS_LITERAL_STRING(MAP_PUSH_MESSAGE_REQ_ID), + bs->DistributeSignal(NS_LITERAL_STRING(MAP_SEND_MESSAGE_REQ_ID), NS_LITERAL_STRING(KEY_ADAPTER), data); } @@ -1442,9 +1453,9 @@ BluetoothMapSmsManager::SendReply(uint8_t aResponseCode) // Section 3.2 "Response Format", IrOBEX 1.2 // [opcode:1][length:2][Headers:var] - uint8_t req[3]; + uint8_t req[kObexRespHeaderSize]; - SendMasObexData(req, aResponseCode, 3); + SendMasObexData(req, aResponseCode, kObexRespHeaderSize); } void diff --git a/dom/bluetooth/bluedroid/BluetoothMapSmsManager.h b/dom/bluetooth/bluedroid/BluetoothMapSmsManager.h index 7649d52131..398e9a4889 100644 --- a/dom/bluetooth/bluedroid/BluetoothMapSmsManager.h +++ b/dom/bluetooth/bluedroid/BluetoothMapSmsManager.h @@ -212,7 +212,6 @@ private: void SendReply(uint8_t aResponse); void HandleNotificationRegistration(const ObexHeaderSet& aHeader); - void HandleEventReport(const ObexHeaderSet& aHeader); void HandleSetMessageStatus(const ObexHeaderSet& aHeader); void HandleSmsMmsFolderListing(const ObexHeaderSet& aHeader); void HandleSmsMmsMsgListing(const ObexHeaderSet& aHeader); diff --git a/dom/bluetooth/bluedroid/BluetoothPbapManager.cpp b/dom/bluetooth/bluedroid/BluetoothPbapManager.cpp index eee4c77180..123a490a53 100644 --- a/dom/bluetooth/bluedroid/BluetoothPbapManager.cpp +++ b/dom/bluetooth/bluedroid/BluetoothPbapManager.cpp @@ -357,24 +357,22 @@ BluetoothPbapManager::ReceiveSocketData(BluetoothSocket* aSocket, bool BluetoothPbapManager::CompareHeaderTarget(const ObexHeaderSet& aHeader) { - if (!aHeader.Has(ObexHeaderId::Target)) { + const ObexHeader* header = aHeader.GetHeader(ObexHeaderId::Target); + + if (!header) { BT_LOGR("No ObexHeaderId::Target in header"); return false; } - uint8_t* targetPtr; - int targetLength; - aHeader.GetTarget(&targetPtr, &targetLength); - - if (targetLength != sizeof(BluetoothUuid)) { - BT_LOGR("Length mismatch: %d != 16", targetLength); + if (header->mDataLength != sizeof(BluetoothUuid)) { + BT_LOGR("Length mismatch: %d != 16", header->mDataLength); return false; } for (uint8_t i = 0; i < sizeof(BluetoothUuid); i++) { - if (targetPtr[i] != kPbapObexTarget.mUuid[i]) { + if (header->mData[i] != kPbapObexTarget.mUuid[i]) { BT_LOGR("UUID mismatch: received target[%d]=0x%x != 0x%x", - i, targetPtr[i], kPbapObexTarget.mUuid[i]); + i, header->mData[i], kPbapObexTarget.mUuid[i]); return false; } } diff --git a/dom/bluetooth/bluedroid/BluetoothServiceBluedroid.cpp b/dom/bluetooth/bluedroid/BluetoothServiceBluedroid.cpp index d08e6ab280..be43a216fd 100644 --- a/dom/bluetooth/bluedroid/BluetoothServiceBluedroid.cpp +++ b/dom/bluetooth/bluedroid/BluetoothServiceBluedroid.cpp @@ -36,20 +36,20 @@ #include "mozilla/StaticPtr.h" #include "mozilla/unused.h" -#define ENSURE_BLUETOOTH_IS_READY(runnable, result) \ +#define ENSURE_BLUETOOTH_IS_ENABLED(runnable, result) \ do { \ - if (!sBtInterface || !IsEnabled()) { \ + if (!IsEnabled()) { \ DispatchReplyError(runnable, \ - NS_LITERAL_STRING("Bluetooth is not ready")); \ + NS_LITERAL_STRING("Bluetooth is not enabled")); \ return result; \ } \ } while(0) -#define ENSURE_BLUETOOTH_IS_READY_VOID(runnable) \ +#define ENSURE_BLUETOOTH_IS_ENABLED_VOID(runnable) \ do { \ - if (!sBtInterface || !IsEnabled()) { \ + if (!IsEnabled()) { \ DispatchReplyError(runnable, \ - NS_LITERAL_STRING("Bluetooth is not ready")); \ + NS_LITERAL_STRING("Bluetooth is not enabled")); \ return; \ } \ } while(0) @@ -68,36 +68,11 @@ using namespace mozilla::ipc; USING_BLUETOOTH_NAMESPACE static BluetoothInterface* sBtInterface; +static BluetoothCoreInterface* sBtCoreInterface; static nsTArray > sControllerArray; -/* - * Static methods - */ - -ControlPlayStatus -BluetoothServiceBluedroid::PlayStatusStringToControlPlayStatus( - const nsAString& aPlayStatus) -{ - ControlPlayStatus playStatus = ControlPlayStatus::PLAYSTATUS_UNKNOWN; - if (aPlayStatus.EqualsLiteral("STOPPED")) { - playStatus = ControlPlayStatus::PLAYSTATUS_STOPPED; - } else if (aPlayStatus.EqualsLiteral("PLAYING")) { - playStatus = ControlPlayStatus::PLAYSTATUS_PLAYING; - } else if (aPlayStatus.EqualsLiteral("PAUSED")) { - playStatus = ControlPlayStatus::PLAYSTATUS_PAUSED; - } else if (aPlayStatus.EqualsLiteral("FWD_SEEK")) { - playStatus = ControlPlayStatus::PLAYSTATUS_FWD_SEEK; - } else if (aPlayStatus.EqualsLiteral("REV_SEEK")) { - playStatus = ControlPlayStatus::PLAYSTATUS_REV_SEEK; - } else if (aPlayStatus.EqualsLiteral("ERROR")) { - playStatus = ControlPlayStatus::PLAYSTATUS_ERROR; - } - - return playStatus; -} - class BluetoothServiceBluedroid::EnableResultHandler final - : public BluetoothResultHandler + : public BluetoothCoreResultHandler { public: void OnError(BluetoothStatus aStatus) override @@ -141,7 +116,16 @@ public: private: void Proceed() const { - sBtInterface->Enable(new EnableResultHandler()); + BluetoothService* bs = BluetoothService::Get(); + NS_ENSURE_TRUE_VOID(bs); + + sBtCoreInterface = sBtInterface->GetBluetoothCoreInterface(); + NS_ENSURE_TRUE_VOID(sBtCoreInterface); + + sBtCoreInterface->SetNotificationHandler( + reinterpret_cast(bs)); + + sBtCoreInterface->Enable(new EnableResultHandler()); } unsigned char mNumProfiles; @@ -208,7 +192,7 @@ BluetoothServiceBluedroid::StartGonkBluetooth() } class BluetoothServiceBluedroid::DisableResultHandler final - : public BluetoothResultHandler + : public BluetoothCoreResultHandler { public: void OnError(BluetoothStatus aStatus) override @@ -238,7 +222,7 @@ BluetoothServiceBluedroid::StopGonkBluetooth() return NS_OK; } - sBtInterface->Disable(new DisableResultHandler()); + sBtCoreInterface->Disable(new DisableResultHandler()); return NS_OK; } @@ -352,11 +336,11 @@ BluetoothServiceBluedroid::StopInternal(BluetoothReplyRunnable* aRunnable) void BluetoothServiceBluedroid::StartLeScanInternal( - const nsTArray& aServiceUuids, + const nsTArray& aServiceUuids, BluetoothReplyRunnable* aRunnable) { MOZ_ASSERT(NS_IsMainThread()); - ENSURE_BLUETOOTH_IS_READY_VOID(aRunnable); + ENSURE_BLUETOOTH_IS_ENABLED_VOID(aRunnable); BluetoothGattManager* gatt = BluetoothGattManager::Get(); ENSURE_GATT_MGR_IS_READY_VOID(gatt, aRunnable); @@ -366,11 +350,11 @@ BluetoothServiceBluedroid::StartLeScanInternal( void BluetoothServiceBluedroid::StopLeScanInternal( - const nsAString& aScanUuid, + const BluetoothUuid& aScanUuid, BluetoothReplyRunnable* aRunnable) { MOZ_ASSERT(NS_IsMainThread()); - ENSURE_BLUETOOTH_IS_READY_VOID(aRunnable); + ENSURE_BLUETOOTH_IS_ENABLED_VOID(aRunnable); BluetoothGattManager* gatt = BluetoothGattManager::Get(); ENSURE_GATT_MGR_IS_READY_VOID(gatt, aRunnable); @@ -380,12 +364,12 @@ BluetoothServiceBluedroid::StopLeScanInternal( void BluetoothServiceBluedroid::ConnectGattClientInternal( - const nsAString& aAppUuid, const nsAString& aDeviceAddress, + const BluetoothUuid& aAppUuid, const BluetoothAddress& aDeviceAddress, BluetoothReplyRunnable* aRunnable) { MOZ_ASSERT(NS_IsMainThread()); - ENSURE_BLUETOOTH_IS_READY_VOID(aRunnable); + ENSURE_BLUETOOTH_IS_ENABLED_VOID(aRunnable); BluetoothGattManager* gatt = BluetoothGattManager::Get(); ENSURE_GATT_MGR_IS_READY_VOID(gatt, aRunnable); @@ -395,12 +379,12 @@ BluetoothServiceBluedroid::ConnectGattClientInternal( void BluetoothServiceBluedroid::DisconnectGattClientInternal( - const nsAString& aAppUuid, const nsAString& aDeviceAddress, + const BluetoothUuid& aAppUuid, const BluetoothAddress& aDeviceAddress, BluetoothReplyRunnable* aRunnable) { MOZ_ASSERT(NS_IsMainThread()); - ENSURE_BLUETOOTH_IS_READY_VOID(aRunnable); + ENSURE_BLUETOOTH_IS_ENABLED_VOID(aRunnable); BluetoothGattManager* gatt = BluetoothGattManager::Get(); ENSURE_GATT_MGR_IS_READY_VOID(gatt, aRunnable); @@ -410,11 +394,11 @@ BluetoothServiceBluedroid::DisconnectGattClientInternal( void BluetoothServiceBluedroid::DiscoverGattServicesInternal( - const nsAString& aAppUuid, BluetoothReplyRunnable* aRunnable) + const BluetoothUuid& aAppUuid, BluetoothReplyRunnable* aRunnable) { MOZ_ASSERT(NS_IsMainThread()); - ENSURE_BLUETOOTH_IS_READY_VOID(aRunnable); + ENSURE_BLUETOOTH_IS_ENABLED_VOID(aRunnable); BluetoothGattManager* gatt = BluetoothGattManager::Get(); ENSURE_GATT_MGR_IS_READY_VOID(gatt, aRunnable); @@ -424,12 +408,12 @@ BluetoothServiceBluedroid::DiscoverGattServicesInternal( void BluetoothServiceBluedroid::GattClientStartNotificationsInternal( - const nsAString& aAppUuid, const BluetoothGattServiceId& aServId, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServId, const BluetoothGattId& aCharId, BluetoothReplyRunnable* aRunnable) { MOZ_ASSERT(NS_IsMainThread()); - ENSURE_BLUETOOTH_IS_READY_VOID(aRunnable); + ENSURE_BLUETOOTH_IS_ENABLED_VOID(aRunnable); BluetoothGattManager* gatt = BluetoothGattManager::Get(); ENSURE_GATT_MGR_IS_READY_VOID(gatt, aRunnable); @@ -439,12 +423,12 @@ BluetoothServiceBluedroid::GattClientStartNotificationsInternal( void BluetoothServiceBluedroid::GattClientStopNotificationsInternal( - const nsAString& aAppUuid, const BluetoothGattServiceId& aServId, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServId, const BluetoothGattId& aCharId, BluetoothReplyRunnable* aRunnable) { MOZ_ASSERT(NS_IsMainThread()); - ENSURE_BLUETOOTH_IS_READY_VOID(aRunnable); + ENSURE_BLUETOOTH_IS_ENABLED_VOID(aRunnable); BluetoothGattManager* gatt = BluetoothGattManager::Get(); ENSURE_GATT_MGR_IS_READY_VOID(gatt, aRunnable); @@ -458,7 +442,7 @@ BluetoothServiceBluedroid::UnregisterGattClientInternal( { MOZ_ASSERT(NS_IsMainThread()); - ENSURE_BLUETOOTH_IS_READY_VOID(aRunnable); + ENSURE_BLUETOOTH_IS_ENABLED_VOID(aRunnable); BluetoothGattManager* gatt = BluetoothGattManager::Get(); ENSURE_GATT_MGR_IS_READY_VOID(gatt, aRunnable); @@ -468,12 +452,12 @@ BluetoothServiceBluedroid::UnregisterGattClientInternal( void BluetoothServiceBluedroid::GattClientReadRemoteRssiInternal( - int aClientIf, const nsAString& aDeviceAddress, + int aClientIf, const BluetoothAddress& aDeviceAddress, BluetoothReplyRunnable* aRunnable) { MOZ_ASSERT(NS_IsMainThread()); - ENSURE_BLUETOOTH_IS_READY_VOID(aRunnable); + ENSURE_BLUETOOTH_IS_ENABLED_VOID(aRunnable); BluetoothGattManager* gatt = BluetoothGattManager::Get(); ENSURE_GATT_MGR_IS_READY_VOID(gatt, aRunnable); @@ -483,14 +467,14 @@ BluetoothServiceBluedroid::GattClientReadRemoteRssiInternal( void BluetoothServiceBluedroid::GattClientReadCharacteristicValueInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServiceId, const BluetoothGattId& aCharacteristicId, BluetoothReplyRunnable* aRunnable) { MOZ_ASSERT(NS_IsMainThread()); - ENSURE_BLUETOOTH_IS_READY_VOID(aRunnable); + ENSURE_BLUETOOTH_IS_ENABLED_VOID(aRunnable); BluetoothGattManager* gatt = BluetoothGattManager::Get(); ENSURE_GATT_MGR_IS_READY_VOID(gatt, aRunnable); @@ -501,7 +485,7 @@ BluetoothServiceBluedroid::GattClientReadCharacteristicValueInternal( void BluetoothServiceBluedroid::GattClientWriteCharacteristicValueInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServiceId, const BluetoothGattId& aCharacteristicId, const BluetoothGattWriteType& aWriteType, @@ -510,7 +494,7 @@ BluetoothServiceBluedroid::GattClientWriteCharacteristicValueInternal( { MOZ_ASSERT(NS_IsMainThread()); - ENSURE_BLUETOOTH_IS_READY_VOID(aRunnable); + ENSURE_BLUETOOTH_IS_ENABLED_VOID(aRunnable); BluetoothGattManager* gatt = BluetoothGattManager::Get(); ENSURE_GATT_MGR_IS_READY_VOID(gatt, aRunnable); @@ -521,7 +505,7 @@ BluetoothServiceBluedroid::GattClientWriteCharacteristicValueInternal( void BluetoothServiceBluedroid::GattClientReadDescriptorValueInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServiceId, const BluetoothGattId& aCharacteristicId, const BluetoothGattId& aDescriptorId, @@ -529,7 +513,7 @@ BluetoothServiceBluedroid::GattClientReadDescriptorValueInternal( { MOZ_ASSERT(NS_IsMainThread()); - ENSURE_BLUETOOTH_IS_READY_VOID(aRunnable); + ENSURE_BLUETOOTH_IS_ENABLED_VOID(aRunnable); BluetoothGattManager* gatt = BluetoothGattManager::Get(); ENSURE_GATT_MGR_IS_READY_VOID(gatt, aRunnable); @@ -540,7 +524,7 @@ BluetoothServiceBluedroid::GattClientReadDescriptorValueInternal( void BluetoothServiceBluedroid::GattClientWriteDescriptorValueInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServiceId, const BluetoothGattId& aCharacteristicId, const BluetoothGattId& aDescriptorId, @@ -549,7 +533,7 @@ BluetoothServiceBluedroid::GattClientWriteDescriptorValueInternal( { MOZ_ASSERT(NS_IsMainThread()); - ENSURE_BLUETOOTH_IS_READY_VOID(aRunnable); + ENSURE_BLUETOOTH_IS_ENABLED_VOID(aRunnable); BluetoothGattManager* gatt = BluetoothGattManager::Get(); ENSURE_GATT_MGR_IS_READY_VOID(gatt, aRunnable); @@ -561,12 +545,12 @@ BluetoothServiceBluedroid::GattClientWriteDescriptorValueInternal( // GATT Server void BluetoothServiceBluedroid::GattServerConnectPeripheralInternal( - const nsAString& aAppUuid, const nsAString& aAddress, + const BluetoothUuid& aAppUuid, const BluetoothAddress& aAddress, BluetoothReplyRunnable* aRunnable) { MOZ_ASSERT(NS_IsMainThread()); - ENSURE_BLUETOOTH_IS_READY_VOID(aRunnable); + ENSURE_BLUETOOTH_IS_ENABLED_VOID(aRunnable); BluetoothGattManager* gatt = BluetoothGattManager::Get(); ENSURE_GATT_MGR_IS_READY_VOID(gatt, aRunnable); @@ -576,12 +560,12 @@ BluetoothServiceBluedroid::GattServerConnectPeripheralInternal( void BluetoothServiceBluedroid::GattServerDisconnectPeripheralInternal( - const nsAString& aAppUuid, const nsAString& aAddress, + const BluetoothUuid& aAppUuid, const BluetoothAddress& aAddress, BluetoothReplyRunnable* aRunnable) { MOZ_ASSERT(NS_IsMainThread()); - ENSURE_BLUETOOTH_IS_READY_VOID(aRunnable); + ENSURE_BLUETOOTH_IS_ENABLED_VOID(aRunnable); BluetoothGattManager* gatt = BluetoothGattManager::Get(); ENSURE_GATT_MGR_IS_READY_VOID(gatt, aRunnable); @@ -595,7 +579,7 @@ BluetoothServiceBluedroid::UnregisterGattServerInternal( { MOZ_ASSERT(NS_IsMainThread()); - ENSURE_BLUETOOTH_IS_READY_VOID(aRunnable); + ENSURE_BLUETOOTH_IS_ENABLED_VOID(aRunnable); BluetoothGattManager* gatt = BluetoothGattManager::Get(); ENSURE_GATT_MGR_IS_READY_VOID(gatt, aRunnable); @@ -605,14 +589,14 @@ BluetoothServiceBluedroid::UnregisterGattServerInternal( void BluetoothServiceBluedroid::GattServerAddServiceInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServiceId, uint16_t aHandleCount, BluetoothReplyRunnable* aRunnable) { MOZ_ASSERT(NS_IsMainThread()); - ENSURE_BLUETOOTH_IS_READY_VOID(aRunnable); + ENSURE_BLUETOOTH_IS_ENABLED_VOID(aRunnable); BluetoothGattManager* gatt = BluetoothGattManager::Get(); ENSURE_GATT_MGR_IS_READY_VOID(gatt, aRunnable); @@ -622,14 +606,14 @@ BluetoothServiceBluedroid::GattServerAddServiceInternal( void BluetoothServiceBluedroid::GattServerAddIncludedServiceInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothAttributeHandle& aServiceHandle, const BluetoothAttributeHandle& aIncludedServiceHandle, BluetoothReplyRunnable* aRunnable) { MOZ_ASSERT(NS_IsMainThread()); - ENSURE_BLUETOOTH_IS_READY_VOID(aRunnable); + ENSURE_BLUETOOTH_IS_ENABLED_VOID(aRunnable); BluetoothGattManager* gatt = BluetoothGattManager::Get(); ENSURE_GATT_MGR_IS_READY_VOID(gatt, aRunnable); @@ -642,7 +626,7 @@ BluetoothServiceBluedroid::GattServerAddIncludedServiceInternal( void BluetoothServiceBluedroid::GattServerAddCharacteristicInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothAttributeHandle& aServiceHandle, const BluetoothUuid& aCharacteristicUuid, BluetoothGattAttrPerm aPermissions, @@ -651,7 +635,7 @@ BluetoothServiceBluedroid::GattServerAddCharacteristicInternal( { MOZ_ASSERT(NS_IsMainThread()); - ENSURE_BLUETOOTH_IS_READY_VOID(aRunnable); + ENSURE_BLUETOOTH_IS_ENABLED_VOID(aRunnable); BluetoothGattManager* gatt = BluetoothGattManager::Get(); ENSURE_GATT_MGR_IS_READY_VOID(gatt, aRunnable); @@ -666,7 +650,7 @@ BluetoothServiceBluedroid::GattServerAddCharacteristicInternal( void BluetoothServiceBluedroid::GattServerAddDescriptorInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothAttributeHandle& aServiceHandle, const BluetoothAttributeHandle& aCharacteristicHandle, const BluetoothUuid& aDescriptorUuid, @@ -675,7 +659,7 @@ BluetoothServiceBluedroid::GattServerAddDescriptorInternal( { MOZ_ASSERT(NS_IsMainThread()); - ENSURE_BLUETOOTH_IS_READY_VOID(aRunnable); + ENSURE_BLUETOOTH_IS_ENABLED_VOID(aRunnable); BluetoothGattManager* gatt = BluetoothGattManager::Get(); ENSURE_GATT_MGR_IS_READY_VOID(gatt, aRunnable); @@ -690,13 +674,13 @@ BluetoothServiceBluedroid::GattServerAddDescriptorInternal( void BluetoothServiceBluedroid::GattServerRemoveServiceInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothAttributeHandle& aServiceHandle, BluetoothReplyRunnable* aRunnable) { MOZ_ASSERT(NS_IsMainThread()); - ENSURE_BLUETOOTH_IS_READY_VOID(aRunnable); + ENSURE_BLUETOOTH_IS_ENABLED_VOID(aRunnable); BluetoothGattManager* gatt = BluetoothGattManager::Get(); ENSURE_GATT_MGR_IS_READY_VOID(gatt, aRunnable); @@ -706,13 +690,13 @@ BluetoothServiceBluedroid::GattServerRemoveServiceInternal( void BluetoothServiceBluedroid::GattServerStartServiceInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothAttributeHandle& aServiceHandle, BluetoothReplyRunnable* aRunnable) { MOZ_ASSERT(NS_IsMainThread()); - ENSURE_BLUETOOTH_IS_READY_VOID(aRunnable); + ENSURE_BLUETOOTH_IS_ENABLED_VOID(aRunnable); BluetoothGattManager* gatt = BluetoothGattManager::Get(); ENSURE_GATT_MGR_IS_READY_VOID(gatt, aRunnable); @@ -722,13 +706,13 @@ BluetoothServiceBluedroid::GattServerStartServiceInternal( void BluetoothServiceBluedroid::GattServerStopServiceInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothAttributeHandle& aServiceHandle, BluetoothReplyRunnable* aRunnable) { MOZ_ASSERT(NS_IsMainThread()); - ENSURE_BLUETOOTH_IS_READY_VOID(aRunnable); + ENSURE_BLUETOOTH_IS_ENABLED_VOID(aRunnable); BluetoothGattManager* gatt = BluetoothGattManager::Get(); ENSURE_GATT_MGR_IS_READY_VOID(gatt, aRunnable); @@ -738,8 +722,8 @@ BluetoothServiceBluedroid::GattServerStopServiceInternal( void BluetoothServiceBluedroid::GattServerSendResponseInternal( - const nsAString& aAppUuid, - const nsAString& aAddress, + const BluetoothUuid& aAppUuid, + const BluetoothAddress& aAddress, uint16_t aStatus, int32_t aRequestId, const BluetoothGattResponse& aRsp, @@ -747,7 +731,7 @@ BluetoothServiceBluedroid::GattServerSendResponseInternal( { MOZ_ASSERT(NS_IsMainThread()); - ENSURE_BLUETOOTH_IS_READY_VOID(aRunnable); + ENSURE_BLUETOOTH_IS_ENABLED_VOID(aRunnable); BluetoothGattManager* gatt = BluetoothGattManager::Get(); ENSURE_GATT_MGR_IS_READY_VOID(gatt, aRunnable); @@ -756,6 +740,30 @@ BluetoothServiceBluedroid::GattServerSendResponseInternal( aAppUuid, aAddress, aStatus, aRequestId, aRsp, aRunnable); } +void +BluetoothServiceBluedroid::GattServerSendIndicationInternal( + const BluetoothUuid& aAppUuid, + const BluetoothAddress& aAddress, + const BluetoothAttributeHandle& aCharacteristicHandle, + bool aConfirm, + const nsTArray& aValue, + BluetoothReplyRunnable* aRunnable) +{ + MOZ_ASSERT(NS_IsMainThread()); + + ENSURE_BLUETOOTH_IS_ENABLED_VOID(aRunnable); + + BluetoothGattManager* gatt = BluetoothGattManager::Get(); + ENSURE_GATT_MGR_IS_READY_VOID(gatt, aRunnable); + + gatt->ServerSendIndication(aAppUuid, + aAddress, + aCharacteristicHandle, + aConfirm, + aValue, + aRunnable); +} + nsresult BluetoothServiceBluedroid::GetAdaptersInternal( BluetoothReplyRunnable* aRunnable) @@ -818,9 +826,8 @@ public: RefPtr mRunnable; }; -class BluetoothServiceBluedroid::GetRemoteDevicePropertiesResultHandler - final - : public BluetoothResultHandler +class BluetoothServiceBluedroid::GetRemoteDevicePropertiesResultHandler final + : public BluetoothCoreResultHandler { public: GetRemoteDevicePropertiesResultHandler( @@ -862,7 +869,7 @@ BluetoothServiceBluedroid::GetConnectedDevicePropertiesInternal( { MOZ_ASSERT(NS_IsMainThread()); - ENSURE_BLUETOOTH_IS_READY(aRunnable, NS_OK); + ENSURE_BLUETOOTH_IS_ENABLED(aRunnable, NS_OK); BluetoothProfileManagerBase* profile = BluetoothUuidHelper::GetBluetoothProfileManager(aServiceUuid); @@ -885,7 +892,7 @@ BluetoothServiceBluedroid::GetConnectedDevicePropertiesInternal( GetDeviceRequest request(1, aRunnable); mGetDeviceRequests.AppendElement(request); - sBtInterface->GetRemoteDeviceProperties(address, + sBtCoreInterface->GetRemoteDeviceProperties(address, new GetRemoteDevicePropertiesResultHandler(mGetDeviceRequests, address)); return NS_OK; @@ -893,11 +900,12 @@ BluetoothServiceBluedroid::GetConnectedDevicePropertiesInternal( nsresult BluetoothServiceBluedroid::GetPairedDevicePropertiesInternal( - const nsTArray& aDeviceAddress, BluetoothReplyRunnable* aRunnable) + const nsTArray& aDeviceAddress, + BluetoothReplyRunnable* aRunnable) { MOZ_ASSERT(NS_IsMainThread()); - ENSURE_BLUETOOTH_IS_READY(aRunnable, NS_OK); + ENSURE_BLUETOOTH_IS_ENABLED(aRunnable, NS_OK); if (aDeviceAddress.IsEmpty()) { DispatchReplySuccess(aRunnable); @@ -909,24 +917,17 @@ BluetoothServiceBluedroid::GetPairedDevicePropertiesInternal( mGetDeviceRequests.AppendElement(request); for (uint8_t i = 0; i < aDeviceAddress.Length(); i++) { - - BluetoothAddress address; - nsresult rv = StringToAddress(aDeviceAddress[i], address); - if (NS_FAILED(rv)) { - DispatchReplyError(aRunnable, STATUS_PARM_INVALID); - return rv; - } - // Retrieve all properties of devices - sBtInterface->GetRemoteDeviceProperties(address, - new GetRemoteDevicePropertiesResultHandler(mGetDeviceRequests, address)); + sBtCoreInterface->GetRemoteDeviceProperties(aDeviceAddress[i], + new GetRemoteDevicePropertiesResultHandler(mGetDeviceRequests, + aDeviceAddress[i])); } return NS_OK; } class BluetoothServiceBluedroid::DispatchReplyErrorResultHandler final - : public BluetoothResultHandler + : public BluetoothCoreResultHandler { public: DispatchReplyErrorResultHandler( @@ -956,20 +957,20 @@ BluetoothServiceBluedroid::StartDiscoveryInternal( BluetoothReplyRunnable* aRunnable) { MOZ_ASSERT(NS_IsMainThread()); - ENSURE_BLUETOOTH_IS_READY_VOID(aRunnable); + ENSURE_BLUETOOTH_IS_ENABLED_VOID(aRunnable); mChangeDiscoveryRunnables.AppendElement(aRunnable); - sBtInterface->StartDiscovery( + sBtCoreInterface->StartDiscovery( new DispatchReplyErrorResultHandler(mChangeDiscoveryRunnables, aRunnable)); } nsresult BluetoothServiceBluedroid::FetchUuidsInternal( - const nsAString& aDeviceAddress, BluetoothReplyRunnable* aRunnable) + const BluetoothAddress& aDeviceAddress, BluetoothReplyRunnable* aRunnable) { MOZ_ASSERT(NS_IsMainThread()); - ENSURE_BLUETOOTH_IS_READY(aRunnable, NS_OK); + ENSURE_BLUETOOTH_IS_ENABLED(aRunnable, NS_OK); /* * get_remote_services request will not be performed by bluedroid @@ -979,15 +980,8 @@ BluetoothServiceBluedroid::FetchUuidsInternal( StopDiscoveryInternal(aRunnable); } - BluetoothAddress address; - nsresult rv = StringToAddress(aDeviceAddress, address); - if (NS_FAILED(rv)) { - DispatchReplyError(aRunnable, STATUS_PARM_INVALID); - return rv; - } - mFetchUuidsRunnables.AppendElement(aRunnable); - sBtInterface->GetRemoteServices(address, + sBtCoreInterface->GetRemoteServices(aDeviceAddress, new DispatchReplyErrorResultHandler(mFetchUuidsRunnables, aRunnable)); return NS_OK; @@ -999,10 +993,10 @@ BluetoothServiceBluedroid::StopDiscoveryInternal( { MOZ_ASSERT(NS_IsMainThread()); - ENSURE_BLUETOOTH_IS_READY_VOID(aRunnable); + ENSURE_BLUETOOTH_IS_ENABLED_VOID(aRunnable); mChangeDiscoveryRunnables.AppendElement(aRunnable); - sBtInterface->CancelDiscovery( + sBtCoreInterface->CancelDiscovery( new DispatchReplyErrorResultHandler(mChangeDiscoveryRunnables, aRunnable)); } @@ -1013,10 +1007,18 @@ BluetoothServiceBluedroid::SetProperty(BluetoothObjectType aType, { MOZ_ASSERT(NS_IsMainThread()); - ENSURE_BLUETOOTH_IS_READY(aRunnable, NS_OK); + ENSURE_BLUETOOTH_IS_ENABLED(aRunnable, NS_OK); + + BluetoothProperty property; + nsresult rv = NamedValueToProperty(aValue, property); + if (NS_FAILED(rv)) { + DispatchReplyError(aRunnable, STATUS_PARM_INVALID); + return rv; + } mSetAdapterPropertyRunnables.AppendElement(aRunnable); - sBtInterface->SetAdapterProperty(aValue, + sBtCoreInterface->SetAdapterProperty( + property, new DispatchReplyErrorResultHandler(mSetAdapterPropertyRunnables, aRunnable)); @@ -1041,7 +1043,7 @@ struct BluetoothServiceBluedroid::GetRemoteServiceRecordRequest final }; class BluetoothServiceBluedroid::GetRemoteServiceRecordResultHandler final - : public BluetoothResultHandler + : public BluetoothCoreResultHandler { public: GetRemoteServiceRecordResultHandler( @@ -1074,7 +1076,7 @@ public: void CancelDiscovery() override { // Disabled discovery mode, now perform SDP operation. - sBtInterface->GetRemoteServiceRecord(mDeviceAddress, mUuid, this); + sBtCoreInterface->GetRemoteServiceRecord(mDeviceAddress, mUuid, this); } private: @@ -1104,7 +1106,7 @@ BluetoothServiceBluedroid::GetServiceChannel( mGetRemoteServiceRecordArray.AppendElement( GetRemoteServiceRecordRequest(aDeviceAddress, aServiceUuid, aManager)); - RefPtr res = + RefPtr res = new GetRemoteServiceRecordResultHandler(mGetRemoteServiceRecordArray, aDeviceAddress, aServiceUuid); @@ -1112,9 +1114,9 @@ BluetoothServiceBluedroid::GetServiceChannel( * won't be performed while the adapter is in discovery mode. */ if (mDiscovering) { - sBtInterface->CancelDiscovery(res); + sBtCoreInterface->CancelDiscovery(res); } else { - sBtInterface->GetRemoteServiceRecord(aDeviceAddress, aServiceUuid, res); + sBtCoreInterface->GetRemoteServiceRecord(aDeviceAddress, aServiceUuid, res); } return NS_OK; @@ -1135,7 +1137,7 @@ struct BluetoothServiceBluedroid::GetRemoteServicesRequest final }; class BluetoothServiceBluedroid::GetRemoteServicesResultHandler final - : public BluetoothResultHandler + : public BluetoothCoreResultHandler { public: GetRemoteServicesResultHandler( @@ -1168,7 +1170,7 @@ public: void CancelDiscovery() override { // Disabled discovery mode, now perform SDP operation. - sBtInterface->GetRemoteServices(mDeviceAddress, this); + sBtCoreInterface->GetRemoteServices(mDeviceAddress, this); } private: @@ -1197,7 +1199,7 @@ BluetoothServiceBluedroid::UpdateSdpRecords( mGetRemoteServicesArray.AppendElement( GetRemoteServicesRequest(aDeviceAddress, aManager)); - RefPtr res = + RefPtr res = new GetRemoteServicesResultHandler(mGetRemoteServicesArray, aDeviceAddress, aManager); @@ -1205,9 +1207,9 @@ BluetoothServiceBluedroid::UpdateSdpRecords( * won't be performed while the adapter is in discovery mode. */ if (mDiscovering) { - sBtInterface->CancelDiscovery(res); + sBtCoreInterface->CancelDiscovery(res); } else { - sBtInterface->GetRemoteServices(aDeviceAddress, res); + sBtCoreInterface->GetRemoteServices(aDeviceAddress, res); } return true; @@ -1215,22 +1217,15 @@ BluetoothServiceBluedroid::UpdateSdpRecords( nsresult BluetoothServiceBluedroid::CreatePairedDeviceInternal( - const nsAString& aDeviceAddress, int aTimeout, + const BluetoothAddress& aDeviceAddress, int aTimeout, BluetoothReplyRunnable* aRunnable) { MOZ_ASSERT(NS_IsMainThread()); - ENSURE_BLUETOOTH_IS_READY(aRunnable, NS_OK); - - BluetoothAddress address; - nsresult rv = StringToAddress(aDeviceAddress, address); - if (NS_FAILED(rv)) { - DispatchReplyError(aRunnable, STATUS_PARM_INVALID); - return rv; - } + ENSURE_BLUETOOTH_IS_ENABLED(aRunnable, NS_OK); mCreateBondRunnables.AppendElement(aRunnable); - sBtInterface->CreateBond(address, TRANSPORT_AUTO, + sBtCoreInterface->CreateBond(aDeviceAddress, TRANSPORT_AUTO, new DispatchReplyErrorResultHandler(mCreateBondRunnables, aRunnable)); return NS_OK; @@ -1238,28 +1233,21 @@ BluetoothServiceBluedroid::CreatePairedDeviceInternal( nsresult BluetoothServiceBluedroid::RemoveDeviceInternal( - const nsAString& aDeviceAddress, BluetoothReplyRunnable* aRunnable) + const BluetoothAddress& aDeviceAddress, BluetoothReplyRunnable* aRunnable) { MOZ_ASSERT(NS_IsMainThread()); - ENSURE_BLUETOOTH_IS_READY(aRunnable, NS_OK); - - BluetoothAddress address; - nsresult rv = StringToAddress(aDeviceAddress, address); - if (NS_FAILED(rv)) { - DispatchReplyError(aRunnable, STATUS_PARM_INVALID); - return rv; - } + ENSURE_BLUETOOTH_IS_ENABLED(aRunnable, NS_OK); mRemoveBondRunnables.AppendElement(aRunnable); - sBtInterface->RemoveBond(address, + sBtCoreInterface->RemoveBond(aDeviceAddress, new DispatchReplyErrorResultHandler(mRemoveBondRunnables, aRunnable)); return NS_OK; } class BluetoothServiceBluedroid::PinReplyResultHandler final - : public BluetoothResultHandler + : public BluetoothCoreResultHandler { public: PinReplyResultHandler(BluetoothReplyRunnable* aRunnable) @@ -1280,36 +1268,50 @@ private: BluetoothReplyRunnable* mRunnable; }; +class BluetoothServiceBluedroid::CancelBondResultHandler final + : public BluetoothCoreResultHandler +{ +public: + CancelBondResultHandler(BluetoothReplyRunnable* aRunnable) + : mRunnable(aRunnable) + { } + + void CancelBond() override + { + DispatchReplySuccess(mRunnable); + } + + void OnError(BluetoothStatus aStatus) override + { + DispatchReplyError(mRunnable, aStatus); + } + +private: + BluetoothReplyRunnable* mRunnable; +}; + void BluetoothServiceBluedroid::PinReplyInternal( - const nsAString& aDeviceAddress, bool aAccept, - const nsAString& aPinCode, BluetoothReplyRunnable* aRunnable) + const BluetoothAddress& aDeviceAddress, bool aAccept, + const BluetoothPinCode& aPinCode, BluetoothReplyRunnable* aRunnable) { MOZ_ASSERT(NS_IsMainThread()); - ENSURE_BLUETOOTH_IS_READY_VOID(aRunnable); + ENSURE_BLUETOOTH_IS_ENABLED_VOID(aRunnable); - BluetoothAddress address; - nsresult rv = StringToAddress(aDeviceAddress, address); - if (NS_FAILED(rv)) { - DispatchReplyError(aRunnable, STATUS_PARM_INVALID); - return; + if (aAccept) { + sBtCoreInterface->PinReply(aDeviceAddress, aAccept, aPinCode, + new PinReplyResultHandler(aRunnable)); + } else { + // Call CancelBond to trigger BondStateChangedNotification + sBtCoreInterface->CancelBond(aDeviceAddress, + new CancelBondResultHandler(aRunnable)); } - - BluetoothPinCode pinCode; - rv = StringToPinCode(aPinCode, pinCode); - if (NS_FAILED(rv)) { - DispatchReplyError(aRunnable, STATUS_PARM_INVALID); - return; - } - - sBtInterface->PinReply(address, aAccept, pinCode, - new PinReplyResultHandler(aRunnable)); } void BluetoothServiceBluedroid::SetPinCodeInternal( - const nsAString& aDeviceAddress, const nsAString& aPinCode, + const BluetoothAddress& aDeviceAddress, const BluetoothPinCode& aPinCode, BluetoothReplyRunnable* aRunnable) { // Legacy method used by BlueZ only. @@ -1317,14 +1319,14 @@ BluetoothServiceBluedroid::SetPinCodeInternal( void BluetoothServiceBluedroid::SetPasskeyInternal( - const nsAString& aDeviceAddress, uint32_t aPasskey, + const BluetoothAddress& aDeviceAddress, uint32_t aPasskey, BluetoothReplyRunnable* aRunnable) { // Legacy method used by BlueZ only. } class BluetoothServiceBluedroid::SspReplyResultHandler final - : public BluetoothResultHandler + : public BluetoothCoreResultHandler { public: SspReplyResultHandler(BluetoothReplyRunnable* aRunnable) @@ -1347,27 +1349,21 @@ private: void BluetoothServiceBluedroid::SspReplyInternal( - const nsAString& aDeviceAddress, BluetoothSspVariant aVariant, + const BluetoothAddress& aDeviceAddress, BluetoothSspVariant aVariant, bool aAccept, BluetoothReplyRunnable* aRunnable) { MOZ_ASSERT(NS_IsMainThread()); - ENSURE_BLUETOOTH_IS_READY_VOID(aRunnable); + ENSURE_BLUETOOTH_IS_ENABLED_VOID(aRunnable); - BluetoothAddress address; - nsresult rv = StringToAddress(aDeviceAddress, address); - if (NS_FAILED(rv)) { - DispatchReplyError(aRunnable, STATUS_PARM_INVALID); - return; - } - - sBtInterface->SspReply(address, aVariant, aAccept, 0 /* passkey */, - new SspReplyResultHandler(aRunnable)); + sBtCoreInterface->SspReply(aDeviceAddress, aVariant, aAccept, + 0 /* passkey */, + new SspReplyResultHandler(aRunnable)); } void BluetoothServiceBluedroid::SetPairingConfirmationInternal( - const nsAString& aDeviceAddress, bool aConfirm, + const BluetoothAddress& aDeviceAddress, bool aConfirm, BluetoothReplyRunnable* aRunnable) { // Legacy method used by BlueZ only. @@ -1390,22 +1386,15 @@ BluetoothServiceBluedroid::NextBluetoothProfileController() void BluetoothServiceBluedroid::ConnectDisconnect( - bool aConnect, const nsAString& aDeviceAddress, + bool aConnect, const BluetoothAddress& aDeviceAddress, BluetoothReplyRunnable* aRunnable, uint16_t aServiceUuid, uint32_t aCod) { MOZ_ASSERT(NS_IsMainThread()); MOZ_ASSERT(aRunnable); - BluetoothAddress address; - nsresult rv = StringToAddress(aDeviceAddress, address); - if (NS_FAILED(rv)) { - DispatchReplyError(aRunnable, STATUS_PARM_INVALID); - return; - } - BluetoothProfileController* controller = - new BluetoothProfileController(aConnect, address, aRunnable, + new BluetoothProfileController(aConnect, aDeviceAddress, aRunnable, NextBluetoothProfileController, aServiceUuid, aCod); sControllerArray.AppendElement(controller); @@ -1421,7 +1410,7 @@ BluetoothServiceBluedroid::ConnectDisconnect( } void -BluetoothServiceBluedroid::Connect(const nsAString& aDeviceAddress, +BluetoothServiceBluedroid::Connect(const BluetoothAddress& aDeviceAddress, uint32_t aCod, uint16_t aServiceUuid, BluetoothReplyRunnable* aRunnable) @@ -1431,34 +1420,27 @@ BluetoothServiceBluedroid::Connect(const nsAString& aDeviceAddress, void BluetoothServiceBluedroid::Disconnect( - const nsAString& aDeviceAddress, uint16_t aServiceUuid, + const BluetoothAddress& aDeviceAddress, uint16_t aServiceUuid, BluetoothReplyRunnable* aRunnable) { ConnectDisconnect(false, aDeviceAddress, aRunnable, aServiceUuid); } void -BluetoothServiceBluedroid::SendFile(const nsAString& aDeviceAddress, +BluetoothServiceBluedroid::SendFile(const BluetoothAddress& aDeviceAddress, BlobParent* aBlobParent, BlobChild* aBlobChild, BluetoothReplyRunnable* aRunnable) { MOZ_ASSERT(NS_IsMainThread()); - BluetoothAddress deviceAddress; - nsresult rv = StringToAddress(aDeviceAddress, deviceAddress); - if (NS_FAILED(rv)) { - DispatchReplyError(aRunnable, STATUS_PARM_INVALID); - return; - } - // Currently we only support one device sending one file at a time, // so we don't need aDeviceAddress here because the target device // has been determined when calling 'Connect()'. Nevertheless, keep // it for future use. BluetoothOppManager* opp = BluetoothOppManager::Get(); - if (!opp || !opp->SendFile(deviceAddress, aBlobParent)) { + if (!opp || !opp->SendFile(aDeviceAddress, aBlobParent)) { DispatchReplyError(aRunnable, NS_LITERAL_STRING("SendFile failed")); return; } @@ -1467,26 +1449,19 @@ BluetoothServiceBluedroid::SendFile(const nsAString& aDeviceAddress, } void -BluetoothServiceBluedroid::SendFile(const nsAString& aDeviceAddress, +BluetoothServiceBluedroid::SendFile(const BluetoothAddress& aDeviceAddress, Blob* aBlob, BluetoothReplyRunnable* aRunnable) { MOZ_ASSERT(NS_IsMainThread()); - BluetoothAddress deviceAddress; - nsresult rv = StringToAddress(aDeviceAddress, deviceAddress); - if (NS_FAILED(rv)) { - DispatchReplyError(aRunnable, STATUS_PARM_INVALID); - return; - } - // Currently we only support one device sending one file at a time, // so we don't need aDeviceAddress here because the target device // has been determined when calling 'Connect()'. Nevertheless, keep // it for future use. BluetoothOppManager* opp = BluetoothOppManager::Get(); - if (!opp || !opp->SendFile(deviceAddress, aBlob)) { + if (!opp || !opp->SendFile(aDeviceAddress, aBlob)) { DispatchReplyError(aRunnable, NS_LITERAL_STRING("SendFile failed")); return; } @@ -1495,8 +1470,8 @@ BluetoothServiceBluedroid::SendFile(const nsAString& aDeviceAddress, } void -BluetoothServiceBluedroid::StopSendingFile(const nsAString& aDeviceAddress, - BluetoothReplyRunnable* aRunnable) +BluetoothServiceBluedroid::StopSendingFile( + const BluetoothAddress& aDeviceAddress, BluetoothReplyRunnable* aRunnable) { MOZ_ASSERT(NS_IsMainThread()); @@ -1517,7 +1492,7 @@ BluetoothServiceBluedroid::StopSendingFile(const nsAString& aDeviceAddress, void BluetoothServiceBluedroid::ConfirmReceivingFile( - const nsAString& aDeviceAddress, bool aConfirm, + const BluetoothAddress& aDeviceAddress, bool aConfirm, BluetoothReplyRunnable* aRunnable) { MOZ_ASSERT(NS_IsMainThread()); @@ -1586,7 +1561,7 @@ BluetoothServiceBluedroid::SetObexPassword(const nsAString& aPassword, { MOZ_ASSERT(NS_IsMainThread()); - ENSURE_BLUETOOTH_IS_READY_VOID(aRunnable); + ENSURE_BLUETOOTH_IS_ENABLED_VOID(aRunnable); BluetoothPbapManager* pbap = BluetoothPbapManager::Get(); if (!pbap) { @@ -1605,7 +1580,7 @@ BluetoothServiceBluedroid::RejectObexAuth( { MOZ_ASSERT(NS_IsMainThread()); - ENSURE_BLUETOOTH_IS_READY_VOID(aRunnable); + ENSURE_BLUETOOTH_IS_ENABLED_VOID(aRunnable); BluetoothPbapManager* pbap = BluetoothPbapManager::Get(); if (!pbap) { @@ -1878,15 +1853,12 @@ BluetoothServiceBluedroid::SendMetaData(const nsAString& aTitle, void BluetoothServiceBluedroid::SendPlayStatus( - int64_t aDuration, int64_t aPosition, - const nsAString& aPlayStatus, + int64_t aDuration, int64_t aPosition, ControlPlayStatus aPlayStatus, BluetoothReplyRunnable* aRunnable) { BluetoothAvrcpManager* avrcp = BluetoothAvrcpManager::Get(); if (avrcp) { - ControlPlayStatus playStatus = - PlayStatusStringToControlPlayStatus(aPlayStatus); - avrcp->UpdatePlayStatus(aDuration, aPosition, playStatus); + avrcp->UpdatePlayStatus(aDuration, aPosition, aPlayStatus); } DispatchReplySuccess(aRunnable); } @@ -1992,6 +1964,7 @@ private: return; } + sBtCoreInterface = nullptr; sBtInterface->Cleanup(new CleanupResultHandler()); } @@ -2001,7 +1974,7 @@ private: class BluetoothServiceBluedroid::SetAdapterPropertyDiscoverableResultHandler final - : public BluetoothResultHandler + : public BluetoothCoreResultHandler { public: void OnError(BluetoothStatus aStatus) override @@ -2091,9 +2064,8 @@ BluetoothServiceBluedroid::AdapterStateChangedNotification(bool aState) // Bluetooth scan mode is SCAN_MODE_CONNECTABLE by default, i.e., it should // be connectable and non-discoverable. - NS_ENSURE_TRUE_VOID(sBtInterface); - sBtInterface->SetAdapterProperty( - BluetoothNamedValue(NS_ConvertUTF8toUTF16("Discoverable"), false), + sBtCoreInterface->SetAdapterProperty( + BluetoothProperty(PROPERTY_ADAPTER_SCAN_MODE, SCAN_MODE_CONNECTABLE), new SetAdapterPropertyDiscoverableResultHandler()); // Trigger OPP & PBAP managers to listen diff --git a/dom/bluetooth/bluedroid/BluetoothServiceBluedroid.h b/dom/bluetooth/bluedroid/BluetoothServiceBluedroid.h index b08dc198ba..2d9af32070 100644 --- a/dom/bluetooth/bluedroid/BluetoothServiceBluedroid.h +++ b/dom/bluetooth/bluedroid/BluetoothServiceBluedroid.h @@ -15,9 +15,12 @@ BEGIN_BLUETOOTH_NAMESPACE -class BluetoothServiceBluedroid : public BluetoothService - , public BluetoothNotificationHandler +class BluetoothServiceBluedroid + : public BluetoothService + , public BluetoothCoreNotificationHandler + , public BluetoothNotificationHandler { + class CancelBondResultHandler; class CleanupResultHandler; class DisableResultHandler; class DispatchReplyErrorResultHandler; @@ -50,11 +53,12 @@ public: BluetoothReplyRunnable* aRunnable); virtual nsresult - GetPairedDevicePropertiesInternal(const nsTArray& aDeviceAddress, - BluetoothReplyRunnable* aRunnable); + GetPairedDevicePropertiesInternal( + const nsTArray& aDeviceAddress, + BluetoothReplyRunnable* aRunnable); virtual nsresult - FetchUuidsInternal(const nsAString& aDeviceAddress, + FetchUuidsInternal(const BluetoothAddress& aDeviceAddress, BluetoothReplyRunnable* aRunnable) override; virtual void StartDiscoveryInternal(BluetoothReplyRunnable* aRunnable); @@ -75,67 +79,67 @@ public: BluetoothProfileManagerBase* aManager); virtual nsresult - CreatePairedDeviceInternal(const nsAString& aDeviceAddress, + CreatePairedDeviceInternal(const BluetoothAddress& aDeviceAddress, int aTimeout, BluetoothReplyRunnable* aRunnable); virtual nsresult - RemoveDeviceInternal(const nsAString& aDeviceObjectPath, + RemoveDeviceInternal(const BluetoothAddress& aDeviceAddress, BluetoothReplyRunnable* aRunnable); virtual void - PinReplyInternal(const nsAString& aDeviceAddress, + PinReplyInternal(const BluetoothAddress& aDeviceAddress, bool aAccept, - const nsAString& aPinCode, + const BluetoothPinCode& aPinCode, BluetoothReplyRunnable* aRunnable); virtual void - SspReplyInternal(const nsAString& aDeviceAddress, + SspReplyInternal(const BluetoothAddress& aDeviceAddress, BluetoothSspVariant aVariant, bool aAccept, BluetoothReplyRunnable* aRunnable); virtual void - SetPinCodeInternal(const nsAString& aDeviceAddress, - const nsAString& aPinCode, + SetPinCodeInternal(const BluetoothAddress& aDeviceAddress, + const BluetoothPinCode& aPinCode, BluetoothReplyRunnable* aRunnable); virtual void - SetPasskeyInternal(const nsAString& aDeviceAddress, + SetPasskeyInternal(const BluetoothAddress& aDeviceAddress, uint32_t aPasskey, BluetoothReplyRunnable* aRunnable); virtual void - SetPairingConfirmationInternal(const nsAString& aDeviceAddress, + SetPairingConfirmationInternal(const BluetoothAddress& aDeviceAddress, bool aConfirm, BluetoothReplyRunnable* aRunnable); virtual void - Connect(const nsAString& aDeviceAddress, + Connect(const BluetoothAddress& aDeviceAddress, uint32_t aCod, uint16_t aServiceUuid, BluetoothReplyRunnable* aRunnable); virtual void - Disconnect(const nsAString& aDeviceAddress, uint16_t aServiceUuid, + Disconnect(const BluetoothAddress& aDeviceAddress, uint16_t aServiceUuid, BluetoothReplyRunnable* aRunnable); virtual void - SendFile(const nsAString& aDeviceAddress, + SendFile(const BluetoothAddress& aDeviceAddress, BlobParent* aBlobParent, BlobChild* aBlobChild, BluetoothReplyRunnable* aRunnable); virtual void - SendFile(const nsAString& aDeviceAddress, + SendFile(const BluetoothAddress& aDeviceAddress, Blob* aBlob, BluetoothReplyRunnable* aRunnable); virtual void - StopSendingFile(const nsAString& aDeviceAddress, + StopSendingFile(const BluetoothAddress& aDeviceAddress, BluetoothReplyRunnable* aRunnable); virtual void - ConfirmReceivingFile(const nsAString& aDeviceAddress, bool aConfirm, + ConfirmReceivingFile(const BluetoothAddress& aDeviceAddress, bool aConfirm, BluetoothReplyRunnable* aRunnable); virtual void @@ -254,7 +258,7 @@ public: virtual void SendPlayStatus(int64_t aDuration, int64_t aPosition, - const nsAString& aPlayStatus, + ControlPlayStatus aPlayStatus, BluetoothReplyRunnable* aRunnable) override; virtual void @@ -274,36 +278,36 @@ public: // GATT Client // - virtual void StartLeScanInternal(const nsTArray& aServiceUuids, + virtual void StartLeScanInternal(const nsTArray& aServiceUuids, BluetoothReplyRunnable* aRunnable); - virtual void StopLeScanInternal(const nsAString& aScanUuid, + virtual void StopLeScanInternal(const BluetoothUuid& aScanUuid, BluetoothReplyRunnable* aRunnable); virtual void - ConnectGattClientInternal(const nsAString& aAppUuid, - const nsAString& aDeviceAddress, + ConnectGattClientInternal(const BluetoothUuid& aAppUuid, + const BluetoothAddress& aDeviceAddress, BluetoothReplyRunnable* aRunnable) override; virtual void - DisconnectGattClientInternal(const nsAString& aAppUuid, - const nsAString& aDeviceAddress, + DisconnectGattClientInternal(const BluetoothUuid& aAppUuid, + const BluetoothAddress& aDeviceAddress, BluetoothReplyRunnable* aRunnable) override; virtual void - DiscoverGattServicesInternal(const nsAString& aAppUuid, + DiscoverGattServicesInternal(const BluetoothUuid& aAppUuid, BluetoothReplyRunnable* aRunnable) override; virtual void GattClientStartNotificationsInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServId, const BluetoothGattId& aCharId, BluetoothReplyRunnable* aRunnable) override; virtual void GattClientStopNotificationsInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServId, const BluetoothGattId& aCharId, BluetoothReplyRunnable* aRunnable) override; @@ -314,19 +318,19 @@ public: virtual void GattClientReadRemoteRssiInternal( - int aClientIf, const nsAString& aDeviceAddress, + int aClientIf, const BluetoothAddress& aDeviceAddress, BluetoothReplyRunnable* aRunnable) override; virtual void GattClientReadCharacteristicValueInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServiceId, const BluetoothGattId& aCharacteristicId, BluetoothReplyRunnable* aRunnable) override; virtual void GattClientWriteCharacteristicValueInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServiceId, const BluetoothGattId& aCharacteristicId, const BluetoothGattWriteType& aWriteType, @@ -335,7 +339,7 @@ public: virtual void GattClientReadDescriptorValueInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServiceId, const BluetoothGattId& aCharacteristicId, const BluetoothGattId& aDescriptorId, @@ -343,7 +347,7 @@ public: virtual void GattClientWriteDescriptorValueInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServiceId, const BluetoothGattId& aCharacteristicId, const BluetoothGattId& aDescriptorId, @@ -352,14 +356,14 @@ public: virtual void GattServerConnectPeripheralInternal( - const nsAString& aAppUuid, - const nsAString& aAddress, + const BluetoothUuid& aAppUuid, + const BluetoothAddress& aAddress, BluetoothReplyRunnable* aRunnable) override; virtual void GattServerDisconnectPeripheralInternal( - const nsAString& aAppUuid, - const nsAString& aAddress, + const BluetoothUuid& aAppUuid, + const BluetoothAddress& aAddress, BluetoothReplyRunnable* aRunnable) override; virtual void @@ -368,21 +372,21 @@ public: virtual void GattServerAddServiceInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServiceId, uint16_t aHandleCount, BluetoothReplyRunnable* aRunnable) override; virtual void GattServerAddIncludedServiceInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothAttributeHandle& aServiceHandle, const BluetoothAttributeHandle& aIncludedServiceHandle, BluetoothReplyRunnable* aRunnable) override; virtual void GattServerAddCharacteristicInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothAttributeHandle& aServiceHandle, const BluetoothUuid& aCharacteristicUuid, BluetoothGattAttrPerm aPermissions, @@ -391,7 +395,7 @@ public: virtual void GattServerAddDescriptorInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothAttributeHandle& aServiceHandle, const BluetoothAttributeHandle& aCharacteristicHandle, const BluetoothUuid& aDescriptorUuid, @@ -400,31 +404,40 @@ public: virtual void GattServerRemoveServiceInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothAttributeHandle& aServiceHandle, BluetoothReplyRunnable* aRunnable) override; virtual void GattServerStartServiceInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothAttributeHandle& aServiceHandle, BluetoothReplyRunnable* aRunnable) override; virtual void GattServerStopServiceInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothAttributeHandle& aServiceHandle, BluetoothReplyRunnable* aRunnable) override; virtual void GattServerSendResponseInternal( - const nsAString& aAppUuid, - const nsAString& aAddress, + const BluetoothUuid& aAppUuid, + const BluetoothAddress& aAddress, uint16_t aStatus, int32_t aRequestId, const BluetoothGattResponse& aRsp, BluetoothReplyRunnable* aRunnable) override; + virtual void + GattServerSendIndicationInternal( + const BluetoothUuid& aAppUuid, + const BluetoothAddress& aAddress, + const BluetoothAttributeHandle& aCharacteristicHandle, + bool aConfirm, + const nsTArray& aValue, + BluetoothReplyRunnable* aRunnable) override; + // // Bluetooth notifications // @@ -476,11 +489,8 @@ protected: static nsresult StartGonkBluetooth(); static nsresult StopGonkBluetooth(); - static ControlPlayStatus PlayStatusStringToControlPlayStatus( - const nsAString& aPlayStatus); - static void ConnectDisconnect(bool aConnect, - const nsAString& aDeviceAddress, + const BluetoothAddress& aDeviceAddress, BluetoothReplyRunnable* aRunnable, uint16_t aServiceUuid, uint32_t aCod = 0); static void NextBluetoothProfileController(); diff --git a/dom/bluetooth/bluedroid/hfp-fallback/BluetoothHfpManager.cpp b/dom/bluetooth/bluedroid/hfp-fallback/BluetoothHfpManager.cpp index dabe109ead..f8555430f4 100644 --- a/dom/bluetooth/bluedroid/hfp-fallback/BluetoothHfpManager.cpp +++ b/dom/bluetooth/bluedroid/hfp-fallback/BluetoothHfpManager.cpp @@ -92,7 +92,7 @@ BluetoothHfpManager::OnGetServiceChannel( } void -BluetoothHfpManager::OnUpdateSdpRecords(const nsAString& aDeviceAddress) +BluetoothHfpManager::OnUpdateSdpRecords(const BluetoothAddress& aDeviceAddress) { MOZ_ASSERT(false); } @@ -106,6 +106,12 @@ BluetoothHfpManager::IsScoConnected() return false; } +bool +BluetoothHfpManager::IsNrecEnabled() +{ + return false; +} + /** * Non-inherited functions */ @@ -202,6 +208,17 @@ BluetoothHfpManager::ConnectSco() return false; } +void +BluetoothHfpManager::HandleBackendError() +{ + /** + * TODO: + * Reset connection state and audio state to DISCONNECTED to handle backend + * error. The state change triggers UI status bar update as ordinary + * bluetooth turn-off sequence. + */ +} + bool BluetoothHfpManager::DisconnectSco() { diff --git a/dom/bluetooth/bluedroid/hfp-fallback/BluetoothHfpManager.h b/dom/bluetooth/bluedroid/hfp-fallback/BluetoothHfpManager.h index c16422ca59..b7093936ea 100644 --- a/dom/bluetooth/bluedroid/hfp-fallback/BluetoothHfpManager.h +++ b/dom/bluetooth/bluedroid/hfp-fallback/BluetoothHfpManager.h @@ -34,6 +34,8 @@ public: bool ConnectSco(); bool DisconnectSco(); + // Handle unexpected backend crash + void HandleBackendError(); protected: virtual ~BluetoothHfpManager() { } diff --git a/dom/bluetooth/bluedroid/hfp/BluetoothHfpManager.cpp b/dom/bluetooth/bluedroid/hfp/BluetoothHfpManager.cpp index ca107130f9..4c80ebe1d9 100644 --- a/dom/bluetooth/bluedroid/hfp/BluetoothHfpManager.cpp +++ b/dom/bluetooth/bluedroid/hfp/BluetoothHfpManager.cpp @@ -276,12 +276,12 @@ BluetoothHfpManager::Init() return true; } -class BluetoothHfpManager::CleanupInitResultHandler final - : public BluetoothHandsfreeResultHandler +class BluetoothHfpManager::RegisterModuleResultHandler final + : public BluetoothSetupResultHandler { public: - CleanupInitResultHandler(BluetoothHandsfreeInterface* aInterface, - BluetoothProfileResultHandler* aRes) + RegisterModuleResultHandler(BluetoothHandsfreeInterface* aInterface, + BluetoothProfileResultHandler* aRes) : mInterface(aInterface) , mRes(aRes) { @@ -290,68 +290,40 @@ public: void OnError(BluetoothStatus aStatus) override { - BT_WARNING("BluetoothHandsfreeInterface::Init failed: %d", (int)aStatus); + MOZ_ASSERT(NS_IsMainThread()); + + BT_WARNING("BluetoothSetupInterface::RegisterModule failed for HFP: %d", + (int)aStatus); + + mInterface->SetNotificationHandler(nullptr); + if (mRes) { mRes->OnError(NS_ERROR_FAILURE); } } - void Init() override + void RegisterModule() override { + MOZ_ASSERT(NS_IsMainThread()); + sBluetoothHfpInterface = mInterface; + if (mRes) { mRes->Init(); } } - void Cleanup() override - { - sBluetoothHfpInterface = nullptr; - /* During re-initialization, a previouly initialized - * |BluetoothHandsfreeInterface| has now been cleaned - * up, so we start initialization. - */ - RunInit(); - } - - void RunInit() - { - BluetoothHfpManager* hfpManager = BluetoothHfpManager::Get(); - - mInterface->Init(hfpManager, BluetoothHfpManager::MAX_NUM_CLIENTS, this); - } - private: BluetoothHandsfreeInterface* mInterface; RefPtr mRes; }; -class BluetoothHfpManager::InitResultHandlerRunnable final +class BluetoothHfpManager::InitProfileResultHandlerRunnable final : public nsRunnable { public: - InitResultHandlerRunnable(CleanupInitResultHandler* aRes) - : mRes(aRes) - { - MOZ_ASSERT(mRes); - } - - NS_IMETHOD Run() override - { - mRes->RunInit(); - return NS_OK; - } - -private: - RefPtr mRes; -}; - -class BluetoothHfpManager::OnErrorProfileResultHandlerRunnable final - : public nsRunnable -{ -public: - OnErrorProfileResultHandlerRunnable(BluetoothProfileResultHandler* aRes, - nsresult aRv) + InitProfileResultHandlerRunnable(BluetoothProfileResultHandler* aRes, + nsresult aRv) : mRes(aRes) , mRv(aRv) { @@ -360,7 +332,13 @@ public: NS_IMETHOD Run() override { - mRes->OnError(mRv); + MOZ_ASSERT(NS_IsMainThread()); + + if (NS_SUCCEEDED(mRv)) { + mRes->Init(); + } else { + mRes->OnError(mRv); + } return NS_OK; } @@ -373,45 +351,64 @@ private: void BluetoothHfpManager::InitHfpInterface(BluetoothProfileResultHandler* aRes) { - BluetoothInterface* btInf = BluetoothInterface::GetInstance(); + MOZ_ASSERT(NS_IsMainThread()); + + if (sBluetoothHfpInterface) { + BT_LOGR("Bluetooth Handsfree interface is already initalized."); + RefPtr r = + new InitProfileResultHandlerRunnable(aRes, NS_OK); + if (NS_FAILED(NS_DispatchToMainThread(r))) { + BT_LOGR("Failed to dispatch HFP Init runnable"); + } + return; + } + + auto btInf = BluetoothInterface::GetInstance(); + if (NS_WARN_IF(!btInf)) { // If there's no backend interface, we dispatch a runnable // that calls the profile result handler. RefPtr r = - new OnErrorProfileResultHandlerRunnable(aRes, NS_ERROR_FAILURE); + new InitProfileResultHandlerRunnable(aRes, NS_ERROR_FAILURE); if (NS_FAILED(NS_DispatchToMainThread(r))) { BT_LOGR("Failed to dispatch HFP OnError runnable"); } return; } - BluetoothHandsfreeInterface *interface = - btInf->GetBluetoothHandsfreeInterface(); + auto setupInterface = btInf->GetBluetoothSetupInterface(); + + if (NS_WARN_IF(!setupInterface)) { + // If there's no Setup interface, we dispatch a runnable + // that calls the profile result handler. + RefPtr r = + new InitProfileResultHandlerRunnable(aRes, NS_ERROR_FAILURE); + if (NS_FAILED(NS_DispatchToMainThread(r))) { + BT_LOGR("Failed to dispatch HFP OnError runnable"); + } + return; + } + + auto interface = btInf->GetBluetoothHandsfreeInterface(); + if (NS_WARN_IF(!interface)) { // If there's no HFP interface, we dispatch a runnable // that calls the profile result handler. RefPtr r = - new OnErrorProfileResultHandlerRunnable(aRes, NS_ERROR_FAILURE); + new InitProfileResultHandlerRunnable(aRes, NS_ERROR_FAILURE); if (NS_FAILED(NS_DispatchToMainThread(r))) { BT_LOGR("Failed to dispatch HFP OnError runnable"); } return; } - RefPtr res = - new CleanupInitResultHandler(interface, aRes); + // Set notification handler _before_ registering the module. It could + // happen that we receive notifications, before the result handler runs. + interface->SetNotificationHandler(BluetoothHfpManager::Get()); - if (sBluetoothHfpInterface) { - // Cleanup an initialized HFP before initializing again. - sBluetoothHfpInterface->Cleanup(res); - } else { - // If there's no HFP interface to cleanup first, we dispatch - // a runnable that calls the profile result handler. - RefPtr r = new InitResultHandlerRunnable(res); - if (NS_FAILED(NS_DispatchToMainThread(r))) { - BT_LOGR("Failed to dispatch HFP init runnable"); - } - } + setupInterface->RegisterModule( + SETUP_SERVICE_ID_HANDSFREE, MODE_NARROWBAND_SPEECH, MAX_NUM_CLIENTS, + new RegisterModuleResultHandler(interface, aRes)); } BluetoothHfpManager::~BluetoothHfpManager() @@ -432,18 +429,22 @@ BluetoothHfpManager::~BluetoothHfpManager() hal::UnregisterBatteryObserver(this); } -class BluetoothHfpManager::CleanupResultHandler final - : public BluetoothHandsfreeResultHandler +class BluetoothHfpManager::UnregisterModuleResultHandler final + : public BluetoothSetupResultHandler { public: - CleanupResultHandler(BluetoothProfileResultHandler* aRes) + UnregisterModuleResultHandler(BluetoothProfileResultHandler* aRes) : mRes(aRes) { } void OnError(BluetoothStatus aStatus) override { - BT_WARNING("BluetoothHandsfreeInterface::Cleanup failed: %d", (int)aStatus); + MOZ_ASSERT(NS_IsMainThread()); + BT_WARNING("BluetoothSetupInterface::UnregisterModule failed for HFP: %d", + (int)aStatus); + + sBluetoothHfpInterface->SetNotificationHandler(nullptr); sBluetoothHfpInterface = nullptr; if (mRes) { @@ -451,9 +452,13 @@ public: } } - void Cleanup() override + void UnregisterModule() override { + MOZ_ASSERT(NS_IsMainThread()); + + sBluetoothHfpInterface->SetNotificationHandler(nullptr); sBluetoothHfpInterface = nullptr; + if (mRes) { mRes->Deinit(); } @@ -463,40 +468,80 @@ private: RefPtr mRes; }; -class BluetoothHfpManager::DeinitResultHandlerRunnable final +class BluetoothHfpManager::DeinitProfileResultHandlerRunnable final : public nsRunnable { public: - DeinitResultHandlerRunnable(BluetoothProfileResultHandler* aRes) + DeinitProfileResultHandlerRunnable(BluetoothProfileResultHandler* aRes, + nsresult aRv) : mRes(aRes) + , mRv(aRv) { MOZ_ASSERT(mRes); } NS_IMETHOD Run() override { - mRes->Deinit(); + MOZ_ASSERT(NS_IsMainThread()); + + if (NS_SUCCEEDED(mRv)) { + mRes->Deinit(); + } else { + mRes->OnError(mRv); + } return NS_OK; } private: RefPtr mRes; + nsresult mRv; }; // static void BluetoothHfpManager::DeinitHfpInterface(BluetoothProfileResultHandler* aRes) { - if (sBluetoothHfpInterface) { - sBluetoothHfpInterface->Cleanup(new CleanupResultHandler(aRes)); - } else if (aRes) { - // We dispatch a runnable here to make the profile resource handler - // behave as if HFP was initialized. - RefPtr r = new DeinitResultHandlerRunnable(aRes); + MOZ_ASSERT(NS_IsMainThread()); + + if (!sBluetoothHfpInterface) { + BT_LOGR("Bluetooth Handsfree interface has not been initialized."); + RefPtr r = + new DeinitProfileResultHandlerRunnable(aRes, NS_OK); if (NS_FAILED(NS_DispatchToMainThread(r))) { - BT_LOGR("Failed to dispatch cleanup-result-handler runnable"); + BT_LOGR("Failed to dispatch HFP Deinit runnable"); } + return; } + + auto btInf = BluetoothInterface::GetInstance(); + + if (NS_WARN_IF(!btInf)) { + // If there's no backend interface, we dispatch a runnable + // that calls the profile result handler. + RefPtr r = + new DeinitProfileResultHandlerRunnable(aRes, NS_ERROR_FAILURE); + if (NS_FAILED(NS_DispatchToMainThread(r))) { + BT_LOGR("Failed to dispatch HFP OnError runnable"); + } + return; + } + + auto setupInterface = btInf->GetBluetoothSetupInterface(); + + if (NS_WARN_IF(!setupInterface)) { + // If there's no Setup interface, we dispatch a runnable + // that calls the profile result handler. + RefPtr r = + new DeinitProfileResultHandlerRunnable(aRes, NS_ERROR_FAILURE); + if (NS_FAILED(NS_DispatchToMainThread(r))) { + BT_LOGR("Failed to dispatch HFP OnError runnable"); + } + return; + } + + setupInterface->UnregisterModule( + SETUP_SERVICE_ID_HANDSFREE, + new UnregisterModuleResultHandler(aRes)); } //static diff --git a/dom/bluetooth/bluedroid/hfp/BluetoothHfpManager.h b/dom/bluetooth/bluedroid/hfp/BluetoothHfpManager.h index 88ac8c0676..950c51dd6b 100644 --- a/dom/bluetooth/bluedroid/hfp/BluetoothHfpManager.h +++ b/dom/bluetooth/bluedroid/hfp/BluetoothHfpManager.h @@ -73,6 +73,12 @@ class BluetoothHfpManager : public BluetoothHfpManagerBase , public BluetoothHandsfreeNotificationHandler , public BatteryObserver { + enum { + MODE_HEADSET = 0x00, + MODE_NARROWBAND_SPEECH = 0x01, + MODE_NARRAWBAND_WIDEBAND_SPEECH = 0x02 + }; + public: BT_DECL_HFP_MGR_BASE @@ -92,7 +98,6 @@ public: bool ConnectSco(); bool DisconnectSco(); - bool IsNrecEnabled(); /** * @param aSend A boolean indicates whether we need to notify headset or not @@ -152,21 +157,20 @@ private: class ConnectResultHandler; class CopsResponseResultHandler; class ClccResponseResultHandler; - class CleanupInitResultHandler; - class CleanupResultHandler; class CloseScoRunnable; class CloseScoTask; - class DeinitResultHandlerRunnable; + class DeinitProfileResultHandlerRunnable; class DeviceStatusNotificationResultHandler; class DisconnectAudioResultHandler; class DisconnectResultHandler; class FormattedAtResponseResultHandler; class GetVolumeTask; - class InitResultHandlerRunnable; + class InitProfileResultHandlerRunnable; class MainThreadTask; - class OnErrorProfileResultHandlerRunnable; class PhoneStateChangeResultHandler; + class RegisterModuleResultHandler; class RespondToBLDNTask; + class UnregisterModuleResultHandler; class VolumeControlResultHandler; friend class BluetoothHfpManagerObserver; diff --git a/dom/bluetooth/bluez/BluetoothDBusService.cpp b/dom/bluetooth/bluez/BluetoothDBusService.cpp index df432b5793..f486140814 100644 --- a/dom/bluetooth/bluez/BluetoothDBusService.cpp +++ b/dom/bluetooth/bluez/BluetoothDBusService.cpp @@ -2703,7 +2703,7 @@ class BluetoothArrayOfDevicePropertiesReplyHandler : public DBusReplyHandler { public: BluetoothArrayOfDevicePropertiesReplyHandler( - const nsTArray& aDeviceAddresses, + const nsTArray& aDeviceAddresses, const FilterFunc aFilterFunc, BluetoothReplyRunnable* aRunnable) : mDeviceAddresses(aDeviceAddresses) , mProcessedDeviceAddresses(0) @@ -2772,8 +2772,11 @@ public: } if (mFilterFunc(deviceProperties)) { + nsString deviceAddressStr; + AddressToString(mDeviceAddresses[i], deviceAddressStr); + mValues.get_ArrayOfBluetoothNamedValue().AppendElement( - BluetoothNamedValue(mDeviceAddresses[i], deviceProperties)); + BluetoothNamedValue(deviceAddressStr, deviceProperties)); } ProcessRemainingDeviceAddresses(); @@ -2822,7 +2825,7 @@ protected: private: nsString mObjectPath; - const nsTArray mDeviceAddresses; + const nsTArray mDeviceAddresses; nsTArray::size_type mProcessedDeviceAddresses; const FilterFunc mFilterFunc; RefPtr mRunnable; @@ -2868,7 +2871,8 @@ BluetoothDBusService::GetConnectedDevicePropertiesInternal( return NS_OK; } - nsTArray deviceAddresses; + nsTArray deviceAddresses; + BluetoothProfileManagerBase* profile = BluetoothUuidHelper::GetBluetoothProfileManager(aServiceUuid); if (!profile) { @@ -2880,11 +2884,7 @@ BluetoothDBusService::GetConnectedDevicePropertiesInternal( if (profile->IsConnected()) { BluetoothAddress address; profile->GetAddress(address); - - nsAutoString addressStr; - AddressToString(address, addressStr); - - deviceAddresses.AppendElement(addressStr); + deviceAddresses.AppendElement(address); } BluetoothArrayOfDevicePropertiesReplyHandler* handler = @@ -2899,8 +2899,8 @@ BluetoothDBusService::GetConnectedDevicePropertiesInternal( nsresult BluetoothDBusService::GetPairedDevicePropertiesInternal( - const nsTArray& aDeviceAddresses, - BluetoothReplyRunnable* aRunnable) + const nsTArray& aDeviceAddresses, + BluetoothReplyRunnable* aRunnable) { MOZ_ASSERT(NS_IsMainThread()); @@ -2921,7 +2921,7 @@ BluetoothDBusService::GetPairedDevicePropertiesInternal( } nsresult -BluetoothDBusService::FetchUuidsInternal(const nsAString& aDeviceAddress, +BluetoothDBusService::FetchUuidsInternal(const BluetoothAddress& aDeviceAddress, BluetoothReplyRunnable* aRunnable) { return NS_OK; @@ -3092,14 +3092,14 @@ BluetoothDBusService::SetProperty(BluetoothObjectType aType, class CreatePairedDeviceInternalTask : public Task { public: - CreatePairedDeviceInternalTask(const nsACString& aDeviceAddress, + CreatePairedDeviceInternalTask(const BluetoothAddress& aDeviceAddress, int aTimeout, BluetoothReplyRunnable* aRunnable) : mDeviceAddress(aDeviceAddress) , mTimeout(aTimeout) , mRunnable(aRunnable) { - MOZ_ASSERT(!mDeviceAddress.IsEmpty()); + MOZ_ASSERT(!mDeviceAddress.IsCleared()); MOZ_ASSERT(mRunnable); } @@ -3109,7 +3109,11 @@ public: MOZ_ASSERT(sDBusConnection); MOZ_ASSERT(!sAdapterPath.IsEmpty()); - const char *deviceAddress = mDeviceAddress.get(); + nsString deviceAddressStr; + AddressToString(mDeviceAddress, deviceAddressStr); + auto utf8DeviceAddressStr = NS_ConvertUTF16toUTF8(deviceAddressStr); + + const char *deviceAddress = utf8DeviceAddressStr.get(); const char *deviceAgentPath = KEY_REMOTE_AGENT; const char *capabilities = B2G_AGENT_CAPABILITIES; @@ -3145,20 +3149,20 @@ public: } private: - const nsCString mDeviceAddress; + BluetoothAddress mDeviceAddress; int mTimeout; RefPtr mRunnable; }; nsresult BluetoothDBusService::CreatePairedDeviceInternal( - const nsAString& aDeviceAddress, - int aTimeout, - BluetoothReplyRunnable* aRunnable) + const BluetoothAddress& aDeviceAddress, + int aTimeout, + BluetoothReplyRunnable* aRunnable) { - Task* task = new CreatePairedDeviceInternalTask( - NS_ConvertUTF16toUTF8(aDeviceAddress), - aTimeout, aRunnable); + Task* task = new CreatePairedDeviceInternalTask(aDeviceAddress, + aTimeout, + aRunnable); DispatchToDBusThread(task); return NS_OK; @@ -3221,8 +3225,9 @@ private: }; nsresult -BluetoothDBusService::RemoveDeviceInternal(const nsAString& aDeviceAddress, - BluetoothReplyRunnable* aRunnable) +BluetoothDBusService::RemoveDeviceInternal( + const BluetoothAddress& aDeviceAddress, + BluetoothReplyRunnable* aRunnable) { MOZ_ASSERT(NS_IsMainThread()); @@ -3232,14 +3237,7 @@ BluetoothDBusService::RemoveDeviceInternal(const nsAString& aDeviceAddress, return NS_OK; } - BluetoothAddress deviceAddress; - auto rv = StringToAddress(aDeviceAddress, deviceAddress); - if (NS_FAILED(rv)) { - DispatchReplyError(aRunnable, STATUS_PARM_INVALID); - return rv; - } - - Task* task = new RemoveDeviceTask(deviceAddress, aRunnable); + Task* task = new RemoveDeviceTask(aDeviceAddress, aRunnable); DispatchToDBusThread(task); return NS_OK; @@ -3249,7 +3247,7 @@ class SetPinCodeTask : public Task { public: SetPinCodeTask(const BluetoothAddress& aDeviceAddress, - const nsACString& aPinCode, + const BluetoothPinCode& aPinCode, BluetoothReplyRunnable* aRunnable) : mDeviceAddress(aDeviceAddress) , mPinCode(aPinCode) @@ -3283,7 +3281,19 @@ public: return; } - const char* pinCode = mPinCode.get(); + nsAutoString pinCodeStr; + if (NS_FAILED(PinCodeToString(mPinCode, pinCodeStr))) { + BT_WARNING("%s: Cannot convert pin code to string.", __FUNCTION__); + dbus_message_unref(msg); + dbus_message_unref(reply); + errorStr.AssignLiteral("Cannot convert pin code to string."); + DispatchBluetoothReply(mRunnable, v, errorStr); + return; + } + + auto utf8PinCodeStr = NS_ConvertUTF16toUTF8(pinCodeStr); + + const char* pinCode = utf8PinCodeStr.get(); if (!dbus_message_append_args(reply, DBUS_TYPE_STRING, &pinCode, @@ -3304,41 +3314,32 @@ public: private: const BluetoothAddress mDeviceAddress; - const nsCString mPinCode; + const BluetoothPinCode mPinCode; RefPtr mRunnable; }; void BluetoothDBusService::PinReplyInternal( - const nsAString& aDeviceAddress, bool aAccept, - const nsAString& aPinCode, BluetoothReplyRunnable* aRunnable) + const BluetoothAddress& aDeviceAddress, bool aAccept, + const BluetoothPinCode& aPinCode, BluetoothReplyRunnable* aRunnable) { // Legacy interface used by Bluedroid only. } void BluetoothDBusService::SspReplyInternal( - const nsAString& aDeviceAddress, BluetoothSspVariant aVariant, + const BluetoothAddress& aDeviceAddress, BluetoothSspVariant aVariant, bool aAccept, BluetoothReplyRunnable* aRunnable) { // Legacy interface used by Bluedroid only. } void -BluetoothDBusService::SetPinCodeInternal(const nsAString& aDeviceAddress, - const nsAString& aPinCode, +BluetoothDBusService::SetPinCodeInternal(const BluetoothAddress& aDeviceAddress, + const BluetoothPinCode& aPinCode, BluetoothReplyRunnable* aRunnable) { - BluetoothAddress deviceAddress; - auto rv = StringToAddress(aDeviceAddress, deviceAddress); - if (NS_FAILED(rv)) { - DispatchReplyError(aRunnable, STATUS_PARM_INVALID); - return; - } - - Task* task = new SetPinCodeTask(deviceAddress, - NS_ConvertUTF16toUTF8(aPinCode), - aRunnable); + Task* task = new SetPinCodeTask(aDeviceAddress, aPinCode, aRunnable); DispatchToDBusThread(task); } @@ -3406,17 +3407,12 @@ private: }; void -BluetoothDBusService::SetPasskeyInternal(const nsAString& aDeviceAddress, - uint32_t aPasskey, - BluetoothReplyRunnable* aRunnable) +BluetoothDBusService::SetPasskeyInternal( + const BluetoothAddress& aDeviceAddress, + uint32_t aPasskey, + BluetoothReplyRunnable* aRunnable) { - BluetoothAddress deviceAddress; - if (NS_FAILED(StringToAddress(aDeviceAddress, deviceAddress))) { - DispatchReplyError(aRunnable, STATUS_PARM_INVALID); - return; - } - - Task* task = new SetPasskeyTask(deviceAddress, + Task* task = new SetPasskeyTask(aDeviceAddress, aPasskey, aRunnable); DispatchToDBusThread(task); @@ -3424,19 +3420,13 @@ BluetoothDBusService::SetPasskeyInternal(const nsAString& aDeviceAddress, void BluetoothDBusService::SetPairingConfirmationInternal( - const nsAString& aDeviceAddress, - bool aConfirm, - BluetoothReplyRunnable* aRunnable) + const BluetoothAddress& aDeviceAddress, + bool aConfirm, + BluetoothReplyRunnable* aRunnable) { MOZ_ASSERT(NS_IsMainThread()); - BluetoothAddress deviceAddress; - if (NS_FAILED(StringToAddress(aDeviceAddress, deviceAddress))) { - DispatchReplyError(aRunnable, STATUS_PARM_INVALID); - return; - } - - Task* task = new SetPairingConfirmationTask(deviceAddress, + Task* task = new SetPairingConfirmationTask(aDeviceAddress, aConfirm, aRunnable); DispatchToDBusThread(task); @@ -3457,22 +3447,15 @@ NextBluetoothProfileController() } static void -ConnectDisconnect(bool aConnect, const nsAString& aDeviceAddress, +ConnectDisconnect(bool aConnect, const BluetoothAddress& aDeviceAddress, BluetoothReplyRunnable* aRunnable, uint16_t aServiceUuid, uint32_t aCod = 0) { MOZ_ASSERT(NS_IsMainThread()); MOZ_ASSERT(aRunnable); - BluetoothAddress deviceAddress; - nsresult rv = StringToAddress(aDeviceAddress, deviceAddress); - if (NS_FAILED(rv)) { - DispatchReplyError(aRunnable, STATUS_PARM_INVALID); - return; - } - BluetoothProfileController* controller = - new BluetoothProfileController(aConnect, deviceAddress, aRunnable, + new BluetoothProfileController(aConnect, aDeviceAddress, aRunnable, NextBluetoothProfileController, aServiceUuid, aCod); sControllerArray.AppendElement(controller); @@ -3488,7 +3471,7 @@ ConnectDisconnect(bool aConnect, const nsAString& aDeviceAddress, } void -BluetoothDBusService::Connect(const nsAString& aDeviceAddress, +BluetoothDBusService::Connect(const BluetoothAddress& aDeviceAddress, uint32_t aCod, uint16_t aServiceUuid, BluetoothReplyRunnable* aRunnable) @@ -3497,7 +3480,7 @@ BluetoothDBusService::Connect(const nsAString& aDeviceAddress, } void -BluetoothDBusService::Disconnect(const nsAString& aDeviceAddress, +BluetoothDBusService::Disconnect(const BluetoothAddress& aDeviceAddress, uint16_t aServiceUuid, BluetoothReplyRunnable* aRunnable) { @@ -3542,16 +3525,13 @@ BluetoothDBusService::ToggleCalls(BluetoothReplyRunnable* aRunnable) class OnUpdateSdpRecordsRunnable : public nsRunnable { public: - OnUpdateSdpRecordsRunnable(const nsAString& aObjectPath, + OnUpdateSdpRecordsRunnable(const BluetoothAddress& aDeviceAddress, BluetoothProfileManagerBase* aManager) - : mManager(aManager) + : mDeviceAddress(aDeviceAddress) + , mManager(aManager) { - MOZ_ASSERT(!aObjectPath.IsEmpty()); - MOZ_ASSERT(aManager); - - const nsString deviceAddressStr = GetAddressFromObjectPath(aObjectPath); - - StringToAddress(deviceAddressStr, mDeviceAddress); + MOZ_ASSERT(!mDeviceAddress.IsCleared()); + MOZ_ASSERT(mManager); } nsresult @@ -3758,7 +3738,7 @@ public: // I choose to use raw pointer here because this is going to be passed as an // argument into SendWithReply() at once. OnUpdateSdpRecordsRunnable* callbackRunnable = - new OnUpdateSdpRecordsRunnable(objectPath, mBluetoothProfileManager); + new OnUpdateSdpRecordsRunnable(mDeviceAddress, mBluetoothProfileManager); sDBusConnection->SendWithReply(DiscoverServicesCallback, (void*)callbackRunnable, -1, @@ -3798,26 +3778,20 @@ BluetoothDBusService::UpdateSdpRecords(const BluetoothAddress& aDeviceAddress, } void -BluetoothDBusService::SendFile(const nsAString& aDeviceAddress, +BluetoothDBusService::SendFile(const BluetoothAddress& aDeviceAddress, BlobParent* aBlobParent, BlobChild* aBlobChild, BluetoothReplyRunnable* aRunnable) { MOZ_ASSERT(NS_IsMainThread()); - BluetoothAddress deviceAddress; - if (NS_FAILED(StringToAddress(aDeviceAddress, deviceAddress))) { - DispatchReplyError(aRunnable, STATUS_PARM_INVALID); - return; - } - // Currently we only support one device sending one file at a time, // so we don't need aDeviceAddress here because the target device // has been determined when calling 'Connect()'. Nevertheless, keep // it for future use. BluetoothOppManager* opp = BluetoothOppManager::Get(); nsAutoString errorStr; - if (!opp || !opp->SendFile(deviceAddress, aBlobParent)) { + if (!opp || !opp->SendFile(aDeviceAddress, aBlobParent)) { errorStr.AssignLiteral("Calling SendFile() failed"); } @@ -3825,25 +3799,19 @@ BluetoothDBusService::SendFile(const nsAString& aDeviceAddress, } void -BluetoothDBusService::SendFile(const nsAString& aDeviceAddress, +BluetoothDBusService::SendFile(const BluetoothAddress& aDeviceAddress, Blob* aBlob, BluetoothReplyRunnable* aRunnable) { MOZ_ASSERT(NS_IsMainThread()); - BluetoothAddress deviceAddress; - if (NS_FAILED(StringToAddress(aDeviceAddress, deviceAddress))) { - DispatchReplyError(aRunnable, STATUS_PARM_INVALID); - return; - } - // Currently we only support one device sending one file at a time, // so we don't need aDeviceAddress here because the target device // has been determined when calling 'Connect()'. Nevertheless, keep // it for future use. BluetoothOppManager* opp = BluetoothOppManager::Get(); nsAutoString errorStr; - if (!opp || !opp->SendFile(deviceAddress, aBlob)) { + if (!opp || !opp->SendFile(aDeviceAddress, aBlob)) { errorStr.AssignLiteral("Calling SendFile() failed"); } @@ -3851,7 +3819,7 @@ BluetoothDBusService::SendFile(const nsAString& aDeviceAddress, } void -BluetoothDBusService::StopSendingFile(const nsAString& aDeviceAddress, +BluetoothDBusService::StopSendingFile(const BluetoothAddress& aDeviceAddress, BluetoothReplyRunnable* aRunnable) { MOZ_ASSERT(NS_IsMainThread()); @@ -3870,9 +3838,10 @@ BluetoothDBusService::StopSendingFile(const nsAString& aDeviceAddress, } void -BluetoothDBusService::ConfirmReceivingFile(const nsAString& aDeviceAddress, - bool aConfirm, - BluetoothReplyRunnable* aRunnable) +BluetoothDBusService::ConfirmReceivingFile( + const BluetoothAddress& aDeviceAddress, + bool aConfirm, + BluetoothReplyRunnable* aRunnable) { MOZ_ASSERT(NS_IsMainThread(), "Must be called from main thread!"); @@ -4075,27 +4044,6 @@ BluetoothDBusService::SendMetaData(const nsAString& aTitle, aMediaNumber, aTotalMediaCount, aDuration); } -static ControlPlayStatus -PlayStatusStringToControlPlayStatus(const nsAString& aPlayStatus) -{ - ControlPlayStatus playStatus = ControlPlayStatus::PLAYSTATUS_UNKNOWN; - if (aPlayStatus.EqualsLiteral("STOPPED")) { - playStatus = ControlPlayStatus::PLAYSTATUS_STOPPED; - } else if (aPlayStatus.EqualsLiteral("PLAYING")) { - playStatus = ControlPlayStatus::PLAYSTATUS_PLAYING; - } else if (aPlayStatus.EqualsLiteral("PAUSED")) { - playStatus = ControlPlayStatus::PLAYSTATUS_PAUSED; - } else if (aPlayStatus.EqualsLiteral("FWD_SEEK")) { - playStatus = ControlPlayStatus::PLAYSTATUS_FWD_SEEK; - } else if (aPlayStatus.EqualsLiteral("REV_SEEK")) { - playStatus = ControlPlayStatus::PLAYSTATUS_REV_SEEK; - } else if (aPlayStatus.EqualsLiteral("ERROR")) { - playStatus = ControlPlayStatus::PLAYSTATUS_ERROR; - } - - return playStatus; -} - class SendPlayStatusTask : public Task { public: @@ -4150,7 +4098,7 @@ private: void BluetoothDBusService::SendPlayStatus(int64_t aDuration, int64_t aPosition, - const nsAString& aPlayStatus, + ControlPlayStatus aPlayStatus, BluetoothReplyRunnable* aRunnable) { MOZ_ASSERT(NS_IsMainThread()); @@ -4161,9 +4109,7 @@ BluetoothDBusService::SendPlayStatus(int64_t aDuration, return; } - ControlPlayStatus playStatus = - PlayStatusStringToControlPlayStatus(aPlayStatus); - if (playStatus == ControlPlayStatus::PLAYSTATUS_UNKNOWN) { + if (aPlayStatus == ControlPlayStatus::PLAYSTATUS_UNKNOWN) { DispatchBluetoothReply(aRunnable, BluetoothValue(), NS_LITERAL_STRING("Invalid play status")); return; @@ -4186,9 +4132,9 @@ BluetoothDBusService::SendPlayStatus(int64_t aDuration, return; } - if (playStatus != avrcp->GetPlayStatus()) { + if (aPlayStatus != avrcp->GetPlayStatus()) { UpdateNotification(ControlEventId::EVENT_PLAYBACK_STATUS_CHANGED, - playStatus); + aPlayStatus); } else if (aPosition != avrcp->GetPosition()) { UpdateNotification(ControlEventId::EVENT_PLAYBACK_POS_CHANGED, aPosition); } @@ -4199,11 +4145,11 @@ BluetoothDBusService::SendPlayStatus(int64_t aDuration, Task* task = new SendPlayStatusTask(deviceAddress, aDuration, aPosition, - playStatus, + aPlayStatus, aRunnable); DispatchToDBusThread(task); - avrcp->UpdatePlayStatus(aDuration, aPosition, playStatus); + avrcp->UpdatePlayStatus(aDuration, aPosition, aPlayStatus); } static void @@ -4349,48 +4295,48 @@ BluetoothDBusService::UpdateNotification(ControlEventId aEventId, void BluetoothDBusService::StartLeScanInternal( - const nsTArray& aServiceUuids, + const nsTArray& aServiceUuids, BluetoothReplyRunnable* aRunnable) { } void BluetoothDBusService::StopLeScanInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, BluetoothReplyRunnable* aRunnable) { } void BluetoothDBusService::ConnectGattClientInternal( - const nsAString& aAppUuid, const nsAString& aDeviceAddress, + const BluetoothUuid& aAppUuid, const BluetoothAddress& aDeviceAddress, BluetoothReplyRunnable* aRunnable) { } void BluetoothDBusService::DisconnectGattClientInternal( - const nsAString& aAppUuid, const nsAString& aDeviceAddress, + const BluetoothUuid& aAppUuid, const BluetoothAddress& aDeviceAddress, BluetoothReplyRunnable* aRunnable) { } void BluetoothDBusService::DiscoverGattServicesInternal( - const nsAString& aAppUuid, BluetoothReplyRunnable* aRunnable) + const BluetoothUuid& aAppUuid, BluetoothReplyRunnable* aRunnable) { } void BluetoothDBusService::GattClientStartNotificationsInternal( - const nsAString& aAppUuid, const BluetoothGattServiceId& aServId, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServId, const BluetoothGattId& aCharId, BluetoothReplyRunnable* aRunnable) { } void BluetoothDBusService::GattClientStopNotificationsInternal( - const nsAString& aAppUuid, const BluetoothGattServiceId& aServId, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServId, const BluetoothGattId& aCharId, BluetoothReplyRunnable* aRunnable) { } @@ -4403,14 +4349,14 @@ BluetoothDBusService::UnregisterGattClientInternal( void BluetoothDBusService::GattClientReadRemoteRssiInternal( - int aClientIf, const nsAString& aDeviceAddress, + int aClientIf, const BluetoothAddress& aDeviceAddress, BluetoothReplyRunnable* aRunnable) { } void BluetoothDBusService::GattClientReadCharacteristicValueInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServiceId, const BluetoothGattId& aCharacteristicId, BluetoothReplyRunnable* aRunnable) @@ -4419,7 +4365,7 @@ BluetoothDBusService::GattClientReadCharacteristicValueInternal( void BluetoothDBusService::GattClientWriteCharacteristicValueInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServiceId, const BluetoothGattId& aCharacteristicId, const BluetoothGattWriteType& aWriteType, @@ -4430,7 +4376,7 @@ BluetoothDBusService::GattClientWriteCharacteristicValueInternal( void BluetoothDBusService::GattClientReadDescriptorValueInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServiceId, const BluetoothGattId& aCharacteristicId, const BluetoothGattId& aDescriptorId, @@ -4440,7 +4386,7 @@ BluetoothDBusService::GattClientReadDescriptorValueInternal( void BluetoothDBusService::GattClientWriteDescriptorValueInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServiceId, const BluetoothGattId& aCharacteristicId, const BluetoothGattId& aDescriptorId, @@ -4576,14 +4522,14 @@ BluetoothDBusService::ReplyTovCardListing( void BluetoothDBusService::GattServerConnectPeripheralInternal( - const nsAString& aAppUuid, const nsAString& aAddress, + const BluetoothUuid& aAppUuid, const BluetoothAddress& aAddress, BluetoothReplyRunnable* aRunnable) { } void BluetoothDBusService::GattServerDisconnectPeripheralInternal( - const nsAString& aAppUuid, const nsAString& aAddress, + const BluetoothUuid& aAppUuid, const BluetoothAddress& aAddress, BluetoothReplyRunnable* aRunnable) { } @@ -4596,7 +4542,7 @@ BluetoothDBusService::UnregisterGattServerInternal( void BluetoothDBusService::GattServerAddServiceInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServiceId, uint16_t aHandleCount, BluetoothReplyRunnable* aRunnable) @@ -4605,7 +4551,7 @@ BluetoothDBusService::GattServerAddServiceInternal( void BluetoothDBusService::GattServerAddIncludedServiceInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothAttributeHandle& aServiceHandle, const BluetoothAttributeHandle& aIncludedServiceHandle, BluetoothReplyRunnable* aRunnable) @@ -4614,7 +4560,7 @@ BluetoothDBusService::GattServerAddIncludedServiceInternal( void BluetoothDBusService::GattServerAddCharacteristicInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothAttributeHandle& aServiceHandle, const BluetoothUuid& aCharacteristicUuid, BluetoothGattAttrPerm aPermissions, @@ -4625,7 +4571,7 @@ BluetoothDBusService::GattServerAddCharacteristicInternal( void BluetoothDBusService::GattServerAddDescriptorInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothAttributeHandle& aServiceHandle, const BluetoothAttributeHandle& aCharacteristicHandle, const BluetoothUuid& aDescriptorUuid, @@ -4636,7 +4582,7 @@ BluetoothDBusService::GattServerAddDescriptorInternal( void BluetoothDBusService::GattServerRemoveServiceInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothAttributeHandle& aServiceHandle, BluetoothReplyRunnable* aRunnable) { @@ -4644,7 +4590,7 @@ BluetoothDBusService::GattServerRemoveServiceInternal( void BluetoothDBusService::GattServerStartServiceInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothAttributeHandle& aServiceHandle, BluetoothReplyRunnable* aRunnable) { @@ -4652,16 +4598,27 @@ BluetoothDBusService::GattServerStartServiceInternal( void BluetoothDBusService::GattServerStopServiceInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothAttributeHandle& aServiceHandle, BluetoothReplyRunnable* aRunnable) { } +void +BluetoothDBusService::GattServerSendIndicationInternal( + const BluetoothUuid& aAppUuid, + const BluetoothAddress& aAddress, + const BluetoothAttributeHandle& aCharacteristicHandle, + bool aConfirm, + const nsTArray& aValue, + BluetoothReplyRunnable* aRunnable) +{ +} + void BluetoothDBusService::GattServerSendResponseInternal( - const nsAString& aAppUuid, - const nsAString& aAddress, + const BluetoothUuid& aAppUuid, + const BluetoothAddress& aAddress, uint16_t aStatus, int32_t aRequestId, const BluetoothGattResponse& aRsp, diff --git a/dom/bluetooth/bluez/BluetoothDBusService.h b/dom/bluetooth/bluez/BluetoothDBusService.h index 474dd4db41..4ab4af6d24 100644 --- a/dom/bluetooth/bluez/BluetoothDBusService.h +++ b/dom/bluetooth/bluez/BluetoothDBusService.h @@ -59,11 +59,12 @@ public: uint16_t aServiceUuid, BluetoothReplyRunnable* aRunnable) override; virtual nsresult - GetPairedDevicePropertiesInternal(const nsTArray& aDeviceAddresses, - BluetoothReplyRunnable* aRunnable) override; + GetPairedDevicePropertiesInternal( + const nsTArray& aDeviceAddresses, + BluetoothReplyRunnable* aRunnable) override; virtual nsresult - FetchUuidsInternal(const nsAString& aDeviceAddress, + FetchUuidsInternal(const BluetoothAddress& aDeviceAddress, BluetoothReplyRunnable* aRunnable) override; virtual void @@ -87,65 +88,67 @@ public: BluetoothProfileManagerBase* aManager) override; virtual nsresult - CreatePairedDeviceInternal(const nsAString& aDeviceAddress, + CreatePairedDeviceInternal(const BluetoothAddress& aDeviceAddress, int aTimeout, BluetoothReplyRunnable* aRunnable) override; virtual nsresult - RemoveDeviceInternal(const nsAString& aDeviceObjectPath, + RemoveDeviceInternal(const BluetoothAddress& aDeviceAddress, BluetoothReplyRunnable* aRunnable) override; virtual void - PinReplyInternal(const nsAString& aDeviceAddress, + PinReplyInternal(const BluetoothAddress& aDeviceAddress, bool aAccept, - const nsAString& aPinCode, + const BluetoothPinCode& aPinCode, BluetoothReplyRunnable* aRunnable); virtual void - SspReplyInternal(const nsAString& aDeviceAddress, + SspReplyInternal(const BluetoothAddress& aDeviceAddress, BluetoothSspVariant aVariant, bool aAccept, BluetoothReplyRunnable* aRunnable); virtual void - SetPinCodeInternal(const nsAString& aDeviceAddress, const nsAString& aPinCode, + SetPinCodeInternal(const BluetoothAddress& aDeviceAddress, + const BluetoothPinCode& aPinCode, BluetoothReplyRunnable* aRunnable) override; virtual void - SetPasskeyInternal(const nsAString& aDeviceAddress, uint32_t aPasskey, + SetPasskeyInternal(const BluetoothAddress& aDeviceAddress, uint32_t aPasskey, BluetoothReplyRunnable* aRunnable) override; virtual void - SetPairingConfirmationInternal(const nsAString& aDeviceAddress, bool aConfirm, + SetPairingConfirmationInternal(const BluetoothAddress& aDeviceAddress, + bool aConfirm, BluetoothReplyRunnable* aRunnable) override; virtual void - Connect(const nsAString& aDeviceAddress, + Connect(const BluetoothAddress& aDeviceAddress, uint32_t aCod, uint16_t aServiceUuid, BluetoothReplyRunnable* aRunnable) override; virtual void - Disconnect(const nsAString& aDeviceAddress, uint16_t aServiceUuid, + Disconnect(const BluetoothAddress& aDeviceAddress, uint16_t aServiceUuid, BluetoothReplyRunnable* aRunnable) override; virtual void - SendFile(const nsAString& aDeviceAddress, + SendFile(const BluetoothAddress& aDeviceAddress, BlobParent* aBlobParent, BlobChild* aBlobChild, BluetoothReplyRunnable* aRunnable) override; virtual void - SendFile(const nsAString& aDeviceAddress, + SendFile(const BluetoothAddress& aDeviceAddress, Blob* aBlob, BluetoothReplyRunnable* aRunnable) override; virtual void - StopSendingFile(const nsAString& aDeviceAddress, + StopSendingFile(const BluetoothAddress& aDeviceAddress, BluetoothReplyRunnable* aRunnable) override; virtual void - ConfirmReceivingFile(const nsAString& aDeviceAddress, bool aConfirm, + ConfirmReceivingFile(const BluetoothAddress& aDeviceAddress, bool aConfirm, BluetoothReplyRunnable* aRunnable) override; virtual void @@ -265,7 +268,7 @@ public: virtual void SendPlayStatus(int64_t aDuration, int64_t aPosition, - const nsAString& aPlayStatus, + ControlPlayStatus aPlayStatus, BluetoothReplyRunnable* aRunnable) override; virtual void @@ -282,37 +285,37 @@ public: const nsAString& aMessage) override; virtual void - StartLeScanInternal(const nsTArray& aServiceUuids, + StartLeScanInternal(const nsTArray& aServiceUuids, BluetoothReplyRunnable* aRunnable) override; virtual void - StopLeScanInternal(const nsAString& aAppUuid, + StopLeScanInternal(const BluetoothUuid& aAppUuid, BluetoothReplyRunnable* aRunnable) override; virtual void - ConnectGattClientInternal(const nsAString& aAppUuid, - const nsAString& aDeviceAddress, + ConnectGattClientInternal(const BluetoothUuid& aAppUuid, + const BluetoothAddress& aDeviceAddress, BluetoothReplyRunnable* aRunnable) override; virtual void - DisconnectGattClientInternal(const nsAString& aAppUuid, - const nsAString& aDeviceAddress, + DisconnectGattClientInternal(const BluetoothUuid& aAppUuid, + const BluetoothAddress& aDeviceAddress, BluetoothReplyRunnable* aRunnable) override; virtual void - DiscoverGattServicesInternal(const nsAString& aAppUuid, + DiscoverGattServicesInternal(const BluetoothUuid& aAppUuid, BluetoothReplyRunnable* aRunnable) override; virtual void GattClientStartNotificationsInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServId, const BluetoothGattId& aCharId, BluetoothReplyRunnable* aRunnable) override; virtual void GattClientStopNotificationsInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServId, const BluetoothGattId& aCharId, BluetoothReplyRunnable* aRunnable) override; @@ -323,19 +326,19 @@ public: virtual void GattClientReadRemoteRssiInternal( - int aClientIf, const nsAString& aDeviceAddress, + int aClientIf, const BluetoothAddress& aDeviceAddress, BluetoothReplyRunnable* aRunnable) override; virtual void GattClientReadCharacteristicValueInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServiceId, const BluetoothGattId& aCharacteristicId, BluetoothReplyRunnable* aRunnable) override; virtual void GattClientWriteCharacteristicValueInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServiceId, const BluetoothGattId& aCharacteristicId, const BluetoothGattWriteType& aWriteType, @@ -344,7 +347,7 @@ public: virtual void GattClientReadDescriptorValueInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServiceId, const BluetoothGattId& aCharacteristicId, const BluetoothGattId& aDescriptorId, @@ -352,7 +355,7 @@ public: virtual void GattClientWriteDescriptorValueInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServiceId, const BluetoothGattId& aCharacteristicId, const BluetoothGattId& aDescriptorId, @@ -361,14 +364,14 @@ public: virtual void GattServerConnectPeripheralInternal( - const nsAString& aAppUuid, - const nsAString& aAddress, + const BluetoothUuid& aAppUuid, + const BluetoothAddress& aAddress, BluetoothReplyRunnable* aRunnable) override; virtual void GattServerDisconnectPeripheralInternal( - const nsAString& aAppUuid, - const nsAString& aAddress, + const BluetoothUuid& aAppUuid, + const BluetoothAddress& aAddress, BluetoothReplyRunnable* aRunnable) override; virtual void @@ -377,21 +380,21 @@ public: virtual void GattServerAddServiceInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServiceId, uint16_t aHandleCount, BluetoothReplyRunnable* aRunnable) override; virtual void GattServerAddIncludedServiceInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothAttributeHandle& aServiceHandle, const BluetoothAttributeHandle& aIncludedServiceHandle, BluetoothReplyRunnable* aRunnable) override; virtual void GattServerAddCharacteristicInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothAttributeHandle& aServiceHandle, const BluetoothUuid& aCharacteristicUuid, BluetoothGattAttrPerm aPermissions, @@ -400,7 +403,7 @@ public: virtual void GattServerAddDescriptorInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothAttributeHandle& aServiceHandle, const BluetoothAttributeHandle& aCharacteristicHandle, const BluetoothUuid& aDescriptorUuid, @@ -409,31 +412,40 @@ public: virtual void GattServerRemoveServiceInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothAttributeHandle& aServiceHandle, BluetoothReplyRunnable* aRunnable) override; virtual void GattServerStartServiceInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothAttributeHandle& aServiceHandle, BluetoothReplyRunnable* aRunnable) override; virtual void GattServerStopServiceInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothAttributeHandle& aServiceHandle, BluetoothReplyRunnable* aRunnable) override; virtual void GattServerSendResponseInternal( - const nsAString& aAppUuid, - const nsAString& aAddress, + const BluetoothUuid& aAppUuid, + const BluetoothAddress& aAddress, uint16_t aStatus, int32_t aRequestId, const BluetoothGattResponse& aRsp, BluetoothReplyRunnable* aRunnable) override; + virtual void + GattServerSendIndicationInternal( + const BluetoothUuid& aAppUuid, + const BluetoothAddress& aAddress, + const BluetoothAttributeHandle& aCharacteristicHandle, + bool aConfirm, + const nsTArray& aValue, + BluetoothReplyRunnable* aRunnable) override; + private: nsresult SendGetPropertyMessage(const nsAString& aPath, const char* aInterface, diff --git a/dom/bluetooth/bluez/BluetoothHfpManager.h b/dom/bluetooth/bluez/BluetoothHfpManager.h index b439e0d953..2aec3cfbd9 100644 --- a/dom/bluetooth/bluez/BluetoothHfpManager.h +++ b/dom/bluetooth/bluez/BluetoothHfpManager.h @@ -87,7 +87,6 @@ public: } static BluetoothHfpManager* Get(); - bool Listen(); /** @@ -104,7 +103,6 @@ public: */ bool ConnectSco(BluetoothReplyRunnable* aRunnable = nullptr); bool DisconnectSco(); - bool IsNrecEnabled(); bool ListenSco(); #ifdef MOZ_B2G_RIL diff --git a/dom/bluetooth/common/BluetoothCommon.cpp b/dom/bluetooth/common/BluetoothCommon.cpp index 6fbd19d09f..28161db8de 100644 --- a/dom/bluetooth/common/BluetoothCommon.cpp +++ b/dom/bluetooth/common/BluetoothCommon.cpp @@ -6,6 +6,10 @@ #include "BluetoothCommon.h" +// FIXME: Bug 1224171: This variable needs to be cleaned up and +// remove from global namespace. +bool gBluetoothDebugFlag = false; + BEGIN_BLUETOOTH_NAMESPACE // diff --git a/dom/bluetooth/common/BluetoothCommon.h b/dom/bluetooth/common/BluetoothCommon.h index b918a8581f..ecf5dd56df 100644 --- a/dom/bluetooth/common/BluetoothCommon.h +++ b/dom/bluetooth/common/BluetoothCommon.h @@ -263,7 +263,7 @@ extern bool gBluetoothDebugFlag; #define MAP_MESSAGES_LISTING_REQ_ID "mapmessageslistingreq" #define MAP_GET_MESSAGE_REQ_ID "mapgetmessagereq" #define MAP_SET_MESSAGE_STATUS_REQ_ID "mapsetmessagestatusreq" -#define MAP_PUSH_MESSAGE_REQ_ID "mappushmessagereq" +#define MAP_SEND_MESSAGE_REQ_ID "mapsendmessagereq" #define MAP_FOLDER_LISTING_REQ_ID "mapfolderlistingreq" #define MAP_MESSAGE_UPDATE_REQ_ID "mapmessageupdatereq" @@ -320,6 +320,7 @@ enum BluetoothStatus { STATUS_UNHANDLED, STATUS_AUTH_FAILURE, STATUS_RMT_DEV_DOWN, + STATUS_AUTH_REJECTED, NUM_STATUS }; @@ -334,6 +335,30 @@ enum BluetoothBondState { BOND_STATE_BONDED }; +enum BluetoothSetupServiceId { + SETUP_SERVICE_ID_SETUP, + SETUP_SERVICE_ID_CORE, + SETUP_SERVICE_ID_SOCKET, + SETUP_SERVICE_ID_HID, + SETUP_SERVICE_ID_PAN, + SETUP_SERVICE_ID_HANDSFREE, + SETUP_SERVICE_ID_A2DP, + SETUP_SERVICE_ID_HEALTH, + SETUP_SERVICE_ID_AVRCP, + SETUP_SERVICE_ID_GATT, + SETUP_SERVICE_ID_HANDSFREE_CLIENT, + SETUP_SERVICE_ID_MAP_CLIENT, + SETUP_SERVICE_ID_AVRCP_CONTROLLER, + SETUP_SERVICE_ID_A2DP_SINK +}; + +/* Physical transport for GATT connections to remote dual-mode devices */ +enum BluetoothTransport { + TRANSPORT_AUTO, /* No preference of physical transport */ + TRANSPORT_BREDR, /* Prefer BR/EDR transport */ + TRANSPORT_LE /* Prefer LE transport */ +}; + enum BluetoothTypeOfDevice { TYPE_OF_DEVICE_BREDR, TYPE_OF_DEVICE_BLE, @@ -650,6 +675,24 @@ struct BluetoothUuid { struct BluetoothPinCode { uint8_t mPinCode[16]; /* not \0-terminated */ uint8_t mLength; + + BluetoothPinCode() + : mLength(0) + { + std::fill(mPinCode, mPinCode + MOZ_ARRAY_LENGTH(mPinCode), 0); + } + + bool operator==(const BluetoothPinCode& aRhs) const + { + MOZ_ASSERT(mLength <= MOZ_ARRAY_LENGTH(mPinCode)); + return (mLength == aRhs.mLength) && + std::equal(aRhs.mPinCode, aRhs.mPinCode + aRhs.mLength, mPinCode); + } + + bool operator!=(const BluetoothPinCode& aRhs) const + { + return !operator==(aRhs); + } }; struct BluetoothServiceName { @@ -710,6 +753,68 @@ struct BluetoothProperty { /* PROPERTY_REMOTE_VERSION_INFO */ BluetoothRemoteInfo mRemoteInfo; + + BluetoothProperty() + : mType(PROPERTY_UNKNOWN) + { } + + explicit BluetoothProperty(BluetoothPropertyType aType, + const BluetoothAddress& aBdAddress) + : mType(aType) + , mBdAddress(aBdAddress) + { } + + explicit BluetoothProperty(BluetoothPropertyType aType, + const nsAString& aString) + : mType(aType) + , mString(aString) + { } + + explicit BluetoothProperty(BluetoothPropertyType aType, + const nsTArray& aUuidArray) + : mType(aType) + , mUuidArray(aUuidArray) + { } + + explicit BluetoothProperty(BluetoothPropertyType aType, + const nsTArray& aBdAddressArray) + : mType(aType) + , mBdAddressArray(aBdAddressArray) + { } + + explicit BluetoothProperty(BluetoothPropertyType aType, uint32_t aUint32) + : mType(aType) + , mUint32(aUint32) + { } + + explicit BluetoothProperty(BluetoothPropertyType aType, int32_t aInt32) + : mType(aType) + , mInt32(aInt32) + { } + + explicit BluetoothProperty(BluetoothPropertyType aType, + BluetoothTypeOfDevice aTypeOfDevice) + : mType(aType) + , mTypeOfDevice(aTypeOfDevice) + { } + + explicit BluetoothProperty(BluetoothPropertyType aType, + const BluetoothServiceRecord& aServiceRecord) + : mType(aType) + , mServiceRecord(aServiceRecord) + { } + + explicit BluetoothProperty(BluetoothPropertyType aType, + BluetoothScanMode aScanMode) + : mType(aType) + , mScanMode(aScanMode) + { } + + explicit BluetoothProperty(BluetoothPropertyType aType, + const BluetoothRemoteInfo& aRemoteInfo) + : mType(aType) + , mRemoteInfo(aRemoteInfo) + { } }; enum BluetoothSocketType { diff --git a/dom/bluetooth/common/BluetoothHfpManagerBase.h b/dom/bluetooth/common/BluetoothHfpManagerBase.h index 504840f955..9c58023840 100644 --- a/dom/bluetooth/common/BluetoothHfpManagerBase.h +++ b/dom/bluetooth/common/BluetoothHfpManagerBase.h @@ -24,7 +24,8 @@ public: #define BT_DECL_HFP_MGR_BASE \ BT_DECL_PROFILE_MGR_BASE \ - virtual bool IsScoConnected() override; + virtual bool IsScoConnected() override; \ + virtual bool IsNrecEnabled() override; END_BLUETOOTH_NAMESPACE diff --git a/dom/bluetooth/common/BluetoothInterface.cpp b/dom/bluetooth/common/BluetoothInterface.cpp index d784f8ab82..0dbb73f3f7 100644 --- a/dom/bluetooth/common/BluetoothInterface.cpp +++ b/dom/bluetooth/common/BluetoothInterface.cpp @@ -45,6 +45,193 @@ BluetoothSetupResultHandler::Configuration() BluetoothSetupInterface::~BluetoothSetupInterface() { } +// +// Bluetooth Core Interface +// + +// Notification handling +// + +BluetoothCoreNotificationHandler::BluetoothCoreNotificationHandler() +{ } + +BluetoothCoreNotificationHandler::~BluetoothCoreNotificationHandler() +{ } + +void +BluetoothCoreNotificationHandler::AdapterStateChangedNotification(bool aState) +{ } + +void +BluetoothCoreNotificationHandler::AdapterPropertiesNotification( + BluetoothStatus aStatus,int aNumProperties, + const BluetoothProperty* aProperties) +{ } + +void +BluetoothCoreNotificationHandler::RemoteDevicePropertiesNotification( + BluetoothStatus aStatus, const BluetoothAddress& aBdAddr, + int aNumProperties, const BluetoothProperty* aProperties) +{ } + +void +BluetoothCoreNotificationHandler::DeviceFoundNotification( + int aNumProperties, const BluetoothProperty* aProperties) +{ } + +void +BluetoothCoreNotificationHandler::DiscoveryStateChangedNotification( + bool aState) +{ } + +void +BluetoothCoreNotificationHandler::PinRequestNotification( + const BluetoothAddress& aRemoteBdAddr, const BluetoothRemoteName& aBdName, + uint32_t aCod) +{ } + +void +BluetoothCoreNotificationHandler::SspRequestNotification( + const BluetoothAddress& aRemoteBdAddr, const BluetoothRemoteName& aBdName, + uint32_t aCod, BluetoothSspVariant aPairingVariant, uint32_t aPassKey) +{ } + +void +BluetoothCoreNotificationHandler::BondStateChangedNotification( + BluetoothStatus aStatus, const BluetoothAddress& aRemoteBdAddr, + BluetoothBondState aState) +{ } + +void +BluetoothCoreNotificationHandler::AclStateChangedNotification( + BluetoothStatus aStatus, const BluetoothAddress& aRemoteBdAddr, + BluetoothAclState aState) +{ } + +void +BluetoothCoreNotificationHandler::DutModeRecvNotification( + uint16_t aOpcode, + const uint8_t* aBuf, + uint8_t aLen) +{ } + +void +BluetoothCoreNotificationHandler::LeTestModeNotification( + BluetoothStatus aStatus, + uint16_t aNumPackets) +{ } + +void +BluetoothCoreNotificationHandler::EnergyInfoNotification( + const BluetoothActivityEnergyInfo& aInfo) +{ } + +// Result handling +// + +void +BluetoothCoreResultHandler::OnError(BluetoothStatus aStatus) +{ + BT_LOGR("Received error code %d", aStatus); +} + +void +BluetoothCoreResultHandler::Enable() +{ } + +void +BluetoothCoreResultHandler::Disable() +{ } + +void +BluetoothCoreResultHandler::GetAdapterProperties() +{ } + +void +BluetoothCoreResultHandler::GetAdapterProperty() +{ } + +void +BluetoothCoreResultHandler::SetAdapterProperty() +{ } + +void +BluetoothCoreResultHandler::GetRemoteDeviceProperties() +{ } + +void +BluetoothCoreResultHandler::GetRemoteDeviceProperty() +{ } + +void +BluetoothCoreResultHandler::SetRemoteDeviceProperty() +{ } + +void +BluetoothCoreResultHandler::GetRemoteServiceRecord() +{ } + +void +BluetoothCoreResultHandler::GetRemoteServices() +{ } + +void +BluetoothCoreResultHandler::StartDiscovery() +{ } + +void +BluetoothCoreResultHandler::CancelDiscovery() +{ } + +void +BluetoothCoreResultHandler::CreateBond() +{ } + +void +BluetoothCoreResultHandler::RemoveBond() +{ } + +void +BluetoothCoreResultHandler::CancelBond() +{ } + +void +BluetoothCoreResultHandler::GetConnectionState() +{ } + +void +BluetoothCoreResultHandler::PinReply() +{ } + +void +BluetoothCoreResultHandler::SspReply() +{ } + +void +BluetoothCoreResultHandler::DutModeConfigure() +{ } + +void +BluetoothCoreResultHandler::DutModeSend() +{ } + +void +BluetoothCoreResultHandler::LeTestMode() +{ } + +void +BluetoothCoreResultHandler::ReadEnergyInfo() +{ } + +// Interface +// + +BluetoothCoreInterface::BluetoothCoreInterface() +{ } + +BluetoothCoreInterface::~BluetoothCoreInterface() +{ } + // // Socket Interface // @@ -187,14 +374,6 @@ BluetoothHandsfreeResultHandler::OnError(BluetoothStatus aStatus) BT_WARNING("Received error code %d", (int)aStatus); } -void -BluetoothHandsfreeResultHandler::Init() -{ } - -void -BluetoothHandsfreeResultHandler::Cleanup() -{ } - void BluetoothHandsfreeResultHandler::Connect() { } @@ -301,14 +480,6 @@ BluetoothA2dpResultHandler::OnError(BluetoothStatus aStatus) BT_WARNING("Received error code %d", (int)aStatus); } -void -BluetoothA2dpResultHandler::Init() -{ } - -void -BluetoothA2dpResultHandler::Cleanup() -{ } - void BluetoothA2dpResultHandler::Connect() { } @@ -384,7 +555,7 @@ BluetoothAvrcpNotificationHandler::RegisterNotificationNotification( void BluetoothAvrcpNotificationHandler::RemoteFeatureNotification( - const nsAString& aBdAddr, unsigned long aFeatures) + const BluetoothAddress& aBdAddr, unsigned long aFeatures) { } void @@ -406,14 +577,6 @@ BluetoothAvrcpResultHandler::OnError(BluetoothStatus aStatus) BT_WARNING("Received error code %d", (int)aStatus); } -void -BluetoothAvrcpResultHandler::Init() -{ } - -void -BluetoothAvrcpResultHandler::Cleanup() -{ } - void BluetoothAvrcpResultHandler::GetPlayStatusRsp() { } @@ -685,14 +848,6 @@ BluetoothGattResultHandler::OnError(BluetoothStatus aStatus) BT_WARNING("Received error code %d", (int)aStatus); } -void -BluetoothGattResultHandler::Init() -{ } - -void -BluetoothGattResultHandler::Cleanup() -{ } - void BluetoothGattResultHandler::RegisterClient() { } @@ -843,7 +998,7 @@ BluetoothGattInterface::~BluetoothGattInterface() { } // -// Bluetooth Core Interface +// Bluetooth Interface // // Notification handling @@ -855,71 +1010,6 @@ BluetoothNotificationHandler::BluetoothNotificationHandler() BluetoothNotificationHandler::~BluetoothNotificationHandler() { } -void -BluetoothNotificationHandler::AdapterStateChangedNotification(bool aState) -{ } - -void -BluetoothNotificationHandler::AdapterPropertiesNotification( - BluetoothStatus aStatus,int aNumProperties, - const BluetoothProperty* aProperties) -{ } - -void -BluetoothNotificationHandler::RemoteDevicePropertiesNotification( - BluetoothStatus aStatus, const BluetoothAddress& aBdAddr, - int aNumProperties, const BluetoothProperty* aProperties) -{ } - -void -BluetoothNotificationHandler::DeviceFoundNotification( - int aNumProperties, const BluetoothProperty* aProperties) -{ } - -void -BluetoothNotificationHandler::DiscoveryStateChangedNotification(bool aState) -{ } - -void -BluetoothNotificationHandler::PinRequestNotification( - const BluetoothAddress& aRemoteBdAddr, const BluetoothRemoteName& aBdName, - uint32_t aCod) -{ } - -void -BluetoothNotificationHandler::SspRequestNotification( - const BluetoothAddress& aRemoteBdAddr, const BluetoothRemoteName& aBdName, - uint32_t aCod, BluetoothSspVariant aPairingVariant, uint32_t aPassKey) -{ } - -void -BluetoothNotificationHandler::BondStateChangedNotification( - BluetoothStatus aStatus, const BluetoothAddress& aRemoteBdAddr, - BluetoothBondState aState) -{ } - -void -BluetoothNotificationHandler::AclStateChangedNotification( - BluetoothStatus aStatus, const BluetoothAddress& aRemoteBdAddr, - BluetoothAclState aState) -{ } - -void -BluetoothNotificationHandler::DutModeRecvNotification(uint16_t aOpcode, - const uint8_t* aBuf, - uint8_t aLen) -{ } - -void -BluetoothNotificationHandler::LeTestModeNotification(BluetoothStatus aStatus, - uint16_t aNumPackets) -{ } - -void -BluetoothNotificationHandler::EnergyInfoNotification( - const BluetoothActivityEnergyInfo& aInfo) -{ } - void BluetoothNotificationHandler::BackendErrorNotification(bool aCrashed) { } @@ -941,94 +1031,6 @@ void BluetoothResultHandler::Cleanup() { } -void -BluetoothResultHandler::Enable() -{ } - -void -BluetoothResultHandler::Disable() -{ } - -void -BluetoothResultHandler::GetAdapterProperties() -{ } - -void -BluetoothResultHandler::GetAdapterProperty() -{ } - -void -BluetoothResultHandler::SetAdapterProperty() -{ } - -void -BluetoothResultHandler::GetRemoteDeviceProperties() -{ } - -void -BluetoothResultHandler::GetRemoteDeviceProperty() -{ } - -void -BluetoothResultHandler::SetRemoteDeviceProperty() -{ } - -void -BluetoothResultHandler::GetRemoteServiceRecord() -{ } - -void -BluetoothResultHandler::GetRemoteServices() -{ } - -void -BluetoothResultHandler::StartDiscovery() -{ } - -void -BluetoothResultHandler::CancelDiscovery() -{ } - -void -BluetoothResultHandler::CreateBond() -{ } - -void -BluetoothResultHandler::RemoveBond() -{ } - -void -BluetoothResultHandler::CancelBond() -{ } - -void -BluetoothResultHandler::GetConnectionState() -{ } - -void -BluetoothResultHandler::PinReply() -{ } - -void -BluetoothResultHandler::SspReply() -{ } - -void -BluetoothResultHandler::DutModeConfigure() -{ } - -void -BluetoothResultHandler::DutModeSend() -{ } - -void -BluetoothResultHandler::LeTestMode() -{ } - -void -BluetoothResultHandler::ReadEnergyInfo() -{ } - // Interface // diff --git a/dom/bluetooth/common/BluetoothInterface.h b/dom/bluetooth/common/BluetoothInterface.h index de5996460b..a8c798268c 100644 --- a/dom/bluetooth/common/BluetoothInterface.h +++ b/dom/bluetooth/common/BluetoothInterface.h @@ -33,12 +33,12 @@ protected: class BluetoothSetupInterface { public: - virtual void RegisterModule(uint8_t aId, + virtual void RegisterModule(BluetoothSetupServiceId aId, uint8_t aMode, uint32_t aMaxNumClients, BluetoothSetupResultHandler* aRes) = 0; - virtual void UnregisterModule(uint8_t aId, + virtual void UnregisterModule(BluetoothSetupServiceId aId, BluetoothSetupResultHandler* aRes) = 0; virtual void Configuration(const BluetoothConfigurationParameter* aParam, @@ -49,6 +49,188 @@ protected: virtual ~BluetoothSetupInterface(); }; +// +// Bluetooth Core Interface +// + +class BluetoothCoreNotificationHandler +{ +public: + virtual void AdapterStateChangedNotification(bool aState); + virtual void AdapterPropertiesNotification( + BluetoothStatus aStatus, int aNumProperties, + const BluetoothProperty* aProperties); + + virtual void RemoteDevicePropertiesNotification( + BluetoothStatus aStatus, const BluetoothAddress& aBdAddr, + int aNumProperties, const BluetoothProperty* aProperties); + + virtual void DeviceFoundNotification( + int aNumProperties, const BluetoothProperty* aProperties); + + virtual void DiscoveryStateChangedNotification(bool aState); + + virtual void PinRequestNotification(const BluetoothAddress& aRemoteBdAddr, + const BluetoothRemoteName& aBdName, + uint32_t aCod); + virtual void SspRequestNotification(const BluetoothAddress& aRemoteBdAddr, + const BluetoothRemoteName& aBdName, + uint32_t aCod, + BluetoothSspVariant aPairingVariant, + uint32_t aPassKey); + + virtual void BondStateChangedNotification( + BluetoothStatus aStatus, const BluetoothAddress& aRemoteBdAddr, + BluetoothBondState aState); + virtual void AclStateChangedNotification( + BluetoothStatus aStatus, const BluetoothAddress& aRemoteBdAddr, + BluetoothAclState aState); + + virtual void DutModeRecvNotification(uint16_t aOpcode, + const uint8_t* aBuf, uint8_t aLen); + virtual void LeTestModeNotification(BluetoothStatus aStatus, + uint16_t aNumPackets); + + virtual void EnergyInfoNotification(const BluetoothActivityEnergyInfo& aInfo); + +protected: + BluetoothCoreNotificationHandler(); + virtual ~BluetoothCoreNotificationHandler(); +}; + +class BluetoothCoreResultHandler + : public mozilla::ipc::DaemonSocketResultHandler +{ +public: + virtual void OnError(BluetoothStatus aStatus); + + virtual void Enable(); + virtual void Disable(); + + virtual void GetAdapterProperties(); + virtual void GetAdapterProperty(); + virtual void SetAdapterProperty(); + + virtual void GetRemoteDeviceProperties(); + virtual void GetRemoteDeviceProperty(); + virtual void SetRemoteDeviceProperty(); + + virtual void GetRemoteServiceRecord(); + virtual void GetRemoteServices(); + + virtual void StartDiscovery(); + virtual void CancelDiscovery(); + + virtual void CreateBond(); + virtual void RemoveBond(); + virtual void CancelBond(); + + virtual void GetConnectionState(); + + virtual void PinReply(); + virtual void SspReply(); + + virtual void DutModeConfigure(); + virtual void DutModeSend(); + + virtual void LeTestMode(); + + virtual void ReadEnergyInfo(); + +protected: + virtual ~BluetoothCoreResultHandler() { } +}; + +class BluetoothCoreInterface +{ +public: + virtual void SetNotificationHandler( + BluetoothCoreNotificationHandler* aNotificationHandler) = 0; + + /* Enable/Disable */ + + virtual void Enable(BluetoothCoreResultHandler* aRes) = 0; + virtual void Disable(BluetoothCoreResultHandler* aRes) = 0; + + /* Adapter Properties */ + + virtual void GetAdapterProperties(BluetoothCoreResultHandler* aRes) = 0; + virtual void GetAdapterProperty(BluetoothPropertyType, + BluetoothCoreResultHandler* aRes) = 0; + virtual void SetAdapterProperty(const BluetoothProperty& aProperty, + BluetoothCoreResultHandler* aRes) = 0; + + /* Remote Device Properties */ + + virtual void GetRemoteDeviceProperties(const BluetoothAddress& aRemoteAddr, + BluetoothCoreResultHandler* aRes) = 0; + virtual void GetRemoteDeviceProperty(const BluetoothAddress& aRemoteAddr, + BluetoothPropertyType aType, + BluetoothCoreResultHandler* aRes) = 0; + virtual void SetRemoteDeviceProperty(const BluetoothAddress& aRemoteAddr, + const BluetoothProperty& aProperty, + BluetoothCoreResultHandler* aRes) = 0; + + /* Remote Services */ + + virtual void GetRemoteServiceRecord(const BluetoothAddress& aRemoteAddr, + const BluetoothUuid& aUuid, + BluetoothCoreResultHandler* aRes) = 0; + virtual void GetRemoteServices(const BluetoothAddress& aRemoteAddr, + BluetoothCoreResultHandler* aRes) = 0; + + /* Discovery */ + + virtual void StartDiscovery(BluetoothCoreResultHandler* aRes) = 0; + virtual void CancelDiscovery(BluetoothCoreResultHandler* aRes) = 0; + + /* Bonds */ + + virtual void CreateBond(const BluetoothAddress& aBdAddr, + BluetoothTransport aTransport, + BluetoothCoreResultHandler* aRes) = 0; + virtual void RemoveBond(const BluetoothAddress& aBdAddr, + BluetoothCoreResultHandler* aRes) = 0; + virtual void CancelBond(const BluetoothAddress& aBdAddr, + BluetoothCoreResultHandler* aRes) = 0; + + /* Connection */ + + virtual void GetConnectionState(const BluetoothAddress& aBdAddr, + BluetoothCoreResultHandler* aRes) = 0; + + /* Authentication */ + + virtual void PinReply(const BluetoothAddress& aBdAddr, bool aAccept, + const BluetoothPinCode& aPinCode, + BluetoothCoreResultHandler* aRes) = 0; + + virtual void SspReply(const BluetoothAddress& aBdAddr, + BluetoothSspVariant aVariant, + bool aAccept, uint32_t aPasskey, + BluetoothCoreResultHandler* aRes) = 0; + + /* DUT Mode */ + + virtual void DutModeConfigure(bool aEnable, + BluetoothCoreResultHandler* aRes) = 0; + virtual void DutModeSend(uint16_t aOpcode, uint8_t* aBuf, uint8_t aLen, + BluetoothCoreResultHandler* aRes) = 0; + + /* LE Mode */ + + virtual void LeTestMode(uint16_t aOpcode, uint8_t* aBuf, uint8_t aLen, + BluetoothCoreResultHandler* aRes) = 0; + + /* Energy Info */ + + virtual void ReadEnergyInfo(BluetoothCoreResultHandler* aRes) = 0; + +protected: + BluetoothCoreInterface(); + virtual ~BluetoothCoreInterface(); +}; + // // Socket Interface // @@ -174,9 +356,6 @@ class BluetoothHandsfreeResultHandler public: virtual void OnError(BluetoothStatus aStatus); - virtual void Init(); - virtual void Cleanup(); - virtual void Connect(); virtual void Disconnect(); virtual void ConnectAudio(); @@ -205,10 +384,8 @@ protected: class BluetoothHandsfreeInterface { public: - virtual void Init( - BluetoothHandsfreeNotificationHandler* aNotificationHandler, - int aMaxNumClients, BluetoothHandsfreeResultHandler* aRes) = 0; - virtual void Cleanup(BluetoothHandsfreeResultHandler* aRes) = 0; + virtual void SetNotificationHandler( + BluetoothHandsfreeNotificationHandler* aNotificationHandler) = 0; /* Connect / Disconnect */ @@ -314,8 +491,6 @@ class BluetoothA2dpResultHandler public: virtual void OnError(BluetoothStatus aStatus); - virtual void Init(); - virtual void Cleanup(); virtual void Connect(); virtual void Disconnect(); @@ -326,9 +501,8 @@ protected: class BluetoothA2dpInterface { public: - virtual void Init(BluetoothA2dpNotificationHandler* aNotificationHandler, - BluetoothA2dpResultHandler* aRes) = 0; - virtual void Cleanup(BluetoothA2dpResultHandler* aRes) = 0; + virtual void SetNotificationHandler( + BluetoothA2dpNotificationHandler* aNotificationHandler) = 0; virtual void Connect(const BluetoothAddress& aBdAddr, BluetoothA2dpResultHandler* aRes) = 0; @@ -381,7 +555,7 @@ public: uint32_t aParam); virtual void - RemoteFeatureNotification(const nsAString& aBdAddr, + RemoteFeatureNotification(const BluetoothAddress& aBdAddr, unsigned long aFeatures); virtual void @@ -401,9 +575,6 @@ class BluetoothAvrcpResultHandler public: virtual void OnError(BluetoothStatus aStatus); - virtual void Init(); - virtual void Cleanup(); - virtual void GetPlayStatusRsp(); virtual void ListPlayerAppAttrRsp(); @@ -428,9 +599,8 @@ protected: class BluetoothAvrcpInterface { public: - virtual void Init(BluetoothAvrcpNotificationHandler* aNotificationHandler, - BluetoothAvrcpResultHandler* aRes) = 0; - virtual void Cleanup(BluetoothAvrcpResultHandler* aRes) = 0; + virtual void SetNotificationHandler( + BluetoothAvrcpNotificationHandler* aNotificationHandler) = 0; virtual void GetPlayStatusRsp(ControlPlayStatus aPlayStatus, uint32_t aSongLen, uint32_t aSongPos, @@ -682,9 +852,6 @@ class BluetoothGattResultHandler public: virtual void OnError(BluetoothStatus aStatus); - virtual void Init(); - virtual void Cleanup(); - virtual void RegisterClient(); virtual void UnregisterClient(); @@ -742,9 +909,8 @@ protected: class BluetoothGattInterface { public: - virtual void Init(BluetoothGattNotificationHandler* aNotificationHandler, - BluetoothGattResultHandler* aRes) = 0; - virtual void Cleanup(BluetoothGattResultHandler* aRes) = 0; + virtual void SetNotificationHandler( + BluetoothGattNotificationHandler* aNotificationHandler) = 0; /* Register / Unregister */ virtual void RegisterClient(const BluetoothUuid& aUuid, @@ -926,13 +1092,13 @@ public: BluetoothGattResultHandler* aRes) = 0; /* Send an indication or a notification */ - virtual void SendIndication(int aServerIf, - int aAttributeHandle, - int aConnId, - const nsTArray& aValue, - bool aConfirm, /* true: indication */ - /* false: notification */ - BluetoothGattResultHandler* aRes) = 0; + virtual void SendIndication( + int aServerIf, + const BluetoothAttributeHandle& aCharacteristicHandle, + int aConnId, + const nsTArray& aValue, + bool aConfirm, /* true: indication; false: notification */ + BluetoothGattResultHandler* aRes) = 0; /* Send a response for an incoming indication */ virtual void SendResponse(int aConnId, @@ -947,49 +1113,12 @@ protected: }; // -// Bluetooth Core Interface +// Bluetooth Interface // class BluetoothNotificationHandler { public: - virtual void AdapterStateChangedNotification(bool aState); - virtual void AdapterPropertiesNotification( - BluetoothStatus aStatus, int aNumProperties, - const BluetoothProperty* aProperties); - - virtual void RemoteDevicePropertiesNotification( - BluetoothStatus aStatus, const BluetoothAddress& aBdAddr, - int aNumProperties, const BluetoothProperty* aProperties); - - virtual void DeviceFoundNotification( - int aNumProperties, const BluetoothProperty* aProperties); - - virtual void DiscoveryStateChangedNotification(bool aState); - - virtual void PinRequestNotification(const BluetoothAddress& aRemoteBdAddr, - const BluetoothRemoteName& aBdName, - uint32_t aCod); - virtual void SspRequestNotification(const BluetoothAddress& aRemoteBdAddr, - const BluetoothRemoteName& aBdName, - uint32_t aCod, - BluetoothSspVariant aPairingVariant, - uint32_t aPassKey); - - virtual void BondStateChangedNotification( - BluetoothStatus aStatus, const BluetoothAddress& aRemoteBdAddr, - BluetoothBondState aState); - virtual void AclStateChangedNotification( - BluetoothStatus aStatus, const BluetoothAddress& aRemoteBdAddr, - BluetoothAclState aState); - - virtual void DutModeRecvNotification(uint16_t aOpcode, - const uint8_t* aBuf, uint8_t aLen); - virtual void LeTestModeNotification(BluetoothStatus aStatus, - uint16_t aNumPackets); - - virtual void EnergyInfoNotification(const BluetoothActivityEnergyInfo& aInfo); - virtual void BackendErrorNotification(bool aCrashed); protected: @@ -1005,38 +1134,6 @@ public: virtual void Init(); virtual void Cleanup(); - virtual void Enable(); - virtual void Disable(); - - virtual void GetAdapterProperties(); - virtual void GetAdapterProperty(); - virtual void SetAdapterProperty(); - - virtual void GetRemoteDeviceProperties(); - virtual void GetRemoteDeviceProperty(); - virtual void SetRemoteDeviceProperty(); - - virtual void GetRemoteServiceRecord(); - virtual void GetRemoteServices(); - - virtual void StartDiscovery(); - virtual void CancelDiscovery(); - - virtual void CreateBond(); - virtual void RemoveBond(); - virtual void CancelBond(); - - virtual void GetConnectionState(); - - virtual void PinReply(); - virtual void SspReply(); - - virtual void DutModeConfigure(); - virtual void DutModeSend(); - - virtual void LeTestMode(); - - virtual void ReadEnergyInfo(); protected: virtual ~BluetoothResultHandler() { } @@ -1051,86 +1148,10 @@ public: BluetoothResultHandler* aRes) = 0; virtual void Cleanup(BluetoothResultHandler* aRes) = 0; - virtual void Enable(BluetoothResultHandler* aRes) = 0; - virtual void Disable(BluetoothResultHandler* aRes) = 0; - - /* Adapter Properties */ - - virtual void GetAdapterProperties(BluetoothResultHandler* aRes) = 0; - virtual void GetAdapterProperty(const nsAString& aName, - BluetoothResultHandler* aRes) = 0; - virtual void SetAdapterProperty(const BluetoothNamedValue& aProperty, - BluetoothResultHandler* aRes) = 0; - - /* Remote Device Properties */ - - virtual void GetRemoteDeviceProperties(const BluetoothAddress& aRemoteAddr, - BluetoothResultHandler* aRes) = 0; - virtual void GetRemoteDeviceProperty(const BluetoothAddress& aRemoteAddr, - const nsAString& aName, - BluetoothResultHandler* aRes) = 0; - virtual void SetRemoteDeviceProperty(const BluetoothAddress& aRemoteAddr, - const BluetoothNamedValue& aProperty, - BluetoothResultHandler* aRes) = 0; - - /* Remote Services */ - - virtual void GetRemoteServiceRecord(const BluetoothAddress& aRemoteAddr, - const BluetoothUuid& aUuid, - BluetoothResultHandler* aRes) = 0; - virtual void GetRemoteServices(const BluetoothAddress& aRemoteAddr, - BluetoothResultHandler* aRes) = 0; - - /* Discovery */ - - virtual void StartDiscovery(BluetoothResultHandler* aRes) = 0; - virtual void CancelDiscovery(BluetoothResultHandler* aRes) = 0; - - /* Bonds */ - - virtual void CreateBond(const BluetoothAddress& aBdAddr, - BluetoothTransport aTransport, - BluetoothResultHandler* aRes) = 0; - virtual void RemoveBond(const BluetoothAddress& aBdAddr, - BluetoothResultHandler* aRes) = 0; - virtual void CancelBond(const BluetoothAddress& aBdAddr, - BluetoothResultHandler* aRes) = 0; - - /* Connection */ - - virtual void GetConnectionState(const BluetoothAddress& aBdAddr, - BluetoothResultHandler* aRes) = 0; - - /* Authentication */ - - virtual void PinReply(const BluetoothAddress& aBdAddr, bool aAccept, - const BluetoothPinCode& aPinCode, - BluetoothResultHandler* aRes) = 0; - - virtual void SspReply(const BluetoothAddress& aBdAddr, - BluetoothSspVariant aVariant, - bool aAccept, uint32_t aPasskey, - BluetoothResultHandler* aRes) = 0; - - /* DUT Mode */ - - virtual void DutModeConfigure(bool aEnable, - BluetoothResultHandler* aRes) = 0; - virtual void DutModeSend(uint16_t aOpcode, uint8_t* aBuf, uint8_t aLen, - BluetoothResultHandler* aRes) = 0; - - /* LE Mode */ - - virtual void LeTestMode(uint16_t aOpcode, uint8_t* aBuf, uint8_t aLen, - BluetoothResultHandler* aRes) = 0; - - /* Energy Info */ - - virtual void ReadEnergyInfo(BluetoothResultHandler* aRes) = 0; - /* Profile Interfaces */ virtual BluetoothSetupInterface* GetBluetoothSetupInterface() = 0; + virtual BluetoothCoreInterface* GetBluetoothCoreInterface() = 0; virtual BluetoothSocketInterface* GetBluetoothSocketInterface() = 0; virtual BluetoothHandsfreeInterface* GetBluetoothHandsfreeInterface() = 0; virtual BluetoothA2dpInterface* GetBluetoothA2dpInterface() = 0; diff --git a/dom/bluetooth/common/BluetoothService.cpp b/dom/bluetooth/common/BluetoothService.cpp index 17013407ce..fee45758ef 100644 --- a/dom/bluetooth/common/BluetoothService.cpp +++ b/dom/bluetooth/common/BluetoothService.cpp @@ -70,8 +70,6 @@ #define DEFAULT_SHUTDOWN_TIMER_MS 5000 -bool gBluetoothDebugFlag = false; - using namespace mozilla; using namespace mozilla::dom; USING_BLUETOOTH_NAMESPACE @@ -119,7 +117,7 @@ GetAllBluetoothActors(InfallibleTArray& aActors) } } -} // anonymous namespace +} // namespace BluetoothService::ToggleBtAck::ToggleBtAck(bool aEnabled) : mEnabled(aEnabled) @@ -242,8 +240,7 @@ BluetoothService::Cleanup() void BluetoothService::RegisterBluetoothSignalHandler( - const nsAString& aNodeName, - BluetoothSignalObserver* aHandler) + const nsAString& aNodeName, BluetoothSignalObserver* aHandler) { MOZ_ASSERT(NS_IsMainThread()); MOZ_ASSERT(aHandler); @@ -336,6 +333,48 @@ BluetoothService::DistributeSignal(const nsAString& aName, DistributeSignal(signal); } +void +BluetoothService::DistributeSignal(const nsAString& aName, + const BluetoothAddress& aAddress) +{ + nsAutoString path; + AddressToString(aAddress, path); + + DistributeSignal(aName, path); +} + +void +BluetoothService::DistributeSignal(const nsAString& aName, + const BluetoothAddress& aAddress, + const BluetoothValue& aValue) +{ + nsAutoString path; + AddressToString(aAddress, path); + + DistributeSignal(aName, path, aValue); +} + +void +BluetoothService::DistributeSignal(const nsAString& aName, + const BluetoothUuid& aUuid) +{ + nsAutoString path; + UuidToString(aUuid, path); + + DistributeSignal(aName, path); +} + +void +BluetoothService::DistributeSignal(const nsAString& aName, + const BluetoothUuid& aUuid, + const BluetoothValue& aValue) +{ + nsAutoString path; + UuidToString(aUuid, path); + + DistributeSignal(aName, path, aValue); +} + void BluetoothService::DistributeSignal(const BluetoothSignal& aSignal) { @@ -532,8 +571,6 @@ BluetoothService::HandleShutdown() // bluetooth is going away, and then we wait for them to acknowledge. Then we // close down all the bluetooth machinery. - sInShutdown = true; - Cleanup(); AutoInfallibleTArray childActors; @@ -633,6 +670,13 @@ BluetoothService::Observe(nsISupports* aSubject, const char* aTopic, } if (!strcmp(aTopic, NS_XPCOM_SHUTDOWN_OBSERVER_ID)) { + /** + * |sInShutdown| flag should be set for instances created in content + * processes or parent processes. Please see bug 1199653 for detailed + * information. + */ + sInShutdown = true; + return HandleShutdown(); } diff --git a/dom/bluetooth/common/BluetoothService.h b/dom/bluetooth/common/BluetoothService.h index cc1c71c148..634d8d95af 100644 --- a/dom/bluetooth/common/BluetoothService.h +++ b/dom/bluetooth/common/BluetoothService.h @@ -107,6 +107,46 @@ public: DistributeSignal(const nsAString& aName, const nsAString& aPath, const BluetoothValue& aValue); + /** + * Create a signal without value and distribute it to the observer list + * + * @param aName Name of the signal + * @param aAddress Path of the signal to distribute to + */ + void + DistributeSignal(const nsAString& aName, const BluetoothAddress& aAddress); + + /** + * Create a signal and distribute it to the observer list + * + * @param aName Name of the signal + * @param aAddress Path of the signal to distribute to + * @param aValue Value of the signal to carry + */ + void + DistributeSignal(const nsAString& aName, const BluetoothAddress& aAddress, + const BluetoothValue& aValue); + + /** + * Create a signal without value and distribute it to the observer list + * + * @param aName Name of the signal + * @param aUuid Path of the signal to distribute to + */ + void + DistributeSignal(const nsAString& aName, const BluetoothUuid& aUuid); + + /** + * Create a signal and distribute it to the observer list + * + * @param aName Name of the signal + * @param aUuid Path of the signal to distribute to + * @param aValue Value of the signal to carry + */ + void + DistributeSignal(const nsAString& aName, const BluetoothUuid& aUuid, + const BluetoothValue& aValue); + /** * Distribute a signal to the observer list * @@ -149,8 +189,9 @@ public: * @return NS_OK on success, NS_ERROR_FAILURE otherwise */ virtual nsresult - GetPairedDevicePropertiesInternal(const nsTArray& aDeviceAddresses, - BluetoothReplyRunnable* aRunnable) = 0; + GetPairedDevicePropertiesInternal( + const nsTArray& aDeviceAddresses, + BluetoothReplyRunnable* aRunnable) = 0; /** * Returns the properties of connected devices regarding to specific profile, @@ -169,7 +210,7 @@ public: * @return NS_OK on success, NS_ERROR_FAILURE otherwise */ virtual nsresult - FetchUuidsInternal(const nsAString& aDeviceAddress, + FetchUuidsInternal(const BluetoothAddress& aDeviceAddress, BluetoothReplyRunnable* aRunnable) = 0; /** @@ -188,14 +229,14 @@ public: * Stops an ongoing Bluetooth LE device scan. */ virtual void - StopLeScanInternal(const nsAString& aScanUuid, + StopLeScanInternal(const BluetoothUuid& aScanUuid, BluetoothReplyRunnable* aRunnable) = 0; /** * Starts a Bluetooth LE device scan. */ virtual void - StartLeScanInternal(const nsTArray& aServiceUuids, + StartLeScanInternal(const nsTArray& aServiceUuids, BluetoothReplyRunnable* aRunnable) = 0; /** @@ -213,12 +254,12 @@ public: BluetoothReplyRunnable* aRunnable) = 0; virtual nsresult - CreatePairedDeviceInternal(const nsAString& aAddress, + CreatePairedDeviceInternal(const BluetoothAddress& aDeviceAddress, int aTimeout, BluetoothReplyRunnable* aRunnable) = 0; virtual nsresult - RemoveDeviceInternal(const nsAString& aObjectPath, + RemoveDeviceInternal(const BluetoothAddress& aDeviceAddress, BluetoothReplyRunnable* aRunnable) = 0; /** @@ -241,13 +282,13 @@ public: BluetoothProfileManagerBase* aManager) = 0; virtual void - PinReplyInternal(const nsAString& aDeviceAddress, + PinReplyInternal(const BluetoothAddress& aDeviceAddress, bool aAccept, - const nsAString& aPinCode, + const BluetoothPinCode& aPinCode, BluetoothReplyRunnable* aRunnable) = 0; virtual void - SspReplyInternal(const nsAString& aDeviceAddress, + SspReplyInternal(const BluetoothAddress& aDeviceAddress, BluetoothSspVariant aVariant, bool aAccept, BluetoothReplyRunnable* aRunnable) = 0; @@ -256,49 +297,51 @@ public: * Legacy method used by bluez only to reply pincode request. */ virtual void - SetPinCodeInternal(const nsAString& aDeviceAddress, - const nsAString& aPinCode, + SetPinCodeInternal(const BluetoothAddress& aDeviceAddress, + const BluetoothPinCode& aPinCode, BluetoothReplyRunnable* aRunnable) = 0; /** * Legacy method used by bluez only to reply passkey entry request. */ virtual void - SetPasskeyInternal(const nsAString& aDeviceAddress, uint32_t aPasskey, + SetPasskeyInternal(const BluetoothAddress& aDeviceAddress, uint32_t aPasskey, BluetoothReplyRunnable* aRunnable) = 0; /** * Legacy method used by bluez only to reply pairing confirmation request. */ virtual void - SetPairingConfirmationInternal(const nsAString& aDeviceAddress, bool aConfirm, + SetPairingConfirmationInternal(const BluetoothAddress& aDeviceAddress, + bool aConfirm, BluetoothReplyRunnable* aRunnable) = 0; virtual void - Connect(const nsAString& aDeviceAddress, uint32_t aCod, uint16_t aServiceUuid, + Connect(const BluetoothAddress& aDeviceAddress, + uint32_t aCod, uint16_t aServiceUuid, BluetoothReplyRunnable* aRunnable) = 0; virtual void - Disconnect(const nsAString& aDeviceAddress, uint16_t aServiceUuid, + Disconnect(const BluetoothAddress& aDeviceAddress, uint16_t aServiceUuid, BluetoothReplyRunnable* aRunnable) = 0; virtual void - SendFile(const nsAString& aDeviceAddress, + SendFile(const BluetoothAddress& aDeviceAddress, BlobParent* aBlobParent, BlobChild* aBlobChild, BluetoothReplyRunnable* aRunnable) = 0; virtual void - SendFile(const nsAString& aDeviceAddress, + SendFile(const BluetoothAddress& aDeviceAddress, Blob* aBlob, BluetoothReplyRunnable* aRunnable) = 0; virtual void - StopSendingFile(const nsAString& aDeviceAddress, + StopSendingFile(const BluetoothAddress& aDeviceAddress, BluetoothReplyRunnable* aRunnable) = 0; virtual void - ConfirmReceivingFile(const nsAString& aDeviceAddress, bool aConfirm, + ConfirmReceivingFile(const BluetoothAddress& aDeviceAddress, bool aConfirm, BluetoothReplyRunnable* aRunnable) = 0; virtual void @@ -418,7 +461,7 @@ public: virtual void SendPlayStatus(int64_t aDuration, int64_t aPosition, - const nsAString& aPlayStatus, + ControlPlayStatus aPlayStatus, BluetoothReplyRunnable* aRunnable) = 0; virtual void @@ -438,8 +481,8 @@ public: * Connect to a remote GATT server. (platform specific implementation) */ virtual void - ConnectGattClientInternal(const nsAString& aAppUuid, - const nsAString& aDeviceAddress, + ConnectGattClientInternal(const BluetoothUuid& aAppUuid, + const BluetoothAddress& aDeviceAddress, BluetoothReplyRunnable* aRunnable) = 0; /** @@ -447,8 +490,8 @@ public: * (platform specific implementation) */ virtual void - DisconnectGattClientInternal(const nsAString& aAppUuid, - const nsAString& aDeviceAddress, + DisconnectGattClientInternal(const BluetoothUuid& aAppUuid, + const BluetoothAddress& aDeviceAddress, BluetoothReplyRunnable* aRunnable) = 0; /** @@ -456,7 +499,7 @@ public: * server. (platform specific implementation) */ virtual void - DiscoverGattServicesInternal(const nsAString& aAppUuid, + DiscoverGattServicesInternal(const BluetoothUuid& aAppUuid, BluetoothReplyRunnable* aRunnable) = 0; /** @@ -464,7 +507,7 @@ public: * (platform specific implementation) */ virtual void - GattClientStartNotificationsInternal(const nsAString& aAppUuid, + GattClientStartNotificationsInternal(const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServId, const BluetoothGattId& aCharId, BluetoothReplyRunnable* aRunnable) = 0; @@ -474,7 +517,7 @@ public: * (platform specific implementation) */ virtual void - GattClientStopNotificationsInternal(const nsAString& aAppUuid, + GattClientStopNotificationsInternal(const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServId, const BluetoothGattId& aCharId, BluetoothReplyRunnable* aRunnable) = 0; @@ -491,7 +534,7 @@ public: */ virtual void GattClientReadRemoteRssiInternal(int aClientIf, - const nsAString& aDeviceAddress, + const BluetoothAddress& aDeviceAddress, BluetoothReplyRunnable* aRunnable) = 0; /** @@ -500,7 +543,7 @@ public: */ virtual void GattClientReadCharacteristicValueInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServiceId, const BluetoothGattId& aCharacteristicId, BluetoothReplyRunnable* aRunnable) = 0; @@ -511,7 +554,7 @@ public: */ virtual void GattClientWriteCharacteristicValueInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServiceId, const BluetoothGattId& aCharacteristicId, const BluetoothGattWriteType& aWriteType, @@ -524,7 +567,7 @@ public: */ virtual void GattClientReadDescriptorValueInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServiceId, const BluetoothGattId& aCharacteristicId, const BluetoothGattId& aDescriptorId, @@ -536,7 +579,7 @@ public: */ virtual void GattClientWriteDescriptorValueInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServiceId, const BluetoothGattId& aCharacteristicId, const BluetoothGattId& aDescriptorId, @@ -545,14 +588,14 @@ public: virtual void GattServerConnectPeripheralInternal( - const nsAString& aAppUuid, - const nsAString& aAddress, + const BluetoothUuid& aAppUuid, + const BluetoothAddress& aAddress, BluetoothReplyRunnable* aRunnable) = 0; virtual void GattServerDisconnectPeripheralInternal( - const nsAString& aAppUuid, - const nsAString& aAddress, + const BluetoothUuid& aAppUuid, + const BluetoothAddress& aAddress, BluetoothReplyRunnable* aRunnable) = 0; /** @@ -564,21 +607,21 @@ public: virtual void GattServerAddServiceInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServiceId, uint16_t aHandleCount, BluetoothReplyRunnable* aRunnable) = 0; virtual void GattServerAddIncludedServiceInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothAttributeHandle& aServiceHandle, const BluetoothAttributeHandle& aIncludedServiceHandle, BluetoothReplyRunnable* aRunnable) = 0; virtual void GattServerAddCharacteristicInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothAttributeHandle& aServiceHandle, const BluetoothUuid& aCharacteristicUuid, BluetoothGattAttrPerm aPermissions, @@ -587,7 +630,7 @@ public: virtual void GattServerAddDescriptorInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothAttributeHandle& aServiceHandle, const BluetoothAttributeHandle& aCharacteristicHandle, const BluetoothUuid& aDescriptorUuid, @@ -596,31 +639,40 @@ public: virtual void GattServerRemoveServiceInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothAttributeHandle& aServiceHandle, BluetoothReplyRunnable* aRunnable) = 0; virtual void GattServerStartServiceInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothAttributeHandle& aServiceHandle, BluetoothReplyRunnable* aRunnable) = 0; virtual void GattServerStopServiceInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothAttributeHandle& aServiceHandle, BluetoothReplyRunnable* aRunnable) = 0; virtual void GattServerSendResponseInternal( - const nsAString& aAppUuid, - const nsAString& aAddress, + const BluetoothUuid& aAppUuid, + const BluetoothAddress& aAddress, uint16_t aStatus, int32_t aRequestId, const BluetoothGattResponse& aRsp, BluetoothReplyRunnable* aRunnable) = 0; + virtual void + GattServerSendIndicationInternal( + const BluetoothUuid& aAppUuid, + const BluetoothAddress& aAddress, + const BluetoothAttributeHandle& aCharacteristicHandle, + bool aConfirm, + const nsTArray& aValue, + BluetoothReplyRunnable* aRunnable) = 0; + bool IsEnabled() const { diff --git a/dom/bluetooth/common/BluetoothUtils.cpp b/dom/bluetooth/common/BluetoothUtils.cpp index 4f3e5352ca..3dfb289437 100644 --- a/dom/bluetooth/common/BluetoothUtils.cpp +++ b/dom/bluetooth/common/BluetoothUtils.cpp @@ -61,6 +61,21 @@ StringToAddress(const nsAString& aString, BluetoothAddress& aAddress) return NS_OK; } +nsresult +PinCodeToString(const BluetoothPinCode& aPinCode, nsAString& aString) +{ + if (aPinCode.mLength > sizeof(aPinCode.mPinCode)) { + BT_LOGR("Pin-code string too long"); + return NS_ERROR_ILLEGAL_VALUE; + } + + aString = NS_ConvertUTF8toUTF16( + nsCString(reinterpret_cast(aPinCode.mPinCode), + aPinCode.mLength)); + + return NS_OK; +} + nsresult StringToPinCode(const nsAString& aString, BluetoothPinCode& aPinCode) { @@ -69,7 +84,7 @@ StringToPinCode(const nsAString& aString, BluetoothPinCode& aPinCode) auto len = stringUTF8.Length(); if (len > sizeof(aPinCode.mPinCode)) { - BT_LOGR("Service-name string too long"); + BT_LOGR("Pin-code string too long"); return NS_ERROR_ILLEGAL_VALUE; } @@ -82,6 +97,97 @@ StringToPinCode(const nsAString& aString, BluetoothPinCode& aPinCode) return NS_OK; } +nsresult +StringToControlPlayStatus(const nsAString& aString, + ControlPlayStatus& aPlayStatus) +{ + if (aString.EqualsLiteral("STOPPED")) { + aPlayStatus = ControlPlayStatus::PLAYSTATUS_STOPPED; + } else if (aString.EqualsLiteral("PLAYING")) { + aPlayStatus = ControlPlayStatus::PLAYSTATUS_PLAYING; + } else if (aString.EqualsLiteral("PAUSED")) { + aPlayStatus = ControlPlayStatus::PLAYSTATUS_PAUSED; + } else if (aString.EqualsLiteral("FWD_SEEK")) { + aPlayStatus = ControlPlayStatus::PLAYSTATUS_FWD_SEEK; + } else if (aString.EqualsLiteral("REV_SEEK")) { + aPlayStatus = ControlPlayStatus::PLAYSTATUS_REV_SEEK; + } else if (aString.EqualsLiteral("ERROR")) { + aPlayStatus = ControlPlayStatus::PLAYSTATUS_ERROR; + } else { + BT_LOGR("Invalid play status: %s", NS_ConvertUTF16toUTF8(aString).get()); + aPlayStatus = ControlPlayStatus::PLAYSTATUS_UNKNOWN; + return NS_ERROR_ILLEGAL_VALUE; + } + + return NS_OK; +} + +nsresult +StringToPropertyType(const nsAString& aString, BluetoothPropertyType& aType) +{ + if (aString.EqualsLiteral("Name")) { + aType = PROPERTY_BDNAME; + } else if (aString.EqualsLiteral("Discoverable")) { + aType = PROPERTY_ADAPTER_SCAN_MODE; + } else if (aString.EqualsLiteral("DiscoverableTimeout")) { + aType = PROPERTY_ADAPTER_DISCOVERY_TIMEOUT; + } else { + BT_LOGR("Invalid property name: %s", NS_ConvertUTF16toUTF8(aString).get()); + aType = PROPERTY_UNKNOWN; // silences compiler warning + return NS_ERROR_ILLEGAL_VALUE; + } + return NS_OK; +} + +nsresult +NamedValueToProperty(const BluetoothNamedValue& aValue, + BluetoothProperty& aProperty) +{ + nsresult rv = StringToPropertyType(aValue.name(), aProperty.mType); + if (NS_FAILED(rv)) { + return rv; + } + + switch (aProperty.mType) { + case PROPERTY_BDNAME: + if (aValue.value().type() != BluetoothValue::TnsString) { + BT_LOGR("Bluetooth property value is not a string"); + return NS_ERROR_ILLEGAL_VALUE; + } + // Set name + aProperty.mString = aValue.value().get_nsString(); + break; + + case PROPERTY_ADAPTER_SCAN_MODE: + if (aValue.value().type() != BluetoothValue::Tbool) { + BT_LOGR("Bluetooth property value is not a boolean"); + return NS_ERROR_ILLEGAL_VALUE; + } + // Set scan mode + if (aValue.value().get_bool()) { + aProperty.mScanMode = SCAN_MODE_CONNECTABLE_DISCOVERABLE; + } else { + aProperty.mScanMode = SCAN_MODE_CONNECTABLE; + } + break; + + case PROPERTY_ADAPTER_DISCOVERY_TIMEOUT: + if (aValue.value().type() != BluetoothValue::Tuint32_t) { + BT_LOGR("Bluetooth property value is not an unsigned integer"); + return NS_ERROR_ILLEGAL_VALUE; + } + // Set discoverable timeout + aProperty.mUint32 = aValue.value().get_uint32_t(); + break; + + default: + BT_LOGR("Invalid property value type"); + return NS_ERROR_ILLEGAL_VALUE; + } + + return NS_OK; +} + void RemoteNameToString(const BluetoothRemoteName& aRemoteName, nsAString& aString) { @@ -139,15 +245,18 @@ UuidToString(const BluetoothUuid& aUuid, nsAString& aString) aString.AssignLiteral(uuidStr); } -void +nsresult StringToUuid(const nsAString& aString, BluetoothUuid& aUuid) { uint32_t uuid0, uuid4; uint16_t uuid1, uuid2, uuid3, uuid5; - sscanf(NS_ConvertUTF16toUTF8(aString).get(), - "%08x-%04hx-%04hx-%04hx-%08x%04hx", - &uuid0, &uuid1, &uuid2, &uuid3, &uuid4, &uuid5); + auto res = sscanf(NS_ConvertUTF16toUTF8(aString).get(), + "%08x-%04hx-%04hx-%04hx-%08x%04hx", + &uuid0, &uuid1, &uuid2, &uuid3, &uuid4, &uuid5); + if (res == EOF || res < 6) { + return NS_ERROR_ILLEGAL_VALUE; + } uuid0 = htonl(uuid0); uuid1 = htons(uuid1); @@ -162,6 +271,28 @@ StringToUuid(const nsAString& aString, BluetoothUuid& aUuid) memcpy(&aUuid.mUuid[8], &uuid3, sizeof(uint16_t)); memcpy(&aUuid.mUuid[10], &uuid4, sizeof(uint32_t)); memcpy(&aUuid.mUuid[14], &uuid5, sizeof(uint16_t)); + + return NS_OK; +} + +nsresult +GenerateUuid(BluetoothUuid &aUuid) +{ + nsresult rv; + nsCOMPtr uuidGenerator = + do_GetService("@mozilla.org/uuid-generator;1", &rv); + NS_ENSURE_SUCCESS(rv, rv); + + nsID uuid; + rv = uuidGenerator->GenerateUUIDInPlace(&uuid); + NS_ENSURE_SUCCESS(rv, rv); + + aUuid = BluetoothUuid(uuid.m0 >> 24, uuid.m0 >> 16, uuid.m0 >> 8, uuid.m0, + uuid.m1 >> 8, uuid.m1, + uuid.m2 >> 8, uuid.m2, + uuid.m3[0], uuid.m3[1], uuid.m3[2], uuid.m3[3], + uuid.m3[4], uuid.m3[5], uuid.m3[6], uuid.m3[7]); + return NS_OK; } nsresult @@ -309,6 +440,26 @@ RegisterBluetoothSignalHandler(const nsAString& aPath, aHandler->SetSignalRegistered(true); } +void +RegisterBluetoothSignalHandler(const BluetoothAddress& aAddress, + BluetoothSignalObserver* aHandler) +{ + nsAutoString path; + AddressToString(aAddress, path); + + RegisterBluetoothSignalHandler(path, aHandler); +} + +void +RegisterBluetoothSignalHandler(const BluetoothUuid& aUuid, + BluetoothSignalObserver* aHandler) +{ + nsAutoString path; + UuidToString(aUuid, path); + + RegisterBluetoothSignalHandler(path, aHandler); +} + void UnregisterBluetoothSignalHandler(const nsAString& aPath, BluetoothSignalObserver* aHandler) @@ -323,6 +474,26 @@ UnregisterBluetoothSignalHandler(const nsAString& aPath, aHandler->SetSignalRegistered(false); } +void +UnregisterBluetoothSignalHandler(const BluetoothAddress& aAddress, + BluetoothSignalObserver* aHandler) +{ + nsAutoString path; + AddressToString(aAddress, path); + + UnregisterBluetoothSignalHandler(path, aHandler); +} + +void +UnregisterBluetoothSignalHandler(const BluetoothUuid& aUuid, + BluetoothSignalObserver* aHandler) +{ + nsAutoString path; + UuidToString(aUuid, path); + + UnregisterBluetoothSignalHandler(path, aHandler); +} + /** * |SetJsObject| is an internal function used by |BroadcastSystemMessage| only */ diff --git a/dom/bluetooth/common/BluetoothUtils.h b/dom/bluetooth/common/BluetoothUtils.h index b8f42bdcf3..f188d27fba 100644 --- a/dom/bluetooth/common/BluetoothUtils.h +++ b/dom/bluetooth/common/BluetoothUtils.h @@ -37,9 +37,35 @@ StringToAddress(const nsAString& aString, BluetoothAddress& aAddress); // Pin code/string conversion // +nsresult +PinCodeToString(const BluetoothPinCode& aPinCode, nsAString& aString); + nsresult StringToPinCode(const nsAString& aString, BluetoothPinCode& aPinCode); +// +// Play status/string conversion +// + +nsresult +StringToControlPlayStatus(const nsAString& aString, + ControlPlayStatus& aPlayStatus); + +// +// Property type/string conversion +// + +nsresult +StringToPropertyType(const nsAString& aString, BluetoothPropertyType& aType); + +// +// Property conversion +// + +nsresult +NamedValueToProperty(const BluetoothNamedValue& aIn, + BluetoothProperty& aProperty); + // // Remote name/string conversion // @@ -74,9 +100,17 @@ UuidToString(const BluetoothUuid& aUuid, nsAString& aString); * Note: This utility function is used by gecko internal only to convert uuid * string created by gecko back to BluetoothUuid representation. */ -void +nsresult StringToUuid(const nsAString& aString, BluetoothUuid& aUuid); +/** + * Generate a random uuid. + * + * @param aUuid [out] The generated uuid. + */ +nsresult +GenerateUuid(BluetoothUuid &aUuid); + /** * Generate a random uuid. * @@ -146,7 +180,7 @@ GeneratePathFromGattId(const BluetoothGattId& aId, // /** - * Register the bluetooth signal handler. + * Register the Bluetooth signal handler. * * @param aPath Path of the signal to be registered. * @param aHandler The message handler object to be added into the observer @@ -157,7 +191,29 @@ RegisterBluetoothSignalHandler(const nsAString& aPath, BluetoothSignalObserver* aHandler); /** - * Unregister the bluetooth signal handler. + * Register the Bluetooth signal handler. + * + * @param aAddress Address of the signal to be unregistered. + * @param aHandler The message handler object to be added into the observer + * list. Note that this function doesn't take references to it. + */ +void +RegisterBluetoothSignalHandler(const BluetoothAddress& aAddress, + BluetoothSignalObserver* aHandler); + +/** + * Register the Bluetooth signal handler. + * + * @param aUuid UUID of the signal to be unregistered. + * @param aHandler The message handler object to be added into the observer + * list. Note that this function doesn't take references to it. + */ +void +RegisterBluetoothSignalHandler(const BluetoothUuid& aUuid, + BluetoothSignalObserver* aHandler); + +/** + * Unregister the Bluetooth signal handler. * * @param aPath Path of the signal to be unregistered. * @param aHandler The message handler object to be removed from the observer @@ -167,6 +223,28 @@ void UnregisterBluetoothSignalHandler(const nsAString& aPath, BluetoothSignalObserver* aHandler); +/** + * Unregister the Bluetooth signal handler. + * + * @param aAddress Address of the signal to be unregistered. + * @param aHandler The message handler object to be removed from the observer + * list. Note that this function doesn't take references to it. + */ +void +UnregisterBluetoothSignalHandler(const BluetoothAddress& aAddress, + BluetoothSignalObserver* aHandler); + +/** + * Unregister the Bluetooth signal handler. + * + * @param aUuid UUID of the signal to be unregistered. + * @param aHandler The message handler object to be removed from the observer + * list. Note that this function doesn't take references to it. + */ +void +UnregisterBluetoothSignalHandler(const BluetoothUuid& aUuid, + BluetoothSignalObserver* aHandler); + // // Broadcast system message // diff --git a/dom/bluetooth/common/ObexBase.h b/dom/bluetooth/common/ObexBase.h index 1de5250165..994eecb657 100644 --- a/dom/bluetooth/common/ObexBase.h +++ b/dom/bluetooth/common/ObexBase.h @@ -248,23 +248,6 @@ public: } } - void GetTarget(uint8_t** aRetTarget, int* aRetTargetLength) const - { - int length = mHeaders.Length(); - *aRetTarget = nullptr; - *aRetTargetLength = 0; - - for (int i = 0; i < length; ++i) { - if (mHeaders[i]->mId == ObexHeaderId::Target) { - uint8_t* ptr = mHeaders[i]->mData.get(); - *aRetTarget = new uint8_t[mHeaders[i]->mDataLength]; - memcpy(*aRetTarget, ptr, mHeaders[i]->mDataLength); - *aRetTargetLength = mHeaders[i]->mDataLength; - return; - } - } - } - void GetAuthChallenge(nsAutoArrayPtr& aRetData, int* aRetDataLength) const { @@ -343,16 +326,20 @@ public: return false; } - bool Has(ObexHeaderId aId) const + const ObexHeader* GetHeader(ObexHeaderId aId) const { - int length = mHeaders.Length(); - for (int i = 0; i < length; ++i) { + for (int i = 0, length = mHeaders.Length(); i < length; ++i) { if (mHeaders[i]->mId == aId) { - return true; + return mHeaders[i]; } } - return false; + return nullptr; + } + + bool Has(ObexHeaderId aId) const + { + return !!GetHeader(aId); } void ClearHeaders() diff --git a/dom/bluetooth/common/webapi/BluetoothAdapter.cpp b/dom/bluetooth/common/webapi/BluetoothAdapter.cpp index 71698119d0..613f80d86c 100644 --- a/dom/bluetooth/common/webapi/BluetoothAdapter.cpp +++ b/dom/bluetooth/common/webapi/BluetoothAdapter.cpp @@ -366,12 +366,16 @@ BluetoothAdapter::Cleanup() BluetoothService* bs = BluetoothService::Get(); NS_ENSURE_TRUE_VOID(bs); - nsString uuid; + nsString uuidStr; for (uint32_t i = 0; i < mLeScanHandleArray.Length(); ++i) { - mLeScanHandleArray[i]->GetLeScanUuid(uuid); + mLeScanHandleArray[i]->GetLeScanUuid(uuidStr); RefPtr results = new BluetoothVoidReplyRunnable(nullptr); - bs->StopLeScanInternal(uuid, results); + + BluetoothUuid uuid; + if (NS_SUCCEEDED(StringToUuid(uuidStr, uuid))) { + bs->StopLeScanInternal(uuid, results); + } } mLeScanHandleArray.Clear(); } @@ -405,13 +409,24 @@ BluetoothAdapter::GetPairedDeviceProperties( BluetoothService* bs = BluetoothService::Get(); NS_ENSURE_TRUE_VOID(bs); + nsTArray deviceAddresses; + deviceAddresses.SetLength(aDeviceAddresses.Length()); + + for (size_t i = 0; i < deviceAddresses.Length(); ++i) { + auto rv = StringToAddress(aDeviceAddresses[i], deviceAddresses[i]); + if (NS_FAILED(rv)) { + BT_WARNING("GetPairedDeviceProperties failed"); + return; + } + } + RefPtr results = new BluetoothVoidReplyRunnable(nullptr); - nsresult rv = - bs->GetPairedDevicePropertiesInternal(aDeviceAddresses, results); + auto rv = bs->GetPairedDevicePropertiesInternal(deviceAddresses, results); if (NS_FAILED(rv)) { BT_WARNING("GetPairedDeviceProperties failed"); + return; } } @@ -552,7 +567,7 @@ BluetoothAdapter::Notify(const BluetoothSignal& aData) HandleMapGetMessage(aData.value()); } else if (aData.name().EqualsLiteral(MAP_SET_MESSAGE_STATUS_REQ_ID)) { HandleMapSetMessageStatus(aData.value()); - } else if (aData.name().EqualsLiteral(MAP_PUSH_MESSAGE_REQ_ID)) { + } else if (aData.name().EqualsLiteral(MAP_SEND_MESSAGE_REQ_ID)) { HandleMapSendMessage(aData.value()); } else if (aData.name().EqualsLiteral(MAP_MESSAGE_UPDATE_REQ_ID)) { HandleMapMessageUpdate(aData.value()); @@ -671,6 +686,16 @@ BluetoothAdapter::StartLeScan(const nsTArray& aServiceUuids, RefPtr promise = Promise::Create(global, aRv); NS_ENSURE_TRUE(!aRv.Failed(), nullptr); + nsTArray serviceUuids; + serviceUuids.SetLength(aServiceUuids.Length()); + + for (size_t i = 0; i < serviceUuids.Length(); ++i) { + BT_ENSURE_TRUE_REJECT(NS_SUCCEEDED(StringToUuid(aServiceUuids[i], + serviceUuids[i])), + promise, + NS_ERROR_DOM_OPERATION_ERR); + } + BT_ENSURE_TRUE_REJECT(mState == BluetoothAdapterState::Enabled, promise, NS_ERROR_DOM_INVALID_STATE_ERR); @@ -680,7 +705,7 @@ BluetoothAdapter::StartLeScan(const nsTArray& aServiceUuids, RefPtr result = new StartLeScanTask(this, promise, aServiceUuids); - bs->StartLeScanInternal(aServiceUuids, result); + bs->StartLeScanInternal(serviceUuids, result); return promise.forget(); } @@ -710,10 +735,16 @@ BluetoothAdapter::StopLeScan(BluetoothDiscoveryHandle& aDiscoveryHandle, promise, NS_ERROR_DOM_BLUETOOTH_DONE); - nsString scanUuid; - aDiscoveryHandle.GetLeScanUuid(scanUuid); + nsString scanUuidStr; + aDiscoveryHandle.GetLeScanUuid(scanUuidStr); + + BluetoothUuid scanUuid; + BT_ENSURE_TRUE_REJECT(NS_SUCCEEDED(StringToUuid(scanUuidStr, scanUuid)), + promise, + NS_ERROR_DOM_OPERATION_ERR); + RefPtr result = - new StopLeScanTask(this, promise, scanUuid); + new StopLeScanTask(this, promise, scanUuidStr); bs->StopLeScanInternal(scanUuid, result); return promise.forget(); @@ -851,11 +882,13 @@ BluetoothAdapter::PairUnpair(bool aPair, const nsAString& aDeviceAddress, /** * Ensure - * - device address is not empty, + * - device address is valid, * - adapter is already enabled, and * - BluetoothService is available. */ - BT_ENSURE_TRUE_REJECT(!aDeviceAddress.IsEmpty(), + BluetoothAddress deviceAddress; + BT_ENSURE_TRUE_REJECT(NS_SUCCEEDED(StringToAddress(aDeviceAddress, + deviceAddress)), promise, NS_ERROR_DOM_INVALID_STATE_ERR); BT_ENSURE_TRUE_REJECT(mState == BluetoothAdapterState::Enabled, @@ -867,10 +900,10 @@ BluetoothAdapter::PairUnpair(bool aPair, const nsAString& aDeviceAddress, nsresult rv; if (aPair) { rv = bs->CreatePairedDeviceInternal( - aDeviceAddress, kCreatePairedDeviceTimeout, + deviceAddress, kCreatePairedDeviceTimeout, new BluetoothVoidReplyRunnable(nullptr, promise)); } else { - rv = bs->RemoveDeviceInternal(aDeviceAddress, + rv = bs->RemoveDeviceInternal(deviceAddress, new BluetoothVoidReplyRunnable(nullptr, promise)); } BT_ENSURE_TRUE_REJECT(NS_SUCCEEDED(rv), promise, NS_ERROR_DOM_OPERATION_ERR); @@ -1338,7 +1371,7 @@ BluetoothAdapter::HandlePullVCardListingReq(const BluetoothValue& aValue) } else if (name.EqualsLiteral("searchKey")) { init.mSearchKey = static_cast(value.get_uint32_t()); } else if (name.EqualsLiteral("searchText")) { - init.mSearchValue = value.get_nsString(); + init.mSearchValue = NS_ConvertUTF8toUTF16(value.get_nsCString()); } else if (name.EqualsLiteral("maxListCount")) { init.mMaxListCount = value.get_uint32_t(); } else if (name.EqualsLiteral("listStartOffset")) { @@ -1419,7 +1452,7 @@ BluetoothAdapter::HandleMapFolderListing(const BluetoothValue& aValue) init.mHandle = BluetoothMapRequestHandle::Create(GetOwner()); - nsRefPtr event = + RefPtr event = BluetoothMapFolderListingEvent::Constructor(this, NS_LITERAL_STRING(MAP_FOLDER_LISTING_REQ_ID), init); DispatchTrustedEvent(event); @@ -1468,7 +1501,7 @@ BluetoothAdapter::HandleMapMessagesListing(const BluetoothValue& aValue) init.mHandle = BluetoothMapRequestHandle::Create(GetOwner()); - nsRefPtr event = + RefPtr event = BluetoothMapMessagesListingEvent::Constructor(this, NS_LITERAL_STRING(MAP_MESSAGES_LISTING_REQ_ID), init); DispatchTrustedEvent(event); @@ -1503,7 +1536,7 @@ BluetoothAdapter::HandleMapGetMessage(const BluetoothValue& aValue) init.mHandle = BluetoothMapRequestHandle::Create(GetOwner()); - nsRefPtr event = + RefPtr event = BluetoothMapGetMessageEvent::Constructor(this, NS_LITERAL_STRING(MAP_GET_MESSAGE_REQ_ID), init); DispatchTrustedEvent(event); @@ -1540,7 +1573,7 @@ BluetoothAdapter::HandleMapSetMessageStatus(const BluetoothValue& aValue) init.mHandle = BluetoothMapRequestHandle::Create(GetOwner()); - nsRefPtr event = + RefPtr event = BluetoothMapSetMessageStatusEvent::Constructor(this, NS_LITERAL_STRING(MAP_SET_MESSAGE_STATUS_REQ_ID), init); DispatchTrustedEvent(event); @@ -1563,9 +1596,9 @@ BluetoothAdapter::HandleMapSendMessage(const BluetoothValue& aValue) const nsString& name = arr[i].name(); const BluetoothValue& value = arr[i].value(); if (name.EqualsLiteral("recipient")) { - init.mRecipient = value.get_nsString(); + init.mRecipient = NS_ConvertUTF8toUTF16(value.get_nsCString()); } else if (name.EqualsLiteral("messageBody")) { - init.mMessageBody = value.get_nsString(); + init.mMessageBody = NS_ConvertUTF8toUTF16(value.get_nsCString()); } else if (name.EqualsLiteral("retry")) { init.mRetry = value.get_uint32_t(); } @@ -1573,9 +1606,9 @@ BluetoothAdapter::HandleMapSendMessage(const BluetoothValue& aValue) init.mHandle = BluetoothMapRequestHandle::Create(GetOwner()); - nsRefPtr event = + RefPtr event = BluetoothMapSendMessageEvent::Constructor(this, - NS_LITERAL_STRING(MAP_PUSH_MESSAGE_REQ_ID), init); + NS_LITERAL_STRING(MAP_SEND_MESSAGE_REQ_ID), init); DispatchTrustedEvent(event); } @@ -1602,7 +1635,7 @@ BluetoothAdapter::HandleMapMessageUpdate(const BluetoothValue& aValue) init.mHandle = BluetoothMapRequestHandle::Create(GetOwner()); - nsRefPtr event = + RefPtr event = BluetoothMapMessageUpdateEvent::Constructor(this, NS_LITERAL_STRING(MAP_MESSAGE_UPDATE_REQ_ID), init); DispatchTrustedEvent(event); @@ -1624,30 +1657,6 @@ BluetoothAdapter::DispatchAttributeEvent(const Sequence& aTypes) DispatchTrustedEvent(event); } -void -BluetoothAdapter::DispatchAttributeEvent(const nsTArray& aTypes) -{ - NS_ENSURE_TRUE_VOID(aTypes.Length()); - - AutoJSAPI jsapi; - NS_ENSURE_TRUE_VOID(jsapi.Init(GetOwner())); - JSContext* cx = jsapi.cx(); - JS::Rooted value(cx); - - if (!ToJSValue(cx, aTypes, &value)) { - JS_ClearPendingException(cx); - return; - } - - RootedDictionary init(cx); - init.mAttrs = value; - RefPtr event = - BluetoothAttributeEvent::Constructor(this, - NS_LITERAL_STRING("attributechanged"), - init); - DispatchTrustedEvent(event); -} - void BluetoothAdapter::DispatchDeviceEvent(const nsAString& aType, const BluetoothDeviceEventInit& aInit) @@ -1684,6 +1693,12 @@ BluetoothAdapter::Connect(BluetoothDevice& aDevice, nsAutoString address; aDevice.GetAddress(address); + BluetoothAddress deviceAddress; + if (NS_FAILED(StringToAddress(address, deviceAddress))) { + aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR); + return nullptr; + } + uint32_t deviceClass = aDevice.Cod()->ToUint32(); uint16_t serviceUuid = 0; if (aServiceUuid.WasPassed()) { @@ -1695,7 +1710,7 @@ BluetoothAdapter::Connect(BluetoothDevice& aDevice, aRv.Throw(NS_ERROR_FAILURE); return nullptr; } - bs->Connect(address, deviceClass, serviceUuid, results); + bs->Connect(deviceAddress, deviceClass, serviceUuid, results); return request.forget(); } @@ -1717,6 +1732,12 @@ BluetoothAdapter::Disconnect(BluetoothDevice& aDevice, nsAutoString address; aDevice.GetAddress(address); + BluetoothAddress deviceAddress; + if (NS_FAILED(StringToAddress(address, deviceAddress))) { + aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR); + return nullptr; + } + uint16_t serviceUuid = 0; if (aServiceUuid.WasPassed()) { serviceUuid = aServiceUuid.Value(); @@ -1727,7 +1748,7 @@ BluetoothAdapter::Disconnect(BluetoothDevice& aDevice, aRv.Throw(NS_ERROR_FAILURE); return nullptr; } - bs->Disconnect(address, serviceUuid, results); + bs->Disconnect(deviceAddress, serviceUuid, results); return request.forget(); } @@ -1746,6 +1767,13 @@ BluetoothAdapter::SendFile(const nsAString& aDeviceAddress, RefPtr results = new BluetoothVoidReplyRunnable(request); + BluetoothAddress deviceAddress; + auto rv = StringToAddress(aDeviceAddress, deviceAddress); + if (NS_FAILED(rv)) { + aRv.Throw(rv); + return nullptr; + } + BluetoothService* bs = BluetoothService::Get(); if (!bs) { aRv.Throw(NS_ERROR_FAILURE); @@ -1754,7 +1782,7 @@ BluetoothAdapter::SendFile(const nsAString& aDeviceAddress, if (XRE_IsParentProcess()) { // In-process transfer - bs->SendFile(aDeviceAddress, &aBlob, results); + bs->SendFile(deviceAddress, &aBlob, results); } else { ContentChild *cc = ContentChild::GetSingleton(); if (!cc) { @@ -1768,7 +1796,7 @@ BluetoothAdapter::SendFile(const nsAString& aDeviceAddress, return nullptr; } - bs->SendFile(aDeviceAddress, nullptr, actor, results); + bs->SendFile(deviceAddress, nullptr, actor, results); } return request.forget(); @@ -1788,12 +1816,19 @@ BluetoothAdapter::StopSendingFile( RefPtr results = new BluetoothVoidReplyRunnable(request); + BluetoothAddress deviceAddress; + auto rv = StringToAddress(aDeviceAddress, deviceAddress); + if (NS_FAILED(rv)) { + aRv.Throw(rv); + return nullptr; + } + BluetoothService* bs = BluetoothService::Get(); if (!bs) { aRv.Throw(NS_ERROR_FAILURE); return nullptr; } - bs->StopSendingFile(aDeviceAddress, results); + bs->StopSendingFile(deviceAddress, results); return request.forget(); } @@ -1812,12 +1847,19 @@ BluetoothAdapter::ConfirmReceivingFile(const nsAString& aDeviceAddress, RefPtr results = new BluetoothVoidReplyRunnable(request); + BluetoothAddress deviceAddress; + auto rv = StringToAddress(aDeviceAddress, deviceAddress); + if (NS_FAILED(rv)) { + aRv.Throw(rv); + return nullptr; + } + BluetoothService* bs = BluetoothService::Get(); if (!bs) { aRv.Throw(NS_ERROR_FAILURE); return nullptr; } - bs->ConfirmReceivingFile(aDeviceAddress, aConfirmation, results); + bs->ConfirmReceivingFile(deviceAddress, aConfirmation, results); return request.forget(); } @@ -2015,6 +2057,13 @@ BluetoothAdapter::SendMediaPlayStatus( return nullptr; } + ControlPlayStatus playStatus; + auto rv = StringToControlPlayStatus(aMediaPlayStatus.mPlayStatus, playStatus); + if (NS_FAILED(rv)) { + aRv.Throw(rv); + return nullptr; + } + RefPtr request = new DOMRequest(win); RefPtr results = new BluetoothVoidReplyRunnable(request); @@ -2026,7 +2075,7 @@ BluetoothAdapter::SendMediaPlayStatus( } bs->SendPlayStatus(aMediaPlayStatus.mDuration, aMediaPlayStatus.mPosition, - aMediaPlayStatus.mPlayStatus, + playStatus, results); return request.forget(); diff --git a/dom/bluetooth/common/webapi/BluetoothDevice.cpp b/dom/bluetooth/common/webapi/BluetoothDevice.cpp index 47a81f393e..a44312900a 100644 --- a/dom/bluetooth/common/webapi/BluetoothDevice.cpp +++ b/dom/bluetooth/common/webapi/BluetoothDevice.cpp @@ -187,10 +187,13 @@ BluetoothDevice::FetchUuids(ErrorResult& aRv) // Ensure BluetoothService is available BluetoothService* bs = BluetoothService::Get(); BT_ENSURE_TRUE_REJECT(bs, promise, NS_ERROR_NOT_AVAILABLE); - + BluetoothAddress address; + BT_ENSURE_TRUE_REJECT(NS_SUCCEEDED(StringToAddress(mAddress, address)), + promise, + NS_ERROR_DOM_INVALID_STATE_ERR); BT_ENSURE_TRUE_REJECT( NS_SUCCEEDED( - bs->FetchUuidsInternal(mAddress, new FetchUuidsTask(promise, this))), + bs->FetchUuidsInternal(address, new FetchUuidsTask(promise, this))), promise, NS_ERROR_DOM_OPERATION_ERR); return promise.forget(); diff --git a/dom/bluetooth/common/webapi/BluetoothGatt.cpp b/dom/bluetooth/common/webapi/BluetoothGatt.cpp index 1a06d24f3e..da4b76f95e 100644 --- a/dom/bluetooth/common/webapi/BluetoothGatt.cpp +++ b/dom/bluetooth/common/webapi/BluetoothGatt.cpp @@ -112,6 +112,17 @@ BluetoothGatt::Connect(ErrorResult& aRv) 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); + + BluetoothAddress deviceAddr; + BT_ENSURE_TRUE_REJECT( + NS_SUCCEEDED(StringToAddress(mDeviceAddr, deviceAddr)), + promise, + NS_ERROR_DOM_OPERATION_ERR); + if (mAppUuid.IsEmpty()) { nsresult rv = GenerateUuid(mAppUuid); BT_ENSURE_TRUE_REJECT(NS_SUCCEEDED(rv) && !mAppUuid.IsEmpty(), @@ -122,7 +133,7 @@ BluetoothGatt::Connect(ErrorResult& aRv) UpdateConnectionState(BluetoothConnectionState::Connecting); bs->ConnectGattClientInternal( - mAppUuid, mDeviceAddr, new BluetoothVoidReplyRunnable(nullptr, promise)); + appUuid, deviceAddr, new BluetoothVoidReplyRunnable(nullptr, promise)); return promise.forget(); } @@ -147,9 +158,20 @@ BluetoothGatt::Disconnect(ErrorResult& aRv) 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); + + BluetoothAddress deviceAddr; + BT_ENSURE_TRUE_REJECT( + NS_SUCCEEDED(StringToAddress(mDeviceAddr, deviceAddr)), + promise, + NS_ERROR_DOM_OPERATION_ERR); + UpdateConnectionState(BluetoothConnectionState::Disconnecting); bs->DisconnectGattClientInternal( - mAppUuid, mDeviceAddr, new BluetoothVoidReplyRunnable(nullptr, promise)); + appUuid, deviceAddr, new BluetoothVoidReplyRunnable(nullptr, promise)); return promise.forget(); } @@ -196,8 +218,14 @@ BluetoothGatt::ReadRemoteRssi(ErrorResult& aRv) BluetoothService* bs = BluetoothService::Get(); BT_ENSURE_TRUE_REJECT(bs, promise, NS_ERROR_NOT_AVAILABLE); + BluetoothAddress deviceAddr; + BT_ENSURE_TRUE_REJECT( + NS_SUCCEEDED(StringToAddress(mDeviceAddr, deviceAddr)), + promise, + NS_ERROR_DOM_OPERATION_ERR); + bs->GattClientReadRemoteRssiInternal( - mClientIf, mDeviceAddr, new ReadRemoteRssiTask(promise)); + mClientIf, deviceAddr, new ReadRemoteRssiTask(promise)); return promise.forget(); } @@ -214,6 +242,11 @@ BluetoothGatt::DiscoverServices(ErrorResult& aRv) RefPtr 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); + BT_ENSURE_TRUE_REJECT( mConnectionState == BluetoothConnectionState::Connected && !mDiscoveringServices, @@ -228,7 +261,7 @@ BluetoothGatt::DiscoverServices(ErrorResult& aRv) BluetoothGattBinding::ClearCachedServicesValue(this); bs->DiscoverGattServicesInternal( - mAppUuid, new BluetoothVoidReplyRunnable(nullptr, promise)); + appUuid, new BluetoothVoidReplyRunnable(nullptr, promise)); return promise.forget(); } diff --git a/dom/bluetooth/common/webapi/BluetoothGattCharacteristic.cpp b/dom/bluetooth/common/webapi/BluetoothGattCharacteristic.cpp index 788481c9d3..10571df065 100644 --- a/dom/bluetooth/common/webapi/BluetoothGattCharacteristic.cpp +++ b/dom/bluetooth/common/webapi/BluetoothGattCharacteristic.cpp @@ -154,8 +154,14 @@ BluetoothGattCharacteristic::StartNotifications(ErrorResult& aRv) BT_ENSURE_TRUE_REJECT(bs, promise, NS_ERROR_NOT_AVAILABLE); BT_ENSURE_TRUE_REJECT(mService, promise, NS_ERROR_NOT_AVAILABLE); + BluetoothUuid appUuid; + BT_ENSURE_TRUE_REJECT(NS_SUCCEEDED(StringToUuid(mService->GetAppUuid(), + appUuid)), + promise, + NS_ERROR_DOM_OPERATION_ERR); + bs->GattClientStartNotificationsInternal( - mService->GetAppUuid(), mService->GetServiceId(), mCharId, + appUuid, mService->GetServiceId(), mCharId, new BluetoothVoidReplyRunnable(nullptr, promise)); return promise.forget(); @@ -181,8 +187,14 @@ BluetoothGattCharacteristic::StopNotifications(ErrorResult& aRv) BT_ENSURE_TRUE_REJECT(bs, promise, NS_ERROR_NOT_AVAILABLE); BT_ENSURE_TRUE_REJECT(mService, promise, NS_ERROR_NOT_AVAILABLE); + BluetoothUuid appUuid; + BT_ENSURE_TRUE_REJECT(NS_SUCCEEDED(StringToUuid(mService->GetAppUuid(), + appUuid)), + promise, + NS_ERROR_DOM_OPERATION_ERR); + bs->GattClientStopNotificationsInternal( - mService->GetAppUuid(), mService->GetServiceId(), mCharId, + appUuid, mService->GetServiceId(), mCharId, new BluetoothVoidReplyRunnable(nullptr, promise)); return promise.forget(); @@ -364,8 +376,14 @@ BluetoothGattCharacteristic::ReadValue(ErrorResult& aRv) BluetoothService* bs = BluetoothService::Get(); BT_ENSURE_TRUE_REJECT(bs, promise, NS_ERROR_NOT_AVAILABLE); + BluetoothUuid appUuid; + BT_ENSURE_TRUE_REJECT(NS_SUCCEEDED(StringToUuid(mService->GetAppUuid(), + appUuid)), + promise, + NS_ERROR_DOM_OPERATION_ERR); + bs->GattClientReadCharacteristicValueInternal( - mService->GetAppUuid(), mService->GetServiceId(), mCharId, + appUuid, mService->GetServiceId(), mCharId, new ReadValueTask(this, promise)); return promise.forget(); @@ -407,9 +425,14 @@ BluetoothGattCharacteristic::WriteValue(const ArrayBuffer& aValue, BluetoothService* bs = BluetoothService::Get(); BT_ENSURE_TRUE_REJECT(bs, promise, NS_ERROR_NOT_AVAILABLE); + BluetoothUuid appUuid; + BT_ENSURE_TRUE_REJECT(NS_SUCCEEDED(StringToUuid(mService->GetAppUuid(), + appUuid)), + promise, + NS_ERROR_DOM_OPERATION_ERR); + bs->GattClientWriteCharacteristicValueInternal( - mService->GetAppUuid(), mService->GetServiceId(), - mCharId, mWriteType, value, + appUuid, mService->GetServiceId(), mCharId, mWriteType, value, new BluetoothVoidReplyRunnable(nullptr, promise)); return promise.forget(); diff --git a/dom/bluetooth/common/webapi/BluetoothGattDescriptor.cpp b/dom/bluetooth/common/webapi/BluetoothGattDescriptor.cpp index 69697624db..d53183dc36 100644 --- a/dom/bluetooth/common/webapi/BluetoothGattDescriptor.cpp +++ b/dom/bluetooth/common/webapi/BluetoothGattDescriptor.cpp @@ -234,6 +234,12 @@ BluetoothGattDescriptor::ReadValue(ErrorResult& aRv) RefPtr promise = Promise::Create(global, aRv); NS_ENSURE_TRUE(!aRv.Failed(), nullptr); + BluetoothUuid appUuid; + BT_ENSURE_TRUE_REJECT(NS_SUCCEEDED(StringToUuid( + mCharacteristic->Service()->GetAppUuid(), appUuid)), + promise, + NS_ERROR_DOM_OPERATION_ERR); + if (mAttRole == ATT_SERVER_ROLE) { promise->MaybeResolve(mValue); return promise.forget(); @@ -243,7 +249,7 @@ BluetoothGattDescriptor::ReadValue(ErrorResult& aRv) BT_ENSURE_TRUE_REJECT(bs, promise, NS_ERROR_NOT_AVAILABLE); bs->GattClientReadDescriptorValueInternal( - mCharacteristic->Service()->GetAppUuid(), + appUuid, mCharacteristic->Service()->GetServiceId(), mCharacteristic->GetCharacteristicId(), mDescriptorId, @@ -265,6 +271,12 @@ BluetoothGattDescriptor::WriteValue( RefPtr promise = Promise::Create(global, aRv); NS_ENSURE_TRUE(!aRv.Failed(), nullptr); + BluetoothUuid appUuid; + BT_ENSURE_TRUE_REJECT(NS_SUCCEEDED(StringToUuid( + mCharacteristic->Service()->GetAppUuid(), appUuid)), + promise, + NS_ERROR_DOM_OPERATION_ERR); + aValue.ComputeLengthAndData(); if (mAttRole == ATT_SERVER_ROLE) { @@ -282,7 +294,7 @@ BluetoothGattDescriptor::WriteValue( BT_ENSURE_TRUE_REJECT(bs, promise, NS_ERROR_NOT_AVAILABLE); bs->GattClientWriteDescriptorValueInternal( - mCharacteristic->Service()->GetAppUuid(), + appUuid, mCharacteristic->Service()->GetServiceId(), mCharacteristic->GetCharacteristicId(), mDescriptorId, diff --git a/dom/bluetooth/common/webapi/BluetoothGattServer.cpp b/dom/bluetooth/common/webapi/BluetoothGattServer.cpp index bfd7b8d267..aa022e34c7 100644 --- a/dom/bluetooth/common/webapi/BluetoothGattServer.cpp +++ b/dom/bluetooth/common/webapi/BluetoothGattServer.cpp @@ -319,12 +319,23 @@ BluetoothGattServer::Connect(const nsAString& aAddress, ErrorResult& aRv) RefPtr 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( - mAppUuid, aAddress, new BluetoothVoidReplyRunnable(nullptr, promise)); + appUuid, address, new BluetoothVoidReplyRunnable(nullptr, promise)); return promise.forget(); } @@ -341,12 +352,23 @@ BluetoothGattServer::Disconnect(const nsAString& aAddress, ErrorResult& aRv) RefPtr 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( - mAppUuid, aAddress, new BluetoothVoidReplyRunnable(nullptr, promise)); + appUuid, address, new BluetoothVoidReplyRunnable(nullptr, promise)); return promise.forget(); } @@ -372,8 +394,13 @@ public: return false; } + BluetoothUuid appUuid; + if (NS_FAILED(StringToUuid(mServer->mAppUuid, appUuid))) { + return false; + } + bs->GattServerAddIncludedServiceInternal( - mServer->mAppUuid, + appUuid, mService->GetServiceHandle(), mIncludedService->GetServiceHandle(), GetReply()); @@ -408,10 +435,15 @@ public: return false; } + BluetoothUuid appUuid; + if (NS_FAILED(StringToUuid(mServer->mAppUuid, appUuid))) { + return false; + } + BluetoothUuid uuid; mCharacteristic->GetUuid(uuid); bs->GattServerAddCharacteristicInternal( - mServer->mAppUuid, + appUuid, mService->GetServiceHandle(), uuid, mCharacteristic->GetPermissions(), @@ -450,10 +482,15 @@ public: return false; } + BluetoothUuid appUuid; + if (NS_FAILED(StringToUuid(mServer->mAppUuid, appUuid))) { + return false; + } + BluetoothUuid uuid; mDescriptor->GetUuid(uuid); bs->GattServerAddDescriptorInternal( - mServer->mAppUuid, + appUuid, mService->GetServiceHandle(), mCharacteristic->GetCharacteristicHandle(), uuid, @@ -489,8 +526,13 @@ public: return false; } + BluetoothUuid appUuid; + if (NS_FAILED(StringToUuid(mServer->mAppUuid, appUuid))) { + return false; + } + bs->GattServerStartServiceInternal( - mServer->mAppUuid, + appUuid, mService->GetServiceHandle(), GetReply()); @@ -616,8 +658,14 @@ private: 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( - mServer->mAppUuid, + appUuid, mService->GetServiceHandle(), new CancelAddServiceTask(mServer, mService, mPromise)); } @@ -704,7 +752,12 @@ BluetoothGattServer::AddService(BluetoothGattService& aService, mPendingService = &aService; - bs->GattServerAddServiceInternal(mAppUuid, + BluetoothUuid appUuid; + if (NS_FAILED(StringToUuid(mAppUuid, appUuid))) { + return false; + } + + bs->GattServerAddServiceInternal(appUuid, mPendingService->GetServiceId(), mPendingService->GetHandleCount(), new AddServiceTask(this, @@ -772,14 +825,65 @@ BluetoothGattServer::RemoveService(BluetoothGattService& aService, 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( - mAppUuid, aService.GetServiceHandle(), new RemoveServiceTask(this, + appUuid, aService.GetServiceHandle(), new RemoveServiceTask(this, &aService, promise)); return promise.forget(); } +already_AddRefed +BluetoothGattServer::NotifyCharacteristicChanged( + const nsAString& aAddress, + BluetoothGattCharacteristic& aCharacteristic, + bool aConfirm, + ErrorResult& aRv) +{ + nsCOMPtr global = do_QueryInterface(GetParentObject()); + if (!global) { + aRv.Throw(NS_ERROR_FAILURE); + return nullptr; + } + + RefPtr 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 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 BluetoothGattServer::SendResponse(const nsAString& aAddress, uint16_t aStatus, @@ -795,6 +899,17 @@ BluetoothGattServer::SendResponse(const nsAString& aAddress, RefPtr 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; @@ -826,8 +941,8 @@ BluetoothGattServer::SendResponse(const nsAString& aAddress, BT_ENSURE_TRUE_REJECT(bs, promise, NS_ERROR_NOT_AVAILABLE); bs->GattServerSendResponseInternal( - mAppUuid, - aAddress, + appUuid, + address, aStatus, aRequestId, response, diff --git a/dom/bluetooth/common/webapi/BluetoothGattServer.h b/dom/bluetooth/common/webapi/BluetoothGattServer.h index e32ea334d3..c178264d70 100644 --- a/dom/bluetooth/common/webapi/BluetoothGattServer.h +++ b/dom/bluetooth/common/webapi/BluetoothGattServer.h @@ -61,6 +61,11 @@ public: ErrorResult& aRv); already_AddRefed RemoveService(BluetoothGattService& aService, ErrorResult& aRv); + already_AddRefed NotifyCharacteristicChanged( + const nsAString& aAddress, + BluetoothGattCharacteristic& aCharacteristic, + bool aConfirm, + ErrorResult& aRv); already_AddRefed SendResponse(const nsAString& aAddress, uint16_t aStatus, diff --git a/dom/bluetooth/common/webapi/BluetoothLeDeviceEvent.cpp b/dom/bluetooth/common/webapi/BluetoothLeDeviceEvent.cpp index e7f33cac15..5d87e63964 100644 --- a/dom/bluetooth/common/webapi/BluetoothLeDeviceEvent.cpp +++ b/dom/bluetooth/common/webapi/BluetoothLeDeviceEvent.cpp @@ -93,13 +93,16 @@ BluetoothLeDeviceEvent::Constructor( e->mDevice = aEventInitDict.mDevice; e->mRssi = aEventInitDict.mRssi; - aEventInitDict.mScanRecord.ComputeLengthAndData(); - const uint8_t* data = aEventInitDict.mScanRecord.Data(); - size_t length = aEventInitDict.mScanRecord.Length(); - e->mScanRecord = ArrayBuffer::Create(aGlobal.Context(), length, data); - if (!e->mScanRecord) { - aRv.Throw(NS_ERROR_OUT_OF_MEMORY); - return nullptr; + if (!aEventInitDict.mScanRecord.IsNull()) { + const auto& scanRecord = aEventInitDict.mScanRecord.Value(); + scanRecord.ComputeLengthAndData(); + e->mScanRecord = ArrayBuffer::Create(aGlobal.Context(), + scanRecord.Length(), + scanRecord.Data()); + if (!e->mScanRecord) { + aRv.Throw(NS_ERROR_OUT_OF_MEMORY); + return nullptr; + } } e->SetTrusted(trusted); @@ -107,7 +110,7 @@ BluetoothLeDeviceEvent::Constructor( } BluetoothDevice* -BluetoothLeDeviceEvent::Device() const +BluetoothLeDeviceEvent::GetDevice() const { return mDevice; } diff --git a/dom/bluetooth/common/webapi/BluetoothLeDeviceEvent.h b/dom/bluetooth/common/webapi/BluetoothLeDeviceEvent.h index 8dd093c188..38dde831bf 100644 --- a/dom/bluetooth/common/webapi/BluetoothLeDeviceEvent.h +++ b/dom/bluetooth/common/webapi/BluetoothLeDeviceEvent.h @@ -47,7 +47,7 @@ public: const BluetoothLeDeviceEventInit& aEventInitDict, ErrorResult& aRv); - BluetoothDevice* Device() const; + BluetoothDevice* GetDevice() const; int16_t Rssi() const; diff --git a/dom/bluetooth/common/webapi/BluetoothPairingHandle.cpp b/dom/bluetooth/common/webapi/BluetoothPairingHandle.cpp index 6cef4d1336..d1922faa7f 100644 --- a/dom/bluetooth/common/webapi/BluetoothPairingHandle.cpp +++ b/dom/bluetooth/common/webapi/BluetoothPairingHandle.cpp @@ -9,6 +9,7 @@ #include "BluetoothPairingHandle.h" #include "BluetoothReplyRunnable.h" #include "BluetoothService.h" +#include "BluetoothUtils.h" #include "mozilla/dom/BluetoothPairingHandleBinding.h" #include "mozilla/dom/Promise.h" @@ -79,10 +80,21 @@ BluetoothPairingHandle::SetPinCode(const nsAString& aPinCode, ErrorResult& aRv) promise, NS_ERROR_DOM_INVALID_STATE_ERR); + BluetoothAddress deviceAddress; + BT_ENSURE_TRUE_REJECT(NS_SUCCEEDED(StringToAddress(mDeviceAddress, + deviceAddress)), + promise, + NS_ERROR_DOM_INVALID_STATE_ERR); + + BluetoothPinCode pinCode; + BT_ENSURE_TRUE_REJECT(NS_SUCCEEDED(StringToPinCode(aPinCode, pinCode)), + promise, + NS_ERROR_DOM_INVALID_STATE_ERR); + BluetoothService* bs = BluetoothService::Get(); BT_ENSURE_TRUE_REJECT(bs, promise, NS_ERROR_NOT_AVAILABLE); - bs->PinReplyInternal(mDeviceAddress, true /* accept */, aPinCode, + bs->PinReplyInternal(deviceAddress, true /* accept */, pinCode, new BluetoothVoidReplyRunnable(nullptr, promise)); return promise.forget(); @@ -108,12 +120,18 @@ BluetoothPairingHandle::Accept(ErrorResult& aRv) BluetoothService* bs = BluetoothService::Get(); BT_ENSURE_TRUE_REJECT(bs, promise, NS_ERROR_NOT_AVAILABLE); + BluetoothAddress deviceAddress; + BT_ENSURE_TRUE_REJECT(NS_SUCCEEDED(StringToAddress(mDeviceAddress, + deviceAddress)), + promise, + NS_ERROR_DOM_INVALID_STATE_ERR); + BluetoothSspVariant variant; BT_ENSURE_TRUE_REJECT(GetSspVariant(variant), promise, NS_ERROR_DOM_OPERATION_ERR); - bs->SspReplyInternal(mDeviceAddress, variant, true /* aAccept */, + bs->SspReplyInternal(deviceAddress, variant, true /* aAccept */, new BluetoothVoidReplyRunnable(nullptr, promise)); return promise.forget(); @@ -131,11 +149,18 @@ BluetoothPairingHandle::Reject(ErrorResult& aRv) RefPtr promise = Promise::Create(global, aRv); NS_ENSURE_TRUE(!aRv.Failed(), nullptr); + BluetoothAddress deviceAddress; + BT_ENSURE_TRUE_REJECT(NS_SUCCEEDED(StringToAddress(mDeviceAddress, + deviceAddress)), + promise, + NS_ERROR_DOM_INVALID_STATE_ERR); + BluetoothService* bs = BluetoothService::Get(); BT_ENSURE_TRUE_REJECT(bs, promise, NS_ERROR_NOT_AVAILABLE); if (mType.EqualsLiteral(PAIRING_REQ_TYPE_ENTERPINCODE)) { // Pin request - bs->PinReplyInternal(mDeviceAddress, false /* aAccept */, EmptyString(), + bs->PinReplyInternal(deviceAddress, false /* aAccept */, + BluetoothPinCode(), new BluetoothVoidReplyRunnable(nullptr, promise)); } else { // Ssp request BluetoothSspVariant variant; @@ -143,7 +168,7 @@ BluetoothPairingHandle::Reject(ErrorResult& aRv) promise, NS_ERROR_DOM_OPERATION_ERR); - bs->SspReplyInternal(mDeviceAddress, variant, false /* aAccept */, + bs->SspReplyInternal(deviceAddress, variant, false /* aAccept */, new BluetoothVoidReplyRunnable(nullptr, promise)); } diff --git a/dom/bluetooth/ipc/BluetoothMessageUtils.h b/dom/bluetooth/ipc/BluetoothMessageUtils.h index a5465ceac3..eab1a59e1b 100644 --- a/dom/bluetooth/ipc/BluetoothMessageUtils.h +++ b/dom/bluetooth/ipc/BluetoothMessageUtils.h @@ -12,6 +12,29 @@ namespace IPC { +template <> +struct ParamTraits +{ + typedef mozilla::dom::bluetooth::BluetoothAddress paramType; + + static void Write(Message* aMsg, const paramType& aParam) + { + for (size_t i = 0; i < MOZ_ARRAY_LENGTH(aParam.mAddr); ++i) { + WriteParam(aMsg, aParam.mAddr[i]); + } + } + + static bool Read(const Message* aMsg, void** aIter, paramType* aResult) + { + for (size_t i = 0; i < MOZ_ARRAY_LENGTH(aResult->mAddr); ++i) { + if (!ReadParam(aMsg, aIter, aResult->mAddr + i)) { + return false; + } + } + return true; + } +}; + template <> struct ParamTraits : public ContiguousEnumSerializer< @@ -20,6 +43,42 @@ struct ParamTraits mozilla::dom::bluetooth::NUM_TYPE> { }; +template <> +struct ParamTraits +{ + typedef mozilla::dom::bluetooth::BluetoothPinCode paramType; + + static void Write(Message* aMsg, const paramType& aParam) + { + WriteParam(aMsg, aParam.mLength); + for (uint8_t i = 0; i < aParam.mLength; ++i) { + WriteParam(aMsg, aParam.mPinCode[i]); + } + } + + static bool Read(const Message* aMsg, void** aIter, paramType* aResult) + { + if (!ReadParam(aMsg, aIter, &aResult->mLength)) { + return false; + } + + auto maxLength = MOZ_ARRAY_LENGTH(aResult->mPinCode); + + if (aResult->mLength > maxLength) { + return false; + } + for (uint8_t i = 0; i < aResult->mLength; ++i) { + if (!ReadParam(aMsg, aIter, aResult->mPinCode + i)) { + return false; + } + } + for (uint8_t i = aResult->mLength; i < maxLength; ++i) { + aResult->mPinCode[i] = 0; + } + return true; + } +}; + template <> struct ParamTraits : public ContiguousEnumSerializer< @@ -198,6 +257,42 @@ struct ParamTraits return true; } }; + +template <> +struct ParamTraits +{ + typedef mozilla::dom::bluetooth::ControlPlayStatus paramType; + + static void Write(Message* aMsg, const paramType& aParam) + { + WriteParam(aMsg, static_cast(aParam)); + } + + static bool Read(const Message* aMsg, void** aIter, paramType* aResult) + { + uint8_t value; + if (!ReadParam(aMsg, aIter, &value)) { + return false; + } + + mozilla::dom::bluetooth::ControlPlayStatus result = + static_cast(value); + + switch (result) { + case mozilla::dom::bluetooth::ControlPlayStatus::PLAYSTATUS_STOPPED: + case mozilla::dom::bluetooth::ControlPlayStatus::PLAYSTATUS_PLAYING: + case mozilla::dom::bluetooth::ControlPlayStatus::PLAYSTATUS_PAUSED: + case mozilla::dom::bluetooth::ControlPlayStatus::PLAYSTATUS_FWD_SEEK: + case mozilla::dom::bluetooth::ControlPlayStatus::PLAYSTATUS_REV_SEEK: + case mozilla::dom::bluetooth::ControlPlayStatus::PLAYSTATUS_ERROR: + *aResult = result; + return true; + default: + return false; + } + } +}; + } // namespace IPC #endif // mozilla_dom_bluetooth_ipc_BluetoothMessageUtils_h diff --git a/dom/bluetooth/ipc/BluetoothParent.cpp b/dom/bluetooth/ipc/BluetoothParent.cpp index 293c7c169d..d4a700c3f9 100644 --- a/dom/bluetooth/ipc/BluetoothParent.cpp +++ b/dom/bluetooth/ipc/BluetoothParent.cpp @@ -334,6 +334,9 @@ BluetoothParent::RecvPBluetoothRequestConstructor( return actor->DoRequest(aRequest.get_GattServerStopServiceRequest()); case Request::TGattServerSendResponseRequest: return actor->DoRequest(aRequest.get_GattServerSendResponseRequest()); + case Request::TGattServerSendIndicationRequest: + return actor->DoRequest( + aRequest.get_GattServerSendIndicationRequest()); default: MOZ_CRASH("Unknown type!"); } @@ -596,7 +599,7 @@ BluetoothRequestParent::DoRequest(const SetPinCodeRequest& aRequest) MOZ_ASSERT(mService); MOZ_ASSERT(mRequestType == Request::TSetPinCodeRequest); - mService->SetPinCodeInternal(aRequest.path(), + mService->SetPinCodeInternal(aRequest.address(), aRequest.pincode(), mReplyRunnable.get()); @@ -609,7 +612,7 @@ BluetoothRequestParent::DoRequest(const SetPasskeyRequest& aRequest) MOZ_ASSERT(mService); MOZ_ASSERT(mRequestType == Request::TSetPasskeyRequest); - mService->SetPasskeyInternal(aRequest.path(), + mService->SetPasskeyInternal(aRequest.address(), aRequest.passkey(), mReplyRunnable.get()); @@ -623,7 +626,7 @@ BluetoothRequestParent::DoRequest(const ConfirmPairingConfirmationRequest& MOZ_ASSERT(mService); MOZ_ASSERT(mRequestType == Request::TConfirmPairingConfirmationRequest); - mService->SetPairingConfirmationInternal(aRequest.path(), + mService->SetPairingConfirmationInternal(aRequest.address(), true, mReplyRunnable.get()); @@ -637,7 +640,7 @@ BluetoothRequestParent::DoRequest(const DenyPairingConfirmationRequest& MOZ_ASSERT(mService); MOZ_ASSERT(mRequestType == Request::TDenyPairingConfirmationRequest); - mService->SetPairingConfirmationInternal(aRequest.path(), + mService->SetPairingConfirmationInternal(aRequest.address(), false, mReplyRunnable.get()); @@ -677,7 +680,7 @@ BluetoothRequestParent::DoRequest(const SendFileRequest& aRequest) MOZ_ASSERT(mService); MOZ_ASSERT(mRequestType == Request::TSendFileRequest); - mService->SendFile(aRequest.devicePath(), + mService->SendFile(aRequest.address(), (BlobParent*)aRequest.blobParent(), (BlobChild*)aRequest.blobChild(), mReplyRunnable.get()); @@ -691,7 +694,7 @@ BluetoothRequestParent::DoRequest(const StopSendingFileRequest& aRequest) MOZ_ASSERT(mService); MOZ_ASSERT(mRequestType == Request::TStopSendingFileRequest); - mService->StopSendingFile(aRequest.devicePath(), + mService->StopSendingFile(aRequest.address(), mReplyRunnable.get()); return true; @@ -703,7 +706,7 @@ BluetoothRequestParent::DoRequest(const ConfirmReceivingFileRequest& aRequest) MOZ_ASSERT(mService); MOZ_ASSERT(mRequestType == Request::TConfirmReceivingFileRequest); - mService->ConfirmReceivingFile(aRequest.devicePath(), + mService->ConfirmReceivingFile(aRequest.address(), true, mReplyRunnable.get()); return true; @@ -715,7 +718,7 @@ BluetoothRequestParent::DoRequest(const DenyReceivingFileRequest& aRequest) MOZ_ASSERT(mService); MOZ_ASSERT(mRequestType == Request::TDenyReceivingFileRequest); - mService->ConfirmReceivingFile(aRequest.devicePath(), + mService->ConfirmReceivingFile(aRequest.address(), false, mReplyRunnable.get()); return true; @@ -1276,6 +1279,24 @@ BluetoothRequestParent::DoRequest( return true; } +bool +BluetoothRequestParent::DoRequest( + const GattServerSendIndicationRequest& aRequest) +{ + MOZ_ASSERT(mService); + MOZ_ASSERT(mRequestType == Request::TGattServerSendIndicationRequest); + + mService->GattServerSendIndicationInternal( + aRequest.appUuid(), + aRequest.address(), + aRequest.characteristicHandle(), + aRequest.confirm(), + aRequest.value(), + mReplyRunnable.get()); + + return true; +} + bool BluetoothRequestParent::DoRequest( const GattServerSendResponseRequest& aRequest) diff --git a/dom/bluetooth/ipc/BluetoothParent.h b/dom/bluetooth/ipc/BluetoothParent.h index 286efc27e4..96d9bb3a2a 100644 --- a/dom/bluetooth/ipc/BluetoothParent.h +++ b/dom/bluetooth/ipc/BluetoothParent.h @@ -327,6 +327,9 @@ protected: bool DoRequest(const GattServerSendResponseRequest& aRequest); + + bool + DoRequest(const GattServerSendIndicationRequest& aRequest); }; END_BLUETOOTH_NAMESPACE diff --git a/dom/bluetooth/ipc/BluetoothServiceChildProcess.cpp b/dom/bluetooth/ipc/BluetoothServiceChildProcess.cpp index 14560c6d9b..79c5920753 100644 --- a/dom/bluetooth/ipc/BluetoothServiceChildProcess.cpp +++ b/dom/bluetooth/ipc/BluetoothServiceChildProcess.cpp @@ -129,8 +129,8 @@ BluetoothServiceChildProcess::GetConnectedDevicePropertiesInternal( nsresult BluetoothServiceChildProcess::GetPairedDevicePropertiesInternal( - const nsTArray& aDeviceAddresses, - BluetoothReplyRunnable* aRunnable) + const nsTArray& aDeviceAddresses, + BluetoothReplyRunnable* aRunnable) { PairedDevicePropertiesRequest request; request.addresses().AppendElements(aDeviceAddresses); @@ -141,9 +141,9 @@ BluetoothServiceChildProcess::GetPairedDevicePropertiesInternal( nsresult BluetoothServiceChildProcess::FetchUuidsInternal( - const nsAString& aDeviceAddress, BluetoothReplyRunnable* aRunnable) + const BluetoothAddress& aDeviceAddress, BluetoothReplyRunnable* aRunnable) { - SendRequest(aRunnable, FetchUuidsRequest(nsString(aDeviceAddress))); + SendRequest(aRunnable, FetchUuidsRequest(aDeviceAddress)); return NS_OK; } @@ -163,15 +163,15 @@ BluetoothServiceChildProcess::StartDiscoveryInternal( void BluetoothServiceChildProcess::StopLeScanInternal( - const nsAString& aScanUuid, + const BluetoothUuid& aScanUuid, BluetoothReplyRunnable* aRunnable) { - SendRequest(aRunnable, StopLeScanRequest(nsString(aScanUuid))); + SendRequest(aRunnable, StopLeScanRequest(aScanUuid)); } void BluetoothServiceChildProcess::StartLeScanInternal( - const nsTArray& aServiceUuids, + const nsTArray& aServiceUuids, BluetoothReplyRunnable* aRunnable) { SendRequest(aRunnable, StartLeScanRequest(aServiceUuids)); @@ -188,22 +188,18 @@ BluetoothServiceChildProcess::SetProperty(BluetoothObjectType aType, nsresult BluetoothServiceChildProcess::CreatePairedDeviceInternal( - const nsAString& aAddress, - int aTimeout, - BluetoothReplyRunnable* aRunnable) + const BluetoothAddress& aDeviceAddress, int aTimeout, + BluetoothReplyRunnable* aRunnable) { - SendRequest(aRunnable, - PairRequest(nsString(aAddress), aTimeout)); + SendRequest(aRunnable, PairRequest(aDeviceAddress, aTimeout)); return NS_OK; } nsresult BluetoothServiceChildProcess::RemoveDeviceInternal( - const nsAString& aObjectPath, - BluetoothReplyRunnable* aRunnable) + const BluetoothAddress& aDeviceAddress, BluetoothReplyRunnable* aRunnable) { - SendRequest(aRunnable, - UnpairRequest(nsString(aObjectPath))); + SendRequest(aRunnable, UnpairRequest(aDeviceAddress)); return NS_OK; } @@ -224,98 +220,83 @@ BluetoothServiceChildProcess::UpdateSdpRecords(const BluetoothAddress& aDeviceAd void BluetoothServiceChildProcess::PinReplyInternal( - const nsAString& aDeviceAddress, bool aAccept, - const nsAString& aPinCode, BluetoothReplyRunnable* aRunnable) + const BluetoothAddress& aDeviceAddress, bool aAccept, + const BluetoothPinCode& aPinCode, BluetoothReplyRunnable* aRunnable) { - SendRequest(aRunnable, - PinReplyRequest(nsString(aDeviceAddress), - aAccept, - nsString(aPinCode))); + SendRequest(aRunnable, PinReplyRequest(aDeviceAddress, aAccept, aPinCode)); } void BluetoothServiceChildProcess::SspReplyInternal( - const nsAString& aDeviceAddress, BluetoothSspVariant aVariant, - bool aAccept, BluetoothReplyRunnable* aRunnable) + const BluetoothAddress& aDeviceAddress, + BluetoothSspVariant aVariant, bool aAccept, + BluetoothReplyRunnable* aRunnable) { - SendRequest(aRunnable, - SspReplyRequest(nsString(aDeviceAddress), - aVariant, - aAccept)); + SendRequest(aRunnable, SspReplyRequest(aDeviceAddress, aVariant, aAccept)); } void BluetoothServiceChildProcess::SetPinCodeInternal( - const nsAString& aDeviceAddress, - const nsAString& aPinCode, - BluetoothReplyRunnable* aRunnable) + const BluetoothAddress& aDeviceAddress, + const BluetoothPinCode& aPinCode, + BluetoothReplyRunnable* aRunnable) { - SendRequest(aRunnable, - SetPinCodeRequest(nsString(aDeviceAddress), nsString(aPinCode))); + SendRequest(aRunnable, SetPinCodeRequest(aDeviceAddress, aPinCode)); } void BluetoothServiceChildProcess::SetPasskeyInternal( - const nsAString& aDeviceAddress, - uint32_t aPasskey, - BluetoothReplyRunnable* aRunnable) + const BluetoothAddress& aDeviceAddress, + uint32_t aPasskey, + BluetoothReplyRunnable* aRunnable) { - SendRequest(aRunnable, - SetPasskeyRequest(nsString(aDeviceAddress), aPasskey)); + SendRequest(aRunnable, SetPasskeyRequest(aDeviceAddress, aPasskey)); } void BluetoothServiceChildProcess::SetPairingConfirmationInternal( - const nsAString& aDeviceAddress, + const BluetoothAddress& aDeviceAddress, bool aConfirm, BluetoothReplyRunnable* aRunnable) { - if(aConfirm) { - SendRequest(aRunnable, - ConfirmPairingConfirmationRequest(nsString(aDeviceAddress))); + if (aConfirm) { + SendRequest(aRunnable, ConfirmPairingConfirmationRequest(aDeviceAddress)); } else { - SendRequest(aRunnable, - DenyPairingConfirmationRequest(nsString(aDeviceAddress))); + SendRequest(aRunnable, DenyPairingConfirmationRequest(aDeviceAddress)); } } void BluetoothServiceChildProcess::Connect( - const nsAString& aDeviceAddress, - uint32_t aCod, - uint16_t aServiceUuid, + const BluetoothAddress& aDeviceAddress, + uint32_t aCod, uint16_t aServiceUuid, BluetoothReplyRunnable* aRunnable) { - SendRequest(aRunnable, - ConnectRequest(nsString(aDeviceAddress), - aCod, - aServiceUuid)); + SendRequest(aRunnable, ConnectRequest(aDeviceAddress, aCod, aServiceUuid)); } void BluetoothServiceChildProcess::Disconnect( - const nsAString& aDeviceAddress, + const BluetoothAddress& aDeviceAddress, uint16_t aServiceUuid, BluetoothReplyRunnable* aRunnable) { - SendRequest(aRunnable, - DisconnectRequest(nsString(aDeviceAddress), aServiceUuid)); + SendRequest(aRunnable, DisconnectRequest(aDeviceAddress, aServiceUuid)); } void BluetoothServiceChildProcess::SendFile( - const nsAString& aDeviceAddress, + const BluetoothAddress& aDeviceAddress, BlobParent* aBlobParent, BlobChild* aBlobChild, BluetoothReplyRunnable* aRunnable) { - SendRequest(aRunnable, - SendFileRequest(nsString(aDeviceAddress), nullptr, aBlobChild)); + SendRequest(aRunnable, SendFileRequest(aDeviceAddress, nullptr, aBlobChild)); } void BluetoothServiceChildProcess::SendFile( - const nsAString& aDeviceAddress, + const BluetoothAddress& aDeviceAddress, Blob* aBlobChild, BluetoothReplyRunnable* aRunnable) { @@ -325,27 +306,23 @@ BluetoothServiceChildProcess::SendFile( void BluetoothServiceChildProcess::StopSendingFile( - const nsAString& aDeviceAddress, + const BluetoothAddress& aDeviceAddress, BluetoothReplyRunnable* aRunnable) { - SendRequest(aRunnable, - StopSendingFileRequest(nsString(aDeviceAddress))); + SendRequest(aRunnable, StopSendingFileRequest(aDeviceAddress)); } void BluetoothServiceChildProcess::ConfirmReceivingFile( - const nsAString& aDeviceAddress, - bool aConfirm, + const BluetoothAddress& aDeviceAddress, bool aConfirm, BluetoothReplyRunnable* aRunnable) { if(aConfirm) { - SendRequest(aRunnable, - ConfirmReceivingFileRequest(nsString(aDeviceAddress))); + SendRequest(aRunnable, ConfirmReceivingFileRequest(aDeviceAddress)); return; } - SendRequest(aRunnable, - DenyReceivingFileRequest(nsString(aDeviceAddress))); + SendRequest(aRunnable, DenyReceivingFileRequest(aDeviceAddress)); } void @@ -564,56 +541,53 @@ BluetoothServiceChildProcess::SendMetaData(const nsAString& aTitle, void BluetoothServiceChildProcess::SendPlayStatus(int64_t aDuration, int64_t aPosition, - const nsAString& aPlayStatus, + ControlPlayStatus aPlayStatus, BluetoothReplyRunnable* aRunnable) { SendRequest(aRunnable, - SendPlayStatusRequest(aDuration, aPosition, - nsString(aPlayStatus))); + SendPlayStatusRequest(aDuration, aPosition, aPlayStatus)); } void BluetoothServiceChildProcess::ConnectGattClientInternal( - const nsAString& aAppUuid, const nsAString& aDeviceAddress, + const BluetoothUuid& aAppUuid, const BluetoothAddress& aDeviceAddress, BluetoothReplyRunnable* aRunnable) { - SendRequest(aRunnable, ConnectGattClientRequest(nsString(aAppUuid), - nsString(aDeviceAddress))); + SendRequest(aRunnable, ConnectGattClientRequest(aAppUuid, aDeviceAddress)); } void BluetoothServiceChildProcess::DisconnectGattClientInternal( - const nsAString& aAppUuid, const nsAString& aDeviceAddress, + const BluetoothUuid& aAppUuid, const BluetoothAddress& aDeviceAddress, BluetoothReplyRunnable* aRunnable) { SendRequest(aRunnable, - DisconnectGattClientRequest(nsString(aAppUuid), nsString(aDeviceAddress))); + DisconnectGattClientRequest(aAppUuid, aDeviceAddress)); } void BluetoothServiceChildProcess::DiscoverGattServicesInternal( - const nsAString& aAppUuid, BluetoothReplyRunnable* aRunnable) + const BluetoothUuid& aAppUuid, BluetoothReplyRunnable* aRunnable) { - SendRequest(aRunnable, - DiscoverGattServicesRequest(nsString(aAppUuid))); + SendRequest(aRunnable, DiscoverGattServicesRequest(aAppUuid)); } void BluetoothServiceChildProcess::GattClientStartNotificationsInternal( - const nsAString& aAppUuid, const BluetoothGattServiceId& aServId, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServId, const BluetoothGattId& aCharId, BluetoothReplyRunnable* aRunnable) { SendRequest(aRunnable, - GattClientStartNotificationsRequest(nsString(aAppUuid), aServId, aCharId)); + GattClientStartNotificationsRequest(aAppUuid, aServId, aCharId)); } void BluetoothServiceChildProcess::GattClientStopNotificationsInternal( - const nsAString& aAppUuid, const BluetoothGattServiceId& aServId, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServId, const BluetoothGattId& aCharId, BluetoothReplyRunnable* aRunnable) { SendRequest(aRunnable, - GattClientStopNotificationsRequest(nsString(aAppUuid), aServId, aCharId)); + GattClientStopNotificationsRequest(aAppUuid, aServId, aCharId)); } void @@ -625,30 +599,29 @@ BluetoothServiceChildProcess::UnregisterGattClientInternal( void BluetoothServiceChildProcess::GattClientReadRemoteRssiInternal( - int aClientIf, const nsAString& aDeviceAddress, + int aClientIf, const BluetoothAddress& aDeviceAddress, BluetoothReplyRunnable* aRunnable) { SendRequest(aRunnable, - GattClientReadRemoteRssiRequest(aClientIf, - nsString(aDeviceAddress))); + GattClientReadRemoteRssiRequest(aClientIf, aDeviceAddress)); } void BluetoothServiceChildProcess::GattClientReadCharacteristicValueInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServiceId, const BluetoothGattId& aCharacteristicId, BluetoothReplyRunnable* aRunnable) { SendRequest(aRunnable, - GattClientReadCharacteristicValueRequest(nsString(aAppUuid), + GattClientReadCharacteristicValueRequest(aAppUuid, aServiceId, aCharacteristicId)); } void BluetoothServiceChildProcess::GattClientWriteCharacteristicValueInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServiceId, const BluetoothGattId& aCharacteristicId, const BluetoothGattWriteType& aWriteType, @@ -656,7 +629,7 @@ BluetoothServiceChildProcess::GattClientWriteCharacteristicValueInternal( BluetoothReplyRunnable* aRunnable) { SendRequest(aRunnable, - GattClientWriteCharacteristicValueRequest(nsString(aAppUuid), + GattClientWriteCharacteristicValueRequest(aAppUuid, aServiceId, aCharacteristicId, aWriteType, @@ -665,14 +638,14 @@ BluetoothServiceChildProcess::GattClientWriteCharacteristicValueInternal( void BluetoothServiceChildProcess::GattClientReadDescriptorValueInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServiceId, const BluetoothGattId& aCharacteristicId, const BluetoothGattId& aDescriptorId, BluetoothReplyRunnable* aRunnable) { SendRequest(aRunnable, - GattClientReadDescriptorValueRequest(nsString(aAppUuid), + GattClientReadDescriptorValueRequest(aAppUuid, aServiceId, aCharacteristicId, aDescriptorId)); @@ -680,7 +653,7 @@ BluetoothServiceChildProcess::GattClientReadDescriptorValueInternal( void BluetoothServiceChildProcess::GattClientWriteDescriptorValueInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServiceId, const BluetoothGattId& aCharacteristicId, const BluetoothGattId& aDescriptorId, @@ -688,7 +661,7 @@ BluetoothServiceChildProcess::GattClientWriteDescriptorValueInternal( BluetoothReplyRunnable* aRunnable) { SendRequest(aRunnable, - GattClientWriteDescriptorValueRequest(nsString(aAppUuid), + GattClientWriteDescriptorValueRequest(aAppUuid, aServiceId, aCharacteristicId, aDescriptorId, @@ -697,24 +670,22 @@ BluetoothServiceChildProcess::GattClientWriteDescriptorValueInternal( void BluetoothServiceChildProcess::GattServerConnectPeripheralInternal( - const nsAString& aAppUuid, - const nsAString& aAddress, + const BluetoothUuid& aAppUuid, + const BluetoothAddress& aAddress, BluetoothReplyRunnable* aRunnable) { SendRequest(aRunnable, - GattServerConnectPeripheralRequest(nsString(aAppUuid), - nsString(aAddress))); + GattServerConnectPeripheralRequest(aAppUuid, aAddress)); } void BluetoothServiceChildProcess::GattServerDisconnectPeripheralInternal( - const nsAString& aAppUuid, - const nsAString& aAddress, + const BluetoothUuid& aAppUuid, + const BluetoothAddress& aAddress, BluetoothReplyRunnable* aRunnable) { SendRequest(aRunnable, - GattServerDisconnectPeripheralRequest(nsString(aAppUuid), - nsString(aAddress))); + GattServerDisconnectPeripheralRequest(aAppUuid, aAddress)); } void @@ -726,31 +697,31 @@ BluetoothServiceChildProcess::UnregisterGattServerInternal( void BluetoothServiceChildProcess::GattServerAddServiceInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServiceId, uint16_t aHandleCount, BluetoothReplyRunnable* aRunnable) { SendRequest(aRunnable, - GattServerAddServiceRequest(nsString(aAppUuid), aServiceId, aHandleCount)); + GattServerAddServiceRequest(aAppUuid, aServiceId, aHandleCount)); } void BluetoothServiceChildProcess::GattServerAddIncludedServiceInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothAttributeHandle& aServiceHandle, const BluetoothAttributeHandle& aIncludedServiceHandle, BluetoothReplyRunnable* aRunnable) { SendRequest(aRunnable, - GattServerAddIncludedServiceRequest(nsString(aAppUuid), + GattServerAddIncludedServiceRequest(aAppUuid, aServiceHandle, aIncludedServiceHandle)); } void BluetoothServiceChildProcess::GattServerAddCharacteristicInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothAttributeHandle& aServiceHandle, const BluetoothUuid& aCharacteristicUuid, BluetoothGattAttrPerm aPermissions, @@ -758,7 +729,7 @@ BluetoothServiceChildProcess::GattServerAddCharacteristicInternal( BluetoothReplyRunnable* aRunnable) { SendRequest(aRunnable, - GattServerAddCharacteristicRequest(nsString(aAppUuid), + GattServerAddCharacteristicRequest(aAppUuid, aServiceHandle, aCharacteristicUuid, aPermissions, @@ -767,7 +738,7 @@ BluetoothServiceChildProcess::GattServerAddCharacteristicInternal( void BluetoothServiceChildProcess::GattServerAddDescriptorInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothAttributeHandle& aServiceHandle, const BluetoothAttributeHandle& aCharacteristicHandle, const BluetoothUuid& aDescriptorUuid, @@ -775,7 +746,7 @@ BluetoothServiceChildProcess::GattServerAddDescriptorInternal( BluetoothReplyRunnable* aRunnable) { SendRequest(aRunnable, - GattServerAddDescriptorRequest(nsString(aAppUuid), + GattServerAddDescriptorRequest(aAppUuid, aServiceHandle, aCharacteristicHandle, aDescriptorUuid, @@ -784,46 +755,66 @@ BluetoothServiceChildProcess::GattServerAddDescriptorInternal( void BluetoothServiceChildProcess::GattServerRemoveServiceInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothAttributeHandle& aServiceHandle, BluetoothReplyRunnable* aRunnable) { SendRequest(aRunnable, - GattServerRemoveServiceRequest(nsString(aAppUuid), aServiceHandle)); + GattServerRemoveServiceRequest(aAppUuid, aServiceHandle)); } void BluetoothServiceChildProcess::GattServerStartServiceInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothAttributeHandle& aServiceHandle, BluetoothReplyRunnable* aRunnable) { SendRequest(aRunnable, - GattServerStartServiceRequest(nsString(aAppUuid), aServiceHandle)); + GattServerStartServiceRequest(aAppUuid, aServiceHandle)); } void BluetoothServiceChildProcess::GattServerStopServiceInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothAttributeHandle& aServiceHandle, BluetoothReplyRunnable* aRunnable) { SendRequest(aRunnable, - GattServerStopServiceRequest(nsString(aAppUuid), aServiceHandle)); + GattServerStopServiceRequest(aAppUuid, aServiceHandle)); } void BluetoothServiceChildProcess::GattServerSendResponseInternal( - const nsAString& aAppUuid, - const nsAString& aAddress, + const BluetoothUuid& aAppUuid, + const BluetoothAddress& aAddress, uint16_t aStatus, int32_t aRequestId, const BluetoothGattResponse& aRsp, BluetoothReplyRunnable* aRunnable) { SendRequest(aRunnable, - GattServerSendResponseRequest( - nsString(aAppUuid), nsString(aAddress), aStatus, aRequestId, aRsp)); + GattServerSendResponseRequest(aAppUuid, + aAddress, + aStatus, + aRequestId, + aRsp)); +} + +void +BluetoothServiceChildProcess::GattServerSendIndicationInternal( + const BluetoothUuid& aAppUuid, + const BluetoothAddress& aAddress, + const BluetoothAttributeHandle& aCharacteristicHandle, + bool aConfirm, + const nsTArray& aValue, + BluetoothReplyRunnable* aRunnable) +{ + SendRequest(aRunnable, + GattServerSendIndicationRequest(aAppUuid, + aAddress, + aCharacteristicHandle, + aConfirm, + aValue)); } nsresult diff --git a/dom/bluetooth/ipc/BluetoothServiceChildProcess.h b/dom/bluetooth/ipc/BluetoothServiceChildProcess.h index 9317d0d1f7..6970b1e733 100644 --- a/dom/bluetooth/ipc/BluetoothServiceChildProcess.h +++ b/dom/bluetooth/ipc/BluetoothServiceChildProcess.h @@ -41,7 +41,7 @@ public: StopInternal(BluetoothReplyRunnable* aRunnable) override; virtual nsresult - GetPairedDevicePropertiesInternal(const nsTArray& aDeviceAddresses, + GetPairedDevicePropertiesInternal(const nsTArray& aDeviceAddresses, BluetoothReplyRunnable* aRunnable) override; @@ -50,7 +50,7 @@ public: BluetoothReplyRunnable* aRunnable) override; virtual nsresult - FetchUuidsInternal(const nsAString& aDeviceAddress, + FetchUuidsInternal(const BluetoothAddress& aDeviceAddress, BluetoothReplyRunnable* aRunnable) override; virtual void @@ -60,11 +60,11 @@ public: StartDiscoveryInternal(BluetoothReplyRunnable* aRunnable) override; virtual void - StopLeScanInternal(const nsAString& aScanUuid, + StopLeScanInternal(const BluetoothUuid& aScanUuid, BluetoothReplyRunnable* aRunnable) override; virtual void - StartLeScanInternal(const nsTArray& aServiceUuids, + StartLeScanInternal(const nsTArray& aServiceUuids, BluetoothReplyRunnable* aRunnable) override; virtual nsresult @@ -73,12 +73,12 @@ public: BluetoothReplyRunnable* aRunnable) override; virtual nsresult - CreatePairedDeviceInternal(const nsAString& aAddress, + CreatePairedDeviceInternal(const BluetoothAddress& aDeviceAddress, int aTimeout, BluetoothReplyRunnable* aRunnable) override; virtual nsresult - RemoveDeviceInternal(const nsAString& aObjectPath, + RemoveDeviceInternal(const BluetoothAddress& aDeviceAddress, BluetoothReplyRunnable* aRunnable) override; virtual nsresult @@ -91,61 +91,61 @@ public: BluetoothProfileManagerBase* aManager) override; virtual void - SetPinCodeInternal(const nsAString& aDeviceAddress, - const nsAString& aPinCode, + SetPinCodeInternal(const BluetoothAddress& aDeviceAddress, + const BluetoothPinCode& aPinCode, BluetoothReplyRunnable* aRunnable) override; virtual void - SetPasskeyInternal(const nsAString& aDeviceAddress, + SetPasskeyInternal(const BluetoothAddress& aDeviceAddress, uint32_t aPasskey, BluetoothReplyRunnable* aRunnable) override; virtual void - SetPairingConfirmationInternal(const nsAString& aDeviceAddress, + SetPairingConfirmationInternal(const BluetoothAddress& aDeviceAddress, bool aConfirm, BluetoothReplyRunnable* aRunnable) override; virtual void - PinReplyInternal(const nsAString& aDeviceAddress, + PinReplyInternal(const BluetoothAddress& aDeviceAddress, bool aAccept, - const nsAString& aPinCode, + const BluetoothPinCode& aPinCode, BluetoothReplyRunnable* aRunnable) override; virtual void - SspReplyInternal(const nsAString& aDeviceAddress, + SspReplyInternal(const BluetoothAddress& aDeviceAddress, BluetoothSspVariant aVariant, bool aAccept, BluetoothReplyRunnable* aRunnable) override; virtual void - Connect(const nsAString& aDeviceAddress, + Connect(const BluetoothAddress& aDeviceAddress, uint32_t aCod, uint16_t aServiceUuid, BluetoothReplyRunnable* aRunnable) override; virtual void - Disconnect(const nsAString& aDeviceAddress, + Disconnect(const BluetoothAddress& aDeviceAddress, uint16_t aServiceUuid, BluetoothReplyRunnable* aRunnable) override; virtual void - SendFile(const nsAString& aDeviceAddress, + SendFile(const BluetoothAddress& aDeviceAddress, BlobParent* aBlobParent, BlobChild* aBlobChild, BluetoothReplyRunnable* aRunnable) override; virtual void - SendFile(const nsAString& aDeviceAddress, + SendFile(const BluetoothAddress& aDeviceAddress, Blob* aBlob, BluetoothReplyRunnable* aRunnable) override; virtual void - StopSendingFile(const nsAString& aDeviceAddress, + StopSendingFile(const BluetoothAddress& aDeviceAddress, BluetoothReplyRunnable* aRunnable) override; virtual void - ConfirmReceivingFile(const nsAString& aDeviceAddress, + ConfirmReceivingFile(const BluetoothAddress& aDeviceAddress, bool aConfirm, BluetoothReplyRunnable* aRunnable) override; @@ -267,7 +267,7 @@ public: virtual void SendPlayStatus(int64_t aDuration, int64_t aPosition, - const nsAString& aPlayStatus, + ControlPlayStatus aPlayStatus, BluetoothReplyRunnable* aRunnable) override; virtual void @@ -284,29 +284,29 @@ public: const nsAString& aMessage) override; virtual void - ConnectGattClientInternal(const nsAString& aAppUuid, - const nsAString& aDeviceAddress, + ConnectGattClientInternal(const BluetoothUuid& aAppUuid, + const BluetoothAddress& aDeviceAddress, BluetoothReplyRunnable* aRunnable) override; virtual void - DisconnectGattClientInternal(const nsAString& aAppUuid, - const nsAString& aDeviceAddress, + DisconnectGattClientInternal(const BluetoothUuid& aAppUuid, + const BluetoothAddress& aDeviceAddress, BluetoothReplyRunnable* aRunnable) override; virtual void - DiscoverGattServicesInternal(const nsAString& aAppUuid, + DiscoverGattServicesInternal(const BluetoothUuid& aAppUuid, BluetoothReplyRunnable* aRunnable) override; virtual void GattClientStartNotificationsInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServId, const BluetoothGattId& aCharId, BluetoothReplyRunnable* aRunnable) override; virtual void GattClientStopNotificationsInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServId, const BluetoothGattId& aCharId, BluetoothReplyRunnable* aRunnable) override; @@ -317,19 +317,19 @@ public: virtual void GattClientReadRemoteRssiInternal(int aClientIf, - const nsAString& aDeviceAddress, + const BluetoothAddress& aDeviceAddress, BluetoothReplyRunnable* aRunnable) override; virtual void GattClientReadCharacteristicValueInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServiceId, const BluetoothGattId& aCharacteristicId, BluetoothReplyRunnable* aRunnable) override; virtual void GattClientWriteCharacteristicValueInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServiceId, const BluetoothGattId& aCharacteristicId, const BluetoothGattWriteType& aWriteType, @@ -338,7 +338,7 @@ public: virtual void GattClientReadDescriptorValueInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServiceId, const BluetoothGattId& aCharacteristicId, const BluetoothGattId& aDescriptorId, @@ -346,7 +346,7 @@ public: virtual void GattClientWriteDescriptorValueInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServiceId, const BluetoothGattId& aCharacteristicId, const BluetoothGattId& aDescriptorId, @@ -355,14 +355,14 @@ public: virtual void GattServerConnectPeripheralInternal( - const nsAString& aAppUuid, - const nsAString& aAddress, + const BluetoothUuid& aAppUuid, + const BluetoothAddress& aAddress, BluetoothReplyRunnable* aRunnable) override; virtual void GattServerDisconnectPeripheralInternal( - const nsAString& aAppUuid, - const nsAString& aAddress, + const BluetoothUuid& aAppUuid, + const BluetoothAddress& aAddress, BluetoothReplyRunnable* aRunnable) override; virtual void @@ -371,21 +371,21 @@ public: virtual void GattServerAddServiceInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothGattServiceId& aServiceId, uint16_t aHandleCount, BluetoothReplyRunnable* aRunnable) override; virtual void GattServerAddIncludedServiceInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothAttributeHandle& aServiceHandle, const BluetoothAttributeHandle& aIncludedServiceHandle, BluetoothReplyRunnable* aRunnable) override; virtual void GattServerAddCharacteristicInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothAttributeHandle& aServiceHandle, const BluetoothUuid& aCharacteristicUuid, BluetoothGattAttrPerm aPermissions, @@ -394,7 +394,7 @@ public: virtual void GattServerAddDescriptorInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothAttributeHandle& aServiceHandle, const BluetoothAttributeHandle& aCharacteristicHandle, const BluetoothUuid& aDescriptorUuid, @@ -403,31 +403,40 @@ public: virtual void GattServerRemoveServiceInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothAttributeHandle& aServiceHandle, BluetoothReplyRunnable* aRunnable) override; virtual void GattServerStartServiceInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothAttributeHandle& aServiceHandle, BluetoothReplyRunnable* aRunnable) override; virtual void GattServerStopServiceInternal( - const nsAString& aAppUuid, + const BluetoothUuid& aAppUuid, const BluetoothAttributeHandle& aServiceHandle, BluetoothReplyRunnable* aRunnable) override; virtual void GattServerSendResponseInternal( - const nsAString& aAppUuid, - const nsAString& aAddress, + const BluetoothUuid& aAppUuid, + const BluetoothAddress& aAddress, uint16_t aStatus, int32_t aRequestId, const BluetoothGattResponse& aRsp, BluetoothReplyRunnable* aRunnable) override; + virtual void + GattServerSendIndicationInternal( + const BluetoothUuid& aAppUuid, + const BluetoothAddress& aAddress, + const BluetoothAttributeHandle& aCharacteristicHandle, + bool aConfirm, + const nsTArray& aValue, + BluetoothReplyRunnable* aRunnable) override; + protected: BluetoothServiceChildProcess(); virtual ~BluetoothServiceChildProcess(); diff --git a/dom/bluetooth/ipc/PBluetooth.ipdl b/dom/bluetooth/ipc/PBluetooth.ipdl index 71227744d9..5a128f24b2 100644 --- a/dom/bluetooth/ipc/PBluetooth.ipdl +++ b/dom/bluetooth/ipc/PBluetooth.ipdl @@ -12,7 +12,14 @@ include BluetoothTypes; include "mozilla/dom/bluetooth/ipc/BluetoothMessageUtils.h"; -using mozilla::dom::bluetooth::BluetoothObjectType from "mozilla/dom/bluetooth/BluetoothCommon.h"; +using mozilla::dom::bluetooth::BluetoothAddress + from "mozilla/dom/bluetooth/BluetoothCommon.h"; +using mozilla::dom::bluetooth::BluetoothObjectType + from "mozilla/dom/bluetooth/BluetoothCommon.h"; +using mozilla::dom::bluetooth::BluetoothPinCode + from "mozilla/dom/bluetooth/BluetoothCommon.h"; +using mozilla::dom::bluetooth::ControlPlayStatus + from "mozilla/dom/bluetooth/BluetoothCommon.h"; namespace mozilla { namespace dom { @@ -42,7 +49,7 @@ struct SetPropertyRequest struct GetPropertyRequest { BluetoothObjectType type; - nsString path; + BluetoothAddress address; }; struct StartDiscoveryRequest @@ -55,64 +62,64 @@ struct StopDiscoveryRequest struct StartLeScanRequest { - nsString[] serviceUuids; + BluetoothUuid[] serviceUuids; }; struct StopLeScanRequest { - nsString scanUuid; + BluetoothUuid scanUuid; }; struct PairRequest { - nsString address; + BluetoothAddress address; uint32_t timeoutMS; }; struct UnpairRequest { - nsString address; + BluetoothAddress address; }; struct PinReplyRequest { - nsString address; + BluetoothAddress address; bool accept; - nsString pinCode; + BluetoothPinCode pinCode; }; struct SspReplyRequest { - nsString address; + BluetoothAddress address; BluetoothSspVariant variant; bool accept; }; struct SetPinCodeRequest { - nsString path; - nsString pincode; + BluetoothAddress address; + BluetoothPinCode pincode; }; struct SetPasskeyRequest { - nsString path; + BluetoothAddress address; uint32_t passkey; }; struct ConfirmPairingConfirmationRequest { - nsString path; + BluetoothAddress address; }; struct DenyPairingConfirmationRequest { - nsString path; + BluetoothAddress address; }; struct PairedDevicePropertiesRequest { - nsString[] addresses; + BluetoothAddress[] addresses; }; struct ConnectedDevicePropertiesRequest @@ -122,41 +129,41 @@ struct ConnectedDevicePropertiesRequest struct FetchUuidsRequest { - nsString address; + BluetoothAddress address; }; struct ConnectRequest { - nsString address; + BluetoothAddress address; uint32_t cod; uint16_t serviceUuid; }; struct DisconnectRequest { - nsString address; + BluetoothAddress address; uint16_t serviceUuid; }; struct SendFileRequest { - nsString devicePath; + BluetoothAddress address; PBlob blob; }; struct StopSendingFileRequest { - nsString devicePath; + BluetoothAddress address; }; struct ConfirmReceivingFileRequest { - nsString devicePath; + BluetoothAddress address; }; struct DenyReceivingFileRequest { - nsString devicePath; + BluetoothAddress address; }; struct ConnectScoRequest @@ -263,36 +270,36 @@ struct SendPlayStatusRequest { int64_t duration; int64_t position; - nsString playStatus; + ControlPlayStatus playStatus; }; struct ConnectGattClientRequest { - nsString appUuid; - nsString deviceAddress; + BluetoothUuid appUuid; + BluetoothAddress deviceAddress; }; struct DisconnectGattClientRequest { - nsString appUuid; - nsString deviceAddress; + BluetoothUuid appUuid; + BluetoothAddress deviceAddress; }; struct DiscoverGattServicesRequest { - nsString appUuid; + BluetoothUuid appUuid; }; struct GattClientStartNotificationsRequest { - nsString appUuid; + BluetoothUuid appUuid; BluetoothGattServiceId servId; BluetoothGattId charId; }; struct GattClientStopNotificationsRequest { - nsString appUuid; + BluetoothUuid appUuid; BluetoothGattServiceId servId; BluetoothGattId charId; }; @@ -305,19 +312,19 @@ struct UnregisterGattClientRequest struct GattClientReadRemoteRssiRequest { int clientIf; - nsString deviceAddress; + BluetoothAddress deviceAddress; }; struct GattClientReadCharacteristicValueRequest { - nsString appUuid; + BluetoothUuid appUuid; BluetoothGattServiceId serviceId; BluetoothGattId charId; }; struct GattClientWriteCharacteristicValueRequest { - nsString appUuid; + BluetoothUuid appUuid; BluetoothGattServiceId serviceId; BluetoothGattId charId; BluetoothGattWriteType writeType; @@ -326,7 +333,7 @@ struct GattClientWriteCharacteristicValueRequest struct GattClientReadDescriptorValueRequest { - nsString appUuid; + BluetoothUuid appUuid; BluetoothGattServiceId serviceId; BluetoothGattId charId; BluetoothGattId descId; @@ -334,7 +341,7 @@ struct GattClientReadDescriptorValueRequest struct GattClientWriteDescriptorValueRequest { - nsString appUuid; + BluetoothUuid appUuid; BluetoothGattServiceId serviceId; BluetoothGattId charId; BluetoothGattId descId; @@ -343,14 +350,14 @@ struct GattClientWriteDescriptorValueRequest struct GattServerConnectPeripheralRequest { - nsString appUuid; - nsString address; + BluetoothUuid appUuid; + BluetoothAddress address; }; struct GattServerDisconnectPeripheralRequest { - nsString appUuid; - nsString address; + BluetoothUuid appUuid; + BluetoothAddress address; }; struct UnregisterGattServerRequest @@ -360,21 +367,21 @@ struct UnregisterGattServerRequest struct GattServerAddServiceRequest { - nsString appUuid; + BluetoothUuid appUuid; BluetoothGattServiceId serviceId; uint16_t handleCount; }; struct GattServerAddIncludedServiceRequest { - nsString appUuid; + BluetoothUuid appUuid; BluetoothAttributeHandle serviceHandle; BluetoothAttributeHandle includedServiceHandle; }; struct GattServerAddCharacteristicRequest { - nsString appUuid; + BluetoothUuid appUuid; BluetoothAttributeHandle serviceHandle; BluetoothUuid characteristicUuid; BluetoothGattAttrPerm permissions; @@ -383,7 +390,7 @@ struct GattServerAddCharacteristicRequest struct GattServerAddDescriptorRequest { - nsString appUuid; + BluetoothUuid appUuid; BluetoothAttributeHandle serviceHandle; BluetoothAttributeHandle characteristicHandle; BluetoothUuid descriptorUuid; @@ -392,31 +399,40 @@ struct GattServerAddDescriptorRequest struct GattServerRemoveServiceRequest { - nsString appUuid; + BluetoothUuid appUuid; BluetoothAttributeHandle serviceHandle; }; struct GattServerStartServiceRequest { - nsString appUuid; + BluetoothUuid appUuid; BluetoothAttributeHandle serviceHandle; }; struct GattServerStopServiceRequest { - nsString appUuid; + BluetoothUuid appUuid; BluetoothAttributeHandle serviceHandle; }; struct GattServerSendResponseRequest { - nsString appUuid; - nsString address; + BluetoothUuid appUuid; + BluetoothAddress address; uint16_t status; int32_t requestId; BluetoothGattResponse response; }; +struct GattServerSendIndicationRequest +{ + BluetoothUuid appUuid; + BluetoothAddress address; + BluetoothAttributeHandle characteristicHandle; + bool confirm; + uint8_t[] value; +}; + union Request { GetAdaptersRequest; @@ -486,6 +502,7 @@ union Request GattServerStartServiceRequest; GattServerStopServiceRequest; GattServerSendResponseRequest; + GattServerSendIndicationRequest; }; protocol PBluetooth diff --git a/dom/bluetooth/moz.build b/dom/bluetooth/moz.build index fddf9d0b1e..4977b95ff1 100644 --- a/dom/bluetooth/moz.build +++ b/dom/bluetooth/moz.build @@ -16,7 +16,6 @@ if CONFIG['MOZ_B2G_BT']: ] SOURCES += [ - 'common/BluetoothCommon.cpp', 'common/BluetoothHidManager.cpp', 'common/BluetoothInterface.cpp', 'common/BluetoothProfileController.cpp', @@ -130,8 +129,6 @@ if CONFIG['MOZ_B2G_BT']: DEFINES['MOZ_BLUETOOTH_DBUS'] = True DEFINES['HAVE_PTHREADS'] = True - FINAL_LIBRARY = 'xul' - # # Exported interfaces # @@ -160,6 +157,11 @@ EXPORTS.mozilla.dom.bluetooth += [ 'common/webapi/BluetoothPairingListener.h', 'common/webapi/BluetoothPbapRequestHandle.h' ] + +UNIFIED_SOURCES += [ + 'common/BluetoothCommon.cpp', +] + IPDL_SOURCES += [ 'ipc/BluetoothTypes.ipdlh', 'ipc/PBluetooth.ipdl', @@ -173,3 +175,5 @@ LOCAL_INCLUDES += [ ] include('/ipc/chromium/chromium-config.mozbuild') + +FINAL_LIBRARY = 'xul' diff --git a/dom/events/EventDispatcher.cpp b/dom/events/EventDispatcher.cpp index ec10403fca..b2f829cac0 100644 --- a/dom/events/EventDispatcher.cpp +++ b/dom/events/EventDispatcher.cpp @@ -642,9 +642,10 @@ EventDispatcher::Dispatch(nsISupports* aTarget, if (NS_SUCCEEDED(rv)) { if (aTargets) { aTargets->Clear(); - aTargets->SetCapacity(chain.Length()); - for (uint32_t i = 0; i < chain.Length(); ++i) { - aTargets->AppendElement(chain[i].CurrentTarget()->GetTargetForDOMEvent()); + uint32_t numTargets = chain.Length(); + EventTarget** targets = aTargets->AppendElements(numTargets); + for (uint32_t i = 0; i < numTargets; ++i) { + targets[i] = chain[i].CurrentTarget()->GetTargetForDOMEvent(); } } else { // Event target chain is created. Handle the chain. diff --git a/dom/fetch/Response.cpp b/dom/fetch/Response.cpp index d2aa5c23d8..e0c53f8536 100644 --- a/dom/fetch/Response.cpp +++ b/dom/fetch/Response.cpp @@ -210,7 +210,10 @@ Response::Constructor(const GlobalObject& aGlobal, if (!contentType.IsVoid() && !internalResponse->Headers()->Has(NS_LITERAL_CSTRING("Content-Type"), aRv)) { - internalResponse->Headers()->Append(NS_LITERAL_CSTRING("Content-Type"), contentType, aRv); + // Ignore Append() failing here. + ErrorResult error; + internalResponse->Headers()->Append(NS_LITERAL_CSTRING("Content-Type"), contentType, error); + error.SuppressException(); } if (aRv.Failed()) { diff --git a/dom/messages/SystemMessageInternal.js b/dom/messages/SystemMessageInternal.js index 2016673b8d..3d7e70bbe0 100644 --- a/dom/messages/SystemMessageInternal.js +++ b/dom/messages/SystemMessageInternal.js @@ -734,11 +734,9 @@ SystemMessageInternal.prototype = { if (!page) { debug("Message " + aType + " is not registered for " + aPageURL + " @ " + aManifestURL); - // FIXME bug 1140275 should only send message to page registered in manifest - // return MSG_SENT_FAILURE_PERM_DENIED; + return MSG_SENT_FAILURE_PERM_DENIED; } - if (page) - this._queueMessage(page, aMessage, aMessageID); + this._queueMessage(page, aMessage, aMessageID); let appPageIsRunning = false; let pageKey = this._createKeyForPage({ type: aType, @@ -793,8 +791,7 @@ SystemMessageInternal.prototype = { result = MSG_SENT_FAILURE_APP_NOT_RUNNING; this._acquireCpuWakeLock(pageKey); } - if (page) - this._openAppPage(page, aMessage, aExtra, result); + this._openAppPage(page, aMessage, aExtra, result); return result; }, diff --git a/dom/messages/test/mochitest.ini b/dom/messages/test/mochitest.ini index ed82016fd2..77d99cbf29 100644 --- a/dom/messages/test/mochitest.ini +++ b/dom/messages/test/mochitest.ini @@ -1,2 +1,6 @@ +[DEFAULT] +support-files = + system_message_chrome_script.js + [test_bug_993732.html] skip-if = buildapp == 'mulet' || (buildapp == 'b2g' && toolkit != 'gonk') #Bug 931116, b2g desktop specific, initial triage diff --git a/dom/messages/test/system_message_chrome_script.js b/dom/messages/test/system_message_chrome_script.js new file mode 100644 index 0000000000..4d6358f517 --- /dev/null +++ b/dom/messages/test/system_message_chrome_script.js @@ -0,0 +1,18 @@ +/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ +'use strict'; + +const { classes: Cc, interfaces: Ci } = Components; + +const systemMessenger = Cc["@mozilla.org/system-message-internal;1"] + .getService(Ci.nsISystemMessagesInternal); +const ioService = Cc["@mozilla.org/network/io-service;1"] + .getService(Ci.nsIIOService); + +addMessageListener("trigger-register-page", function(aData) { + systemMessenger.registerPage(aData.type, + ioService.newURI(aData.pageURL, null, null), + ioService.newURI(aData.manifestURL, null, null)); + sendAsyncMessage("page-registered"); +}); diff --git a/dom/messages/test/test_bug_993732.html b/dom/messages/test/test_bug_993732.html index d26cc4928b..f6baa18f16 100644 --- a/dom/messages/test/test_bug_993732.html +++ b/dom/messages/test/test_bug_993732.html @@ -19,6 +19,20 @@ // listening system message is broadcast. So this test case uses the alarm message // to test if a running app can receive the system message. + function registerPage() { + var gScript = SpecialPowers.loadChromeScript(SimpleTest.getTestFileURL('system_message_chrome_script.js')); + gScript.addMessageListener("page-registered", function pageRegisteredHandler() { + gScript.removeMessageListener("page-registered", pageRegisteredHandler); + gScript.destroy(); + testAlarm(10000); + }); + + gScript.sendAsyncMessage("trigger-register-page", + { type: "alarm", + manifestURL: window.location.origin + "/manifest.webapp", + pageURL: window.location.href }); + } + function testAlarm(aMillisecondsFromNow) { var at = new Date(); at.setTime(at.getTime() + aMillisecondsFromNow); @@ -40,7 +54,7 @@ // Waiting for alarm message. }; domRequest.onerror = function(e) { - ok(false, "Unable to add alarm for tomorrow`."); + ok(false, "Unable to add alarm."); SimpleTest.finish(); }; } @@ -52,7 +66,7 @@ if (navigator.userAgent.indexOf("Mobile") != -1 && navigator.appVersion.indexOf("Android") == -1) { - testAlarm(10000); + registerPage(); } else { ok(true, "mozAlarms on Firefox OS only."); SimpleTest.finish(); diff --git a/dom/presentation/PresentationSessionInfo.cpp b/dom/presentation/PresentationSessionInfo.cpp index 18d987d38b..ccea2e18a0 100644 --- a/dom/presentation/PresentationSessionInfo.cpp +++ b/dom/presentation/PresentationSessionInfo.cpp @@ -38,14 +38,11 @@ using namespace mozilla; using namespace mozilla::dom; using namespace mozilla::services; -inline static PRLogModuleInfo* -GetPresentationSessionInfoLog() -{ - static PRLogModuleInfo* log = PR_NewLogModule("PresentationSessionInfo"); - return log; -} + +static LazyLogModule gPresentationSessionInfoLog("PresentationSessionInfo"); + #undef LOG -#define LOG(...) MOZ_LOG(GetPresentationSessionInfoLog(), mozilla::LogLevel::Error, (__VA_ARGS__)) +#define LOG(...) MOZ_LOG(gPresentationSessionInfoLog, mozilla::LogLevel::Error, (__VA_ARGS__)) /* diff --git a/dom/push/PushManager.cpp b/dom/push/PushManager.cpp index 7c9918c470..41dee1a27e 100644 --- a/dom/push/PushManager.cpp +++ b/dom/push/PushManager.cpp @@ -778,10 +778,7 @@ public: RefPtr promise = mProxy->WorkerPromise(); if (NS_SUCCEEDED(mStatus)) { - MOZ_ASSERT(uint32_t(mState) < ArrayLength(PushPermissionStateValues::strings)); - nsAutoCString stringState(PushPermissionStateValues::strings[uint32_t(mState)].value, - PushPermissionStateValues::strings[uint32_t(mState)].length); - promise->MaybeResolve(NS_ConvertUTF8toUTF16(stringState)); + promise->MaybeResolve(mState); } else { promise->MaybeReject(aCx, JS::UndefinedHandleValue); } diff --git a/dom/requestsync/RequestSyncService.jsm b/dom/requestsync/RequestSyncService.jsm index 65ff90c931..f302662528 100644 --- a/dom/requestsync/RequestSyncService.jsm +++ b/dom/requestsync/RequestSyncService.jsm @@ -7,7 +7,7 @@ const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components; function debug(s) { - dump('DEBUG RequestSyncService: ' + s + '\n'); + //dump('DEBUG RequestSyncService: ' + s + '\n'); } const RSYNCDB_VERSION = 1; @@ -47,6 +47,10 @@ XPCOMUtils.defineLazyServiceGetter(this, "secMan", "@mozilla.org/scriptsecuritymanager;1", "nsIScriptSecurityManager"); +XPCOMUtils.defineLazyServiceGetter(this, "powerManagerService", + "@mozilla.org/power/powermanagerservice;1", + "nsIPowerManagerService"); + XPCOMUtils.defineLazyModuleGetter(this, "AlarmService", "resource://gre/modules/AlarmService.jsm"); @@ -76,6 +80,10 @@ this.RequestSyncService = { _timers: {}, _pendingRequests: {}, + // This array contains functions to be executed after the scheduling of the + // current task or immediately if there are not scheduling in progress. + _afterSchedulingTasks: [], + // Initialization of the RequestSyncService. init: function() { debug("init"); @@ -94,16 +102,16 @@ this.RequestSyncService = { // Any incoming message will be stored and processed when the async // operation is completed. - let self = this; this.dbTxn("readonly", function(aStore) { - aStore.openCursor().onsuccess = function(event) { + aStore.openCursor().onsuccess = event => { let cursor = event.target.result; if (cursor) { - self.addRegistration(cursor.value); - cursor.continue(); + this.addRegistration(cursor.value, function() { + cursor.continue(); + }); } } - }, + }.bind(this), function() { debug("initialization done"); }, @@ -127,11 +135,10 @@ this.RequestSyncService = { this.close(); // Removing all the registrations will delete the pending timers. - let self = this; this.forEachRegistration(function(aObj) { - let key = self.principalToKey(aObj.principal); - self.removeRegistrationInternal(aObj.data.task, key); - }); + let key = this.principalToKey(aObj.principal); + this.removeRegistrationInternal(aObj.data.task, key); + }.bind(this)); }, observe: function(aSubject, aTopic, aData) { @@ -139,15 +146,21 @@ this.RequestSyncService = { switch (aTopic) { case 'xpcom-shutdown': - this.shutdown(); + this.executeAfterScheduling(function() { + this.shutdown(); + }.bind(this)); break; case 'clear-origin-data': - this.clearData(aData); + this.executeAfterScheduling(function() { + this.clearData(aData); + }.bind(this)); break; case 'wifi-state-changed': - this.wifiStateChanged(aSubject == 'enabled'); + this.executeAfterScheduling(function() { + this.wifiStateChanged(aSubject == 'enabled'); + }.bind(this)); break; default: @@ -208,7 +221,7 @@ this.RequestSyncService = { }, // Add a task to the _registrations map and create the timer if it's needed. - addRegistration: function(aObj) { + addRegistration: function(aObj, aCb) { debug('addRegistration'); let key = this.principalToKey(aObj.principal); @@ -216,8 +229,12 @@ this.RequestSyncService = { this._registrations[key] = {}; } - this.scheduleTimer(aObj); - this._registrations[key][aObj.data.task] = aObj; + this.scheduleTimer(aObj, function() { + this._registrations[key][aObj.data.task] = aObj; + if (aCb) { + aCb(); + } + }.bind(this)); }, // Remove a task from the _registrations map and delete the timer if it's @@ -289,31 +306,45 @@ this.RequestSyncService = { switch (aMessage.name) { case "RequestSync:Register": - this.register(aMessage.target, aMessage.data, principal); + this.executeAfterScheduling(function() { + this.register(aMessage.target, aMessage.data, principal); + }.bind(this)); break; case "RequestSync:Unregister": - this.unregister(aMessage.target, aMessage.data, principal); + this.executeAfterScheduling(function() { + this.unregister(aMessage.target, aMessage.data, principal); + }.bind(this)); break; case "RequestSync:Registrations": - this.registrations(aMessage.target, aMessage.data, principal); + this.executeAfterScheduling(function() { + this.registrations(aMessage.target, aMessage.data, principal); + }.bind(this)); break; case "RequestSync:Registration": - this.registration(aMessage.target, aMessage.data, principal); + this.executeAfterScheduling(function() { + this.registration(aMessage.target, aMessage.data, principal); + }.bind(this)); break; case "RequestSyncManager:Registrations": - this.managerRegistrations(aMessage.target, aMessage.data, principal); + this.executeAfterScheduling(function() { + this.managerRegistrations(aMessage.target, aMessage.data, principal); + }.bind(this)); break; case "RequestSyncManager:SetPolicy": - this.managerSetPolicy(aMessage.target, aMessage.data, principal); + this.executeAfterScheduling(function() { + this.managerSetPolicy(aMessage.target, aMessage.data, principal); + }.bind(this)); break; case "RequestSyncManager:RunTask": - this.managerRunTask(aMessage.target, aMessage.data, principal); + this.executeAfterScheduling(function() { + this.managerRunTask(aMessage.target, aMessage.data, principal); + }.bind(this)); break; default: @@ -389,9 +420,10 @@ this.RequestSyncService = { aStore.put(data, data.dbKey); }, function() { - self.addRegistration(data); - aTarget.sendAsyncMessage("RequestSync:Register:Return", - { requestID: aData.requestID }); + self.addRegistration(data, function() { + aTarget.sendAsyncMessage("RequestSync:Register:Return", + { requestID: aData.requestID }); + }); }, function() { aTarget.sendAsyncMessage("RequestSync:Register:Return", @@ -524,9 +556,10 @@ this.RequestSyncService = { } this.updateObjectInDB(toSave, function() { - self.scheduleTimer(toSave); - aTarget.sendAsyncMessage("RequestSyncManager:SetPolicy:Return", - { requestID: aData.requestID }); + self.scheduleTimer(toSave, function() { + aTarget.sendAsyncMessage("RequestSyncManager:SetPolicy:Return", + { requestID: aData.requestID }); + }); }); }, @@ -567,7 +600,7 @@ this.RequestSyncService = { // Storing the requestID into the task for the callback. this.storePendingRequest(task, aTarget, aData.requestID); - this.timeout(task); + this.timeout(task, null); }, // We cannot expose the full internal object to content but just a subset. @@ -600,29 +633,60 @@ this.RequestSyncService = { }, // Creation of the timer for a particular task object. - scheduleTimer: function(aObj) { + scheduleTimer: function(aObj, aCb) { debug("scheduleTimer"); + aCb = aCb || function() {}; + this.removeTimer(aObj); // A registration can be already inactive if it was 1 shot. if (!aObj.active) { + aCb(); return; } if (aObj.data.state == RSYNC_STATE_DISABLED) { + aCb(); return; } // WifiOnly check. if (aObj.data.state == RSYNC_STATE_WIFIONLY && !this._wifi) { + aCb(); return; } - this.createTimer(aObj); + if (this.scheduling) { + dump("ERROR!! RequestSyncService - ScheduleTimer called into ScheduleTimer.\n"); + aCb(); + return; + } + + this.scheduling = true; + + this.createTimer(aObj, function() { + this.scheduling = false; + + while (this._afterSchedulingTasks.length) { + var cb = this._afterSchedulingTasks.shift(); + cb(); + } + + aCb(); + }.bind(this)); }, - timeout: function(aObj) { + executeAfterScheduling: function(aCb) { + if (!this.scheduling) { + aCb(); + return; + } + + this._afterSchedulingTasks.push(aCb); + }, + + timeout: function(aObj, aWakeLock) { debug("timeout"); if (this._activeTask) { @@ -631,6 +695,7 @@ this.RequestSyncService = { if (this._queuedTasks.indexOf(aObj) == -1) { this._queuedTasks.push(aObj); } + this.maybeReleaseWakeLock(aWakeLock); return; } @@ -638,7 +703,9 @@ this.RequestSyncService = { if (!app) { dump("ERROR!! RequestSyncService - Failed to retrieve app data from a principal.\n"); aObj.active = false; - this.updateObjectInDB(aObj); + this.updateObjectInDB(aObj, () => { + this.maybeReleaseWakeLock(aWakeLock); + }); return; } @@ -647,20 +714,25 @@ this.RequestSyncService = { // Maybe need to be rescheduled? if (this.hasPendingMessages('request-sync', manifestURL, pageURL)) { - this.scheduleTimer(aObj); + this.scheduleTimer(aObj, () => { + this.maybeReleaseWakeLock(aWakeLock); + }); return; } this.removeTimer(aObj); - this._activeTask = aObj; if (!manifestURL || !pageURL) { dump("ERROR!! RequestSyncService - Failed to create URI for the page or the manifest\n"); aObj.active = false; - this.updateObjectInDB(aObj); + this.updateObjectInDB(aObj, () => { + this.maybeReleaseWakeLock(aWakeLock); + }); return; } + this._activeTask = aObj; + // We don't want to run more than 1 task at the same time. We do this using // the promise created by sendMessage(). But if the task takes more than // RSYNC_OPERATION_TIMEOUT millisecs, we have to ignore the promise and @@ -668,6 +740,14 @@ this.RequestSyncService = { let timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer); + // We need a wakelock to keep the device alive and we want to release it + // only when all the steps are fully completely. This can involve calling + // timeout() again if we have something in _queuedTasks. In this scenario + // we want to reuse the same wakelock and we receive it as param. + // The Wakelock is passed to operationCompleted() because we want to wait + // until the data is written into IDB and maybe until all the pending next + // tasks are executed too. + let wakeLock = aWakeLock ? aWakeLock : powerManagerService.newWakeLock("cpu"); let done = false; let self = this; function taskCompleted() { @@ -675,7 +755,7 @@ this.RequestSyncService = { if (!done) { done = true; - self.operationCompleted(); + self.operationCompleted(wakeLock); } timer.cancel(); @@ -709,11 +789,12 @@ this.RequestSyncService = { }); }, - operationCompleted: function() { + operationCompleted: function(aWakeLock) { debug("operationCompleted"); if (!this._activeTask) { dump("ERROR!! RequestSyncService - OperationCompleted called without an active task\n"); + aWakeLock.unlock(); return; } @@ -728,30 +809,29 @@ this.RequestSyncService = { { requestID: pendingRequests[i].requestID }); } - let self = this; this.updateObjectInDB(this._activeTask, function() { - // SchedulerTimer creates a timer and a nsITimer cannot be cloned. This - // is the reason why this operation has to be done after storing the task - // into IDB. - if (!self._activeTask.data.oneShot) { - self.scheduleTimer(self._activeTask); + if (!this._activeTask.data.oneShot) { + this.scheduleTimer(this._activeTask, function() { + this.processNextTask(aWakeLock); + }.bind(this)); + } else { + this.processNextTask(aWakeLock); } - - self.processNextTask(); - }); + }.bind(this)); }, - processNextTask: function() { + processNextTask: function(aWakeLock) { debug("processNextTask"); this._activeTask = null; if (this._queuedTasks.length == 0) { + aWakeLock.unlock(); return; } let task = this._queuedTasks.shift(); - this.timeout(task); + this.timeout(task, aWakeLock); }, hasPendingMessages: function(aMessageName, aManifestURL, aPageURL) { @@ -836,36 +916,37 @@ this.RequestSyncService = { wifiStateChanged: function(aEnabled) { debug("onWifiStateChanged"); + this._wifi = aEnabled; if (!this._wifi) { // Disable all the wifiOnly tasks. - let self = this; this.forEachRegistration(function(aObj) { - if (aObj.data.state == RSYNC_STATE_WIFIONLY && self.hasTimer(aObj)) { - self.removeTimer(aObj); + if (aObj.data.state == RSYNC_STATE_WIFIONLY && this.hasTimer(aObj)) { + this.removeTimer(aObj); // It can be that this task has been already schedulated. - self.removeTaskFromQueue(aObj); + this.removeTaskFromQueue(aObj); } - }); + }.bind(this)); return; } // Enable all the tasks. - let self = this; this.forEachRegistration(function(aObj) { - if (aObj.active && !self.hasTimer(aObj)) { + if (aObj.active && !this.hasTimer(aObj)) { if (!aObj.data.wifiOnly) { dump("ERROR - Found a disabled task that is not wifiOnly."); } - self.scheduleTimer(aObj); + this.scheduleTimer(aObj); } - }); + }.bind(this)); }, - createTimer: function(aObj) { + createTimer: function(aObj, aCb) { + aCb = aCb || function() {}; + let interval = aObj.data.minInterval; if (aObj.data.overwrittenMinInterval > 0) { interval = aObj.data.overwrittenMinInterval; @@ -874,8 +955,12 @@ this.RequestSyncService = { AlarmService.add( { date: new Date(Date.now() + interval * 1000), ignoreTimezone: false }, - () => this.timeout(aObj), - aTimerId => this._timers[aObj.dbKey] = aTimerId); + () => this.timeout(aObj, null), + function(aTimerId) { + this._timers[aObj.dbKey] = aTimerId; + aCb(); + }.bind(this), + () => aCb()); }, hasTimer: function(aObj) { @@ -906,6 +991,12 @@ this.RequestSyncService = { let requests = this._pendingRequests[aObj.dbKey]; delete this._pendingRequests[aObj.dbKey]; return requests; + }, + + maybeReleaseWakeLock: function(aWakeLock) { + if (aWakeLock) { + aWakeLock.unlock(); + } } } diff --git a/dom/requestsync/tests/mochitest.ini b/dom/requestsync/tests/mochitest.ini index 8da48c024c..96f937990e 100644 --- a/dom/requestsync/tests/mochitest.ini +++ b/dom/requestsync/tests/mochitest.ini @@ -1,20 +1,25 @@ [DEFAULT] -skip-if = e10s support-files = file_app.template.webapp file_app.sjs file_basic_app.html common_app.js common_basic.js + system_message_chrome_script.js [test_webidl.html] +skip-if = os == "android" || toolkit == "gonk" [test_minInterval.html] +skip-if = os == "android" || toolkit == "gonk" [test_basic.html] +skip-if = os == "android" || toolkit == "gonk" [test_basic_app.html] -run-if = buildapp != 'b2g' +skip-if = os == "android" || buildapp == 'b2g' || e10s # mozapps [test_wakeUp.html] run-if = buildapp == 'b2g' && toolkit == 'gonk' [test_runNow.html] run-if = buildapp == 'b2g' && toolkit == 'gonk' [test_promise.html] +skip-if = os == "android" || toolkit == "gonk" [test_bug1151082.html] +skip-if = os == "android" || toolkit == "gonk" diff --git a/dom/requestsync/tests/system_message_chrome_script.js b/dom/requestsync/tests/system_message_chrome_script.js new file mode 100644 index 0000000000..b00d744ac1 --- /dev/null +++ b/dom/requestsync/tests/system_message_chrome_script.js @@ -0,0 +1,18 @@ +/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ +'use strict'; + +var { classes: Cc, interfaces: Ci } = Components; + +const systemMessenger = Cc["@mozilla.org/system-message-internal;1"] + .getService(Ci.nsISystemMessagesInternal); +const ioService = Cc["@mozilla.org/network/io-service;1"] + .getService(Ci.nsIIOService); + +addMessageListener("trigger-register-page", function(aData) { + systemMessenger.registerPage(aData.type, + ioService.newURI(aData.pageURL, null, null), + ioService.newURI(aData.manifestURL, null, null)); + sendAsyncMessage("page-registered"); +}); diff --git a/dom/requestsync/tests/test_basic.html b/dom/requestsync/tests/test_basic.html index e95974cad6..455fcdf1be 100644 --- a/dom/requestsync/tests/test_basic.html +++ b/dom/requestsync/tests/test_basic.html @@ -24,9 +24,7 @@ }, function() { - if (SpecialPowers.isMainProcess()) { - SpecialPowers.Cu.import("resource://gre/modules/RequestSyncService.jsm"); - } + SpecialPowers.importInMainProcess("resource://gre/modules/RequestSyncService.jsm"); runTests(); }, diff --git a/dom/requestsync/tests/test_basic_app.html b/dom/requestsync/tests/test_basic_app.html index a72211ce6c..d804fe2b95 100644 --- a/dom/requestsync/tests/test_basic_app.html +++ b/dom/requestsync/tests/test_basic_app.html @@ -85,10 +85,7 @@ }, function() { - if (SpecialPowers.isMainProcess()) { - SpecialPowers.Cu.import("resource://gre/modules/RequestSyncService.jsm"); - } - + SpecialPowers.importInMainProcess("resource://gre/modules/RequestSyncService.jsm"); SpecialPowers.setAllAppsLaunchable(true); SpecialPowers.pushPrefEnv({"set":[["dom.mozBrowserFramesEnabled", true]]}, runTests); }, diff --git a/dom/requestsync/tests/test_bug1151082.html b/dom/requestsync/tests/test_bug1151082.html index 12ae8c9869..61fd820cab 100644 --- a/dom/requestsync/tests/test_bug1151082.html +++ b/dom/requestsync/tests/test_bug1151082.html @@ -24,9 +24,7 @@ }, function() { - if (SpecialPowers.isMainProcess()) { - SpecialPowers.Cu.import("resource://gre/modules/RequestSyncService.jsm"); - } + SpecialPowers.importInMainProcess("resource://gre/modules/RequestSyncService.jsm"); runTests(); }, diff --git a/dom/requestsync/tests/test_minInterval.html b/dom/requestsync/tests/test_minInterval.html index 0ef132afa4..dbb6d666de 100644 --- a/dom/requestsync/tests/test_minInterval.html +++ b/dom/requestsync/tests/test_minInterval.html @@ -30,9 +30,7 @@ var tests = [ function() { - if (SpecialPowers.isMainProcess()) { - SpecialPowers.Cu.import("resource://gre/modules/RequestSyncService.jsm"); - } + SpecialPowers.importInMainProcess("resource://gre/modules/RequestSyncService.jsm"); runTests(); }, diff --git a/dom/requestsync/tests/test_runNow.html b/dom/requestsync/tests/test_runNow.html index 6bd290fbb0..056d5e1eb9 100644 --- a/dom/requestsync/tests/test_runNow.html +++ b/dom/requestsync/tests/test_runNow.html @@ -13,6 +13,20 @@ var taskExecuted = false; + function registerPage() { + var gScript = SpecialPowers.loadChromeScript(SimpleTest.getTestFileURL('system_message_chrome_script.js')); + gScript.addMessageListener("page-registered", function pageRegisteredHandler() { + gScript.removeMessageListener("page-registered", pageRegisteredHandler); + gScript.destroy(); + runTests(); + }); + + gScript.sendAsyncMessage("trigger-register-page", + { type: "request-sync", + manifestURL: window.location.origin + "/manifest.webapp", + pageURL: window.location.href }); + } + function setMessageHandler() { navigator.mozSetMessageHandler('request-sync', function(e) { ok(true, "One event has been received!"); @@ -79,12 +93,12 @@ }, function() { - if (SpecialPowers.isMainProcess()) { - SpecialPowers.Cu.import("resource://gre/modules/RequestSyncService.jsm"); - } + SpecialPowers.importInMainProcess("resource://gre/modules/RequestSyncService.jsm"); runTests(); }, + registerPage, + setMessageHandler, test_register_oneShot, diff --git a/dom/requestsync/tests/test_wakeUp.html b/dom/requestsync/tests/test_wakeUp.html index 7e48a5d6f4..434deeea56 100644 --- a/dom/requestsync/tests/test_wakeUp.html +++ b/dom/requestsync/tests/test_wakeUp.html @@ -20,6 +20,20 @@ } } + function registerPage() { + var gScript = SpecialPowers.loadChromeScript(SimpleTest.getTestFileURL('system_message_chrome_script.js')); + gScript.addMessageListener("page-registered", function pageRegisteredHandler() { + gScript.removeMessageListener("page-registered", pageRegisteredHandler); + gScript.destroy(); + runTests(); + }); + + gScript.sendAsyncMessage("trigger-register-page", + { type: "request-sync", + manifestURL: window.location.origin + "/manifest.webapp", + pageURL: window.location.href }); + } + function setMessageHandler() { navigator.mozSetMessageHandler('request-sync', function(e) { ok(true, "One event has been received!"); @@ -140,12 +154,11 @@ }, function() { - if (SpecialPowers.isMainProcess()) { - SpecialPowers.Cu.import("resource://gre/modules/RequestSyncService.jsm"); - } + SpecialPowers.importInMainProcess("resource://gre/modules/RequestSyncService.jsm"); runTests(); }, + registerPage, setMessageHandler, test_register_oneShot, diff --git a/dom/secureelement/gonk/ACEService.js b/dom/secureelement/gonk/ACEService.js index 64a48de77b..d801b2c5eb 100644 --- a/dom/secureelement/gonk/ACEService.js +++ b/dom/secureelement/gonk/ACEService.js @@ -9,6 +9,7 @@ const { classes: Cc, interfaces: Ci, utils: Cu } = Components; Cu.import("resource://gre/modules/XPCOMUtils.jsm"); Cu.import("resource://gre/modules/Promise.jsm"); +Cu.import("resource://gre/modules/Services.jsm"); XPCOMUtils.defineLazyModuleGetter(this, "DOMApplicationRegistry", "resource://gre/modules/Webapps.jsm"); @@ -22,7 +23,7 @@ XPCOMUtils.defineLazyGetter(this, "SE", function() { return obj; }); -let DEBUG = SE.DEBUG_ACE; +var DEBUG = SE.DEBUG_ACE; function debug(msg) { if (DEBUG) { dump("ACEservice: " + msg + "\n"); @@ -120,6 +121,11 @@ ACEService.prototype = { _rulesManagers: null, isAccessAllowed: function isAccessAllowed(localId, seType, aid) { + if(!Services.prefs.getBoolPref("devtools.debugger.forbid-certified-apps")) { + debug("Certified apps debug enabled, allowing access"); + return Promise.resolve(true); + } + let manifestURL = DOMApplicationRegistry.getManifestURLByLocalId(localId); if (!manifestURL) { return Promise.reject(Error("Missing manifest for app: " + localId)); diff --git a/dom/secureelement/gonk/UiccConnector.js b/dom/secureelement/gonk/UiccConnector.js index 6e204ba61b..517303de29 100644 --- a/dom/secureelement/gonk/UiccConnector.js +++ b/dom/secureelement/gonk/UiccConnector.js @@ -328,7 +328,7 @@ UiccConnector.prototype = { unregisterListener: function(listener) { let idx = this._SEListeners.indexOf(listener); if (idx !== -1) { - this._listeners.splice(idx, 1); + this._SEListeners.splice(idx, 1); } }, diff --git a/dom/webidl/ActivityRequestHandler.webidl b/dom/webidl/ActivityRequestHandler.webidl index 3d0f930cdc..7fc1966479 100644 --- a/dom/webidl/ActivityRequestHandler.webidl +++ b/dom/webidl/ActivityRequestHandler.webidl @@ -4,7 +4,7 @@ [Pref="dom.sysmsg.enabled", JSImplementation="@mozilla.org/dom/activities/request-handler;1", - ChromeConstructor(DOMString id, optional ActivityOptions options), + ChromeConstructor(DOMString id, optional ActivityOptions options, optional boolean returnvalue), ChromeOnly] interface ActivityRequestHandler { diff --git a/dom/webidl/BluetoothAttributeEvent.webidl b/dom/webidl/BluetoothAttributeEvent.webidl index fd011a699b..c8bc60e7ec 100644 --- a/dom/webidl/BluetoothAttributeEvent.webidl +++ b/dom/webidl/BluetoothAttributeEvent.webidl @@ -15,5 +15,5 @@ interface BluetoothAttributeEvent : Event dictionary BluetoothAttributeEventInit : EventInit { - required sequence attrs; + sequence attrs = []; }; diff --git a/dom/webidl/BluetoothGattCharacteristicEvent.webidl b/dom/webidl/BluetoothGattCharacteristicEvent.webidl index 1696330509..ce6b87ce09 100644 --- a/dom/webidl/BluetoothGattCharacteristicEvent.webidl +++ b/dom/webidl/BluetoothGattCharacteristicEvent.webidl @@ -9,10 +9,10 @@ optional BluetoothGattCharacteristicEventInit eventInitDict)] interface BluetoothGattCharacteristicEvent : Event { - readonly attribute BluetoothGattCharacteristic characteristic; + readonly attribute BluetoothGattCharacteristic? characteristic; }; dictionary BluetoothGattCharacteristicEventInit : EventInit { - required BluetoothGattCharacteristic characteristic; + BluetoothGattCharacteristic? characteristic = null; }; diff --git a/dom/webidl/BluetoothGattServer.webidl b/dom/webidl/BluetoothGattServer.webidl index efb91afbd5..5dfe0e56b6 100644 --- a/dom/webidl/BluetoothGattServer.webidl +++ b/dom/webidl/BluetoothGattServer.webidl @@ -46,6 +46,16 @@ interface BluetoothGattServer : EventTarget [NewObject] Promise removeService(BluetoothGattService service); + /** + * Notify the remote BLE device that the value of a characteristic has been + * changed. + */ + [NewObject] + Promise notifyCharacteristicChanged( + DOMString address, + BluetoothGattCharacteristic characteristic, + boolean confirm); + /** * Send a read/write response to a remote BLE client */ diff --git a/dom/webidl/BluetoothLeDeviceEvent.webidl b/dom/webidl/BluetoothLeDeviceEvent.webidl index e56a84e199..fb70dd2591 100644 --- a/dom/webidl/BluetoothLeDeviceEvent.webidl +++ b/dom/webidl/BluetoothLeDeviceEvent.webidl @@ -8,15 +8,15 @@ Constructor(DOMString type, optional BluetoothLeDeviceEventInit eventInitDict)] interface BluetoothLeDeviceEvent : Event { - readonly attribute BluetoothDevice device; + readonly attribute BluetoothDevice? device; readonly attribute short rssi; [Throws] - readonly attribute ArrayBuffer scanRecord; + readonly attribute ArrayBuffer? scanRecord; }; dictionary BluetoothLeDeviceEventInit : EventInit { - required BluetoothDevice device; - short rssi = 0; - required ArrayBuffer scanRecord; + BluetoothDevice? device = null; + short rssi = 0; + ArrayBuffer? scanRecord = null; }; diff --git a/dom/webidl/BluetoothPairingEvent.webidl b/dom/webidl/BluetoothPairingEvent.webidl index 3a51af354e..d9bb965970 100644 --- a/dom/webidl/BluetoothPairingEvent.webidl +++ b/dom/webidl/BluetoothPairingEvent.webidl @@ -9,12 +9,12 @@ optional BluetoothPairingEventInit eventInitDict)] interface BluetoothPairingEvent : Event { - readonly attribute DOMString deviceName; - readonly attribute BluetoothPairingHandle handle; + readonly attribute DOMString deviceName; + readonly attribute BluetoothPairingHandle? handle; }; dictionary BluetoothPairingEventInit : EventInit { - required DOMString deviceName; - required BluetoothPairingHandle handle; + DOMString deviceName = ""; + BluetoothPairingHandle? handle = null; }; diff --git a/media/webrtc/signaling/test/common.build b/media/webrtc/signaling/test/common.build index b3bb19f04b..c0a624fc1e 100644 --- a/media/webrtc/signaling/test/common.build +++ b/media/webrtc/signaling/test/common.build @@ -12,7 +12,9 @@ for var in ('MOZILLA_EXTERNAL_LINKAGE', 'USE_FAKE_MEDIA_STREAMS', 'USE_FAKE_PCOB DEFINES[var] = True LOCAL_INCLUDES += [ - '!/dom/bindings', + '!/dist/include/mozilla/dom', # Binding headers (because binding + # implementations include them). + '!/dom/bindings', # Binding implementations (urk). '/dom/media/', '/ipc/chromium/src', '/media/mtransport', diff --git a/media/webrtc/signaling/test/signaling_unittests.cpp b/media/webrtc/signaling/test/signaling_unittests.cpp index 11ad65ab39..fd176945e5 100644 --- a/media/webrtc/signaling/test/signaling_unittests.cpp +++ b/media/webrtc/signaling/test/signaling_unittests.cpp @@ -40,7 +40,9 @@ #include "logging.h" #include "stunserver.h" #include "stunserver.cpp" +#ifdef SIGNALING_UNITTEST_STANDALONE #include "PeerConnectionImplEnumsBinding.cpp" +#endif #include "ice_ctx.h" #include "ice_peer_ctx.h" @@ -340,6 +342,44 @@ TestObserver::NotifyDataChannel(nsIDOMDataChannel *channel, ER&) return NS_OK; } +static const char* PCImplSignalingStateStrings[] = { + "SignalingInvalid", + "SignalingStable", + "SignalingHaveLocalOffer", + "SignalingHaveRemoteOffer", + "SignalingHaveLocalPranswer", + "SignalingHaveRemotePranswer", + "SignalingClosed" +}; + +static const char* PCImplIceConnectionStateStrings[] = { + "new", + "checking", + "connected", + "completed", + "failed", + "disconnected", + "closed" +}; + +static const char* PCImplIceGatheringStateStrings[] = { + "new", + "gathering", + "complete" +}; + +#ifdef SIGNALING_UNITTEST_STANDALONE +static_assert(ArrayLength(PCImplSignalingStateStrings) == + size_t(PCImplSignalingState::EndGuard_), + "Table sizes must match"); +static_assert(ArrayLength(PCImplIceConnectionStateStrings) == + size_t(PCImplIceConnectionState::EndGuard_), + "Table sizes must match"); +static_assert(ArrayLength(PCImplIceGatheringStateStrings) == + size_t(PCImplIceGatheringState::EndGuard_), + "Table sizes must match"); +#endif // SIGNALING_UNITTEST_STANDALONE + NS_IMETHODIMP TestObserver::OnStateChange(PCObserverStateType state_type, ER&, void*) { @@ -357,7 +397,7 @@ TestObserver::OnStateChange(PCObserverStateType state_type, ER&, void*) rv = pc->IceConnectionState(&gotice); NS_ENSURE_SUCCESS(rv, rv); std::cout << "ICE Connection State: " - << PCImplIceConnectionStateValues::strings[int(gotice)].value + << PCImplIceConnectionStateStrings[int(gotice)] << std::endl; break; case PCObserverStateType::IceGatheringState: @@ -366,7 +406,7 @@ TestObserver::OnStateChange(PCObserverStateType state_type, ER&, void*) NS_ENSURE_SUCCESS(rv, rv); std::cout << "ICE Gathering State: " - << PCImplIceGatheringStateValues::strings[int(goticegathering)].value + << PCImplIceGatheringStateStrings[int(goticegathering)] << std::endl; break; case PCObserverStateType::SdpState: @@ -378,7 +418,7 @@ TestObserver::OnStateChange(PCObserverStateType state_type, ER&, void*) rv = pc->SignalingState(&gotsignaling); NS_ENSURE_SUCCESS(rv, rv); std::cout << "Signaling State: " - << PCImplSignalingStateValues::strings[int(gotsignaling)].value + << PCImplSignalingStateStrings[int(gotsignaling)] << std::endl; break; default: @@ -4712,6 +4752,19 @@ static int gtest_main(int argc, char **argv) { return result; } +#ifdef SIGNALING_UNITTEST_STANDALONE +static void verifyStringTable(const EnumEntry* bindingTable, + const char** ourTable) +{ + while (bindingTable->value) { + if (strcmp(bindingTable->value, *ourTable)) { + MOZ_CRASH("Our tables are out of sync with the bindings"); + } + ++bindingTable; + ++ourTable; + } +} +#endif // SIGNALING_UNITTEST_STANDALONE int main(int argc, char **argv) { @@ -4726,6 +4779,16 @@ int main(int argc, char **argv) { calleeName = ansiMagenta + calleeName + ansiColorOff; } +#ifdef SIGNALING_UNITTEST_STANDALONE + // Verify our string tables are correct. + verifyStringTable(PCImplSignalingStateValues::strings, + test::PCImplSignalingStateStrings); + verifyStringTable(PCImplIceConnectionStateValues::strings, + test::PCImplIceConnectionStateStrings); + verifyStringTable(PCImplIceGatheringStateValues::strings, + test::PCImplIceGatheringStateStrings); +#endif // SIGNALING_UNITTEST_STANDALONE + std::string tmp = get_environment("STUN_SERVER_ADDRESS"); if (tmp != "") g_stun_server_address = tmp; diff --git a/media/webrtc/signaling/test/standalone/moz.build b/media/webrtc/signaling/test/standalone/moz.build index d0021eeb03..5bb7fe6e35 100644 --- a/media/webrtc/signaling/test/standalone/moz.build +++ b/media/webrtc/signaling/test/standalone/moz.build @@ -39,6 +39,7 @@ LOCAL_INCLUDES += [ USE_LIBS += [ '/media/webrtc/signalingstandalone/signaling_ecc/ecc', 'fallible', + 'js', # Turns out, binding implementations use JS, who knew. 'media_standalone', 'mfbt', 'mozglue', diff --git a/media/webrtc/signaling/test/standalone/signaling_unittests_standalone.cpp b/media/webrtc/signaling/test/standalone/signaling_unittests_standalone.cpp index 796aa23b52..8a0524f3ef 100644 --- a/media/webrtc/signaling/test/standalone/signaling_unittests_standalone.cpp +++ b/media/webrtc/signaling/test/standalone/signaling_unittests_standalone.cpp @@ -2,4 +2,5 @@ * 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/. */ +#define SIGNALING_UNITTEST_STANDALONE 1 #include "../signaling_unittests.cpp" diff --git a/testing/web-platform/mozilla/meta/service-workers/service-worker/invalid-blobtype.https.html.ini b/testing/web-platform/mozilla/meta/service-workers/service-worker/invalid-blobtype.https.html.ini deleted file mode 100644 index f72053f271..0000000000 --- a/testing/web-platform/mozilla/meta/service-workers/service-worker/invalid-blobtype.https.html.ini +++ /dev/null @@ -1,10 +0,0 @@ -[invalid-blobtype.https.html] - type: testharness - expected: - if debug and (os == "win") and (version == "6.1.7601") and (processor == "x86") and (bits == 32): CRASH - if debug and (os == "win") and (version == "5.1.2600") and (processor == "x86") and (bits == 32): CRASH - if debug and (os == "win") and (version == "6.2.9200") and (processor == "x86_64") and (bits == 64): CRASH - TIMEOUT - [Verify the response of FetchEvent using XMLHttpRequest] - expected: TIMEOUT - diff --git a/testing/web-platform/mozilla/tests/service-workers/service-worker/resources/invalid-blobtype-worker.js b/testing/web-platform/mozilla/tests/service-workers/service-worker/resources/invalid-blobtype-worker.js index de9e7c7e15..93f496ef44 100644 --- a/testing/web-platform/mozilla/tests/service-workers/service-worker/resources/invalid-blobtype-worker.js +++ b/testing/web-platform/mozilla/tests/service-workers/service-worker/resources/invalid-blobtype-worker.js @@ -4,7 +4,6 @@ self.addEventListener('fetch', function(event) { return; } event.respondWith(new Promise(function(resolve) { - var headers = new Headers; // null byte in blob type resolve(new Response(new Blob([],{type: 'a\0b'}))); }));