fake_bluetooth_device_client.cc 81 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987
  1. // Copyright (c) 2013 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "device/bluetooth/dbus/fake_bluetooth_device_client.h"
  5. #include <fcntl.h>
  6. #include <stddef.h>
  7. #include <sys/socket.h>
  8. #include <sys/types.h>
  9. #include <unistd.h>
  10. #include <algorithm>
  11. #include <memory>
  12. #include <string>
  13. #include <utility>
  14. #include "base/base64.h"
  15. #include "base/callback_helpers.h"
  16. #include "base/containers/contains.h"
  17. #include "base/location.h"
  18. #include "base/logging.h"
  19. #include "base/memory/ptr_util.h"
  20. #include "base/memory/ref_counted.h"
  21. #include "base/observer_list.h"
  22. #include "base/rand_util.h"
  23. #include "base/strings/string_util.h"
  24. #include "base/task/single_thread_task_runner.h"
  25. #include "base/task/thread_pool.h"
  26. #include "base/threading/thread_task_runner_handle.h"
  27. #include "base/time/time.h"
  28. #include "device/bluetooth/bluez/bluetooth_service_attribute_value_bluez.h"
  29. #include "device/bluetooth/dbus/bluetooth_gatt_characteristic_client.h"
  30. #include "device/bluetooth/dbus/bluez_dbus_manager.h"
  31. #include "device/bluetooth/dbus/fake_bluetooth_adapter_client.h"
  32. #include "device/bluetooth/dbus/fake_bluetooth_agent_manager_client.h"
  33. #include "device/bluetooth/dbus/fake_bluetooth_agent_service_provider.h"
  34. #include "device/bluetooth/dbus/fake_bluetooth_gatt_service_client.h"
  35. #include "device/bluetooth/dbus/fake_bluetooth_input_client.h"
  36. #include "device/bluetooth/dbus/fake_bluetooth_profile_manager_client.h"
  37. #include "device/bluetooth/dbus/fake_bluetooth_profile_service_provider.h"
  38. #include "third_party/cros_system_api/dbus/service_constants.h"
  39. namespace bluez {
  40. namespace {
  41. // Default interval between simulated events.
  42. const int kSimulationIntervalMs = 750;
  43. // Minimum and maximum bounds for randomly generated RSSI values.
  44. const int kMinRSSI = -90;
  45. const int kMaxRSSI = -30;
  46. // The default value of connection info properties from GetConnInfo().
  47. const int kUnkownPower = 127;
  48. // This is meant to delay the removal of a pre defined device until the
  49. // developer has time to see it.
  50. const int kVanishingDevicePairTimeMultiplier = 4;
  51. // Meant to delay a pair request for an observable amount of time.
  52. const int kIncomingSimulationPairTimeMultiplier = 45;
  53. // Meant to delay a request that asks for pair requests for an observable
  54. // amount of time.
  55. const int kIncomingSimulationStartPairTimeMultiplier = 30;
  56. // This allows the PIN code dialog to be shown for a long enough time to see
  57. // the PIN code UI in detail.
  58. const int kPinCodeDevicePairTimeMultiplier = 7;
  59. // This allows the pairing dialog to be shown for a long enough time to see
  60. // its UI in detail.
  61. const int kSimulateNormalPairTimeMultiplier = 3;
  62. void SimulatedProfileSocket(int fd) {
  63. // Simulate a server-side socket of a profile; read data from the socket,
  64. // write it back, and then close.
  65. char buf[1024];
  66. ssize_t len;
  67. ssize_t count;
  68. len = read(fd, buf, sizeof buf);
  69. if (len < 0) {
  70. close(fd);
  71. return;
  72. }
  73. count = len;
  74. len = write(fd, buf, count);
  75. if (len < 0) {
  76. close(fd);
  77. return;
  78. }
  79. close(fd);
  80. }
  81. void SimpleErrorCallback(const std::string& error_name,
  82. const std::string& error_message) {
  83. DVLOG(1) << "Bluetooth Error: " << error_name << ": " << error_message;
  84. }
  85. BluetoothDeviceClient::ServiceRecordList CreateFakeServiceRecords() {
  86. BluetoothDeviceClient::ServiceRecordList records;
  87. std::unique_ptr<BluetoothServiceRecordBlueZ> record1 =
  88. std::make_unique<BluetoothServiceRecordBlueZ>();
  89. // ID 0 = handle.
  90. record1->AddRecordEntry(
  91. 0x0, BluetoothServiceAttributeValueBlueZ(
  92. BluetoothServiceAttributeValueBlueZ::UINT, 4,
  93. std::make_unique<base::Value>(static_cast<int32_t>(0x1337))));
  94. // ID 1 = service class id list.
  95. std::unique_ptr<BluetoothServiceAttributeValueBlueZ::Sequence> class_id_list =
  96. std::make_unique<BluetoothServiceAttributeValueBlueZ::Sequence>();
  97. class_id_list->emplace_back(BluetoothServiceAttributeValueBlueZ::UUID, 4,
  98. std::make_unique<base::Value>("1802"));
  99. record1->AddRecordEntry(
  100. 0x1, BluetoothServiceAttributeValueBlueZ(std::move(class_id_list)));
  101. records.emplace_back(*record1);
  102. std::unique_ptr<BluetoothServiceRecordBlueZ> record2 =
  103. std::make_unique<BluetoothServiceRecordBlueZ>();
  104. // ID 0 = handle.
  105. record2->AddRecordEntry(
  106. 0x0,
  107. BluetoothServiceAttributeValueBlueZ(
  108. BluetoothServiceAttributeValueBlueZ::UINT, 4,
  109. std::make_unique<base::Value>(static_cast<int32_t>(0xffffffff))));
  110. records.emplace_back(*record2);
  111. return records;
  112. }
  113. } // namespace
  114. const char FakeBluetoothDeviceClient::kTestPinCode[] = "123456";
  115. const int FakeBluetoothDeviceClient::kTestPassKey = 123456;
  116. const char FakeBluetoothDeviceClient::kPairingMethodNone[] = "None";
  117. const char FakeBluetoothDeviceClient::kPairingMethodPinCode[] = "PIN Code";
  118. const char FakeBluetoothDeviceClient::kPairingMethodPassKey[] = "PassKey";
  119. const char FakeBluetoothDeviceClient::kPairingActionConfirmation[] =
  120. "Confirmation";
  121. const char FakeBluetoothDeviceClient::kPairingActionDisplay[] = "Display";
  122. const char FakeBluetoothDeviceClient::kPairingActionFail[] = "Fail";
  123. const char FakeBluetoothDeviceClient::kPairingActionRequest[] = "Request";
  124. const char FakeBluetoothDeviceClient::kPairedDevicePath[] = "/fake/hci0/dev0";
  125. const char FakeBluetoothDeviceClient::kPairedDeviceAddress[] =
  126. "00:11:22:33:44:55";
  127. const char FakeBluetoothDeviceClient::kPairedDeviceName[] =
  128. "Fake Device (name)";
  129. const char FakeBluetoothDeviceClient::kPairedDeviceAlias[] =
  130. "Fake Device (alias)";
  131. const uint32_t FakeBluetoothDeviceClient::kPairedDeviceClass = 0x000104;
  132. const char FakeBluetoothDeviceClient::kLegacyAutopairPath[] = "/fake/hci0/dev1";
  133. const char FakeBluetoothDeviceClient::kLegacyAutopairAddress[] =
  134. "28:CF:DA:00:00:00";
  135. const char FakeBluetoothDeviceClient::kLegacyAutopairName[] =
  136. "Bluetooth 2.0 Mouse";
  137. const uint32_t FakeBluetoothDeviceClient::kLegacyAutopairClass = 0x002580;
  138. const char FakeBluetoothDeviceClient::kDisplayPinCodePath[] = "/fake/hci0/dev2";
  139. const char FakeBluetoothDeviceClient::kDisplayPinCodeAddress[] =
  140. "28:37:37:00:00:00";
  141. const char FakeBluetoothDeviceClient::kDisplayPinCodeName[] =
  142. "Bluetooth 2.0 Keyboard";
  143. const uint32_t FakeBluetoothDeviceClient::kDisplayPinCodeClass = 0x002540;
  144. const char FakeBluetoothDeviceClient::kVanishingDevicePath[] =
  145. "/fake/hci0/dev3";
  146. const char FakeBluetoothDeviceClient::kVanishingDeviceAddress[] =
  147. "01:02:03:04:05:06";
  148. const char FakeBluetoothDeviceClient::kVanishingDeviceName[] =
  149. "Vanishing Device";
  150. const uint32_t FakeBluetoothDeviceClient::kVanishingDeviceClass = 0x000104;
  151. const char FakeBluetoothDeviceClient::kConnectUnpairablePath[] =
  152. "/fake/hci0/dev4";
  153. const char FakeBluetoothDeviceClient::kConnectUnpairableAddress[] =
  154. "7C:ED:8D:00:00:00";
  155. const char FakeBluetoothDeviceClient::kConnectUnpairableName[] =
  156. "Unpairable Device";
  157. const uint32_t FakeBluetoothDeviceClient::kConnectUnpairableClass = 0x002580;
  158. const char FakeBluetoothDeviceClient::kDisplayPasskeyPath[] = "/fake/hci0/dev5";
  159. const char FakeBluetoothDeviceClient::kDisplayPasskeyAddress[] =
  160. "00:0F:F6:00:00:00";
  161. const char FakeBluetoothDeviceClient::kDisplayPasskeyName[] =
  162. "Bluetooth 2.1+ Keyboard";
  163. const uint32_t FakeBluetoothDeviceClient::kDisplayPasskeyClass = 0x002540;
  164. const char FakeBluetoothDeviceClient::kRequestPinCodePath[] = "/fake/hci0/dev6";
  165. const char FakeBluetoothDeviceClient::kRequestPinCodeAddress[] =
  166. "00:24:BE:00:00:00";
  167. const char FakeBluetoothDeviceClient::kRequestPinCodeName[] = "PIN Device";
  168. const uint32_t FakeBluetoothDeviceClient::kRequestPinCodeClass = 0x240408;
  169. const char FakeBluetoothDeviceClient::kConfirmPasskeyPath[] = "/fake/hci0/dev7";
  170. const char FakeBluetoothDeviceClient::kConfirmPasskeyAddress[] =
  171. "20:7D:74:00:00:00";
  172. const char FakeBluetoothDeviceClient::kConfirmPasskeyName[] = "Phone";
  173. const uint32_t FakeBluetoothDeviceClient::kConfirmPasskeyClass = 0x7a020c;
  174. const char FakeBluetoothDeviceClient::kRequestPasskeyPath[] = "/fake/hci0/dev8";
  175. const char FakeBluetoothDeviceClient::kRequestPasskeyAddress[] =
  176. "20:7D:74:00:00:01";
  177. const char FakeBluetoothDeviceClient::kRequestPasskeyName[] = "Passkey Device";
  178. const uint32_t FakeBluetoothDeviceClient::kRequestPasskeyClass = 0x7a020c;
  179. const char FakeBluetoothDeviceClient::kUnconnectableDevicePath[] =
  180. "/fake/hci0/dev9";
  181. const char FakeBluetoothDeviceClient::kUnconnectableDeviceAddress[] =
  182. "20:7D:74:00:00:02";
  183. const char FakeBluetoothDeviceClient::kUnconnectableDeviceName[] =
  184. "Unconnectable Device";
  185. const uint32_t FakeBluetoothDeviceClient::kUnconnectableDeviceClass = 0x7a020c;
  186. const char FakeBluetoothDeviceClient::kUnpairableDevicePath[] =
  187. "/fake/hci0/devA";
  188. const char FakeBluetoothDeviceClient::kUnpairableDeviceAddress[] =
  189. "20:7D:74:00:00:03";
  190. const char FakeBluetoothDeviceClient::kUnpairableDeviceName[] =
  191. "Unpairable Device";
  192. const uint32_t FakeBluetoothDeviceClient::kUnpairableDeviceClass = 0x002540;
  193. const char FakeBluetoothDeviceClient::kJustWorksPath[] = "/fake/hci0/devB";
  194. const char FakeBluetoothDeviceClient::kJustWorksAddress[] = "00:0C:8A:00:00:00";
  195. const char FakeBluetoothDeviceClient::kJustWorksName[] = "Just-Works Device";
  196. const uint32_t FakeBluetoothDeviceClient::kJustWorksClass = 0x240428;
  197. const char FakeBluetoothDeviceClient::kLowEnergyPath[] = "/fake/hci0/devC";
  198. const char FakeBluetoothDeviceClient::kLowEnergyAddress[] = "00:1A:11:00:15:30";
  199. const char FakeBluetoothDeviceClient::kLowEnergyName[] =
  200. "Bluetooth 4.0 Heart Rate Monitor";
  201. const uint32_t FakeBluetoothDeviceClient::kLowEnergyClass =
  202. 0x000918; // Major class "Health", Minor class "Heart/Pulse Rate Monitor."
  203. const char FakeBluetoothDeviceClient::kDualPath[] = "/fake/hci0/devF";
  204. const char FakeBluetoothDeviceClient::kDualAddress[] = "00:1A:11:00:15:40";
  205. const char FakeBluetoothDeviceClient::kDualName[] =
  206. "Bluetooth 4.0 Battery Monitor";
  207. const char FakeBluetoothDeviceClient::kPairedUnconnectableDevicePath[] =
  208. "/fake/hci0/devD";
  209. const char FakeBluetoothDeviceClient::kPairedUnconnectableDeviceAddress[] =
  210. "20:7D:74:00:00:04";
  211. const char FakeBluetoothDeviceClient::kPairedUnconnectableDeviceName[] =
  212. "Paired Unconnectable Device (name)";
  213. const char FakeBluetoothDeviceClient::kPairedUnconnectableDeviceAlias[] =
  214. "Paired Unconnectable Device (alias)";
  215. const uint32_t FakeBluetoothDeviceClient::kPairedUnconnectableDeviceClass =
  216. 0x000104;
  217. const char FakeBluetoothDeviceClient::kConnectedTrustedNotPairedDevicePath[] =
  218. "/fake/hci0/devE";
  219. const char
  220. FakeBluetoothDeviceClient::kConnectedTrustedNotPairedDeviceAddress[] =
  221. "11:22:33:44:55:66";
  222. const char FakeBluetoothDeviceClient::kConnectedTrustedNotPairedDeviceName[] =
  223. "Connected Pairable Device";
  224. const uint32_t
  225. FakeBluetoothDeviceClient::kConnectedTrustedNotPairedDeviceClass = 0x7a020c;
  226. FakeBluetoothDeviceClient::Properties::Properties(
  227. const PropertyChangedCallback& callback)
  228. : BluetoothDeviceClient::Properties(
  229. NULL,
  230. bluetooth_device::kBluetoothDeviceInterface,
  231. callback) {}
  232. FakeBluetoothDeviceClient::Properties::~Properties() = default;
  233. void FakeBluetoothDeviceClient::Properties::Get(
  234. dbus::PropertyBase* property,
  235. dbus::PropertySet::GetCallback callback) {
  236. DVLOG(1) << "Get " << property->name();
  237. std::move(callback).Run(false);
  238. }
  239. void FakeBluetoothDeviceClient::Properties::GetAll() {
  240. DVLOG(1) << "GetAll";
  241. }
  242. void FakeBluetoothDeviceClient::Properties::Set(
  243. dbus::PropertyBase* property,
  244. dbus::PropertySet::SetCallback callback) {
  245. DVLOG(1) << "Set " << property->name();
  246. if (property->name() == trusted.name()) {
  247. std::move(callback).Run(true);
  248. property->ReplaceValueWithSetValue();
  249. } else {
  250. std::move(callback).Run(false);
  251. }
  252. }
  253. FakeBluetoothDeviceClient::SimulatedPairingOptions::SimulatedPairingOptions() =
  254. default;
  255. FakeBluetoothDeviceClient::SimulatedPairingOptions::~SimulatedPairingOptions() =
  256. default;
  257. FakeBluetoothDeviceClient::IncomingDeviceProperties::
  258. IncomingDeviceProperties() = default;
  259. FakeBluetoothDeviceClient::IncomingDeviceProperties::
  260. ~IncomingDeviceProperties() = default;
  261. FakeBluetoothDeviceClient::FakeBluetoothDeviceClient()
  262. : simulation_interval_ms_(kSimulationIntervalMs),
  263. discovery_simulation_step_(0),
  264. incoming_pairing_simulation_step_(0),
  265. pairing_cancelled_(false),
  266. connection_rssi_(kUnkownPower),
  267. transmit_power_(kUnkownPower),
  268. max_transmit_power_(kUnkownPower),
  269. delay_start_discovery_(false),
  270. should_leave_connections_pending_(false) {
  271. auto properties = std::make_unique<Properties>(base::BindRepeating(
  272. &FakeBluetoothDeviceClient::OnPropertyChanged, base::Unretained(this),
  273. dbus::ObjectPath(kPairedDevicePath)));
  274. properties->address.ReplaceValue(kPairedDeviceAddress);
  275. properties->bluetooth_class.ReplaceValue(
  276. static_cast<int>(kPairedDeviceClass));
  277. properties->name.ReplaceValue(kPairedDeviceName);
  278. properties->name.set_valid(true);
  279. properties->alias.ReplaceValue(kPairedDeviceAlias);
  280. properties->paired.ReplaceValue(true);
  281. properties->trusted.ReplaceValue(true);
  282. properties->adapter.ReplaceValue(
  283. dbus::ObjectPath(FakeBluetoothAdapterClient::kAdapterPath));
  284. std::vector<std::string> uuids;
  285. uuids.push_back("00001800-0000-1000-8000-00805f9b34fb");
  286. uuids.push_back("00001801-0000-1000-8000-00805f9b34fb");
  287. properties->uuids.ReplaceValue(uuids);
  288. properties->modalias.ReplaceValue("usb:v05ACp030Dd0306");
  289. properties_map_.insert(std::make_pair(dbus::ObjectPath(kPairedDevicePath),
  290. std::move(properties)));
  291. device_list_.push_back(dbus::ObjectPath(kPairedDevicePath));
  292. properties = std::make_unique<Properties>(base::BindRepeating(
  293. &FakeBluetoothDeviceClient::OnPropertyChanged, base::Unretained(this),
  294. dbus::ObjectPath(kPairedUnconnectableDevicePath)));
  295. properties->address.ReplaceValue(kPairedUnconnectableDeviceAddress);
  296. properties->bluetooth_class.ReplaceValue(kPairedUnconnectableDeviceClass);
  297. properties->name.ReplaceValue(kPairedUnconnectableDeviceName);
  298. properties->name.set_valid(true);
  299. properties->alias.ReplaceValue(kPairedUnconnectableDeviceAlias);
  300. properties->paired.ReplaceValue(true);
  301. properties->trusted.ReplaceValue(true);
  302. properties->adapter.ReplaceValue(
  303. dbus::ObjectPath(FakeBluetoothAdapterClient::kAdapterPath));
  304. properties->uuids.ReplaceValue(uuids);
  305. properties->modalias.ReplaceValue("usb:v05ACp030Dd0306");
  306. properties_map_.insert(std::make_pair(
  307. dbus::ObjectPath(kPairedUnconnectableDevicePath), std::move(properties)));
  308. device_list_.push_back(dbus::ObjectPath(kPairedUnconnectableDevicePath));
  309. }
  310. FakeBluetoothDeviceClient::~FakeBluetoothDeviceClient() = default;
  311. void FakeBluetoothDeviceClient::LeaveConnectionsPending() {
  312. should_leave_connections_pending_ = true;
  313. }
  314. void FakeBluetoothDeviceClient::Init(
  315. dbus::Bus* bus,
  316. const std::string& bluetooth_service_name) {}
  317. void FakeBluetoothDeviceClient::AddObserver(Observer* observer) {
  318. observers_.AddObserver(observer);
  319. }
  320. void FakeBluetoothDeviceClient::RemoveObserver(Observer* observer) {
  321. observers_.RemoveObserver(observer);
  322. }
  323. std::vector<dbus::ObjectPath> FakeBluetoothDeviceClient::GetDevicesForAdapter(
  324. const dbus::ObjectPath& adapter_path) {
  325. if (adapter_path ==
  326. dbus::ObjectPath(FakeBluetoothAdapterClient::kAdapterPath))
  327. return device_list_;
  328. else
  329. return std::vector<dbus::ObjectPath>();
  330. }
  331. FakeBluetoothDeviceClient::Properties* FakeBluetoothDeviceClient::GetProperties(
  332. const dbus::ObjectPath& object_path) {
  333. PropertiesMap::const_iterator iter = properties_map_.find(object_path);
  334. if (iter != properties_map_.end())
  335. return iter->second.get();
  336. return NULL;
  337. }
  338. FakeBluetoothDeviceClient::SimulatedPairingOptions*
  339. FakeBluetoothDeviceClient::GetPairingOptions(
  340. const dbus::ObjectPath& object_path) {
  341. PairingOptionsMap::const_iterator iter =
  342. pairing_options_map_.find(object_path);
  343. if (iter != pairing_options_map_.end())
  344. return iter->second.get();
  345. return iter != pairing_options_map_.end() ? iter->second.get() : nullptr;
  346. }
  347. void FakeBluetoothDeviceClient::Connect(const dbus::ObjectPath& object_path,
  348. base::OnceClosure callback,
  349. ErrorCallback error_callback) {
  350. DVLOG(1) << "Connect: " << object_path.value();
  351. Properties* properties = GetProperties(object_path);
  352. if (properties->connected.value() == true) {
  353. // Already connected.
  354. std::move(callback).Run();
  355. return;
  356. }
  357. if (should_leave_connections_pending_)
  358. return;
  359. if (properties->paired.value() != true &&
  360. object_path != dbus::ObjectPath(kConnectUnpairablePath) &&
  361. object_path != dbus::ObjectPath(kLowEnergyPath)) {
  362. // Must be paired.
  363. std::move(error_callback).Run(bluetooth_device::kErrorFailed, "Not paired");
  364. return;
  365. } else if (properties->paired.value() == true &&
  366. (object_path == dbus::ObjectPath(kUnconnectableDevicePath) ||
  367. object_path ==
  368. dbus::ObjectPath(kPairedUnconnectableDevicePath))) {
  369. // Must not be paired
  370. std::move(error_callback)
  371. .Run(bluetooth_device::kErrorFailed, "Connection fails while paired");
  372. return;
  373. }
  374. // The device can be connected.
  375. properties->connected.ReplaceValue(true);
  376. if (object_path == dbus::ObjectPath(kLowEnergyPath))
  377. properties->connected_le.ReplaceValue(true);
  378. std::move(callback).Run();
  379. // Expose GATT services if connected to LE device.
  380. if (object_path == dbus::ObjectPath(kLowEnergyPath)) {
  381. FakeBluetoothGattServiceClient* gatt_service_client =
  382. static_cast<FakeBluetoothGattServiceClient*>(
  383. bluez::BluezDBusManager::Get()->GetBluetoothGattServiceClient());
  384. gatt_service_client->ExposeHeartRateService(object_path);
  385. properties->services_resolved.ReplaceValue(true);
  386. }
  387. AddInputDeviceIfNeeded(object_path, properties);
  388. }
  389. void FakeBluetoothDeviceClient::ConnectClassic(
  390. const dbus::ObjectPath& object_path,
  391. base::OnceClosure callback,
  392. ErrorCallback error_callback) {
  393. Connect(object_path, std::move(callback), std::move(error_callback));
  394. }
  395. void FakeBluetoothDeviceClient::ConnectLE(const dbus::ObjectPath& object_path,
  396. base::OnceClosure callback,
  397. ErrorCallback error_callback) {
  398. Connect(object_path, std::move(callback), std::move(error_callback));
  399. }
  400. void FakeBluetoothDeviceClient::DisconnectLE(
  401. const dbus::ObjectPath& object_path,
  402. base::OnceClosure callback,
  403. ErrorCallback error_callback) {
  404. Disconnect(object_path, std::move(callback), std::move(error_callback));
  405. }
  406. void FakeBluetoothDeviceClient::Disconnect(const dbus::ObjectPath& object_path,
  407. base::OnceClosure callback,
  408. ErrorCallback error_callback) {
  409. DVLOG(1) << "Disconnect: " << object_path.value();
  410. Properties* properties = GetProperties(object_path);
  411. if (!properties->connected.value()) {
  412. std::move(error_callback)
  413. .Run(bluetooth_device::kErrorNotConnected, "Not Connected");
  414. return;
  415. }
  416. // Hide the Heart Rate Service if disconnected from LE device.
  417. if (object_path == dbus::ObjectPath(kLowEnergyPath)) {
  418. FakeBluetoothGattServiceClient* gatt_service_client =
  419. static_cast<FakeBluetoothGattServiceClient*>(
  420. bluez::BluezDBusManager::Get()->GetBluetoothGattServiceClient());
  421. gatt_service_client->HideHeartRateService();
  422. }
  423. std::move(callback).Run();
  424. properties->connected.ReplaceValue(false);
  425. properties->connected_le.ReplaceValue(false);
  426. }
  427. void FakeBluetoothDeviceClient::ConnectProfile(
  428. const dbus::ObjectPath& object_path,
  429. const std::string& uuid,
  430. base::OnceClosure callback,
  431. ErrorCallback error_callback) {
  432. DVLOG(1) << "ConnectProfile: " << object_path.value() << " " << uuid;
  433. FakeBluetoothProfileManagerClient* fake_bluetooth_profile_manager_client =
  434. static_cast<FakeBluetoothProfileManagerClient*>(
  435. bluez::BluezDBusManager::Get()->GetBluetoothProfileManagerClient());
  436. FakeBluetoothProfileServiceProvider* profile_service_provider =
  437. fake_bluetooth_profile_manager_client->GetProfileServiceProvider(uuid);
  438. if (profile_service_provider == NULL) {
  439. std::move(error_callback).Run(kNoResponseError, "Missing profile");
  440. return;
  441. }
  442. if (object_path == dbus::ObjectPath(kPairedUnconnectableDevicePath)) {
  443. std::move(error_callback)
  444. .Run(bluetooth_device::kErrorFailed, "unconnectable");
  445. return;
  446. }
  447. // Make a socket pair of a compatible type with the type used by Bluetooth;
  448. // spin up a thread to simulate the server side and wrap the client side in
  449. // a D-Bus file descriptor object.
  450. int socket_type = SOCK_STREAM;
  451. if (uuid == FakeBluetoothProfileManagerClient::kL2capUuid)
  452. socket_type = SOCK_SEQPACKET;
  453. int fds[2];
  454. if (socketpair(AF_UNIX, socket_type, 0, fds) < 0) {
  455. std::move(error_callback).Run(kNoResponseError, "socketpair call failed");
  456. return;
  457. }
  458. int args;
  459. args = fcntl(fds[1], F_GETFL, NULL);
  460. if (args < 0) {
  461. std::move(error_callback)
  462. .Run(kNoResponseError, "failed to get socket flags");
  463. return;
  464. }
  465. args |= O_NONBLOCK;
  466. if (fcntl(fds[1], F_SETFL, args) < 0) {
  467. std::move(error_callback)
  468. .Run(kNoResponseError, "failed to set socket non-blocking");
  469. return;
  470. }
  471. base::ThreadPool::PostTask(
  472. FROM_HERE,
  473. {base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
  474. base::BindOnce(&SimulatedProfileSocket, fds[0]));
  475. base::ScopedFD fd(fds[1]);
  476. // Post the new connection to the service provider.
  477. BluetoothProfileServiceProvider::Delegate::Options options;
  478. profile_service_provider->NewConnection(
  479. object_path, std::move(fd), options,
  480. base::BindOnce(&FakeBluetoothDeviceClient::ConnectionCallback,
  481. base::Unretained(this), object_path, std::move(callback),
  482. std::move(error_callback)));
  483. }
  484. void FakeBluetoothDeviceClient::DisconnectProfile(
  485. const dbus::ObjectPath& object_path,
  486. const std::string& uuid,
  487. base::OnceClosure callback,
  488. ErrorCallback error_callback) {
  489. DVLOG(1) << "DisconnectProfile: " << object_path.value() << " " << uuid;
  490. FakeBluetoothProfileManagerClient* fake_bluetooth_profile_manager_client =
  491. static_cast<FakeBluetoothProfileManagerClient*>(
  492. bluez::BluezDBusManager::Get()->GetBluetoothProfileManagerClient());
  493. FakeBluetoothProfileServiceProvider* profile_service_provider =
  494. fake_bluetooth_profile_manager_client->GetProfileServiceProvider(uuid);
  495. if (profile_service_provider == NULL) {
  496. std::move(error_callback).Run(kNoResponseError, "Missing profile");
  497. return;
  498. }
  499. profile_service_provider->RequestDisconnection(
  500. object_path,
  501. base::BindOnce(&FakeBluetoothDeviceClient::DisconnectionCallback,
  502. base::Unretained(this), object_path, std::move(callback),
  503. std::move(error_callback)));
  504. }
  505. void FakeBluetoothDeviceClient::Pair(const dbus::ObjectPath& object_path,
  506. base::OnceClosure callback,
  507. ErrorCallback error_callback) {
  508. DVLOG(1) << "Pair: " << object_path.value();
  509. Properties* properties = GetProperties(object_path);
  510. if (properties->paired.value() == true) {
  511. // Already paired.
  512. std::move(callback).Run();
  513. return;
  514. }
  515. SimulatePairing(object_path, false, std::move(callback),
  516. std::move(error_callback));
  517. }
  518. void FakeBluetoothDeviceClient::CancelPairing(
  519. const dbus::ObjectPath& object_path,
  520. base::OnceClosure callback,
  521. ErrorCallback error_callback) {
  522. DVLOG(1) << "CancelPairing: " << object_path.value();
  523. pairing_cancelled_ = true;
  524. std::move(callback).Run();
  525. }
  526. void FakeBluetoothDeviceClient::GetConnInfo(const dbus::ObjectPath& object_path,
  527. ConnInfoCallback callback,
  528. ErrorCallback error_callback) {
  529. Properties* properties = GetProperties(object_path);
  530. if (!properties->connected.value()) {
  531. std::move(error_callback)
  532. .Run(bluetooth_device::kErrorNotConnected, "Not Connected");
  533. return;
  534. }
  535. std::move(callback).Run(connection_rssi_, transmit_power_,
  536. max_transmit_power_);
  537. }
  538. void FakeBluetoothDeviceClient::SetLEConnectionParameters(
  539. const dbus::ObjectPath& object_path,
  540. const ConnectionParameters& conn_params,
  541. base::OnceClosure callback,
  542. ErrorCallback error_callback) {
  543. Properties* properties = GetProperties(object_path);
  544. if (!properties->type.is_valid() || properties->type.value() == kTypeBredr) {
  545. std::move(error_callback)
  546. .Run(bluetooth_device::kErrorFailed, "BR/EDR devices not supported");
  547. return;
  548. }
  549. std::move(callback).Run();
  550. }
  551. void FakeBluetoothDeviceClient::GetServiceRecords(
  552. const dbus::ObjectPath& object_path,
  553. ServiceRecordsCallback callback,
  554. ErrorCallback error_callback) {
  555. Properties* properties = GetProperties(object_path);
  556. if (!properties->connected.value()) {
  557. std::move(error_callback)
  558. .Run(bluetooth_device::kErrorNotConnected, "Not Connected");
  559. return;
  560. }
  561. std::move(callback).Run(CreateFakeServiceRecords());
  562. }
  563. void FakeBluetoothDeviceClient::ExecuteWrite(
  564. const dbus::ObjectPath& object_path,
  565. base::OnceClosure callback,
  566. ErrorCallback error_callback) {
  567. for (const auto& prepare_write_request : prepare_write_requests_) {
  568. bluez::BluezDBusManager::Get()
  569. ->GetBluetoothGattCharacteristicClient()
  570. ->WriteValue(prepare_write_request.first, prepare_write_request.second,
  571. bluetooth_gatt_characteristic::kTypeRequest,
  572. base::DoNothing(), base::DoNothing());
  573. }
  574. prepare_write_requests_.clear();
  575. std::move(callback).Run();
  576. }
  577. void FakeBluetoothDeviceClient::AbortWrite(const dbus::ObjectPath& object_path,
  578. base::OnceClosure callback,
  579. ErrorCallback error_callback) {
  580. prepare_write_requests_.clear();
  581. std::move(callback).Run();
  582. }
  583. void FakeBluetoothDeviceClient::BeginDiscoverySimulation(
  584. const dbus::ObjectPath& adapter_path) {
  585. DVLOG(1) << "starting discovery simulation";
  586. discovery_simulation_step_ = 1;
  587. int delay = delay_start_discovery_ ? simulation_interval_ms_ : 0;
  588. base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
  589. FROM_HERE,
  590. base::BindOnce(&FakeBluetoothDeviceClient::DiscoverySimulationTimer,
  591. base::Unretained(this)),
  592. base::Milliseconds(delay));
  593. }
  594. void FakeBluetoothDeviceClient::EndDiscoverySimulation(
  595. const dbus::ObjectPath& adapter_path) {
  596. DVLOG(1) << "stopping discovery simulation";
  597. discovery_simulation_step_ = 0;
  598. InvalidateDeviceRSSI(dbus::ObjectPath(kLowEnergyPath));
  599. }
  600. void FakeBluetoothDeviceClient::BeginIncomingPairingSimulation(
  601. const dbus::ObjectPath& adapter_path) {
  602. DVLOG(1) << "starting incoming pairing simulation";
  603. incoming_pairing_simulation_step_ = 1;
  604. base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
  605. FROM_HERE,
  606. base::BindOnce(&FakeBluetoothDeviceClient::IncomingPairingSimulationTimer,
  607. base::Unretained(this)),
  608. base::Milliseconds(kIncomingSimulationStartPairTimeMultiplier *
  609. simulation_interval_ms_));
  610. }
  611. void FakeBluetoothDeviceClient::EndIncomingPairingSimulation(
  612. const dbus::ObjectPath& adapter_path) {
  613. DVLOG(1) << "stopping incoming pairing simulation";
  614. incoming_pairing_simulation_step_ = 0;
  615. }
  616. void FakeBluetoothDeviceClient::SetSimulationIntervalMs(int interval_ms) {
  617. simulation_interval_ms_ = interval_ms;
  618. }
  619. void FakeBluetoothDeviceClient::CreateDevice(
  620. const dbus::ObjectPath& adapter_path,
  621. const dbus::ObjectPath& device_path) {
  622. if (base::Contains(device_list_, device_path))
  623. return;
  624. std::unique_ptr<Properties> properties(new Properties(
  625. base::BindRepeating(&FakeBluetoothDeviceClient::OnPropertyChanged,
  626. base::Unretained(this), device_path)));
  627. properties->adapter.ReplaceValue(adapter_path);
  628. properties->type.ReplaceValue(BluetoothDeviceClient::kTypeBredr);
  629. properties->type.set_valid(true);
  630. if (device_path == dbus::ObjectPath(kLegacyAutopairPath)) {
  631. properties->address.ReplaceValue(kLegacyAutopairAddress);
  632. properties->bluetooth_class.ReplaceValue(kLegacyAutopairClass);
  633. properties->name.ReplaceValue(kLegacyAutopairName);
  634. properties->name.set_valid(true);
  635. std::vector<std::string> uuids;
  636. uuids.push_back("00001124-0000-1000-8000-00805f9b34fb");
  637. properties->uuids.ReplaceValue(uuids);
  638. } else if (device_path == dbus::ObjectPath(kDisplayPinCodePath)) {
  639. properties->address.ReplaceValue(kDisplayPinCodeAddress);
  640. properties->bluetooth_class.ReplaceValue(kDisplayPinCodeClass);
  641. properties->name.ReplaceValue(kDisplayPinCodeName);
  642. properties->name.set_valid(true);
  643. std::vector<std::string> uuids;
  644. uuids.push_back("00001124-0000-1000-8000-00805f9b34fb");
  645. properties->uuids.ReplaceValue(uuids);
  646. } else if (device_path == dbus::ObjectPath(kVanishingDevicePath)) {
  647. properties->address.ReplaceValue(kVanishingDeviceAddress);
  648. properties->bluetooth_class.ReplaceValue(kVanishingDeviceClass);
  649. properties->name.ReplaceValue(kVanishingDeviceName);
  650. properties->name.set_valid(true);
  651. } else if (device_path == dbus::ObjectPath(kConnectUnpairablePath)) {
  652. properties->address.ReplaceValue(kConnectUnpairableAddress);
  653. properties->bluetooth_class.ReplaceValue(kConnectUnpairableClass);
  654. properties->name.ReplaceValue(kConnectUnpairableName);
  655. properties->name.set_valid(true);
  656. std::vector<std::string> uuids;
  657. uuids.push_back("00001124-0000-1000-8000-00805f9b34fb");
  658. properties->uuids.ReplaceValue(uuids);
  659. } else if (device_path == dbus::ObjectPath(kDisplayPasskeyPath)) {
  660. properties->address.ReplaceValue(kDisplayPasskeyAddress);
  661. properties->bluetooth_class.ReplaceValue(kDisplayPasskeyClass);
  662. properties->name.ReplaceValue(kDisplayPasskeyName);
  663. properties->name.set_valid(true);
  664. std::vector<std::string> uuids;
  665. uuids.push_back("00001124-0000-1000-8000-00805f9b34fb");
  666. properties->uuids.ReplaceValue(uuids);
  667. } else if (device_path == dbus::ObjectPath(kRequestPinCodePath)) {
  668. properties->address.ReplaceValue(kRequestPinCodeAddress);
  669. properties->bluetooth_class.ReplaceValue(kRequestPinCodeClass);
  670. properties->name.ReplaceValue(kRequestPinCodeName);
  671. properties->name.set_valid(true);
  672. } else if (device_path == dbus::ObjectPath(kConfirmPasskeyPath)) {
  673. properties->address.ReplaceValue(kConfirmPasskeyAddress);
  674. properties->bluetooth_class.ReplaceValue(kConfirmPasskeyClass);
  675. properties->name.ReplaceValue(kConfirmPasskeyName);
  676. properties->name.set_valid(true);
  677. } else if (device_path == dbus::ObjectPath(kRequestPasskeyPath)) {
  678. properties->address.ReplaceValue(kRequestPasskeyAddress);
  679. properties->bluetooth_class.ReplaceValue(kRequestPasskeyClass);
  680. properties->name.ReplaceValue(kRequestPasskeyName);
  681. properties->name.set_valid(true);
  682. } else if (device_path == dbus::ObjectPath(kUnconnectableDevicePath)) {
  683. properties->address.ReplaceValue(kUnconnectableDeviceAddress);
  684. properties->bluetooth_class.ReplaceValue(kUnconnectableDeviceClass);
  685. properties->name.ReplaceValue(kUnconnectableDeviceName);
  686. properties->name.set_valid(true);
  687. } else if (device_path == dbus::ObjectPath(kUnpairableDevicePath)) {
  688. properties->address.ReplaceValue(kUnpairableDeviceAddress);
  689. properties->bluetooth_class.ReplaceValue(kUnpairableDeviceClass);
  690. properties->name.ReplaceValue(kUnpairableDeviceName);
  691. properties->name.set_valid(true);
  692. } else if (device_path == dbus::ObjectPath(kJustWorksPath)) {
  693. properties->address.ReplaceValue(kJustWorksAddress);
  694. properties->bluetooth_class.ReplaceValue(kJustWorksClass);
  695. properties->name.ReplaceValue(kJustWorksName);
  696. properties->name.set_valid(true);
  697. } else if (device_path == dbus::ObjectPath(kLowEnergyPath)) {
  698. properties->address.ReplaceValue(kLowEnergyAddress);
  699. properties->bluetooth_class.ReplaceValue(kLowEnergyClass);
  700. properties->name.ReplaceValue(kLowEnergyName);
  701. properties->name.set_valid(true);
  702. properties->services_resolved.ReplaceValue(false);
  703. properties->type.ReplaceValue(BluetoothDeviceClient::kTypeLe);
  704. properties->uuids.ReplaceValue(std::vector<std::string>(
  705. {FakeBluetoothGattServiceClient::kHeartRateServiceUUID}));
  706. std::vector<uint8_t> eir = {0x0a, 0x0b, 0x0c};
  707. properties->eir.ReplaceValue(eir);
  708. properties->eir.set_valid(true);
  709. properties->rssi.ReplaceValue(-45);
  710. properties->rssi.set_valid(true);
  711. } else if (device_path == dbus::ObjectPath(kDualPath)) {
  712. properties->address.ReplaceValue(kDualAddress);
  713. properties->name.ReplaceValue(kDualName);
  714. properties->name.set_valid(true);
  715. properties->services_resolved.ReplaceValue(false);
  716. properties->type.ReplaceValue(BluetoothDeviceClient::kTypeDual);
  717. properties->uuids.ReplaceValue(std::vector<std::string>(
  718. {FakeBluetoothGattServiceClient::kGenericAccessServiceUUID,
  719. FakeBluetoothGattServiceClient::kHeartRateServiceUUID}));
  720. } else if (device_path ==
  721. dbus::ObjectPath(kConnectedTrustedNotPairedDevicePath)) {
  722. properties->address.ReplaceValue(kConnectedTrustedNotPairedDeviceAddress);
  723. properties->bluetooth_class.ReplaceValue(
  724. kConnectedTrustedNotPairedDeviceClass);
  725. properties->trusted.ReplaceValue(true);
  726. properties->connected.ReplaceValue(true);
  727. properties->connected_le.ReplaceValue(true);
  728. properties->paired.ReplaceValue(false);
  729. properties->name.ReplaceValue(kConnectedTrustedNotPairedDeviceName);
  730. properties->name.set_valid(true);
  731. } else {
  732. NOTREACHED();
  733. }
  734. properties_map_.insert(std::make_pair(device_path, std::move(properties)));
  735. device_list_.push_back(device_path);
  736. for (auto& observer : observers_)
  737. observer.DeviceAdded(device_path);
  738. }
  739. void FakeBluetoothDeviceClient::CreateDeviceWithProperties(
  740. const dbus::ObjectPath& adapter_path,
  741. const IncomingDeviceProperties& props) {
  742. dbus::ObjectPath device_path(props.device_path);
  743. if (base::Contains(device_list_, device_path))
  744. return;
  745. std::unique_ptr<Properties> properties(new Properties(
  746. base::BindRepeating(&FakeBluetoothDeviceClient::OnPropertyChanged,
  747. base::Unretained(this), device_path)));
  748. properties->adapter.ReplaceValue(adapter_path);
  749. properties->name.ReplaceValue(props.device_name);
  750. properties->name.set_valid(true);
  751. properties->alias.ReplaceValue(props.device_alias);
  752. properties->address.ReplaceValue(props.device_address);
  753. properties->bluetooth_class.ReplaceValue(props.device_class);
  754. properties->trusted.ReplaceValue(props.is_trusted);
  755. if (props.is_trusted)
  756. properties->paired.ReplaceValue(true);
  757. std::unique_ptr<SimulatedPairingOptions> options(new SimulatedPairingOptions);
  758. options->pairing_method = props.pairing_method;
  759. options->pairing_auth_token = props.pairing_auth_token;
  760. options->pairing_action = props.pairing_action;
  761. options->incoming = props.incoming;
  762. properties_map_.insert(std::make_pair(device_path, std::move(properties)));
  763. device_list_.push_back(device_path);
  764. pairing_options_map_.insert(std::make_pair(device_path, std::move(options)));
  765. for (auto& observer : observers_)
  766. observer.DeviceAdded(device_path);
  767. }
  768. base::Value FakeBluetoothDeviceClient::GetBluetoothDevicesAsDictionaries()
  769. const {
  770. base::Value::List predefined_devices;
  771. base::Value::Dict paired_device;
  772. paired_device.Set("path", kPairedDevicePath);
  773. paired_device.Set("address", kPairedDeviceAddress);
  774. paired_device.Set("name", kPairedDeviceName);
  775. paired_device.Set("alias", kPairedDeviceName);
  776. paired_device.Set("pairingMethod", "");
  777. paired_device.Set("pairingAuthToken", "");
  778. paired_device.Set("pairingAction", "");
  779. paired_device.Set("classValue", static_cast<int>(kPairedDeviceClass));
  780. paired_device.Set("discoverable", true);
  781. paired_device.Set("isTrusted", true);
  782. paired_device.Set("paired", true);
  783. paired_device.Set("incoming", false);
  784. predefined_devices.Append(std::move(paired_device));
  785. base::Value::Dict legacy_device;
  786. legacy_device.Set("path", kLegacyAutopairPath);
  787. legacy_device.Set("address", kLegacyAutopairAddress);
  788. legacy_device.Set("name", kLegacyAutopairName);
  789. legacy_device.Set("alias", kLegacyAutopairName);
  790. legacy_device.Set("pairingMethod", "");
  791. legacy_device.Set("pairingAuthToken", "");
  792. legacy_device.Set("pairingAction", "");
  793. legacy_device.Set("classValue", static_cast<int>(kLegacyAutopairClass));
  794. legacy_device.Set("isTrusted", true);
  795. legacy_device.Set("discoverable", false);
  796. legacy_device.Set("paired", false);
  797. legacy_device.Set("incoming", false);
  798. predefined_devices.Append(std::move(legacy_device));
  799. base::Value::Dict pin;
  800. pin.Set("path", kDisplayPinCodePath);
  801. pin.Set("address", kDisplayPinCodeAddress);
  802. pin.Set("name", kDisplayPinCodeName);
  803. pin.Set("alias", kDisplayPinCodeName);
  804. pin.Set("pairingMethod", kPairingMethodPinCode);
  805. pin.Set("pairingAuthToken", kTestPinCode);
  806. pin.Set("pairingAction", kPairingActionDisplay);
  807. pin.Set("classValue", static_cast<int>(kDisplayPinCodeClass));
  808. pin.Set("isTrusted", false);
  809. pin.Set("discoverable", false);
  810. pin.Set("paired", false);
  811. pin.Set("incoming", false);
  812. predefined_devices.Append(std::move(pin));
  813. base::Value::Dict vanishing;
  814. vanishing.Set("path", kVanishingDevicePath);
  815. vanishing.Set("address", kVanishingDeviceAddress);
  816. vanishing.Set("name", kVanishingDeviceName);
  817. vanishing.Set("alias", kVanishingDeviceName);
  818. vanishing.Set("pairingMethod", "");
  819. vanishing.Set("pairingAuthToken", "");
  820. vanishing.Set("pairingAction", "");
  821. vanishing.Set("classValue", static_cast<int>(kVanishingDeviceClass));
  822. vanishing.Set("isTrusted", false);
  823. vanishing.Set("discoverable", false);
  824. vanishing.Set("paired", false);
  825. vanishing.Set("incoming", false);
  826. predefined_devices.Append(std::move(vanishing));
  827. base::Value::Dict connect_unpairable;
  828. connect_unpairable.Set("path", kConnectUnpairablePath);
  829. connect_unpairable.Set("address", kConnectUnpairableAddress);
  830. connect_unpairable.Set("name", kConnectUnpairableName);
  831. connect_unpairable.Set("pairingMethod", "");
  832. connect_unpairable.Set("pairingAuthToken", "");
  833. connect_unpairable.Set("pairingAction", "");
  834. connect_unpairable.Set("alias", kConnectUnpairableName);
  835. connect_unpairable.Set("classValue",
  836. static_cast<int>(kConnectUnpairableClass));
  837. connect_unpairable.Set("isTrusted", false);
  838. connect_unpairable.Set("discoverable", false);
  839. connect_unpairable.Set("paired", false);
  840. connect_unpairable.Set("incoming", false);
  841. predefined_devices.Append(std::move(connect_unpairable));
  842. base::Value::Dict passkey;
  843. passkey.Set("path", kDisplayPasskeyPath);
  844. passkey.Set("address", kDisplayPasskeyAddress);
  845. passkey.Set("name", kDisplayPasskeyName);
  846. passkey.Set("alias", kDisplayPasskeyName);
  847. passkey.Set("pairingMethod", kPairingMethodPassKey);
  848. passkey.Set("pairingAuthToken", kTestPassKey);
  849. passkey.Set("pairingAction", kPairingActionDisplay);
  850. passkey.Set("classValue", static_cast<int>(kDisplayPasskeyClass));
  851. passkey.Set("isTrusted", false);
  852. passkey.Set("discoverable", false);
  853. passkey.Set("paired", false);
  854. passkey.Set("incoming", false);
  855. predefined_devices.Append(std::move(passkey));
  856. base::Value::Dict request_pin;
  857. request_pin.Set("path", kRequestPinCodePath);
  858. request_pin.Set("address", kRequestPinCodeAddress);
  859. request_pin.Set("name", kRequestPinCodeName);
  860. request_pin.Set("alias", kRequestPinCodeName);
  861. request_pin.Set("pairingMethod", "");
  862. request_pin.Set("pairingAuthToken", "");
  863. request_pin.Set("pairingAction", kPairingActionRequest);
  864. request_pin.Set("classValue", static_cast<int>(kRequestPinCodeClass));
  865. request_pin.Set("isTrusted", false);
  866. request_pin.Set("discoverable", false);
  867. request_pin.Set("paired", false);
  868. request_pin.Set("incoming", false);
  869. predefined_devices.Append(std::move(request_pin));
  870. base::Value::Dict confirm;
  871. confirm.Set("path", kConfirmPasskeyPath);
  872. confirm.Set("address", kConfirmPasskeyAddress);
  873. confirm.Set("name", kConfirmPasskeyName);
  874. confirm.Set("alias", kConfirmPasskeyName);
  875. confirm.Set("pairingMethod", "");
  876. confirm.Set("pairingAuthToken", kTestPassKey);
  877. confirm.Set("pairingAction", kPairingActionConfirmation);
  878. confirm.Set("classValue", static_cast<int>(kConfirmPasskeyClass));
  879. confirm.Set("isTrusted", false);
  880. confirm.Set("discoverable", false);
  881. confirm.Set("paired", false);
  882. confirm.Set("incoming", false);
  883. predefined_devices.Append(std::move(confirm));
  884. base::Value::Dict request_passkey;
  885. request_passkey.Set("path", kRequestPasskeyPath);
  886. request_passkey.Set("address", kRequestPasskeyAddress);
  887. request_passkey.Set("name", kRequestPasskeyName);
  888. request_passkey.Set("alias", kRequestPasskeyName);
  889. request_passkey.Set("pairingMethod", kPairingMethodPassKey);
  890. request_passkey.Set("pairingAction", kPairingActionRequest);
  891. request_passkey.Set("pairingAuthToken", kTestPassKey);
  892. request_passkey.Set("classValue", static_cast<int>(kRequestPasskeyClass));
  893. request_passkey.Set("isTrusted", false);
  894. request_passkey.Set("discoverable", false);
  895. request_passkey.Set("paired", false);
  896. request_passkey.Set("incoming", false);
  897. predefined_devices.Append(std::move(request_passkey));
  898. base::Value::Dict unconnectable;
  899. unconnectable.Set("path", kUnconnectableDevicePath);
  900. unconnectable.Set("address", kUnconnectableDeviceAddress);
  901. unconnectable.Set("name", kUnconnectableDeviceName);
  902. unconnectable.Set("alias", kUnconnectableDeviceName);
  903. unconnectable.Set("pairingMethod", "");
  904. unconnectable.Set("pairingAuthToken", "");
  905. unconnectable.Set("pairingAction", "");
  906. unconnectable.Set("classValue", static_cast<int>(kUnconnectableDeviceClass));
  907. unconnectable.Set("isTrusted", true);
  908. unconnectable.Set("discoverable", false);
  909. unconnectable.Set("paired", false);
  910. unconnectable.Set("incoming", false);
  911. predefined_devices.Append(std::move(unconnectable));
  912. base::Value::Dict unpairable;
  913. unpairable.Set("path", kUnpairableDevicePath);
  914. unpairable.Set("address", kUnpairableDeviceAddress);
  915. unpairable.Set("name", kUnpairableDeviceName);
  916. unpairable.Set("alias", kUnpairableDeviceName);
  917. unpairable.Set("pairingMethod", "");
  918. unpairable.Set("pairingAuthToken", "");
  919. unpairable.Set("pairingAction", kPairingActionFail);
  920. unpairable.Set("classValue", static_cast<int>(kUnpairableDeviceClass));
  921. unpairable.Set("isTrusted", false);
  922. unpairable.Set("discoverable", false);
  923. unpairable.Set("paired", false);
  924. unpairable.Set("incoming", false);
  925. predefined_devices.Append(std::move(unpairable));
  926. base::Value::Dict just_works;
  927. just_works.Set("path", kJustWorksPath);
  928. just_works.Set("address", kJustWorksAddress);
  929. just_works.Set("name", kJustWorksName);
  930. just_works.Set("alias", kJustWorksName);
  931. just_works.Set("pairingMethod", "");
  932. just_works.Set("pairingAuthToken", "");
  933. just_works.Set("pairingAction", "");
  934. just_works.Set("classValue", static_cast<int>(kJustWorksClass));
  935. just_works.Set("isTrusted", false);
  936. just_works.Set("discoverable", false);
  937. just_works.Set("paired", false);
  938. just_works.Set("incoming", false);
  939. predefined_devices.Append(std::move(just_works));
  940. base::Value::Dict low_energy;
  941. low_energy.Set("path", kLowEnergyPath);
  942. low_energy.Set("address", kLowEnergyAddress);
  943. low_energy.Set("name", kLowEnergyName);
  944. low_energy.Set("alias", kLowEnergyName);
  945. low_energy.Set("pairingMethod", "");
  946. low_energy.Set("pairingAuthToken", "");
  947. low_energy.Set("pairingAction", "");
  948. low_energy.Set("classValue", static_cast<int>(kLowEnergyClass));
  949. low_energy.Set("isTrusted", false);
  950. low_energy.Set("discoverable", false);
  951. low_energy.Set("paireed", false);
  952. low_energy.Set("incoming", false);
  953. predefined_devices.Append(std::move(low_energy));
  954. base::Value::Dict paired_unconnectable;
  955. paired_unconnectable.Set("path", kPairedUnconnectableDevicePath);
  956. paired_unconnectable.Set("address", kPairedUnconnectableDeviceAddress);
  957. paired_unconnectable.Set("name", kPairedUnconnectableDeviceName);
  958. paired_unconnectable.Set("pairingMethod", "");
  959. paired_unconnectable.Set("pairingAuthToken", "");
  960. paired_unconnectable.Set("pairingAction", "");
  961. paired_unconnectable.Set("alias", kPairedUnconnectableDeviceName);
  962. paired_unconnectable.Set("classValue",
  963. static_cast<int>(kPairedUnconnectableDeviceClass));
  964. paired_unconnectable.Set("isTrusted", false);
  965. paired_unconnectable.Set("discoverable", true);
  966. paired_unconnectable.Set("paired", true);
  967. paired_unconnectable.Set("incoming", false);
  968. predefined_devices.Append(std::move(paired_unconnectable));
  969. base::Value::Dict connected_trusted_not_paired;
  970. connected_trusted_not_paired.Set("path",
  971. kConnectedTrustedNotPairedDevicePath);
  972. connected_trusted_not_paired.Set("address",
  973. kConnectedTrustedNotPairedDeviceAddress);
  974. connected_trusted_not_paired.Set("name",
  975. kConnectedTrustedNotPairedDeviceName);
  976. connected_trusted_not_paired.Set("pairingMethod", "");
  977. connected_trusted_not_paired.Set("pairingAuthToken", "");
  978. connected_trusted_not_paired.Set("pairingAction", "");
  979. connected_trusted_not_paired.Set("alias",
  980. kConnectedTrustedNotPairedDeviceName);
  981. connected_trusted_not_paired.Set(
  982. "classValue", static_cast<int>(kConnectedTrustedNotPairedDeviceClass));
  983. connected_trusted_not_paired.Set("isTrusted", true);
  984. connected_trusted_not_paired.Set("discoverable", true);
  985. connected_trusted_not_paired.Set("paired", false);
  986. connected_trusted_not_paired.Set("incoming", false);
  987. predefined_devices.Append(std::move(connected_trusted_not_paired));
  988. return base::Value(std::move(predefined_devices));
  989. }
  990. void FakeBluetoothDeviceClient::RemoveDevice(
  991. const dbus::ObjectPath& adapter_path,
  992. const dbus::ObjectPath& device_path) {
  993. auto listiter =
  994. std::find(device_list_.begin(), device_list_.end(), device_path);
  995. if (listiter == device_list_.end())
  996. return;
  997. PropertiesMap::const_iterator iter = properties_map_.find(device_path);
  998. Properties* properties = iter->second.get();
  999. DVLOG(1) << "removing device: " << properties->name.value();
  1000. device_list_.erase(listiter);
  1001. // Remove the Input interface if it exists. This should be called before the
  1002. // BluetoothDeviceClient::Observer::DeviceRemoved because it deletes the
  1003. // BluetoothDeviceBlueZ object, including the device_path referenced here.
  1004. FakeBluetoothInputClient* fake_bluetooth_input_client =
  1005. static_cast<FakeBluetoothInputClient*>(
  1006. bluez::BluezDBusManager::Get()->GetBluetoothInputClient());
  1007. fake_bluetooth_input_client->RemoveInputDevice(device_path);
  1008. if (device_path == dbus::ObjectPath(kLowEnergyPath)) {
  1009. FakeBluetoothGattServiceClient* gatt_service_client =
  1010. static_cast<FakeBluetoothGattServiceClient*>(
  1011. bluez::BluezDBusManager::Get()->GetBluetoothGattServiceClient());
  1012. gatt_service_client->HideHeartRateService();
  1013. }
  1014. for (auto& observer : observers_)
  1015. observer.DeviceRemoved(device_path);
  1016. properties_map_.erase(iter);
  1017. PairingOptionsMap::const_iterator options_iter =
  1018. pairing_options_map_.find(device_path);
  1019. if (options_iter != pairing_options_map_.end()) {
  1020. pairing_options_map_.erase(options_iter);
  1021. }
  1022. }
  1023. void FakeBluetoothDeviceClient::OnPropertyChanged(
  1024. const dbus::ObjectPath& object_path,
  1025. const std::string& property_name) {
  1026. DVLOG(2) << "Fake Bluetooth device property changed: " << object_path.value()
  1027. << ": " << property_name;
  1028. for (auto& observer : observers_)
  1029. observer.DevicePropertyChanged(object_path, property_name);
  1030. }
  1031. void FakeBluetoothDeviceClient::DiscoverySimulationTimer() {
  1032. if (!discovery_simulation_step_)
  1033. return;
  1034. // Timer fires every .75s, the numbers below are arbitrary to give a feel
  1035. // for a discovery process.
  1036. DVLOG(1) << "discovery simulation, step " << discovery_simulation_step_;
  1037. uint32_t initial_step = delay_start_discovery_ ? 2 : 1;
  1038. if (discovery_simulation_step_ == initial_step) {
  1039. CreateDevice(dbus::ObjectPath(FakeBluetoothAdapterClient::kAdapterPath),
  1040. dbus::ObjectPath(kLegacyAutopairPath));
  1041. CreateDevice(dbus::ObjectPath(FakeBluetoothAdapterClient::kAdapterPath),
  1042. dbus::ObjectPath(kLowEnergyPath));
  1043. if (!delay_start_discovery_) {
  1044. // Include a device that requires a pairing overlay in the UI.
  1045. CreateDevice(dbus::ObjectPath(FakeBluetoothAdapterClient::kAdapterPath),
  1046. dbus::ObjectPath(kRequestPinCodePath));
  1047. }
  1048. } else if (discovery_simulation_step_ == 4) {
  1049. UpdateDeviceRSSI(dbus::ObjectPath(kLowEnergyPath),
  1050. base::RandInt(kMinRSSI, kMaxRSSI));
  1051. CreateDevice(dbus::ObjectPath(FakeBluetoothAdapterClient::kAdapterPath),
  1052. dbus::ObjectPath(kDisplayPinCodePath));
  1053. CreateDevice(dbus::ObjectPath(FakeBluetoothAdapterClient::kAdapterPath),
  1054. dbus::ObjectPath(kVanishingDevicePath));
  1055. } else if (discovery_simulation_step_ == 7) {
  1056. CreateDevice(dbus::ObjectPath(FakeBluetoothAdapterClient::kAdapterPath),
  1057. dbus::ObjectPath(kConnectUnpairablePath));
  1058. UpdateDeviceRSSI(dbus::ObjectPath(kLowEnergyPath),
  1059. base::RandInt(kMinRSSI, kMaxRSSI));
  1060. } else if (discovery_simulation_step_ == 8) {
  1061. CreateDevice(dbus::ObjectPath(FakeBluetoothAdapterClient::kAdapterPath),
  1062. dbus::ObjectPath(kDisplayPasskeyPath));
  1063. if (delay_start_discovery_) {
  1064. CreateDevice(dbus::ObjectPath(FakeBluetoothAdapterClient::kAdapterPath),
  1065. dbus::ObjectPath(kRequestPinCodePath));
  1066. }
  1067. UpdateDeviceRSSI(dbus::ObjectPath(kLowEnergyPath),
  1068. base::RandInt(kMinRSSI, kMaxRSSI));
  1069. } else if (discovery_simulation_step_ == 10) {
  1070. CreateDevice(dbus::ObjectPath(FakeBluetoothAdapterClient::kAdapterPath),
  1071. dbus::ObjectPath(kConfirmPasskeyPath));
  1072. CreateDevice(dbus::ObjectPath(FakeBluetoothAdapterClient::kAdapterPath),
  1073. dbus::ObjectPath(kRequestPasskeyPath));
  1074. CreateDevice(dbus::ObjectPath(FakeBluetoothAdapterClient::kAdapterPath),
  1075. dbus::ObjectPath(kUnconnectableDevicePath));
  1076. CreateDevice(dbus::ObjectPath(FakeBluetoothAdapterClient::kAdapterPath),
  1077. dbus::ObjectPath(kUnpairableDevicePath));
  1078. CreateDevice(dbus::ObjectPath(FakeBluetoothAdapterClient::kAdapterPath),
  1079. dbus::ObjectPath(kJustWorksPath));
  1080. UpdateDeviceRSSI(dbus::ObjectPath(kLowEnergyPath),
  1081. base::RandInt(kMinRSSI, kMaxRSSI));
  1082. } else if (discovery_simulation_step_ == 13) {
  1083. UpdateDeviceRSSI(dbus::ObjectPath(kLowEnergyPath),
  1084. base::RandInt(kMinRSSI, kMaxRSSI));
  1085. RemoveDevice(dbus::ObjectPath(FakeBluetoothAdapterClient::kAdapterPath),
  1086. dbus::ObjectPath(kVanishingDevicePath));
  1087. } else if (discovery_simulation_step_ == 14) {
  1088. UpdateDeviceRSSI(dbus::ObjectPath(kLowEnergyPath),
  1089. base::RandInt(kMinRSSI, kMaxRSSI));
  1090. return;
  1091. }
  1092. ++discovery_simulation_step_;
  1093. base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
  1094. FROM_HERE,
  1095. base::BindOnce(&FakeBluetoothDeviceClient::DiscoverySimulationTimer,
  1096. base::Unretained(this)),
  1097. base::Milliseconds(simulation_interval_ms_));
  1098. }
  1099. void FakeBluetoothDeviceClient::IncomingPairingSimulationTimer() {
  1100. if (!incoming_pairing_simulation_step_)
  1101. return;
  1102. DVLOG(1) << "incoming pairing simulation, step "
  1103. << incoming_pairing_simulation_step_;
  1104. switch (incoming_pairing_simulation_step_) {
  1105. case 1:
  1106. CreateDevice(dbus::ObjectPath(FakeBluetoothAdapterClient::kAdapterPath),
  1107. dbus::ObjectPath(kConfirmPasskeyPath));
  1108. SimulatePairing(dbus::ObjectPath(kConfirmPasskeyPath), true,
  1109. base::DoNothing(), base::BindOnce(&SimpleErrorCallback));
  1110. break;
  1111. case 2:
  1112. CreateDevice(dbus::ObjectPath(FakeBluetoothAdapterClient::kAdapterPath),
  1113. dbus::ObjectPath(kJustWorksPath));
  1114. SimulatePairing(dbus::ObjectPath(kJustWorksPath), true, base::DoNothing(),
  1115. base::BindOnce(&SimpleErrorCallback));
  1116. break;
  1117. case 3:
  1118. CreateDevice(dbus::ObjectPath(FakeBluetoothAdapterClient::kAdapterPath),
  1119. dbus::ObjectPath(kDisplayPinCodePath));
  1120. SimulatePairing(dbus::ObjectPath(kDisplayPinCodePath), true,
  1121. base::DoNothing(), base::BindOnce(&SimpleErrorCallback));
  1122. break;
  1123. case 4:
  1124. CreateDevice(dbus::ObjectPath(FakeBluetoothAdapterClient::kAdapterPath),
  1125. dbus::ObjectPath(kDisplayPasskeyPath));
  1126. SimulatePairing(dbus::ObjectPath(kDisplayPasskeyPath), true,
  1127. base::DoNothing(), base::BindOnce(&SimpleErrorCallback));
  1128. break;
  1129. case 5:
  1130. CreateDevice(dbus::ObjectPath(FakeBluetoothAdapterClient::kAdapterPath),
  1131. dbus::ObjectPath(kRequestPinCodePath));
  1132. SimulatePairing(dbus::ObjectPath(kRequestPinCodePath), true,
  1133. base::DoNothing(), base::BindOnce(&SimpleErrorCallback));
  1134. break;
  1135. case 6:
  1136. CreateDevice(dbus::ObjectPath(FakeBluetoothAdapterClient::kAdapterPath),
  1137. dbus::ObjectPath(kRequestPasskeyPath));
  1138. SimulatePairing(dbus::ObjectPath(kRequestPasskeyPath), true,
  1139. base::DoNothing(), base::BindOnce(&SimpleErrorCallback));
  1140. break;
  1141. default:
  1142. return;
  1143. }
  1144. ++incoming_pairing_simulation_step_;
  1145. base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
  1146. FROM_HERE,
  1147. base::BindOnce(&FakeBluetoothDeviceClient::IncomingPairingSimulationTimer,
  1148. base::Unretained(this)),
  1149. base::Milliseconds(kIncomingSimulationPairTimeMultiplier *
  1150. simulation_interval_ms_));
  1151. }
  1152. void FakeBluetoothDeviceClient::SimulatePairing(
  1153. const dbus::ObjectPath& object_path,
  1154. bool incoming_request,
  1155. base::OnceClosure callback,
  1156. ErrorCallback error_callback) {
  1157. pairing_cancelled_ = false;
  1158. FakeBluetoothAgentManagerClient* fake_bluetooth_agent_manager_client =
  1159. static_cast<FakeBluetoothAgentManagerClient*>(
  1160. bluez::BluezDBusManager::Get()->GetBluetoothAgentManagerClient());
  1161. FakeBluetoothAgentServiceProvider* agent_service_provider =
  1162. fake_bluetooth_agent_manager_client->GetAgentServiceProvider();
  1163. CHECK(agent_service_provider != NULL);
  1164. // Grab the device's pairing properties.
  1165. PairingOptionsMap::const_iterator iter =
  1166. pairing_options_map_.find(object_path);
  1167. // If the device with path |object_path| has simulated pairing properties
  1168. // defined, then pair it based on its |pairing_method|.
  1169. if (iter != pairing_options_map_.end()) {
  1170. if (iter->second->pairing_action == kPairingActionFail) {
  1171. // Fails the pairing with an org.bluez.Error.Failed error.
  1172. base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
  1173. FROM_HERE,
  1174. base::BindOnce(&FakeBluetoothDeviceClient::FailSimulatedPairing,
  1175. base::Unretained(this), object_path,
  1176. std::move(error_callback)),
  1177. base::Milliseconds(simulation_interval_ms_));
  1178. } else if (iter->second->pairing_method == kPairingMethodNone ||
  1179. iter->second->pairing_method.empty()) {
  1180. if (!iter->second->incoming) {
  1181. // Simply pair and connect the device.
  1182. base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
  1183. FROM_HERE,
  1184. base::BindOnce(&FakeBluetoothDeviceClient::CompleteSimulatedPairing,
  1185. base::Unretained(this), object_path,
  1186. std::move(callback), std::move(error_callback)),
  1187. base::Milliseconds(kSimulateNormalPairTimeMultiplier *
  1188. simulation_interval_ms_));
  1189. } else {
  1190. agent_service_provider->RequestAuthorization(
  1191. object_path,
  1192. base::BindOnce(&FakeBluetoothDeviceClient::ConfirmationCallback,
  1193. base::Unretained(this), object_path,
  1194. std::move(callback), std::move(error_callback)));
  1195. }
  1196. } else if (iter->second->pairing_method == kPairingMethodPinCode) {
  1197. if (iter->second->pairing_action == kPairingActionDisplay) {
  1198. // Display a Pincode, and wait before acting as if the other end
  1199. // accepted it.
  1200. agent_service_provider->DisplayPinCode(
  1201. object_path, iter->second->pairing_auth_token);
  1202. base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
  1203. FROM_HERE,
  1204. base::BindOnce(&FakeBluetoothDeviceClient::CompleteSimulatedPairing,
  1205. base::Unretained(this), object_path,
  1206. std::move(callback), std::move(error_callback)),
  1207. base::Milliseconds(kPinCodeDevicePairTimeMultiplier *
  1208. simulation_interval_ms_));
  1209. } else if (iter->second->pairing_action == kPairingActionRequest) {
  1210. // Request a pin code.
  1211. agent_service_provider->RequestPinCode(
  1212. object_path,
  1213. base::BindOnce(&FakeBluetoothDeviceClient::PinCodeCallback,
  1214. base::Unretained(this), object_path,
  1215. std::move(callback), std::move(error_callback)));
  1216. } else if (iter->second->pairing_action == kPairingActionConfirmation) {
  1217. std::move(error_callback)
  1218. .Run(kNoResponseError, "No confirm for pincode pairing.");
  1219. }
  1220. } else if (iter->second->pairing_method == kPairingMethodPassKey) {
  1221. // Display a passkey, and each interval act as if another key was entered
  1222. // for it.
  1223. if (iter->second->pairing_action == kPairingActionDisplay) {
  1224. agent_service_provider->DisplayPasskey(
  1225. object_path, std::stoi(iter->second->pairing_auth_token), 0);
  1226. base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
  1227. FROM_HERE,
  1228. base::BindOnce(&FakeBluetoothDeviceClient::SimulateKeypress,
  1229. base::Unretained(this), 1, object_path,
  1230. std::move(callback), std::move(error_callback)),
  1231. base::Milliseconds(simulation_interval_ms_));
  1232. } else if (iter->second->pairing_action == kPairingActionRequest) {
  1233. agent_service_provider->RequestPasskey(
  1234. object_path,
  1235. base::BindOnce(&FakeBluetoothDeviceClient::PasskeyCallback,
  1236. base::Unretained(this), object_path,
  1237. std::move(callback), std::move(error_callback)));
  1238. } else if (iter->second->pairing_action == kPairingActionConfirmation) {
  1239. agent_service_provider->RequestConfirmation(
  1240. object_path, std::stoi(iter->second->pairing_auth_token),
  1241. base::BindOnce(&FakeBluetoothDeviceClient::ConfirmationCallback,
  1242. base::Unretained(this), object_path,
  1243. std::move(callback), std::move(error_callback)));
  1244. }
  1245. }
  1246. } else {
  1247. if (object_path == dbus::ObjectPath(kLegacyAutopairPath) ||
  1248. object_path == dbus::ObjectPath(kConnectUnpairablePath) ||
  1249. object_path == dbus::ObjectPath(kUnconnectableDevicePath) ||
  1250. object_path == dbus::ObjectPath(kLowEnergyPath)) {
  1251. // No need to call anything on the pairing delegate, just wait 3 times
  1252. // the interval before acting as if the other end accepted it.
  1253. base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
  1254. FROM_HERE,
  1255. base::BindOnce(&FakeBluetoothDeviceClient::CompleteSimulatedPairing,
  1256. base::Unretained(this), object_path,
  1257. std::move(callback), std::move(error_callback)),
  1258. base::Milliseconds(kSimulateNormalPairTimeMultiplier *
  1259. simulation_interval_ms_));
  1260. } else if (object_path == dbus::ObjectPath(kDisplayPinCodePath)) {
  1261. // Display a Pincode, and wait before acting as if the other end accepted
  1262. // it.
  1263. agent_service_provider->DisplayPinCode(object_path, kTestPinCode);
  1264. base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
  1265. FROM_HERE,
  1266. base::BindOnce(&FakeBluetoothDeviceClient::CompleteSimulatedPairing,
  1267. base::Unretained(this), object_path,
  1268. std::move(callback), std::move(error_callback)),
  1269. base::Milliseconds(kPinCodeDevicePairTimeMultiplier *
  1270. simulation_interval_ms_));
  1271. } else if (object_path == dbus::ObjectPath(kVanishingDevicePath)) {
  1272. // The vanishing device simulates being too far away, and thus times out.
  1273. base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
  1274. FROM_HERE,
  1275. base::BindOnce(&FakeBluetoothDeviceClient::TimeoutSimulatedPairing,
  1276. base::Unretained(this), object_path,
  1277. std::move(error_callback)),
  1278. base::Milliseconds(kVanishingDevicePairTimeMultiplier *
  1279. simulation_interval_ms_));
  1280. } else if (object_path == dbus::ObjectPath(kDisplayPasskeyPath)) {
  1281. // Display a passkey, and each interval act as if another key was entered
  1282. // for it.
  1283. agent_service_provider->DisplayPasskey(object_path, kTestPassKey, 0);
  1284. base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
  1285. FROM_HERE,
  1286. base::BindOnce(&FakeBluetoothDeviceClient::SimulateKeypress,
  1287. base::Unretained(this), 1, object_path,
  1288. std::move(callback), std::move(error_callback)),
  1289. base::Milliseconds(simulation_interval_ms_));
  1290. } else if (object_path == dbus::ObjectPath(kRequestPinCodePath)) {
  1291. // Request a Pincode.
  1292. agent_service_provider->RequestPinCode(
  1293. object_path,
  1294. base::BindOnce(&FakeBluetoothDeviceClient::PinCodeCallback,
  1295. base::Unretained(this), object_path,
  1296. std::move(callback), std::move(error_callback)));
  1297. } else if (object_path == dbus::ObjectPath(kConfirmPasskeyPath) ||
  1298. object_path ==
  1299. dbus::ObjectPath(kConnectedTrustedNotPairedDevicePath)) {
  1300. // Request confirmation of a Passkey.
  1301. agent_service_provider->RequestConfirmation(
  1302. object_path, kTestPassKey,
  1303. base::BindOnce(&FakeBluetoothDeviceClient::ConfirmationCallback,
  1304. base::Unretained(this), object_path,
  1305. std::move(callback), std::move(error_callback)));
  1306. } else if (object_path == dbus::ObjectPath(kRequestPasskeyPath)) {
  1307. // Request a Passkey from the user.
  1308. agent_service_provider->RequestPasskey(
  1309. object_path,
  1310. base::BindOnce(&FakeBluetoothDeviceClient::PasskeyCallback,
  1311. base::Unretained(this), object_path,
  1312. std::move(callback), std::move(error_callback)));
  1313. } else if (object_path == dbus::ObjectPath(kUnpairableDevicePath)) {
  1314. // Fails the pairing with an org.bluez.Error.Failed error.
  1315. base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
  1316. FROM_HERE,
  1317. base::BindOnce(&FakeBluetoothDeviceClient::FailSimulatedPairing,
  1318. base::Unretained(this), object_path,
  1319. std::move(error_callback)),
  1320. base::Milliseconds(simulation_interval_ms_));
  1321. } else if (object_path == dbus::ObjectPath(kJustWorksPath)) {
  1322. if (incoming_request) {
  1323. agent_service_provider->RequestAuthorization(
  1324. object_path,
  1325. base::BindOnce(&FakeBluetoothDeviceClient::ConfirmationCallback,
  1326. base::Unretained(this), object_path,
  1327. std::move(callback), std::move(error_callback)));
  1328. } else {
  1329. // No need to call anything on the pairing delegate, just wait before
  1330. // acting as if the other end accepted it.
  1331. base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
  1332. FROM_HERE,
  1333. base::BindOnce(&FakeBluetoothDeviceClient::CompleteSimulatedPairing,
  1334. base::Unretained(this), object_path,
  1335. std::move(callback), std::move(error_callback)),
  1336. base::Milliseconds(kSimulateNormalPairTimeMultiplier *
  1337. simulation_interval_ms_));
  1338. }
  1339. } else {
  1340. std::move(error_callback).Run(kNoResponseError, "No pairing fake");
  1341. }
  1342. }
  1343. }
  1344. void FakeBluetoothDeviceClient::CompleteSimulatedPairing(
  1345. const dbus::ObjectPath& object_path,
  1346. base::OnceClosure callback,
  1347. ErrorCallback error_callback) {
  1348. DVLOG(1) << "CompleteSimulatedPairing: " << object_path.value();
  1349. if (pairing_cancelled_) {
  1350. pairing_cancelled_ = false;
  1351. std::move(error_callback)
  1352. .Run(bluetooth_device::kErrorAuthenticationCanceled, "Cancelled");
  1353. } else {
  1354. Properties* properties = GetProperties(object_path);
  1355. properties->paired.ReplaceValue(true);
  1356. std::move(callback).Run();
  1357. AddInputDeviceIfNeeded(object_path, properties);
  1358. }
  1359. }
  1360. void FakeBluetoothDeviceClient::TimeoutSimulatedPairing(
  1361. const dbus::ObjectPath& object_path,
  1362. ErrorCallback error_callback) {
  1363. DVLOG(1) << "TimeoutSimulatedPairing: " << object_path.value();
  1364. std::move(error_callback)
  1365. .Run(bluetooth_device::kErrorAuthenticationTimeout, "Timed out");
  1366. }
  1367. void FakeBluetoothDeviceClient::CancelSimulatedPairing(
  1368. const dbus::ObjectPath& object_path,
  1369. ErrorCallback error_callback) {
  1370. DVLOG(1) << "CancelSimulatedPairing: " << object_path.value();
  1371. std::move(error_callback)
  1372. .Run(bluetooth_device::kErrorAuthenticationCanceled, "Canceled");
  1373. }
  1374. void FakeBluetoothDeviceClient::RejectSimulatedPairing(
  1375. const dbus::ObjectPath& object_path,
  1376. ErrorCallback error_callback) {
  1377. DVLOG(1) << "RejectSimulatedPairing: " << object_path.value();
  1378. std::move(error_callback)
  1379. .Run(bluetooth_device::kErrorAuthenticationRejected, "Rejected");
  1380. }
  1381. void FakeBluetoothDeviceClient::FailSimulatedPairing(
  1382. const dbus::ObjectPath& object_path,
  1383. ErrorCallback error_callback) {
  1384. DVLOG(1) << "FailSimulatedPairing: " << object_path.value();
  1385. std::move(error_callback).Run(bluetooth_device::kErrorFailed, "Failed");
  1386. }
  1387. void FakeBluetoothDeviceClient::AddInputDeviceIfNeeded(
  1388. const dbus::ObjectPath& object_path,
  1389. Properties* properties) {
  1390. // If the paired device is a HID device based on it's bluetooth class,
  1391. // simulate the Input interface.
  1392. FakeBluetoothInputClient* fake_bluetooth_input_client =
  1393. static_cast<FakeBluetoothInputClient*>(
  1394. bluez::BluezDBusManager::Get()->GetBluetoothInputClient());
  1395. if ((properties->bluetooth_class.value() & 0x001f03) == 0x000500)
  1396. fake_bluetooth_input_client->AddInputDevice(object_path);
  1397. }
  1398. void FakeBluetoothDeviceClient::InvalidateDeviceRSSI(
  1399. const dbus::ObjectPath& object_path) {
  1400. PropertiesMap::const_iterator iter = properties_map_.find(object_path);
  1401. if (iter == properties_map_.end()) {
  1402. DVLOG(2) << "Fake device does not exist: " << object_path.value();
  1403. return;
  1404. }
  1405. Properties* properties = iter->second.get();
  1406. DCHECK(properties);
  1407. // Invalidate the value and notify that it changed.
  1408. properties->rssi.set_valid(false);
  1409. properties->rssi.ReplaceValue(0);
  1410. }
  1411. void FakeBluetoothDeviceClient::UpdateDeviceRSSI(
  1412. const dbus::ObjectPath& object_path,
  1413. int16_t rssi) {
  1414. PropertiesMap::const_iterator iter = properties_map_.find(object_path);
  1415. if (iter == properties_map_.end()) {
  1416. DVLOG(2) << "Fake device does not exist: " << object_path.value();
  1417. return;
  1418. }
  1419. Properties* properties = iter->second.get();
  1420. DCHECK(properties);
  1421. properties->rssi.set_valid(true);
  1422. properties->rssi.ReplaceValue(rssi);
  1423. }
  1424. void FakeBluetoothDeviceClient::UpdateServiceAndManufacturerData(
  1425. const dbus::ObjectPath& object_path,
  1426. const std::vector<std::string>& service_uuids,
  1427. const std::map<std::string, std::vector<uint8_t>>& service_data,
  1428. const std::map<uint16_t, std::vector<uint8_t>>& manufacturer_data) {
  1429. PropertiesMap::const_iterator iter = properties_map_.find(object_path);
  1430. if (iter == properties_map_.end()) {
  1431. DVLOG(2) << "Fake device does not exist: " << object_path.value();
  1432. return;
  1433. }
  1434. Properties* properties = iter->second.get();
  1435. DCHECK(properties);
  1436. properties->uuids.set_valid(true);
  1437. properties->service_data.set_valid(true);
  1438. properties->manufacturer_data.set_valid(true);
  1439. // BlueZ caches all the previously received advertisements. To mimic BlueZ
  1440. // caching behavior, merge the new data here with the existing data.
  1441. // TODO(crbug.com/707039): once the BlueZ caching behavior is changed, this
  1442. // needs to be updated as well.
  1443. std::vector<std::string> merged_uuids = service_uuids;
  1444. merged_uuids.insert(merged_uuids.begin(), properties->uuids.value().begin(),
  1445. properties->uuids.value().end());
  1446. properties->uuids.ReplaceValue(merged_uuids);
  1447. std::map<std::string, std::vector<uint8_t>> merged_service_data =
  1448. service_data;
  1449. merged_service_data.insert(properties->service_data.value().begin(),
  1450. properties->service_data.value().end());
  1451. properties->service_data.ReplaceValue(merged_service_data);
  1452. std::map<uint16_t, std::vector<uint8_t>> merged_manufacturer_data =
  1453. manufacturer_data;
  1454. merged_manufacturer_data.insert(properties->manufacturer_data.value().begin(),
  1455. properties->manufacturer_data.value().end());
  1456. properties->manufacturer_data.ReplaceValue(merged_manufacturer_data);
  1457. }
  1458. void FakeBluetoothDeviceClient::UpdateEIR(const dbus::ObjectPath& object_path,
  1459. const std::vector<uint8_t>& eir) {
  1460. PropertiesMap::const_iterator iter = properties_map_.find(object_path);
  1461. if (iter == properties_map_.end()) {
  1462. DVLOG(2) << "Fake device does not exist: " << object_path.value();
  1463. return;
  1464. }
  1465. Properties* properties = iter->second.get();
  1466. DCHECK(properties);
  1467. properties->eir.set_valid(true);
  1468. properties->eir.ReplaceValue(eir);
  1469. }
  1470. void FakeBluetoothDeviceClient::UpdateConnectionInfo(
  1471. uint16_t connection_rssi,
  1472. uint16_t transmit_power,
  1473. uint16_t max_transmit_power) {
  1474. connection_rssi_ = connection_rssi;
  1475. transmit_power_ = transmit_power;
  1476. max_transmit_power_ = max_transmit_power;
  1477. }
  1478. void FakeBluetoothDeviceClient::PinCodeCallback(
  1479. const dbus::ObjectPath& object_path,
  1480. base::OnceClosure callback,
  1481. ErrorCallback error_callback,
  1482. BluetoothAgentServiceProvider::Delegate::Status status,
  1483. const std::string& pincode) {
  1484. DVLOG(1) << "PinCodeCallback: " << object_path.value();
  1485. if (status == BluetoothAgentServiceProvider::Delegate::SUCCESS) {
  1486. PairingOptionsMap::const_iterator iter =
  1487. pairing_options_map_.find(object_path);
  1488. bool success = true;
  1489. // If the device has pairing options defined
  1490. if (iter != pairing_options_map_.end()) {
  1491. success = iter->second->pairing_auth_token == pincode;
  1492. }
  1493. if (success) {
  1494. base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
  1495. FROM_HERE,
  1496. base::BindOnce(&FakeBluetoothDeviceClient::CompleteSimulatedPairing,
  1497. base::Unretained(this), object_path,
  1498. std::move(callback), std::move(error_callback)),
  1499. base::Milliseconds(kSimulateNormalPairTimeMultiplier *
  1500. simulation_interval_ms_));
  1501. } else {
  1502. base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
  1503. FROM_HERE,
  1504. base::BindOnce(&FakeBluetoothDeviceClient::RejectSimulatedPairing,
  1505. base::Unretained(this), object_path,
  1506. std::move(error_callback)),
  1507. base::Milliseconds(simulation_interval_ms_));
  1508. }
  1509. } else if (status == BluetoothAgentServiceProvider::Delegate::CANCELLED) {
  1510. base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
  1511. FROM_HERE,
  1512. base::BindOnce(&FakeBluetoothDeviceClient::CancelSimulatedPairing,
  1513. base::Unretained(this), object_path,
  1514. std::move(error_callback)),
  1515. base::Milliseconds(simulation_interval_ms_));
  1516. } else if (status == BluetoothAgentServiceProvider::Delegate::REJECTED) {
  1517. base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
  1518. FROM_HERE,
  1519. base::BindOnce(&FakeBluetoothDeviceClient::RejectSimulatedPairing,
  1520. base::Unretained(this), object_path,
  1521. std::move(error_callback)),
  1522. base::Milliseconds(simulation_interval_ms_));
  1523. }
  1524. }
  1525. void FakeBluetoothDeviceClient::PasskeyCallback(
  1526. const dbus::ObjectPath& object_path,
  1527. base::OnceClosure callback,
  1528. ErrorCallback error_callback,
  1529. BluetoothAgentServiceProvider::Delegate::Status status,
  1530. uint32_t passkey) {
  1531. DVLOG(1) << "PasskeyCallback: " << object_path.value();
  1532. if (status == BluetoothAgentServiceProvider::Delegate::SUCCESS) {
  1533. PairingOptionsMap::const_iterator iter =
  1534. pairing_options_map_.find(object_path);
  1535. bool success = true;
  1536. if (iter != pairing_options_map_.end()) {
  1537. success = static_cast<uint32_t>(
  1538. std::stoi(iter->second->pairing_auth_token)) == passkey;
  1539. }
  1540. if (success) {
  1541. base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
  1542. FROM_HERE,
  1543. base::BindOnce(&FakeBluetoothDeviceClient::CompleteSimulatedPairing,
  1544. base::Unretained(this), object_path,
  1545. std::move(callback), std::move(error_callback)),
  1546. base::Milliseconds(kSimulateNormalPairTimeMultiplier *
  1547. simulation_interval_ms_));
  1548. } else {
  1549. base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
  1550. FROM_HERE,
  1551. base::BindOnce(&FakeBluetoothDeviceClient::RejectSimulatedPairing,
  1552. base::Unretained(this), object_path,
  1553. std::move(error_callback)),
  1554. base::Milliseconds(simulation_interval_ms_));
  1555. }
  1556. } else if (status == BluetoothAgentServiceProvider::Delegate::CANCELLED) {
  1557. base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
  1558. FROM_HERE,
  1559. base::BindOnce(&FakeBluetoothDeviceClient::CancelSimulatedPairing,
  1560. base::Unretained(this), object_path,
  1561. std::move(error_callback)),
  1562. base::Milliseconds(simulation_interval_ms_));
  1563. } else if (status == BluetoothAgentServiceProvider::Delegate::REJECTED) {
  1564. base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
  1565. FROM_HERE,
  1566. base::BindOnce(&FakeBluetoothDeviceClient::RejectSimulatedPairing,
  1567. base::Unretained(this), object_path,
  1568. std::move(error_callback)),
  1569. base::Milliseconds(simulation_interval_ms_));
  1570. }
  1571. }
  1572. void FakeBluetoothDeviceClient::ConfirmationCallback(
  1573. const dbus::ObjectPath& object_path,
  1574. base::OnceClosure callback,
  1575. ErrorCallback error_callback,
  1576. BluetoothAgentServiceProvider::Delegate::Status status) {
  1577. DVLOG(1) << "ConfirmationCallback: " << object_path.value();
  1578. if (status == BluetoothAgentServiceProvider::Delegate::SUCCESS) {
  1579. base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
  1580. FROM_HERE,
  1581. base::BindOnce(&FakeBluetoothDeviceClient::CompleteSimulatedPairing,
  1582. base::Unretained(this), object_path, std::move(callback),
  1583. std::move(error_callback)),
  1584. base::Milliseconds(kSimulateNormalPairTimeMultiplier *
  1585. simulation_interval_ms_));
  1586. } else if (status == BluetoothAgentServiceProvider::Delegate::CANCELLED) {
  1587. base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
  1588. FROM_HERE,
  1589. base::BindOnce(&FakeBluetoothDeviceClient::CancelSimulatedPairing,
  1590. base::Unretained(this), object_path,
  1591. std::move(error_callback)),
  1592. base::Milliseconds(simulation_interval_ms_));
  1593. } else if (status == BluetoothAgentServiceProvider::Delegate::REJECTED) {
  1594. base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
  1595. FROM_HERE,
  1596. base::BindOnce(&FakeBluetoothDeviceClient::RejectSimulatedPairing,
  1597. base::Unretained(this), object_path,
  1598. std::move(error_callback)),
  1599. base::Milliseconds(simulation_interval_ms_));
  1600. }
  1601. }
  1602. void FakeBluetoothDeviceClient::SimulateKeypress(
  1603. uint16_t entered,
  1604. const dbus::ObjectPath& object_path,
  1605. base::OnceClosure callback,
  1606. ErrorCallback error_callback) {
  1607. DVLOG(1) << "SimulateKeypress " << entered << ": " << object_path.value();
  1608. FakeBluetoothAgentManagerClient* fake_bluetooth_agent_manager_client =
  1609. static_cast<FakeBluetoothAgentManagerClient*>(
  1610. bluez::BluezDBusManager::Get()->GetBluetoothAgentManagerClient());
  1611. FakeBluetoothAgentServiceProvider* agent_service_provider =
  1612. fake_bluetooth_agent_manager_client->GetAgentServiceProvider();
  1613. // The agent service provider object could have been destroyed after the
  1614. // pairing is canceled.
  1615. if (!agent_service_provider)
  1616. return;
  1617. agent_service_provider->DisplayPasskey(object_path, kTestPassKey, entered);
  1618. if (entered < 7) {
  1619. base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
  1620. FROM_HERE,
  1621. base::BindOnce(&FakeBluetoothDeviceClient::SimulateKeypress,
  1622. base::Unretained(this), entered + 1, object_path,
  1623. std::move(callback), std::move(error_callback)),
  1624. base::Milliseconds(simulation_interval_ms_));
  1625. } else {
  1626. base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
  1627. FROM_HERE,
  1628. base::BindOnce(&FakeBluetoothDeviceClient::CompleteSimulatedPairing,
  1629. base::Unretained(this), object_path, std::move(callback),
  1630. std::move(error_callback)),
  1631. base::Milliseconds(simulation_interval_ms_));
  1632. }
  1633. }
  1634. void FakeBluetoothDeviceClient::ConnectionCallback(
  1635. const dbus::ObjectPath& object_path,
  1636. base::OnceClosure callback,
  1637. ErrorCallback error_callback,
  1638. BluetoothProfileServiceProvider::Delegate::Status status) {
  1639. DVLOG(1) << "ConnectionCallback: " << object_path.value();
  1640. if (status == BluetoothProfileServiceProvider::Delegate::SUCCESS) {
  1641. std::move(callback).Run();
  1642. } else if (status == BluetoothProfileServiceProvider::Delegate::CANCELLED) {
  1643. // TODO(keybuk): tear down this side of the connection
  1644. std::move(error_callback).Run(bluetooth_device::kErrorFailed, "Canceled");
  1645. } else if (status == BluetoothProfileServiceProvider::Delegate::REJECTED) {
  1646. // TODO(keybuk): tear down this side of the connection
  1647. std::move(error_callback).Run(bluetooth_device::kErrorFailed, "Rejected");
  1648. }
  1649. }
  1650. void FakeBluetoothDeviceClient::DisconnectionCallback(
  1651. const dbus::ObjectPath& object_path,
  1652. base::OnceClosure callback,
  1653. ErrorCallback error_callback,
  1654. BluetoothProfileServiceProvider::Delegate::Status status) {
  1655. DVLOG(1) << "DisconnectionCallback: " << object_path.value();
  1656. if (status == BluetoothProfileServiceProvider::Delegate::SUCCESS) {
  1657. // TODO(keybuk): tear down this side of the connection
  1658. std::move(callback).Run();
  1659. } else if (status == BluetoothProfileServiceProvider::Delegate::CANCELLED) {
  1660. std::move(error_callback).Run(bluetooth_device::kErrorFailed, "Canceled");
  1661. } else if (status == BluetoothProfileServiceProvider::Delegate::REJECTED) {
  1662. std::move(error_callback).Run(bluetooth_device::kErrorFailed, "Rejected");
  1663. }
  1664. }
  1665. void FakeBluetoothDeviceClient::RemoveAllDevices() {
  1666. device_list_.clear();
  1667. }
  1668. void FakeBluetoothDeviceClient::CreateTestDevice(
  1669. const dbus::ObjectPath& adapter_path,
  1670. const absl::optional<std::string> name,
  1671. const std::string alias,
  1672. const std::string device_address,
  1673. const std::vector<std::string>& service_uuids,
  1674. device::BluetoothTransport type,
  1675. const std::map<std::string, std::vector<uint8_t>>& service_data,
  1676. const std::map<uint16_t, std::vector<uint8_t>>& manufacturer_data) {
  1677. // Create a random device path.
  1678. dbus::ObjectPath device_path;
  1679. std::string id;
  1680. do {
  1681. // Construct an id that is valid according to the DBUS specification.
  1682. base::Base64Encode(base::RandBytesAsString(10), &id);
  1683. base::RemoveChars(id, "+/=", &id);
  1684. device_path = dbus::ObjectPath(adapter_path.value() + "/dev" + id);
  1685. } while (base::Contains(device_list_, device_path));
  1686. std::unique_ptr<Properties> properties(new Properties(
  1687. base::BindRepeating(&FakeBluetoothDeviceClient::OnPropertyChanged,
  1688. base::Unretained(this), device_path)));
  1689. properties->adapter.ReplaceValue(adapter_path);
  1690. properties->address.ReplaceValue(device_address);
  1691. properties->name.ReplaceValue(
  1692. name.value_or("Invalid Device Name set in "
  1693. "FakeBluetoothDeviceClient::CreateTestDevice"));
  1694. properties->name.set_valid(name.has_value());
  1695. properties->alias.ReplaceValue(alias);
  1696. properties->uuids.ReplaceValue(service_uuids);
  1697. properties->bluetooth_class.ReplaceValue(
  1698. 0x1F00u); // Unspecified Device Class
  1699. switch (type) {
  1700. case device::BLUETOOTH_TRANSPORT_CLASSIC:
  1701. properties->type.ReplaceValue(BluetoothDeviceClient::kTypeBredr);
  1702. break;
  1703. case device::BLUETOOTH_TRANSPORT_LE:
  1704. properties->type.ReplaceValue(BluetoothDeviceClient::kTypeLe);
  1705. break;
  1706. case device::BLUETOOTH_TRANSPORT_DUAL:
  1707. properties->type.ReplaceValue(BluetoothDeviceClient::kTypeDual);
  1708. break;
  1709. default:
  1710. NOTREACHED();
  1711. }
  1712. properties->type.set_valid(true);
  1713. if (!service_data.empty()) {
  1714. properties->service_data.ReplaceValue(service_data);
  1715. properties->service_data.set_valid(true);
  1716. }
  1717. if (!manufacturer_data.empty()) {
  1718. properties->manufacturer_data.ReplaceValue(manufacturer_data);
  1719. properties->manufacturer_data.set_valid(true);
  1720. }
  1721. properties_map_.insert(std::make_pair(device_path, std::move(properties)));
  1722. device_list_.push_back(device_path);
  1723. for (auto& observer : observers_)
  1724. observer.DeviceAdded(device_path);
  1725. }
  1726. void FakeBluetoothDeviceClient::AddPrepareWriteRequest(
  1727. const dbus::ObjectPath& object_path,
  1728. const std::vector<uint8_t>& value) {
  1729. prepare_write_requests_.emplace_back(object_path, value);
  1730. }
  1731. } // namespace bluez