summaryrefslogtreecommitdiffstats
path: root/testing/web-platform/tests/bluetooth/resources/bluetooth-fake-devices.js
blob: b718ab579a1822e08d7f9026ceb519eccabca39f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
'use strict';

/* Bluetooth Constants */

/**
 * HCI Error Codes.
 * Used for simulateGATT{Dis}ConnectionResponse. For a complete list of
 * possible error codes see BT 4.2 Vol 2 Part D 1.3 List Of Error Codes.
 */
const HCI_SUCCESS = 0x0000;
const HCI_CONNECTION_TIMEOUT = 0x0008;

/**
 * GATT Error codes.
 * Used for GATT operations responses. BT 4.2 Vol 3 Part F 3.4.1.1 Error
 * Response
 */
const GATT_SUCCESS = 0x0000;
const GATT_INVALID_HANDLE = 0x0001;

/* Bluetooth UUID Constants */

/* Service UUIDs */
var blocklist_test_service_uuid = '611c954a-263b-4f4a-aab6-01ddb953f985';
var request_disconnection_service_uuid = '01d7d889-7451-419f-aeb8-d65e7b9277af';

/* Characteristic UUIDs */
var blocklist_exclude_reads_characteristic_uuid =
    'bad1c9a2-9a5b-4015-8b60-1579bbbf2135';
var request_disconnection_characteristic_uuid =
    '01d7d88a-7451-419f-aeb8-d65e7b9277af';

/* Descriptor UUIDs */
var blocklist_test_descriptor_uuid = 'bad2ddcf-60db-45cd-bef9-fd72b153cf7c';
var blocklist_exclude_reads_descriptor_uuid =
    'bad3ec61-3cc3-4954-9702-7977df514114';

/**
 * Helper objects that associate Bluetooth names, aliases, and UUIDs. These are
 * useful for tests that check that the same result is produces when using all
 * three methods of referring to a Bluetooth UUID.
 */
var generic_access = {
  alias: 0x1800,
  name: 'generic_access',
  uuid: '00001800-0000-1000-8000-00805f9b34fb'
};
var device_name = {
  alias: 0x2a00,
  name: 'gap.device_name',
  uuid: '00002a00-0000-1000-8000-00805f9b34fb'
};
var reconnection_address = {
  alias: 0x2a03,
  name: 'gap.reconnection_address',
  uuid: '00002a03-0000-1000-8000-00805f9b34fb'
};
var heart_rate = {
  alias: 0x180d,
  name: 'heart_rate',
  uuid: '0000180d-0000-1000-8000-00805f9b34fb'
};
var health_thermometer = {
  alias: 0x1809,
  name: 'health_thermometer',
  uuid: '00001809-0000-1000-8000-00805f9b34fb'
};
var body_sensor_location = {
  alias: 0x2a38,
  name: 'body_sensor_location',
  uuid: '00002a38-0000-1000-8000-00805f9b34fb'
};
var glucose = {
  alias: 0x1808,
  name: 'glucose',
  uuid: '00001808-0000-1000-8000-00805f9b34fb'
};
var battery_service = {
  alias: 0x180f,
  name: 'battery_service',
  uuid: '0000180f-0000-1000-8000-00805f9b34fb'
};
var battery_level = {
  alias: 0x2A19,
  name: 'battery_level',
  uuid: '00002a19-0000-1000-8000-00805f9b34fb'
};
var user_description = {
  alias: 0x2901,
  name: 'gatt.characteristic_user_description',
  uuid: '00002901-0000-1000-8000-00805f9b34fb'
};
var client_characteristic_configuration = {
  alias: 0x2902,
  name: 'gatt.client_characteristic_configuration',
  uuid: '00002902-0000-1000-8000-00805f9b34fb'
};
var measurement_interval = {
  alias: 0x2a21,
  name: 'measurement_interval',
  uuid: '00002a21-0000-1000-8000-00805f9b34fb'
};

/**
 * An advertisement packet object that simulates a Health Thermometer device.
 * @type {ScanResult}
 */
const health_thermometer_ad_packet = {
  deviceAddress: '09:09:09:09:09:09',
  rssi: -10,
  scanRecord: {
    name: 'Health Thermometer',
    uuids: [health_thermometer.uuid],
  },
};

/**
 * An advertisement packet object that simulates a Heart Rate device.
 * @type {ScanResult}
 */
const heart_rate_ad_packet = {
  deviceAddress: '08:08:08:08:08:08',
  rssi: -10,
  scanRecord: {
    name: 'Heart Rate',
    uuids: [heart_rate.uuid],
  },
};

const uuid1234 = BluetoothUUID.getService(0x1234);
const uuid5678 = BluetoothUUID.getService(0x5678);
const uuidABCD = BluetoothUUID.getService(0xABCD);
const manufacturer1Data = new Uint8Array([1, 2]);
const manufacturer2Data = new Uint8Array([3, 4]);
const uuid1234Data = new Uint8Array([5, 6]);
const uuid5678Data = new Uint8Array([7, 8]);
const uuidABCDData = new Uint8Array([9, 10]);

// TODO(crbug.com/1163207): Add the blocklist link.
// Fake manufacturer data following iBeacon format listed in
// https://en.wikipedia.org/wiki/IBeacon, which will be blocked according to [TBD blocklist link].
const blocklistedManufacturerId = 0x4c;
const blocklistedManufacturerData = new Uint8Array([
  0x02, 0x15, 0xb3, 0xeb, 0x8d, 0xb1, 0x30, 0xa5, 0x44, 0x8d, 0xb4, 0xac,
  0xfb, 0x68, 0xc9, 0x23, 0xa3, 0x0e, 0x00, 0x00, 0x00, 0x00, 0xbf
]);
// Fake manufacturer data that is not in [TBD blocklist link].
const nonBlocklistedManufacturerId = 0x0001;
const nonBlocklistedManufacturerData =  new Uint8Array([1, 2]);

/**
 * An advertisement packet object that simulates a device that advertises
 * service and manufacturer data.
 * @type {ScanResult}
 */
const service_and_manufacturer_data_ad_packet = {
  deviceAddress: '07:07:07:07:07:07',
  rssi: -10,
  scanRecord: {
    name: 'LE Device',
    uuids: [uuid1234],
    manufacturerData: {0x0001: manufacturer1Data, 0x0002: manufacturer2Data},
    serviceData: {
      [uuid1234]: uuid1234Data,
      [uuid5678]: uuid5678Data,
      [uuidABCD]: uuidABCDData
    }
  }
};

/** Bluetooth Helpers */

/**
 * Helper class to create a BluetoothCharacteristicProperties object using an
 * array of strings corresponding to the property bit to set.
 */
class TestCharacteristicProperties {
  /** @param {Array<string>} properties */
  constructor(properties) {
    this.broadcast = false;
    this.read = false;
    this.writeWithoutResponse = false;
    this.write = false;
    this.notify = false;
    this.indicate = false;
    this.authenticatedSignedWrites = false;
    this.reliableWrite = false;
    this.writableAuxiliaries = false;

    properties.forEach(val => {
      if (this.hasOwnProperty(val))
        this[val] = true;
      else
        throw `Invalid member '${val}'`;
    });
  }
}

/**
 * Produces an array of BluetoothLEScanFilterInit objects containing the list of
 * services in |services| and various permutations of the other
 * BluetoothLEScanFilterInit properties. This method is used to test that the
 * |services| are valid so the other properties do not matter.
 * @param {BluetoothServiceUUID} services
 * @returns {Array<RequestDeviceOptions>} A list of options containing
 *     |services| and various permutations of other options.
 */
function generateRequestDeviceArgsWithServices(services = ['heart_rate']) {
  return [
    {filters: [{services: services}]},
    {filters: [{services: services, name: 'Name'}]},
    {filters: [{services: services, namePrefix: 'Pre'}]}, {
      filters: [
        {services: services, manufacturerData: [{companyIdentifier: 0x0001}]}
      ]
    },
    {
      filters: [{
        services: services,
        name: 'Name',
        namePrefix: 'Pre',
        manufacturerData: [{companyIdentifier: 0x0001}]
      }]
    },
    {filters: [{services: services}], optionalServices: ['heart_rate']}, {
      filters: [{services: services, name: 'Name'}],
      optionalServices: ['heart_rate']
    },
    {
      filters: [{services: services, namePrefix: 'Pre'}],
      optionalServices: ['heart_rate']
    },
    {
      filters: [
        {services: services, manufacturerData: [{companyIdentifier: 0x0001}]}
      ],
      optionalServices: ['heart_rate']
    },
    {
      filters: [{
        services: services,
        name: 'Name',
        namePrefix: 'Pre',
        manufacturerData: [{companyIdentifier: 0x0001}]
      }],
      optionalServices: ['heart_rate']
    }
  ];
}

/**
 * Causes |fake_peripheral| to disconnect and returns a promise that resolves
 * once `gattserverdisconnected` has been fired on |device|.
 * @param {BluetoothDevice} device The device to check if the
 *     `gattserverdisconnected` promise was fired.
 * @param {FakePeripheral} fake_peripheral The device fake that represents
 *     |device|.
 * @returns {Promise<Array<Object>>} A promise that resolves when the device has
 *     successfully disconnected.
 */
function simulateGATTDisconnectionAndWait(device, fake_peripheral) {
  return Promise.all([
    eventPromise(device, 'gattserverdisconnected'),
    fake_peripheral.simulateGATTDisconnection(),
  ]);
}

/** @type {FakeCentral} The fake adapter for the current test. */
let fake_central = null;

async function initializeFakeCentral({state = 'powered-on'}) {
  if (!fake_central) {
    fake_central = await navigator.bluetooth.test.simulateCentral({state});
  }
}

/**
 * A dictionary for specifying fake Bluetooth device setup options.
 * @typedef {{address: !string, name: !string,
 *            manufacturerData: !Object<uint16,Array<uint8>>,
 *            knownServiceUUIDs: !Array<string>, connectable: !boolean,
 *            serviceDiscoveryComplete: !boolean}}
 */
let FakeDeviceOptions;

/**
 * @typedef {{fakeDeviceOptions: FakeDeviceOptions,
 *            requestDeviceOptions: RequestDeviceOptions}}
 */
let SetupOptions;

/**
 * Default options for setting up a Bluetooth device.
 * @type {FakeDeviceOptions}
 */
const fakeDeviceOptionsDefault = {
  address: '00:00:00:00:00:00',
  name: 'LE Device',
  manufacturerData: {},
  knownServiceUUIDs: [],
  connectable: false,
  serviceDiscoveryComplete: false,
};

/**
 * A dictionary containing the fake Bluetooth device object. The dictionary can
 * optionally contain its fake services and its BluetoothDevice counterpart.
 * @typedef {{fake_peripheral: !FakePeripheral,
 *            fake_services: Object<string, FakeService>,
 *            device: BluetoothDevice}}
 */
let FakeDevice;

/**
 * Creates a SetupOptions object using |setupOptionsDefault| as the base options
 * object with the options from |setupOptionsOverride| overriding these
 * defaults.
 * @param {SetupOptions} setupOptionsDefault The default options object to use
 *     as the base.
 * @param {SetupOptions} setupOptionsOverride The options to override the
 *     defaults with.
 * @returns {SetupOptions} The merged setup options containing the defaults with
 *     the overrides applied.
 */
function createSetupOptions(setupOptionsDefault, setupOptionsOverride) {
  // Merge the properties of |setupOptionsDefault| and |setupOptionsOverride|
  // without modifying |setupOptionsDefault|.
  let fakeDeviceOptions = Object.assign(
      {...setupOptionsDefault.fakeDeviceOptions},
      setupOptionsOverride.fakeDeviceOptions);
  let requestDeviceOptions = Object.assign(
      {...setupOptionsDefault.requestDeviceOptions},
      setupOptionsOverride.requestDeviceOptions);

  return {fakeDeviceOptions, requestDeviceOptions};
}

/**
 * Adds a preconnected device with the given options. A preconnected device is a
 * device that has been paired with the system previously. This can be done if,
 * for example, the user pairs the device using the OS'es settings.
 *
 * By default, the preconnected device will be set up using the
 * |fakeDeviceOptionsDefault| and will not use a RequestDeviceOption object.
 * This means that the device will not be requested during the setup.
 *
 * If |setupOptionsOverride| is provided, these options will override the
 * defaults. If |setupOptionsOverride| includes the requestDeviceOptions
 * property, then the device will be requested using those options.
 * @param {SetupOptions} setupOptionsOverride An object containing options for
 *     setting up a fake Bluetooth device and for requesting the device.
 * @returns {Promise<FakeDevice>} The device fake initialized with the
 *     parameter values.
 */
async function setUpPreconnectedFakeDevice(setupOptionsOverride) {
  await initializeFakeCentral({state: 'powered-on'});

  let setupOptions = createSetupOptions(
      {fakeDeviceOptions: fakeDeviceOptionsDefault}, setupOptionsOverride);

  // Simulate the fake peripheral.
  let preconnectedDevice = {};
  preconnectedDevice.fake_peripheral =
      await fake_central.simulatePreconnectedPeripheral({
        address: setupOptions.fakeDeviceOptions.address,
        name: setupOptions.fakeDeviceOptions.name,
        manufacturerData: setupOptions.fakeDeviceOptions.manufacturerData,
        knownServiceUUIDs: setupOptions.fakeDeviceOptions.knownServiceUUIDs,
      });

  if (setupOptions.fakeDeviceOptions.connectable) {
    await preconnectedDevice.fake_peripheral.setNextGATTConnectionResponse(
        {code: HCI_SUCCESS});
  }

  // Add known services.
  preconnectedDevice.fake_services = new Map();
  for (let service of setupOptions.fakeDeviceOptions.knownServiceUUIDs) {
    let fake_service = await preconnectedDevice.fake_peripheral.addFakeService(
        {uuid: service});
    preconnectedDevice.fake_services.set(service, fake_service);
  }

  // Request the device if the request option isn't empty.
  if (Object.keys(setupOptions.requestDeviceOptions).length !== 0) {
    preconnectedDevice.device =
        await requestDeviceWithTrustedClick(setupOptions.requestDeviceOptions);
  }

  // Set up services discovered state.
  if (setupOptions.fakeDeviceOptions.serviceDiscoveryComplete) {
    await preconnectedDevice.fake_peripheral.setNextGATTDiscoveryResponse(
        {code: HCI_SUCCESS});
  }

  return preconnectedDevice;
}

/** Blocklisted GATT Device Helper Methods */

/** @type {FakeDeviceOptions} */
const blocklistFakeDeviceOptionsDefault = {
  address: '11:11:11:11:11:11',
  name: 'Blocklist Device',
  knownServiceUUIDs: ['generic_access', blocklist_test_service_uuid],
  connectable: true,
  serviceDiscoveryComplete: true
};

/** @type {RequestDeviceOptions} */
const blocklistRequestDeviceOptionsDefault = {
  filters: [{services: [blocklist_test_service_uuid]}]
};

/** @type {SetupOptions} */
const blocklistSetupOptionsDefault = {
  fakeDeviceOptions: blocklistFakeDeviceOptionsDefault,
  requestDeviceOptions: blocklistRequestDeviceOptionsDefault
};

/**
 * Returns an object containing a BluetoothDevice discovered using |options|,
 * its corresponding FakePeripheral and FakeRemoteGATTServices.
 * The simulated device is called 'Blocklist Device' and it has one known
 * service UUID |blocklist_test_service_uuid|. The |blocklist_test_service_uuid|
 * service contains two characteristics:
 *   - |blocklist_exclude_reads_characteristic_uuid| (read, write)
 *   - 'gap.peripheral_privacy_flag' (read, write)
 * The 'gap.peripheral_privacy_flag' characteristic contains three descriptors:
 *   - |blocklist_test_descriptor_uuid|
 *   - |blocklist_exclude_reads_descriptor_uuid|
 *   - 'gatt.client_characteristic_configuration'
 * These are special UUIDs that have been added to the blocklist found at
 * https://github.com/WebBluetoothCG/registries/blob/master/gatt_blocklist.txt
 * There are also test UUIDs that have been added to the test environment which
 * other implementations should add as test UUIDs as well.
 * The device has been connected to and its attributes are ready to be
 * discovered.
 * @returns {Promise<{device: BluetoothDevice, fake_peripheral: FakePeripheral,
 *     fake_blocklist_test_service: FakeRemoteGATTService,
 *     fake_blocklist_exclude_reads_characteristic:
 *         FakeRemoteGATTCharacteristic,
 *     fake_blocklist_exclude_writes_characteristic:
 *         FakeRemoteGATTCharacteristic,
 *     fake_blocklist_descriptor: FakeRemoteGATTDescriptor,
 *     fake_blocklist_exclude_reads_descriptor: FakeRemoteGATTDescriptor,
 *     fake_blocklist_exclude_writes_descriptor: FakeRemoteGATTDescriptor}>} An
 *         object containing the BluetoothDevice object and its corresponding
 *         GATT fake objects.
 */
async function getBlocklistDevice(setupOptionsOverride = {}) {
  let setupOptions =
      createSetupOptions(blocklistSetupOptionsDefault, setupOptionsOverride);
  let fakeDevice = await setUpPreconnectedFakeDevice(setupOptions);
  await fakeDevice.device.gatt.connect();

  let fake_blocklist_test_service =
      fakeDevice.fake_services.get(blocklist_test_service_uuid);

  let fake_blocklist_exclude_reads_characteristic =
      await fake_blocklist_test_service.addFakeCharacteristic({
        uuid: blocklist_exclude_reads_characteristic_uuid,
        properties: ['read', 'write'],
      });
  let fake_blocklist_exclude_writes_characteristic =
      await fake_blocklist_test_service.addFakeCharacteristic({
        uuid: 'gap.peripheral_privacy_flag',
        properties: ['read', 'write'],
      });

  let fake_blocklist_descriptor =
      await fake_blocklist_exclude_writes_characteristic.addFakeDescriptor(
          {uuid: blocklist_test_descriptor_uuid});
  let fake_blocklist_exclude_reads_descriptor =
      await fake_blocklist_exclude_writes_characteristic.addFakeDescriptor(
          {uuid: blocklist_exclude_reads_descriptor_uuid});
  let fake_blocklist_exclude_writes_descriptor =
      await fake_blocklist_exclude_writes_characteristic.addFakeDescriptor(
          {uuid: 'gatt.client_characteristic_configuration'});
  return {
    device: fakeDevice.device,
    fake_peripheral: fakeDevice.fake_peripheral,
    fake_blocklist_test_service,
    fake_blocklist_exclude_reads_characteristic,
    fake_blocklist_exclude_writes_characteristic,
    fake_blocklist_descriptor,
    fake_blocklist_exclude_reads_descriptor,
    fake_blocklist_exclude_writes_descriptor,
  };
}

/**
 * Returns an object containing a Blocklist Test BluetoothRemoteGattService and
 * its corresponding FakeRemoteGATTService.
 * @returns {Promise<{device: BluetoothDevice, fake_peripheral: FakePeripheral,
 *     fake_blocklist_test_service: FakeRemoteGATTService,
 *     fake_blocklist_exclude_reads_characteristic:
 *         FakeRemoteGATTCharacteristic,
 *     fake_blocklist_exclude_writes_characteristic:
 *         FakeRemoteGATTCharacteristic,
 *     fake_blocklist_descriptor: FakeRemoteGATTDescriptor,
 *     fake_blocklist_exclude_reads_descriptor: FakeRemoteGATTDescriptor,
 *     fake_blocklist_exclude_writes_descriptor: FakeRemoteGATTDescriptor,
 *     service: BluetoothRemoteGATTService,
 *     fake_service: FakeBluetoothRemoteGATTService}>} An object containing the
 *         BluetoothDevice object and its corresponding GATT fake objects.
 */
async function getBlocklistTestService() {
  let result = await getBlocklistDevice();
  let service =
      await result.device.gatt.getPrimaryService(blocklist_test_service_uuid);
  return Object.assign(result, {
    service,
    fake_service: result.fake_blocklist_test_service,
  });
}

/**
 * Returns an object containing a blocklisted BluetoothRemoteGATTCharacteristic
 * that excludes reads and its corresponding FakeRemoteGATTCharacteristic.
 * @returns {Promise<{device: BluetoothDevice, fake_peripheral: FakePeripheral,
 *     fake_blocklist_test_service: FakeRemoteGATTService,
 *     fake_blocklist_exclude_reads_characteristic:
 *         FakeRemoteGATTCharacteristic,
 *     fake_blocklist_exclude_writes_characteristic:
 *         FakeRemoteGATTCharacteristic,
 *     fake_blocklist_descriptor: FakeRemoteGATTDescriptor,
 *     fake_blocklist_exclude_reads_descriptor: FakeRemoteGATTDescriptor,
 *     fake_blocklist_exclude_writes_descriptor: FakeRemoteGATTDescriptor,
 *     service: BluetoothRemoteGATTService,
 *     fake_service: FakeBluetoothRemoteGATTService,
 *     characteristic: BluetoothRemoteGATTCharacteristic,
 *     fake_characteristic: FakeBluetoothRemoteGATTCharacteristic}>} An object
 *         containing the BluetoothDevice object and its corresponding GATT fake
 *         objects.
 */
async function getBlocklistExcludeReadsCharacteristic() {
  let result = await getBlocklistTestService();
  let characteristic = await result.service.getCharacteristic(
      blocklist_exclude_reads_characteristic_uuid);
  return Object.assign(result, {
    characteristic,
    fake_characteristic: result.fake_blocklist_exclude_reads_characteristic
  });
}

/**
 * Returns an object containing a blocklisted BluetoothRemoteGATTCharacteristic
 * that excludes writes and its corresponding FakeRemoteGATTCharacteristic.
 * @returns {Promise<{device: BluetoothDevice, fake_peripheral: FakePeripheral,
 *     fake_blocklist_test_service: FakeRemoteGATTService,
 *     fake_blocklist_exclude_reads_characteristic:
 *         FakeRemoteGATTCharacteristic,
 *     fake_blocklist_exclude_writes_characteristic:
 *         FakeRemoteGATTCharacteristic,
 *     fake_blocklist_descriptor: FakeRemoteGATTDescriptor,
 *     fake_blocklist_exclude_reads_descriptor: FakeRemoteGATTDescriptor,
 *     fake_blocklist_exclude_writes_descriptor: FakeRemoteGATTDescriptor,
 *     service: BluetoothRemoteGATTService,
 *     fake_service: FakeBluetoothRemoteGATTService,
 *     characteristic: BluetoothRemoteGATTCharacteristic,
 *     fake_characteristic: FakeBluetoothRemoteGATTCharacteristic}>} An object
 *         containing the BluetoothDevice object and its corresponding GATT fake
 *         objects.
 */
async function getBlocklistExcludeWritesCharacteristic() {
  let result = await getBlocklistTestService();
  let characteristic =
      await result.service.getCharacteristic('gap.peripheral_privacy_flag');
  return Object.assign(result, {
    characteristic,
    fake_characteristic: result.fake_blocklist_exclude_writes_characteristic
  });
}

/**
 * Returns an object containing a blocklisted BluetoothRemoteGATTDescriptor that
 * excludes reads and its corresponding FakeRemoteGATTDescriptor.
 * @returns {Promise<{device: BluetoothDevice, fake_peripheral: FakePeripheral,
 *     fake_blocklist_test_service: FakeRemoteGATTService,
 *     fake_blocklist_exclude_reads_characteristic:
 *         FakeRemoteGATTCharacteristic,
 *     fake_blocklist_exclude_writes_characteristic:
 *         FakeRemoteGATTCharacteristic,
 *     fake_blocklist_descriptor: FakeRemoteGATTDescriptor,
 *     fake_blocklist_exclude_reads_descriptor: FakeRemoteGATTDescriptor,
 *     fake_blocklist_exclude_writes_descriptor: FakeRemoteGATTDescriptor,
 *     service: BluetoothRemoteGATTService,
 *     fake_service: FakeBluetoothRemoteGATTService,
 *     characteristic: BluetoothRemoteGATTCharacteristic,
 *     fake_characteristic: FakeBluetoothRemoteGATTCharacteristic,
 *     descriptor: BluetoothRemoteGATTDescriptor,
 *     fake_descriptor: FakeBluetoothRemoteGATTDescriptor}>} An object
 *         containing the BluetoothDevice object and its corresponding GATT fake
 *         objects.
 */
async function getBlocklistExcludeReadsDescriptor() {
  let result = await getBlocklistExcludeWritesCharacteristic();
  let descriptor = await result.characteristic.getDescriptor(
      blocklist_exclude_reads_descriptor_uuid);
  return Object.assign(result, {
    descriptor,
    fake_descriptor: result.fake_blocklist_exclude_reads_descriptor
  });
}

/**
 * Returns an object containing a blocklisted BluetoothRemoteGATTDescriptor that
 * excludes writes and its corresponding FakeRemoteGATTDescriptor.
 * @returns {Promise<{device: BluetoothDevice, fake_peripheral: FakePeripheral,
 *     fake_blocklist_test_service: FakeRemoteGATTService,
 *     fake_blocklist_exclude_reads_characteristic:
 *         FakeRemoteGATTCharacteristic,
 *     fake_blocklist_exclude_writes_characteristic:
 *         FakeRemoteGATTCharacteristic,
 *     fake_blocklist_descriptor: FakeRemoteGATTDescriptor,
 *     fake_blocklist_exclude_reads_descriptor: FakeRemoteGATTDescriptor,
 *     fake_blocklist_exclude_writes_descriptor: FakeRemoteGATTDescriptor,
 *     service: BluetoothRemoteGATTService,
 *     fake_service: FakeBluetoothRemoteGATTService,
 *     characteristic: BluetoothRemoteGATTCharacteristic,
 *     fake_characteristic: FakeBluetoothRemoteGATTCharacteristic,
 *     descriptor: BluetoothRemoteGATTDescriptor,
 *     fake_descriptor: FakeBluetoothRemoteGATTDescriptor}>} An object
 *         containing the BluetoothDevice object and its corresponding GATT fake
 *         objects.
 */
async function getBlocklistExcludeWritesDescriptor() {
  let result = await getBlocklistExcludeWritesCharacteristic();
  let descriptor = await result.characteristic.getDescriptor(
      'gatt.client_characteristic_configuration');
  return Object.assign(result, {
    descriptor: descriptor,
    fake_descriptor: result.fake_blocklist_exclude_writes_descriptor,
  });
}

/** Bluetooth HID Device Helper Methods */

/** @type {FakeDeviceOptions} */
const connectedHIDFakeDeviceOptionsDefault = {
  address: '10:10:10:10:10:10',
  name: 'HID Device',
  knownServiceUUIDs: [
    'generic_access',
    'device_information',
    'human_interface_device',
  ],
  connectable: true,
  serviceDiscoveryComplete: false
};

/** @type {RequestDeviceOptions} */
const connectedHIDRequestDeviceOptionsDefault = {
  filters: [{services: ['device_information']}],
  optionalServices: ['human_interface_device']
};

/** @type {SetupOptions} */
const connectedHIDSetupOptionsDefault = {
  fakeDeviceOptions: connectedHIDFakeDeviceOptionsDefault,
  requestDeviceOptions: connectedHIDRequestDeviceOptionsDefault
};

/**
 * Similar to getHealthThermometerDevice except the GATT discovery
 * response has not been set yet so more attributes can still be added.
 * TODO(crbug.com/719816): Add descriptors.
 * @param {RequestDeviceOptions} options The options for requesting a Bluetooth
 *     Device.
 * @returns {device: BluetoothDevice, fake_peripheral: FakePeripheral} An object
 *     containing a requested BluetoothDevice and its fake counter part.
 */
async function getConnectedHIDDevice(
    requestDeviceOptionsOverride, fakeDeviceOptionsOverride) {
  let setupOptions = createSetupOptions(connectedHIDSetupOptionsDefault, {
    fakeDeviceOptions: fakeDeviceOptionsOverride,
    requestDeviceOptions: requestDeviceOptionsOverride
  });

  let fakeDevice = await setUpPreconnectedFakeDevice(setupOptions);
  await fakeDevice.device.gatt.connect();

  // Blocklisted Characteristic:
  // https://github.com/WebBluetoothCG/registries/blob/master/gatt_blocklist.txt
  let dev_info = fakeDevice.fake_services.get('device_information');
  await dev_info.addFakeCharacteristic({
    uuid: 'serial_number_string',
    properties: ['read'],
  });
  return fakeDevice;
}

/**
 * Returns a BluetoothDevice discovered using |options| and its
 * corresponding FakePeripheral.
 * The simulated device is called 'HID Device' it has three known service
 * UUIDs: 'generic_access', 'device_information', 'human_interface_device'.
 * The primary service with 'device_information' UUID has a characteristics
 * with UUID 'serial_number_string'. The device has been connected to and its
 * attributes are ready to be discovered.
 * @param {RequestDeviceOptions} options The options for requesting a Bluetooth
 *     Device.
 * @returns {device: BluetoothDevice, fake_peripheral: FakePeripheral} An object
 *     containing a requested BluetoothDevice and its fake counter part.
 */
async function getHIDDevice(options) {
  let result =
      await getConnectedHIDDevice(options, {serviceDiscoveryComplete: true});
  return result;
}

/** Health Thermometer Bluetooth Device Helper Methods */

/** @type {FakeDeviceOptions} */
const healthTherometerFakeDeviceOptionsDefault = {
  address: '09:09:09:09:09:09',
  name: 'Health Thermometer',
  manufacturerData: {0x0001: manufacturer1Data, 0x0002: manufacturer2Data},
  knownServiceUUIDs: ['generic_access', 'health_thermometer'],
};

/**
 * Returns a FakeDevice that corresponds to a simulated pre-connected device
 * called 'Health Thermometer'. The device has two known serviceUUIDs:
 * 'generic_access' and 'health_thermometer' and some fake manufacturer data.
 * @returns {Promise<FakeDevice>} The device fake initialized as a Health
 *     Thermometer device.
 */
async function setUpHealthThermometerDevice(setupOptionsOverride = {}) {
  let setupOptions = createSetupOptions(
      {fakeDeviceOptions: healthTherometerFakeDeviceOptionsDefault},
      setupOptionsOverride);
  return await setUpPreconnectedFakeDevice(setupOptions);
}

/**
 * Returns the same fake device as setUpHealthThermometerDevice() except
 * that connecting to the peripheral will succeed.
 * @returns {Promise<FakeDevice>} The device fake initialized as a
 *     connectable Health Thermometer device.
 */
async function setUpConnectableHealthThermometerDevice() {
  let fake_device = await setUpHealthThermometerDevice(
      {fakeDeviceOptions: {connectable: true}});
  return fake_device;
}

/**
 * Populates a fake_device with various fakes appropriate for a health
 * thermometer. This resolves to an associative array composed of the fakes,
 * including the |fake_peripheral|.
 * @param {FakeDevice} fake_device The Bluetooth fake to populate GATT
 *     services, characteristics, and descriptors on.
 * @returns {Promise<{fake_peripheral: FakePeripheral,
 *     fake_generic_access: FakeRemoteGATTService,
 *     fake_health_thermometer: FakeRemoteGATTService,
 *     fake_measurement_interval: FakeRemoteGATTCharacteristic,
 *     fake_cccd: FakeRemoteGATTDescriptor,
 *     fake_user_description: FakeRemoteGATTDescriptor,
 *     fake_temperature_measurement: FakeRemoteGATTCharacteristic,
 *     fake_temperature_type: FakeRemoteGATTCharacteristic}>} The FakePeripheral
 * passed into this method along with the fake GATT services, characteristics,
 *         and descriptors added to it.
 */
async function populateHealthThermometerFakes(fake_device) {
  let fake_peripheral = fake_device.fake_peripheral;
  let fake_generic_access = fake_device.fake_services.get('generic_access');
  let fake_health_thermometer =
      fake_device.fake_services.get('health_thermometer');
  let fake_measurement_interval =
      await fake_health_thermometer.addFakeCharacteristic({
        uuid: 'measurement_interval',
        properties: ['read', 'write', 'indicate'],
      });
  let fake_user_description =
      await fake_measurement_interval.addFakeDescriptor({
        uuid: 'gatt.characteristic_user_description',
      });
  let fake_cccd = await fake_measurement_interval.addFakeDescriptor({
    uuid: 'gatt.client_characteristic_configuration',
  });
  let fake_temperature_measurement =
      await fake_health_thermometer.addFakeCharacteristic({
        uuid: 'temperature_measurement',
        properties: ['indicate'],
      });
  let fake_temperature_type =
      await fake_health_thermometer.addFakeCharacteristic({
        uuid: 'temperature_type',
        properties: ['read'],
      });
  return {
    fake_peripheral,
    fake_generic_access,
    fake_health_thermometer,
    fake_measurement_interval,
    fake_cccd,
    fake_user_description,
    fake_temperature_measurement,
    fake_temperature_type,
  };
}

/**
 * Returns the same device and fake peripheral as getHealthThermometerDevice()
 * after another frame (an iframe we insert) discovered the device,
 * connected to it and discovered its services.
 * @param {RequestDeviceOptions} options The options for requesting a Bluetooth
 *     Device.
 * @returns {Promise<{device: BluetoothDevice, fakes: {
 *         fake_peripheral: FakePeripheral,
 *         fake_generic_access: FakeRemoteGATTService,
 *         fake_health_thermometer: FakeRemoteGATTService,
 *         fake_measurement_interval: FakeRemoteGATTCharacteristic,
 *         fake_cccd: FakeRemoteGATTDescriptor,
 *         fake_user_description: FakeRemoteGATTDescriptor,
 *         fake_temperature_measurement: FakeRemoteGATTCharacteristic,
 *         fake_temperature_type: FakeRemoteGATTCharacteristic}}>} An object
 *         containing a requested BluetoothDevice and all of the GATT fake
 *         objects.
 */
async function getHealthThermometerDeviceWithServicesDiscovered(options) {
  let iframe = document.createElement('iframe');
  let fake_device = await setUpConnectableHealthThermometerDevice();
  let fakes = populateHealthThermometerFakes(fake_device);
  await fake_device.fake_peripheral.setNextGATTDiscoveryResponse({
    code: HCI_SUCCESS,
  });
  await new Promise(resolve => {
    let src = '/bluetooth/resources/health-thermometer-iframe.html';
    // TODO(509038): Can be removed once LayoutTests/bluetooth/* that
    // use health-thermometer-iframe.html have been moved to
    // LayoutTests/external/wpt/bluetooth/*
    if (window.location.pathname.includes('/LayoutTests/')) {
      src =
          '../../../external/wpt/bluetooth/resources/health-thermometer-iframe.html';
    }
    iframe.src = src;
    document.body.appendChild(iframe);
    iframe.addEventListener('load', resolve);
  });
  await new Promise((resolve, reject) => {
    callWithTrustedClick(() => {
      iframe.contentWindow.postMessage(
          {type: 'DiscoverServices', options: options}, '*');
    });

    function messageHandler(messageEvent) {
      if (messageEvent.data == 'DiscoveryComplete') {
        window.removeEventListener('message', messageHandler);
        resolve();
      } else {
        reject(new Error(`Unexpected message: ${messageEvent.data}`));
      }
    }
    window.addEventListener('message', messageHandler);
  });
  let device = await requestDeviceWithTrustedClick(options);
  await device.gatt.connect();
  return Object.assign({device}, fakes);
}

/**
 * Returns the device requested and connected in the given iframe context and
 * fakes from populateHealthThermometerFakes().
 * @param {object} iframe The iframe element set up by the caller document.
 * @returns {Promise<{device: BluetoothDevice, fakes: {
 *         fake_peripheral: FakePeripheral,
 *         fake_generic_access: FakeRemoteGATTService,
 *         fake_health_thermometer: FakeRemoteGATTService,
 *         fake_measurement_interval: FakeRemoteGATTCharacteristic,
 *         fake_cccd: FakeRemoteGATTDescriptor,
 *         fake_user_description: FakeRemoteGATTDescriptor,
 *         fake_temperature_measurement: FakeRemoteGATTCharacteristic,
 *         fake_temperature_type: FakeRemoteGATTCharacteristic}}>} An object
 *         containing a requested BluetoothDevice and all of the GATT fake
 *         objects.
 */
async function getHealthThermometerDeviceFromIframe(iframe) {
  const fake_device = await setUpConnectableHealthThermometerDevice();
  const fakes = await populateHealthThermometerFakes(fake_device);
  await new Promise(resolve => {
    let src = '/bluetooth/resources/health-thermometer-iframe.html';
    iframe.src = src;
    document.body.appendChild(iframe);
    iframe.addEventListener('load', resolve, {once: true});
  });
  await new Promise((resolve, reject) => {
    callWithTrustedClick(() => {
      iframe.contentWindow.postMessage(
          {
            type: 'RequestAndConnect',
            options: {filters: [{services: [health_thermometer.name]}]}
          },
          '*');
    });

    function messageHandler(messageEvent) {
      if (messageEvent.data == 'Connected') {
        window.removeEventListener('message', messageHandler);
        resolve();
      } else {
        reject(new Error(`Unexpected message: ${messageEvent.data}`));
      }
    }
    window.addEventListener('message', messageHandler, {once: true});
  });
  const devices = await iframe.contentWindow.navigator.bluetooth.getDevices();
  assert_equals(devices.length, 1);
  return Object.assign({device: devices[0]}, {fakes});
}

/**
 * Similar to getHealthThermometerDevice() except the device
 * is not connected and thus its services have not been
 * discovered.
 * @param {RequestDeviceOptions} options The options for requesting a Bluetooth
 *     Device.
 * @returns {device: BluetoothDevice, fake_peripheral: FakePeripheral} An object
 *     containing a requested BluetoothDevice and its fake counter part.
 */
async function getDiscoveredHealthThermometerDevice(options = {
  filters: [{services: ['health_thermometer']}]
}) {
  return await setUpHealthThermometerDevice({requestDeviceOptions: options});
}

/**
 * Similar to getHealthThermometerDevice() except the device has no services,
 * characteristics, or descriptors.
 * @param {RequestDeviceOptions} options The options for requesting a Bluetooth
 *     Device.
 * @returns {device: BluetoothDevice, fake_peripheral: FakePeripheral} An object
 *     containing a requested BluetoothDevice and its fake counter part.
 */
async function getEmptyHealthThermometerDevice(options) {
  let fake_device = await getDiscoveredHealthThermometerDevice(options);
  let fake_generic_access = fake_device.fake_services.get('generic_access');
  let fake_health_thermometer =
      fake_device.fake_services.get('health_thermometer');
  // Remove services that have been set up by previous steps.
  await fake_generic_access.remove();
  await fake_health_thermometer.remove();
  await fake_device.fake_peripheral.setNextGATTConnectionResponse(
      {code: HCI_SUCCESS});
  await fake_device.device.gatt.connect();
  await fake_device.fake_peripheral.setNextGATTDiscoveryResponse(
      {code: HCI_SUCCESS});
  return fake_device;
}

/**
 * Similar to getHealthThermometerService() except the service has no
 * characteristics or included services.
 * @param {RequestDeviceOptions} options The options for requesting a Bluetooth
 *     Device.
 * @returns {service: BluetoothRemoteGATTService,
 *     fake_health_thermometer: FakeRemoteGATTService} An object containing the
 * health themometer service object and its corresponding fake.
 */
async function getEmptyHealthThermometerService(options) {
  let result = await getDiscoveredHealthThermometerDevice(options);
  await result.fake_peripheral.setNextGATTConnectionResponse(
      {code: HCI_SUCCESS});
  await result.device.gatt.connect();
  let fake_health_thermometer =
      await result.fake_peripheral.addFakeService({uuid: 'health_thermometer'});
  await result.fake_peripheral.setNextGATTDiscoveryResponse(
      {code: HCI_SUCCESS});
  let service =
      await result.device.gatt.getPrimaryService('health_thermometer');
  return {
    service: service,
    fake_health_thermometer: fake_health_thermometer,
  };
}

/**
 * Similar to getHealthThermometerDevice except the GATT discovery
 * response has not been set yet so more attributes can still be added.
 * @param {RequestDeviceOptions} options The options for requesting a Bluetooth
 *     Device.
 * @returns {Promise<{device: BluetoothDevice, fakes: {
 *         fake_peripheral: FakePeripheral,
 *         fake_generic_access: FakeRemoteGATTService,
 *         fake_health_thermometer: FakeRemoteGATTService,
 *         fake_measurement_interval: FakeRemoteGATTCharacteristic,
 *         fake_cccd: FakeRemoteGATTDescriptor,
 *         fake_user_description: FakeRemoteGATTDescriptor,
 *         fake_temperature_measurement: FakeRemoteGATTCharacteristic,
 *         fake_temperature_type: FakeRemoteGATTCharacteristic}}>} An object
 *         containing a requested BluetoothDevice and all of the GATT fake
 *         objects.
 */
async function getConnectedHealthThermometerDevice(options) {
  let fake_device = await getDiscoveredHealthThermometerDevice(options);
  await fake_device.fake_peripheral.setNextGATTConnectionResponse({
    code: HCI_SUCCESS,
  });
  let fakes = await populateHealthThermometerFakes(fake_device);
  await fake_device.device.gatt.connect();
  return Object.assign({device: fake_device.device}, fakes);
}

/**
 * Returns an object containing a BluetoothDevice discovered using |options|,
 * its corresponding FakePeripheral and FakeRemoteGATTServices.
 * The simulated device is called 'Health Thermometer' it has two known service
 * UUIDs: 'generic_access' and 'health_thermometer' which correspond to two
 * services with the same UUIDs. The 'health thermometer' service contains three
 * characteristics:
 *  - 'temperature_measurement' (indicate),
 *  - 'temperature_type' (read),
 *  - 'measurement_interval' (read, write, indicate)
 * The 'measurement_interval' characteristic contains a
 * 'gatt.client_characteristic_configuration' descriptor and a
 * 'characteristic_user_description' descriptor.
 * The device has been connected to and its attributes are ready to be
 * discovered.
 * @param {RequestDeviceOptions} options The options for requesting a Bluetooth
 *     Device.
 * @returns {Promise<{device: BluetoothDevice, fakes: {
 *         fake_peripheral: FakePeripheral,
 *         fake_generic_access: FakeRemoteGATTService,
 *         fake_health_thermometer: FakeRemoteGATTService,
 *         fake_measurement_interval: FakeRemoteGATTCharacteristic,
 *         fake_cccd: FakeRemoteGATTDescriptor,
 *         fake_user_description: FakeRemoteGATTDescriptor,
 *         fake_temperature_measurement: FakeRemoteGATTCharacteristic,
 *         fake_temperature_type: FakeRemoteGATTCharacteristic}}>} An object
 *         containing a requested BluetoothDevice and all of the GATT fake
 *         objects.
 */
async function getHealthThermometerDevice(options) {
  let result = await getConnectedHealthThermometerDevice(options);
  await result.fake_peripheral.setNextGATTDiscoveryResponse({
    code: HCI_SUCCESS,
  });
  return result;
}

/**
 * Similar to getHealthThermometerDevice except that the peripheral has two
 * 'health_thermometer' services.
 * @param {RequestDeviceOptions} options The options for requesting a Bluetooth
 *     Device.
 * @returns {Promise<{device: BluetoothDevice, fake_peripheral: FakePeripheral,
 *     fake_generic_access: FakeRemoteGATTService, fake_health_thermometer1:
 * FakeRemoteGATTService, fake_health_thermometer2: FakeRemoteGATTService}>} An
 * object containing a requested Bluetooth device and two fake health
 * thermometer GATT services.
 */
async function getTwoHealthThermometerServicesDevice(options) {
  let result = await getConnectedHealthThermometerDevice(options);
  let fake_health_thermometer2 =
      await result.fake_peripheral.addFakeService({uuid: 'health_thermometer'});
  await result.fake_peripheral.setNextGATTDiscoveryResponse(
      {code: HCI_SUCCESS});
  return {
    device: result.device,
    fake_peripheral: result.fake_peripheral,
    fake_generic_access: result.fake_generic_access,
    fake_health_thermometer1: result.fake_health_thermometer,
    fake_health_thermometer2: fake_health_thermometer2
  };
}

/**
 * Returns an object containing a Health Thermometer BluetoothRemoteGattService
 * and its corresponding FakeRemoteGATTService.
 * @returns {Promise<{device: BluetoothDevice, fakes: {
 *         fake_peripheral: FakePeripheral,
 *         fake_generic_access: FakeRemoteGATTService,
 *         fake_health_thermometer: FakeRemoteGATTService,
 *         fake_measurement_interval: FakeRemoteGATTCharacteristic,
 *         fake_cccd: FakeRemoteGATTDescriptor,
 *         fake_user_description: FakeRemoteGATTDescriptor,
 *         fake_temperature_measurement: FakeRemoteGATTCharacteristic,
 *         fake_temperature_type: FakeRemoteGATTCharacteristic,
 *         service: BluetoothRemoteGATTService,
 *         fake_service: FakeRemoteGATTService}}>} An object
 *         containing a requested BluetoothDevice and all of the GATT fake
 *         objects.
 */
async function getHealthThermometerService() {
  let result = await getHealthThermometerDevice();
  let service =
      await result.device.gatt.getPrimaryService('health_thermometer');
  return Object.assign(result, {
    service,
    fake_service: result.fake_health_thermometer,
  });
}

/**
 * Returns an object containing a Measurement Interval
 * BluetoothRemoteGATTCharacteristic and its corresponding
 * FakeRemoteGATTCharacteristic.
 * @returns {Promise<{device: BluetoothDevice, fakes: {
 *         fake_peripheral: FakePeripheral,
 *         fake_generic_access: FakeRemoteGATTService,
 *         fake_health_thermometer: FakeRemoteGATTService,
 *         fake_measurement_interval: FakeRemoteGATTCharacteristic,
 *         fake_cccd: FakeRemoteGATTDescriptor,
 *         fake_user_description: FakeRemoteGATTDescriptor,
 *         fake_temperature_measurement: FakeRemoteGATTCharacteristic,
 *         fake_temperature_type: FakeRemoteGATTCharacteristic,
 *         service: BluetoothRemoteGATTService,
 *         fake_service: FakeRemoteGATTService,
 *         characteristic: BluetoothRemoteGATTCharacteristic,
 *         fake_characteristic: FakeRemoteGATTCharacteristic}}>} An object
 *         containing a requested BluetoothDevice and all of the GATT fake
 *         objects.
 */
async function getMeasurementIntervalCharacteristic() {
  let result = await getHealthThermometerService();
  let characteristic =
      await result.service.getCharacteristic('measurement_interval');
  return Object.assign(result, {
    characteristic,
    fake_characteristic: result.fake_measurement_interval,
  });
}

/**
 * Returns an object containing a User Description
 * BluetoothRemoteGATTDescriptor and its corresponding
 * FakeRemoteGATTDescriptor.
 * @returns {Promise<{device: BluetoothDevice, fakes: {
 *         fake_peripheral: FakePeripheral,
 *         fake_generic_access: FakeRemoteGATTService,
 *         fake_health_thermometer: FakeRemoteGATTService,
 *         fake_measurement_interval: FakeRemoteGATTCharacteristic,
 *         fake_cccd: FakeRemoteGATTDescriptor,
 *         fake_user_description: FakeRemoteGATTDescriptor,
 *         fake_temperature_measurement: FakeRemoteGATTCharacteristic,
 *         fake_temperature_type: FakeRemoteGATTCharacteristic,
 *         service: BluetoothRemoteGATTService,
 *         fake_service: FakeRemoteGATTService,
 *         characteristic: BluetoothRemoteGATTCharacteristic,
 *         fake_characteristic: FakeRemoteGATTCharacteristic
 *         descriptor: BluetoothRemoteGATTDescriptor,
 *         fake_descriptor: FakeRemoteGATTDescriptor}}>} An object
 *         containing a requested BluetoothDevice and all of the GATT fake
 *         objects.
 */
async function getUserDescriptionDescriptor() {
  let result = await getMeasurementIntervalCharacteristic();
  let descriptor = await result.characteristic.getDescriptor(
      'gatt.characteristic_user_description');
  return Object.assign(result, {
    descriptor,
    fake_descriptor: result.fake_user_description,
  });
}

/** Heart Rate Bluetooth Device Helper Methods */

/** @type {FakeDeviceOptions} */
const heartRateFakeDeviceOptionsDefault = {
  address: '08:08:08:08:08:08',
  name: 'Heart Rate',
  knownServiceUUIDs: ['generic_access', 'heart_rate'],
  connectable: false,
  serviceDiscoveryComplete: false,
};

/** @type {RequestDeviceOptions} */
const heartRateRequestDeviceOptionsDefault = {
  filters: [{services: ['heart_rate']}]
};

async function getHeartRateDevice(setupOptionsOverride) {
  let setupOptions = createSetupOptions(
      {fakeDeviceOptions: heartRateFakeDeviceOptionsDefault},
      setupOptionsOverride);
  return await setUpPreconnectedFakeDevice(setupOptions);
}

/**
 * Returns an array containing two FakePeripherals corresponding
 * to the simulated devices.
 * @returns {Promise<Array<FakePeripheral>>} The device fakes initialized as
 *     Health Thermometer and Heart Rate devices.
 */
async function setUpHealthThermometerAndHeartRateDevices() {
  await initializeFakeCentral({state: 'powered-on'});
  return Promise.all([
    fake_central.simulatePreconnectedPeripheral({
      address: '09:09:09:09:09:09',
      name: 'Health Thermometer',
      manufacturerData: {},
      knownServiceUUIDs: ['generic_access', 'health_thermometer'],
    }),
    fake_central.simulatePreconnectedPeripheral({
      address: '08:08:08:08:08:08',
      name: 'Heart Rate',
      manufacturerData: {},
      knownServiceUUIDs: ['generic_access', 'heart_rate'],
    })
  ]);
}