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 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976
|
// Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ash/arc/bluetooth/arc_bluetooth_bridge.h"
#include <bluetooth/bluetooth.h>
#include <bluetooth/l2cap.h>
#include <bluetooth/rfcomm.h>
#include <fcntl.h>
#include <stdint.h>
#include <sys/socket.h>
#include <algorithm>
#include <iomanip>
#include <optional>
#include <string>
#include <utility>
#include "ash/constants/ash_pref_names.h"
#include "base/containers/contains.h"
#include "base/containers/queue.h"
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/functional/callback_helpers.h"
#include "base/json/json_writer.h"
#include "base/logging.h"
#include "base/memory/singleton.h"
#include "base/posix/eintr_wrapper.h"
#include "base/strings/string_number_conversions.h"
#include "base/task/sequenced_task_runner.h"
#include "base/task/thread_pool.h"
#include "base/time/time.h"
#include "chrome/browser/ash/arc/bluetooth/arc_bluez_bridge.h"
#include "chrome/browser/ash/arc/bluetooth/arc_floss_bridge.h"
#include "chrome/browser/ash/profiles/profile_helper.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/webui/ash/bluetooth/bluetooth_pairing_dialog.h"
#include "chromeos/ash/experiences/arc/arc_browser_context_keyed_service_factory_base.h"
#include "chromeos/ash/experiences/arc/bluetooth/bluetooth_type_converters.h"
#include "chromeos/ash/experiences/arc/intent_helper/arc_intent_helper_bridge.h"
#include "chromeos/ash/experiences/arc/intent_helper/arc_intent_helper_package.h"
#include "chromeos/ash/experiences/arc/session/arc_bridge_service.h"
#include "components/device_event_log/device_event_log.h"
#include "components/prefs/pref_service.h"
#include "components/user_manager/user_manager.h"
#include "device/bluetooth/bluetooth_common.h"
#include "device/bluetooth/bluetooth_device.h"
#include "device/bluetooth/bluetooth_gatt_connection.h"
#include "device/bluetooth/bluetooth_gatt_notify_session.h"
#include "device/bluetooth/bluetooth_local_gatt_characteristic.h"
#include "device/bluetooth/bluetooth_local_gatt_descriptor.h"
#include "device/bluetooth/bluez/bluetooth_device_bluez.h"
#include "device/bluetooth/bluez/bluetooth_local_gatt_characteristic_bluez.h"
#include "device/bluetooth/bluez/bluetooth_remote_gatt_characteristic_bluez.h"
#include "device/bluetooth/floss/bluetooth_gatt_characteristic_floss.h"
#include "device/bluetooth/floss/floss_features.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/platform/platform_handle.h"
#include "mojo/public/cpp/system/platform_handle.h"
// Enable VLOG level 1.
#undef ENABLED_VLOG_LEVEL
#define ENABLED_VLOG_LEVEL 1
using device::BluetoothAdapter;
using device::BluetoothAdapterFactory;
using device::BluetoothAdvertisement;
using device::BluetoothDevice;
using device::BluetoothDiscoveryFilter;
using device::BluetoothDiscoverySession;
using device::BluetoothGattCharacteristic;
using device::BluetoothGattConnection;
using device::BluetoothGattDescriptor;
using device::BluetoothGattNotifySession;
using device::BluetoothGattService;
using device::BluetoothLocalGattCharacteristic;
using device::BluetoothLocalGattDescriptor;
using device::BluetoothLocalGattService;
using device::BluetoothRemoteGattCharacteristic;
using device::BluetoothRemoteGattDescriptor;
using device::BluetoothRemoteGattService;
using device::BluetoothTransport;
using device::BluetoothUUID;
namespace {
// Bluetooth Spec Vol 3, Part G, 3.3.3.3 Client Characteristic Configuration.
constexpr uint8_t DISABLE_NOTIFICATION_VALUE = 0;
constexpr uint8_t ENABLE_NOTIFICATION_VALUE = 1;
constexpr uint8_t ENABLE_INDICATION_VALUE = 2;
constexpr int32_t kInvalidGattAttributeHandle = -1;
constexpr int32_t kInvalidAdvertisementHandle = -1;
// Bluetooth Specification Version 4.2 Vol 3 Part F Section 3.2.2
// An attribute handle of value 0xFFFF is known as the maximum attribute handle.
constexpr int32_t kMaxGattAttributeHandle = 0xFFFF;
// Bluetooth Specification Version 4.2 Vol 3 Part F Section 3.2.9
// The maximum length of an attribute value shall be 512 octets.
constexpr int kMaxGattAttributeLength = 512;
// Copied from Android at system/bt/stack/btm/btm_ble_int.h
// https://android.googlesource.com/platform/system/bt/+/android-n-preview-5/stack/btm/btm_ble_int.h?pli=1#109
constexpr uint16_t kAndroidMBluetoothVersionNumber = 95;
// Timeout for Bluetooth Discovery (scan)
// 120 seconds is used here as the upper bound of the time need to do device
// discovery once, 20 seconds for inquiry scan and 100 seconds for page scan
// for 100 new devices.
constexpr base::TimeDelta kDiscoveryTimeout = base::Seconds(120);
// From https://www.bluetooth.com/specifications/assigned-numbers/baseband
// The Class of Device for generic computer.
constexpr uint32_t kBluetoothComputerClass = 0x100;
// Timeout for Android to complete a disabling op to adapter.
// In the case where an enabling op happens immediately after a disabling op,
// Android takes the following enabling op as a no-op and waits 3~4 seconds for
// the previous disabling op to finish, so the enabling op will never be
// fulfilled by Android, and the disabling op will later routed back to Chrome
// while Chrome's adapter is enabled. This results in the wrong power state
// which should be enabled. Since the signaling from Android to Chrome for
// Bluetooth is via Bluetooth HAL layer which run on the same process as
// Bluetooth Service in Java space, so the signaling to Chrome about the
// to-be-happen sleep cannot be done. This timeout tries to ensure the validity
// and the order of toggles on power state sent to Android.
// If Android takes more than 8 seconds to complete the intent initiated by
// Chrome, Chrome will take EnableAdapter/DisableAdapter calls as a request from
// Android to toggle the power state. The power state will be synced on both
// Chrome and Android, but as a result, Bluetooth will be off.
constexpr base::TimeDelta kPowerIntentTimeout = base::Seconds(8);
// Client name for logging in BLE scanning.
constexpr char kScanClientName[] = "ARC";
arc::mojom::BluetoothGattStatus ConvertGattErrorCodeToStatus(
const device::BluetoothGattService::GattErrorCode& error_code,
bool is_read_operation) {
switch (error_code) {
case device::BluetoothGattService::GattErrorCode::kInvalidLength:
return arc::mojom::BluetoothGattStatus::GATT_INVALID_ATTRIBUTE_LENGTH;
case device::BluetoothGattService::GattErrorCode::kNotPermitted:
return is_read_operation
? arc::mojom::BluetoothGattStatus::GATT_READ_NOT_PERMITTED
: arc::mojom::BluetoothGattStatus::GATT_WRITE_NOT_PERMITTED;
case device::BluetoothGattService::GattErrorCode::kNotAuthorized:
return arc::mojom::BluetoothGattStatus::GATT_INSUFFICIENT_AUTHENTICATION;
case device::BluetoothGattService::GattErrorCode::kNotSupported:
return arc::mojom::BluetoothGattStatus::GATT_REQUEST_NOT_SUPPORTED;
case device::BluetoothGattService::GattErrorCode::kUnknown:
case device::BluetoothGattService::GattErrorCode::kFailed:
case device::BluetoothGattService::GattErrorCode::kInProgress:
case device::BluetoothGattService::GattErrorCode::kNotPaired:
default:
return arc::mojom::BluetoothGattStatus::GATT_FAILURE;
}
}
// Example of identifier: /org/bluez/hci0/dev_E0_CF_65_8C_86_1A/service001a
// Convert the last 4 characters of |identifier| to an
// int, by interpreting them as hexadecimal digits.
std::optional<uint16_t> ConvertGattIdentifierToId(
const std::string& identifier) {
uint32_t result;
if (identifier.size() < 4 ||
!base::HexStringToUInt(identifier.substr(identifier.size() - 4), &result))
return std::nullopt;
return result;
}
// Create GattDBElement and fill in common data for
// Gatt Service/Characteristic/Descriptor.
template <class RemoteGattAttribute>
arc::mojom::BluetoothGattDBElementPtr CreateGattDBElement(
const arc::mojom::BluetoothGattDBAttributeType type,
const RemoteGattAttribute* attribute) {
std::optional<uint16_t> id =
ConvertGattIdentifierToId(attribute->GetIdentifier());
if (!id)
return nullptr;
arc::mojom::BluetoothGattDBElementPtr element =
arc::mojom::BluetoothGattDBElement::New();
element->type = type;
element->uuid = attribute->GetUUID();
element->element_id = element->attribute_handle = element->start_handle =
element->end_handle = *id;
// TODO(b/191129417) remove once ARC++ handles new field
element->deprecated_id = *id;
element->properties = 0;
return element;
}
template <class RemoteGattAttribute>
RemoteGattAttribute* FindGattAttributeByUuid(
const std::vector<RemoteGattAttribute*>& attributes,
const BluetoothUUID& uuid) {
auto it = std::ranges::find(attributes, uuid, &RemoteGattAttribute::GetUUID);
return it != attributes.end() ? *it : nullptr;
}
// Common success callback for GATT operations that only need to report
// GattStatus back to Android.
void OnGattOperationDone(arc::ArcBluetoothBridge::GattStatusCallback callback) {
std::move(callback).Run(arc::mojom::BluetoothGattStatus::GATT_SUCCESS);
}
// Common error callback for GATT operations that only need to report
// GattStatus back to Android.
void OnGattOperationError(arc::ArcBluetoothBridge::GattStatusCallback callback,
BluetoothGattService::GattErrorCode error_code) {
std::move(callback).Run(ConvertGattErrorCodeToStatus(
error_code, /* is_read_operation = */ false));
}
// Common callback (success and error) for ReadGattCharacteristic and
// ReadGattDescriptor.
void OnGattRead(
arc::ArcBluetoothBridge::GattReadCallback callback,
std::optional<device::BluetoothGattService::GattErrorCode> error_code,
const std::vector<uint8_t>& result) {
arc::mojom::BluetoothGattValuePtr gattValue =
arc::mojom::BluetoothGattValue::New();
if (error_code.has_value()) {
gattValue->status = ConvertGattErrorCodeToStatus(
error_code.value(), /*is_read_operation=*/true);
} else {
gattValue->status = arc::mojom::BluetoothGattStatus::GATT_SUCCESS;
}
gattValue->value = result;
std::move(callback).Run(std::move(gattValue));
}
// Callback function for mojom::BluetoothInstance::RequestGattRead
void OnGattServerRead(
BluetoothLocalGattService::Delegate::ValueCallback callback,
arc::mojom::BluetoothGattStatus status,
const std::vector<uint8_t>& value) {
if (status == arc::mojom::BluetoothGattStatus::GATT_SUCCESS) {
std::move(callback).Run(/*error_code=*/std::nullopt, value);
} else {
std::move(callback).Run(BluetoothGattService::GattErrorCode::kFailed,
/*value=*/std::vector<uint8_t>());
}
}
// Callback function for mojom::BluetoothInstance::RequestGattWrite
void OnGattServerWrite(
base::OnceClosure success_callback,
BluetoothLocalGattService::Delegate::ErrorCallback error_callback,
arc::mojom::BluetoothGattStatus status) {
if (status == arc::mojom::BluetoothGattStatus::GATT_SUCCESS)
std::move(success_callback).Run();
else
std::move(error_callback).Run();
}
bool IsGattOffsetValid(int offset) {
return 0 <= offset && offset < kMaxGattAttributeLength;
}
// This is needed because Android only support UUID 16 bits in service data
// section in advertising data
std::optional<uint16_t> GetUUID16(const BluetoothUUID& uuid) {
// Convert xxxxyyyy-xxxx-xxxx-xxxx-xxxxxxxxxxxx to int16 yyyy
uint32_t result;
if (uuid.canonical_value().size() < 8 ||
!base::HexStringToUInt(uuid.canonical_value().substr(4, 4), &result))
return std::nullopt;
return result;
}
arc::mojom::BluetoothPropertyPtr GetDiscoveryTimeoutProperty(uint32_t timeout) {
return arc::mojom::BluetoothProperty::NewDiscoveryTimeout(timeout);
}
const device::BluetoothLocalGattDescriptor* FindCCCD(
const device::BluetoothLocalGattCharacteristic* characteristic) {
for (auto descriptor : characteristic->GetDescriptors()) {
if (descriptor->GetUUID() ==
BluetoothGattDescriptor::ClientCharacteristicConfigurationUuid()) {
return descriptor;
}
}
return nullptr;
}
std::vector<uint8_t> MakeCCCDValue(uint8_t value) {
return {value, 0};
}
void SendRssiOnGetConnectionInfoDone(
arc::ArcBluetoothBridge::ReadRemoteRssiCallback callback,
const device::BluetoothDevice::ConnectionInfo& conn_info) {
std::move(callback).Run(conn_info.rssi);
}
} // namespace
namespace arc {
namespace {
// Singleton factory for ArcAccessibilityHelperBridge.
class ArcBluezBridgeFactory
: public internal::ArcBrowserContextKeyedServiceFactoryBase<
ArcBluezBridge,
ArcBluezBridgeFactory> {
public:
// Factory name used by ArcBrowserContextKeyedServiceFactoryBase.
static constexpr const char* kName = "ArcBluezBridgeFactory";
static ArcBluezBridgeFactory* GetInstance() {
return base::Singleton<ArcBluezBridgeFactory>::get();
}
private:
friend base::DefaultSingletonTraits<ArcBluezBridgeFactory>;
ArcBluezBridgeFactory() = default;
~ArcBluezBridgeFactory() override = default;
};
// Singleton factory for ArcAccessibilityHelperBridge.
class ArcFlossBridgeFactory
: public internal::ArcBrowserContextKeyedServiceFactoryBase<
ArcFlossBridge,
ArcFlossBridgeFactory> {
public:
// Factory name used by ArcBrowserContextKeyedServiceFactoryBase.
static constexpr const char* kName = "ArcFlossBridgeFactory";
static ArcFlossBridgeFactory* GetInstance() {
return base::Singleton<ArcFlossBridgeFactory>::get();
}
private:
friend base::DefaultSingletonTraits<ArcFlossBridgeFactory>;
ArcFlossBridgeFactory() = default;
~ArcFlossBridgeFactory() override = default;
};
} // namespace
// static
ArcBluetoothBridge* ArcBluetoothBridge::GetForBrowserContext(
content::BrowserContext* context) {
if (floss::features::IsFlossEnabled()) {
return ArcFlossBridgeFactory::GetForBrowserContext(context);
} else {
return ArcBluezBridgeFactory::GetForBrowserContext(context);
}
}
ArcBluetoothBridge::ArcBluetoothBridge(content::BrowserContext* context,
ArcBridgeService* bridge_service)
: arc_bridge_service_(bridge_service),
bluetooth_arc_connection_observer_(this) {
arc_bridge_service_->app()->AddObserver(this);
arc_bridge_service_->intent_helper()->AddObserver(this);
if (BluetoothAdapterFactory::IsBluetoothSupported()) {
VLOG(1) << "Registering bluetooth adapter.";
BluetoothAdapterFactory::Get()->GetAdapter(base::BindOnce(
&ArcBluetoothBridge::OnAdapterInitialized, weak_factory_.GetWeakPtr()));
} else {
VLOG(1) << "Bluetooth not supported.";
}
}
ArcBluetoothBridge::~ArcBluetoothBridge() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
if (bluetooth_adapter_)
bluetooth_adapter_->RemoveObserver(this);
arc_bridge_service_->app()->RemoveObserver(this);
arc_bridge_service_->intent_helper()->RemoveObserver(this);
arc_bridge_service_->bluetooth()->SetHost(nullptr);
}
void ArcBluetoothBridge::OnAdapterInitialized(
scoped_refptr<BluetoothAdapter> adapter) {
DCHECK(adapter);
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
bluetooth_adapter_ = adapter;
if (!bluetooth_adapter_->HasObserver(this))
bluetooth_adapter_->AddObserver(this);
// Once the bluetooth adapter is ready, we can now signal the container that
// the interface is ready to be interacted with. This avoids races in most
// methods, since it's undesirable to implement a retry mechanism for the
// cases when an inbound method is called and the adapter is not ready yet.
arc_bridge_service_->bluetooth()->SetHost(this);
}
void ArcBluetoothBridge::AdapterPoweredChanged(BluetoothAdapter* adapter,
bool powered) {
AdapterPowerState power_change =
powered ? AdapterPowerState::TURN_ON : AdapterPowerState::TURN_OFF;
if (IsPowerChangeInitiatedByRemote(power_change))
DequeueRemotePowerChange(power_change);
else
EnqueueLocalPowerChange(power_change);
}
void ArcBluetoothBridge::DeviceAdded(BluetoothAdapter* adapter,
BluetoothDevice* device) {
DeviceChanged(adapter, device);
// We need to trigger this manually if the device is connected when it is
// added. This may happen for a incoming connection from an unknown device.
if (device->IsConnected())
DeviceConnectedStateChanged(adapter, device, /*is_now_connected=*/true);
}
void ArcBluetoothBridge::DeviceChanged(BluetoothAdapter* adapter,
BluetoothDevice* device) {
if (!arc_bridge_service_->bluetooth()->IsConnected())
return;
std::string addr = device->GetAddress();
if (IsDiscoveringOrScanning() && discovered_devices_.insert(addr).second) {
auto* bluetooth_instance = ARC_GET_INSTANCE_FOR_METHOD(
arc_bridge_service_->bluetooth(), OnDeviceFound);
if (bluetooth_instance) {
bluetooth_instance->OnDeviceFound(
GetDeviceProperties(mojom::BluetoothPropertyType::ALL, device));
}
} else if (discovered_devices_.contains(addr)) {
auto* bluetooth_instance = ARC_GET_INSTANCE_FOR_METHOD(
arc_bridge_service_->bluetooth(), OnDevicePropertiesChanged);
if (bluetooth_instance) {
bluetooth_instance->OnDevicePropertiesChanged(
mojom::BluetoothAddress::From(addr),
GetDeviceProperties(mojom::BluetoothPropertyType::ALL, device));
}
}
TrackPairingState(device);
}
void ArcBluetoothBridge::TrackPairingState(const BluetoothDevice* device) {
const std::string addr = device->GetAddress();
// A device in pairing is in |devices_paired_by_arc_| from CreateBond() is
// called until at least pairing is finished (either succeed or fail), so we
// don't need to do anything here if the device is not in the list.
if (devices_paired_by_arc_.find(addr) == devices_paired_by_arc_.end())
return;
const auto itr = devices_pairing_.find(addr);
bool was_pairing = itr != devices_pairing_.end();
// The actions we need to take depends on the combination of |was_pairing|,
// IsConnecting() and IsPaired():
// If not |was_pairing|:
// - !IsConnecting() means device is not pairing, do nothing;
// - IsPaired() means device has already been paired, do nothing;
// - IsConnecting() && !IsPaired() means device is pairing now, we should add
// it into our list.
// If |was_pairing|:
// - IsPaired() means pairing succeeded, we should remove the device from our
// list.
// - IsConnecting() && !IsPaired() means device is still in pairing, do
// nothing;
// - !IsConnecting() && !IsPaired() means pairing failed, we should notify
// Android, and remove the device from our list;
if (!was_pairing) {
if (device->IsConnecting() && !device->IsPaired())
devices_pairing_.insert(addr);
return;
}
if (device->IsPaired()) {
devices_pairing_.erase(itr);
} else if (!device->IsConnecting()) {
LOG(WARNING) << "Pairing failed for device " << addr;
OnPairedError(mojom::BluetoothAddress::From(addr),
BluetoothDevice::ERROR_FAILED);
devices_pairing_.erase(itr);
}
}
void ArcBluetoothBridge::DeviceAddressChanged(BluetoothAdapter* adapter,
BluetoothDevice* device,
const std::string& old_address) {
if (!arc_bridge_service_->bluetooth()->IsConnected())
return;
std::string new_address = device->GetAddress();
if (old_address == new_address)
return;
if (!(device->GetType() & device::BLUETOOTH_TRANSPORT_LE))
return;
if (devices_paired_by_arc_.erase(old_address) == 1)
devices_paired_by_arc_.insert(new_address);
auto it = gatt_connections_.find(old_address);
if (it == gatt_connections_.end())
return;
gatt_connections_.emplace(new_address, std::move(it->second));
gatt_connections_.erase(it);
auto* btle_instance = ARC_GET_INSTANCE_FOR_METHOD(
arc_bridge_service_->bluetooth(), OnLEDeviceAddressChange);
if (!btle_instance)
return;
btle_instance->OnLEDeviceAddressChange(
mojom::BluetoothAddress::From(old_address),
mojom::BluetoothAddress::From(new_address));
}
void ArcBluetoothBridge::DevicePairedChanged(BluetoothAdapter* adapter,
BluetoothDevice* device,
bool new_paired_status) {
if (!arc_bridge_service_->bluetooth()->IsConnected())
return;
DCHECK(adapter);
DCHECK(device);
mojom::BluetoothAddressPtr addr =
mojom::BluetoothAddress::From(device->GetAddress());
if (new_paired_status) {
// OnBondStateChanged must be called with BluetoothBondState::BONDING to
// make sure the bond state machine on Android is ready to take the
// pair-done event. Otherwise the pair-done event will be dropped as an
// invalid change of paired status.
OnPairing(addr->Clone());
OnPairedDone(std::move(addr));
} else {
OnForgetDone(std::move(addr));
}
}
void ArcBluetoothBridge::DeviceMTUChanged(BluetoothAdapter* adapter,
BluetoothDevice* device,
uint16_t mtu) {
if (!arc_bridge_service_->bluetooth()->IsConnected())
return;
auto* bluetooth_instance = ARC_GET_INSTANCE_FOR_METHOD(
arc_bridge_service_->bluetooth(), OnMTUReceived);
if (!device->IsConnected() || bluetooth_instance == nullptr)
return;
bluetooth_instance->OnMTUReceived(
mojom::BluetoothAddress::From(device->GetAddress()), mtu);
}
void ArcBluetoothBridge::DeviceAdvertisementReceived(
BluetoothAdapter* adapter,
BluetoothDevice* device,
int16_t rssi,
const std::vector<uint8_t>& eir) {
if (!arc_bridge_service_->bluetooth()->IsConnected())
return;
mojom::BluetoothAddressPtr addr =
mojom::BluetoothAddress::From(device->GetAddress());
if ((IsDiscoveringOrScanning() &&
scanned_devices_.insert(device->GetAddress()).second) ||
scanned_devices_.contains(device->GetAddress())) {
auto* bluetooth_instance = ARC_GET_INSTANCE_FOR_METHOD(
arc_bridge_service_->bluetooth(), OnLEDeviceFound);
if (bluetooth_instance) {
bluetooth_instance->OnLEDeviceFound(std::move(addr), rssi, eir);
}
}
}
void ArcBluetoothBridge::DeviceConnectedStateChanged(BluetoothAdapter* adapter,
BluetoothDevice* device,
bool is_now_connected) {
if (!arc_bridge_service_->bluetooth()->IsConnected())
return;
const std::string addr = device->GetAddress();
// If this event is about 1) an device supports LE becomes disconnected and 2)
// we are holding the connection object for this device, we need to remove
// this object and notify Android.
bool support_le = device->GetType() & device::BLUETOOTH_TRANSPORT_LE;
auto it = gatt_connections_.find(addr);
if (support_le && it != gatt_connections_.end() && !is_now_connected)
OnGattDisconnected(mojom::BluetoothAddress::From(addr));
auto* bluetooth_instance = ARC_GET_INSTANCE_FOR_METHOD(
arc_bridge_service_->bluetooth(), OnConnectionStateChanged);
if (!bluetooth_instance)
return;
bluetooth_instance->OnConnectionStateChanged(
mojom::BluetoothAddress::From(addr), device->GetType(), is_now_connected);
}
void ArcBluetoothBridge::DeviceRemoved(BluetoothAdapter* adapter,
BluetoothDevice* device) {
if (!arc_bridge_service_->bluetooth()->IsConnected())
return;
DCHECK(adapter);
DCHECK(device);
std::string address = device->GetAddress();
if (gatt_connections_.find(address) != gatt_connections_.end())
OnGattDisconnected(mojom::BluetoothAddress::From(address));
OnForgetDone(mojom::BluetoothAddress::From(address));
}
void ArcBluetoothBridge::OnGetServiceRecordsFinished(
mojom::BluetoothAddressPtr remote_addr,
const BluetoothUUID& target_uuid,
const std::vector<bluez::BluetoothServiceRecordBlueZ>& records_bluez) {
// TODO(b/288866953): ARCVM crashes if records are empty
if (records_bluez.size() == 0) {
return;
}
auto* sdp_bluetooth_instance = ARC_GET_INSTANCE_FOR_METHOD(
arc_bridge_service_->bluetooth(), OnGetSdpRecords);
if (!sdp_bluetooth_instance) {
LOG(ERROR) << "Could not get bluetooth instance to return SDP records";
return;
}
std::vector<mojom::BluetoothSdpRecordPtr> records;
for (const auto& r : records_bluez) {
records.push_back(mojom::BluetoothSdpRecord::From(r));
}
sdp_bluetooth_instance->OnGetSdpRecords(mojom::BluetoothStatus::SUCCESS,
std::move(remote_addr), target_uuid,
std::move(records));
}
void ArcBluetoothBridge::OnGetServiceRecordsError(
mojom::BluetoothAddressPtr remote_addr,
const BluetoothUUID& target_uuid,
bluez::BluetoothServiceRecordBlueZ::ErrorCode error_code) {
auto* sdp_bluetooth_instance = ARC_GET_INSTANCE_FOR_METHOD(
arc_bridge_service_->bluetooth(), OnGetSdpRecords);
if (!sdp_bluetooth_instance) {
LOG(ERROR) << "Could not get bluetooth instance to return SDP error";
return;
}
mojom::BluetoothStatus status;
switch (error_code) {
case bluez::BluetoothServiceRecordBlueZ::ErrorCode::ERROR_ADAPTER_NOT_READY:
status = mojom::BluetoothStatus::NOT_READY;
break;
case bluez::BluetoothServiceRecordBlueZ::ErrorCode::
ERROR_DEVICE_DISCONNECTED:
status = mojom::BluetoothStatus::RMT_DEV_DOWN;
break;
default:
status = mojom::BluetoothStatus::FAIL;
break;
}
sdp_bluetooth_instance->OnGetSdpRecords(
status, std::move(remote_addr), target_uuid,
std::vector<mojom::BluetoothSdpRecordPtr>());
}
void ArcBluetoothBridge::GattServiceAdded(BluetoothAdapter* adapter,
BluetoothDevice* device,
BluetoothRemoteGattService* service) {
if (!arc_bridge_service_->bluetooth()->IsConnected())
return;
// Placeholder for GATT client functionality
GattServiceChanged(adapter, service);
}
void ArcBluetoothBridge::GattServiceRemoved(
BluetoothAdapter* adapter,
BluetoothDevice* device,
BluetoothRemoteGattService* service) {
if (!arc_bridge_service_->bluetooth()->IsConnected())
return;
// Placeholder for GATT client functionality
GattServiceChanged(adapter, service);
}
void ArcBluetoothBridge::GattServicesDiscovered(BluetoothAdapter* adapter,
BluetoothDevice* device) {
if (!arc_bridge_service_->bluetooth()->IsConnected())
return;
auto* btle_instance = ARC_GET_INSTANCE_FOR_METHOD(
arc_bridge_service_->bluetooth(), OnSearchComplete);
if (!btle_instance)
return;
mojom::BluetoothAddressPtr addr =
mojom::BluetoothAddress::From(device->GetAddress());
btle_instance->OnSearchComplete(std::move(addr),
mojom::BluetoothGattStatus::GATT_SUCCESS);
}
void ArcBluetoothBridge::GattDiscoveryCompleteForService(
BluetoothAdapter* adapter,
BluetoothRemoteGattService* service) {
if (!arc_bridge_service_->bluetooth()->IsConnected())
return;
// Placeholder for GATT client functionality
}
void ArcBluetoothBridge::GattNeedsDiscovery(BluetoothDevice* device) {
if (!arc_bridge_service_->bluetooth()->IsConnected()) {
return;
}
// This is a bit of a misnomer from ARC side: OnServiceChanged needs to be
// called when we get the signal that something is changed on the peer side,
// so ARC can start to re-discover everything again.
// However, the GattServiceChanged below indicates we have updated a service,
// so it doesn't actually mean ARC needs to re-discover everything.
auto* btle_instance = ARC_GET_INSTANCE_FOR_METHOD(
arc_bridge_service_->bluetooth(), OnServiceChanged);
if (!btle_instance) {
return;
}
btle_instance->OnServiceChanged(
mojom::BluetoothAddress::From(device->GetAddress()));
}
// TODO(b/284429795) This is wrong. See GattNeedsDiscovery above.
void ArcBluetoothBridge::GattServiceChanged(
BluetoothAdapter* adapter,
BluetoothRemoteGattService* service) {
if (!arc_bridge_service_->bluetooth()->IsConnected())
return;
BluetoothDevice* device = service->GetDevice();
if (!device)
return;
auto* btle_instance = ARC_GET_INSTANCE_FOR_METHOD(
arc_bridge_service_->bluetooth(), OnServiceChanged);
if (!btle_instance)
return;
btle_instance->OnServiceChanged(
mojom::BluetoothAddress::From(device->GetAddress()));
}
void ArcBluetoothBridge::GattCharacteristicAdded(
BluetoothAdapter* adapter,
BluetoothRemoteGattCharacteristic* characteristic) {
if (!arc_bridge_service_->bluetooth()->IsConnected())
return;
// Placeholder for GATT client functionality
}
void ArcBluetoothBridge::GattCharacteristicRemoved(
BluetoothAdapter* adapter,
BluetoothRemoteGattCharacteristic* characteristic) {
if (!arc_bridge_service_->bluetooth()->IsConnected())
return;
// Placeholder for GATT client functionality
}
void ArcBluetoothBridge::GattDescriptorAdded(
BluetoothAdapter* adapter,
BluetoothRemoteGattDescriptor* descriptor) {
if (!arc_bridge_service_->bluetooth()->IsConnected())
return;
// Placeholder for GATT client functionality
}
void ArcBluetoothBridge::GattDescriptorRemoved(
BluetoothAdapter* adapter,
BluetoothRemoteGattDescriptor* descriptor) {
if (!arc_bridge_service_->bluetooth()->IsConnected())
return;
// Placeholder for GATT client functionality
}
void ArcBluetoothBridge::GattCharacteristicValueChanged(
BluetoothAdapter* adapter,
BluetoothRemoteGattCharacteristic* characteristic,
const std::vector<uint8_t>& value) {
if (!arc_bridge_service_->bluetooth()->IsConnected())
return;
auto* btle_instance = ARC_GET_INSTANCE_FOR_METHOD(
arc_bridge_service_->bluetooth(), OnGattNotify);
if (!btle_instance)
return;
const std::optional<uint16_t> char_inst_id =
ConvertGattIdentifierToId(characteristic->GetIdentifier());
if (!char_inst_id)
return;
BluetoothRemoteGattService* service = characteristic->GetService();
const std::optional<uint16_t> service_inst_id =
ConvertGattIdentifierToId(service->GetIdentifier());
if (!service_inst_id)
return;
BluetoothDevice* device = service->GetDevice();
mojom::BluetoothAddressPtr address =
mojom::BluetoothAddress::From(device->GetAddress());
mojom::BluetoothGattServiceIDPtr service_id =
mojom::BluetoothGattServiceID::New();
service_id->is_primary = service->IsPrimary();
service_id->id = mojom::BluetoothGattID::New();
service_id->id->instance_id = *service_inst_id;
// TODO(b/191129417) remove once ARC++ handles new field
service_id->id->deprecated_inst_id = *service_inst_id;
service_id->id->uuid = service->GetUUID();
mojom::BluetoothGattIDPtr char_id = mojom::BluetoothGattID::New();
char_id->instance_id = *char_inst_id;
// TODO(b/191129417) remove once ARC++ handles new field
char_id->deprecated_inst_id = *char_inst_id;
char_id->uuid = characteristic->GetUUID();
btle_instance->OnGattNotify(std::move(address), std::move(service_id),
std::move(char_id), true /* is_notify */, value);
}
void ArcBluetoothBridge::GattDescriptorValueChanged(
BluetoothAdapter* adapter,
BluetoothRemoteGattDescriptor* descriptor,
const std::vector<uint8_t>& value) {
if (!arc_bridge_service_->bluetooth()->IsConnected())
return;
// Placeholder for GATT client functionality
}
template <class LocalGattAttribute>
void ArcBluetoothBridge::OnGattAttributeReadRequest(
const BluetoothDevice* device,
const LocalGattAttribute* attribute,
int offset,
mojom::BluetoothGattDBAttributeType attribute_type,
ValueCallback callback) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
auto* bluetooth_instance = ARC_GET_INSTANCE_FOR_METHOD(
arc_bridge_service_->bluetooth(), RequestGattRead);
if (!bluetooth_instance || !IsGattOffsetValid(offset)) {
std::move(callback).Run(BluetoothGattService::GattErrorCode::kFailed,
/*value=*/std::vector<uint8_t>());
return;
}
DCHECK(gatt_handle_.find(attribute->GetIdentifier()) != gatt_handle_.end());
bluetooth_instance->RequestGattRead(
mojom::BluetoothAddress::From(device->GetAddress()),
gatt_handle_[attribute->GetIdentifier()], offset, false /* is_long */,
attribute_type, base::BindOnce(&OnGattServerRead, std::move(callback)));
}
void ArcBluetoothBridge::OnGattServerPrepareWrite(
mojom::BluetoothAddressPtr addr,
bool has_subsequent_write,
base::OnceClosure success_callback,
ErrorCallback error_callback,
mojom::BluetoothGattStatus status) {
bool success = (status == mojom::BluetoothGattStatus::GATT_SUCCESS);
if (success && has_subsequent_write) {
std::move(success_callback).Run();
return;
}
auto* bluetooth_instance = ARC_GET_INSTANCE_FOR_METHOD(
arc_bridge_service_->bluetooth(), RequestGattExecuteWrite);
if (bluetooth_instance == nullptr) {
std::move(error_callback).Run();
return;
}
if (!success) {
auto split_callback = base::SplitOnceCallback(std::move(error_callback));
success_callback = std::move(split_callback.first);
error_callback = std::move(split_callback.second);
}
bluetooth_instance->RequestGattExecuteWrite(
std::move(addr), success,
base::BindOnce(&OnGattServerWrite, std::move(success_callback),
std::move(error_callback)));
}
template <class LocalGattAttribute>
void ArcBluetoothBridge::OnGattAttributeWriteRequest(
const BluetoothDevice* device,
const LocalGattAttribute* attribute,
const std::vector<uint8_t>& value,
int offset,
mojom::BluetoothGattDBAttributeType attribute_type,
bool is_prepare,
bool has_subsequent_write,
base::OnceClosure success_callback,
ErrorCallback error_callback) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
auto* bluetooth_instance = ARC_GET_INSTANCE_FOR_METHOD(
arc_bridge_service_->bluetooth(), RequestGattWrite);
if (!bluetooth_instance || !IsGattOffsetValid(offset)) {
std::move(error_callback).Run();
return;
}
GattStatusCallback callback =
is_prepare
? base::BindOnce(&ArcBluetoothBridge::OnGattServerPrepareWrite,
weak_factory_.GetWeakPtr(),
mojom::BluetoothAddress::From(device->GetAddress()),
has_subsequent_write, std::move(success_callback),
std::move(error_callback))
: base::BindOnce(&OnGattServerWrite, std::move(success_callback),
std::move(error_callback));
DCHECK(gatt_handle_.find(attribute->GetIdentifier()) != gatt_handle_.end());
bluetooth_instance->RequestGattWrite(
mojom::BluetoothAddress::From(device->GetAddress()),
gatt_handle_[attribute->GetIdentifier()], offset, value, attribute_type,
is_prepare, std::move(callback));
}
void ArcBluetoothBridge::OnCharacteristicReadRequest(
const BluetoothDevice* device,
const BluetoothLocalGattCharacteristic* characteristic,
int offset,
ValueCallback callback) {
OnGattAttributeReadRequest(
device, characteristic, offset,
mojom::BluetoothGattDBAttributeType::BTGATT_DB_CHARACTERISTIC,
std::move(callback));
}
void ArcBluetoothBridge::OnCharacteristicWriteRequest(
const BluetoothDevice* device,
const BluetoothLocalGattCharacteristic* characteristic,
const std::vector<uint8_t>& value,
int offset,
base::OnceClosure callback,
ErrorCallback error_callback) {
OnGattAttributeWriteRequest(
device, characteristic, value, offset,
mojom::BluetoothGattDBAttributeType::BTGATT_DB_CHARACTERISTIC,
/* is_prepare = */ false, /* has_subsequent_write, = */ false,
std::move(callback), std::move(error_callback));
}
void ArcBluetoothBridge::OnCharacteristicPrepareWriteRequest(
const BluetoothDevice* device,
const BluetoothLocalGattCharacteristic* characteristic,
const std::vector<uint8_t>& value,
int offset,
bool has_subsequent_write,
base::OnceClosure callback,
ErrorCallback error_callback) {
OnGattAttributeWriteRequest(
device, characteristic, value, offset,
mojom::BluetoothGattDBAttributeType::BTGATT_DB_CHARACTERISTIC,
/* is_prepare = */ true, has_subsequent_write, std::move(callback),
std::move(error_callback));
}
void ArcBluetoothBridge::OnDescriptorReadRequest(
const BluetoothDevice* device,
const BluetoothLocalGattDescriptor* descriptor,
int offset,
ValueCallback callback) {
OnGattAttributeReadRequest(
device, descriptor, offset,
mojom::BluetoothGattDBAttributeType::BTGATT_DB_DESCRIPTOR,
std::move(callback));
}
void ArcBluetoothBridge::OnDescriptorWriteRequest(
const BluetoothDevice* device,
const BluetoothLocalGattDescriptor* descriptor,
const std::vector<uint8_t>& value,
int offset,
base::OnceClosure callback,
ErrorCallback error_callback) {
OnGattAttributeWriteRequest(
device, descriptor, value, offset,
mojom::BluetoothGattDBAttributeType::BTGATT_DB_DESCRIPTOR,
/* is_prepare = */ false, /* has_subsequent_write = */ false,
std::move(callback), std::move(error_callback));
}
void ArcBluetoothBridge::OnNotificationsStart(
const BluetoothDevice* device,
device::BluetoothGattCharacteristic::NotificationType notification_type,
const BluetoothLocalGattCharacteristic* characteristic) {
const BluetoothLocalGattDescriptor* cccd = FindCCCD(characteristic);
if (cccd == nullptr)
return;
OnDescriptorWriteRequest(
device, cccd,
MakeCCCDValue(notification_type ==
device::BluetoothRemoteGattCharacteristic::
NotificationType::kNotification
? ENABLE_NOTIFICATION_VALUE
: ENABLE_INDICATION_VALUE),
0, base::DoNothing(), base::DoNothing());
}
void ArcBluetoothBridge::OnNotificationsStop(
const BluetoothDevice* device,
const BluetoothLocalGattCharacteristic* characteristic) {
const BluetoothLocalGattDescriptor* cccd = FindCCCD(characteristic);
if (cccd == nullptr)
return;
OnDescriptorWriteRequest(device, cccd,
MakeCCCDValue(DISABLE_NOTIFICATION_VALUE), 0,
base::DoNothing(), base::DoNothing());
}
void ArcBluetoothBridge::OnDeviceFound(
device::BluetoothLowEnergyScanSession* scan_session,
device::BluetoothDevice* device) {
DeviceAdded(bluetooth_adapter_.get(), device);
}
void ArcBluetoothBridge::OnDeviceLost(
device::BluetoothLowEnergyScanSession* scan_session,
device::BluetoothDevice* device) {}
void ArcBluetoothBridge::OnSessionStarted(
device::BluetoothLowEnergyScanSession* scan_session,
std::optional<device::BluetoothLowEnergyScanSession::ErrorCode>
error_code) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
if (error_code) {
LOG(WARNING) << "failed to start LE scan, error_code = "
<< static_cast<int>(error_code.value());
ResetLEScanSession();
} else {
StartLEScanOffTimer();
}
discovery_queue_.Pop();
}
void ArcBluetoothBridge::OnSessionInvalidated(
device::BluetoothLowEnergyScanSession* scan_session) {
LOG(WARNING) << "LE scan session was invalidated";
ResetLEScanSession();
}
void ArcBluetoothBridge::EnableAdapter(EnableAdapterCallback callback) {
DCHECK(bluetooth_adapter_);
if (IsPowerChangeInitiatedByLocal(AdapterPowerState::TURN_ON)) {
BLUETOOTH_LOG(EVENT) << "Received a request to enable adapter (local)";
DequeueLocalPowerChange(AdapterPowerState::TURN_ON);
} else {
BLUETOOTH_LOG(EVENT) << "Received a request to enable adapter (remote)";
if (!bluetooth_adapter_->IsPowered()) {
EnqueueRemotePowerChange(AdapterPowerState::TURN_ON, std::move(callback));
return;
}
}
OnPoweredOn(std::move(callback), false /* save_user_pref */);
}
void ArcBluetoothBridge::DisableAdapter(DisableAdapterCallback callback) {
DCHECK(bluetooth_adapter_);
if (IsPowerChangeInitiatedByLocal(AdapterPowerState::TURN_OFF)) {
BLUETOOTH_LOG(EVENT) << "Received a request to disable adapter (local)";
DequeueLocalPowerChange(AdapterPowerState::TURN_OFF);
} else {
BLUETOOTH_LOG(EVENT) << "Received a request to disable adapter (remote)";
// Silently ignore any request to turn off Bluetooth from Android.
// Android will still receive the success callback.
// (https://crbug.com/851097)
}
OnPoweredOff(std::move(callback), false /* save_user_pref */);
}
void ArcBluetoothBridge::GetAdapterProperty(mojom::BluetoothPropertyType type) {
DCHECK(bluetooth_adapter_);
auto* bluetooth_instance = ARC_GET_INSTANCE_FOR_METHOD(
arc_bridge_service_->bluetooth(), OnAdapterProperties);
if (!bluetooth_instance)
return;
std::vector<mojom::BluetoothPropertyPtr> properties =
GetAdapterProperties(type);
bluetooth_instance->OnAdapterProperties(mojom::BluetoothStatus::SUCCESS,
std::move(properties));
}
void ArcBluetoothBridge::OnSetDiscoverable(bool discoverable,
bool success,
uint32_t timeout) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
if (success && discoverable && timeout > 0) {
discoverable_off_timer_.Start(
FROM_HERE, base::Seconds(timeout),
base::BindOnce(&ArcBluetoothBridge::SetDiscoverable,
weak_factory_.GetWeakPtr(), false, 0));
}
auto status =
success ? mojom::BluetoothStatus::SUCCESS : mojom::BluetoothStatus::FAIL;
OnSetAdapterProperty(status, GetDiscoveryTimeoutProperty(timeout));
}
// Set discoverable state to on / off.
// In case of turning on, start timer to turn it back off in |timeout| seconds.
void ArcBluetoothBridge::SetDiscoverable(bool discoverable, uint32_t timeout) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
DCHECK(bluetooth_adapter_);
bool currently_discoverable = bluetooth_adapter_->IsDiscoverable();
if (!discoverable && !currently_discoverable)
return;
if (discoverable && currently_discoverable) {
if (base::Seconds(timeout) > discoverable_off_timer_.GetCurrentDelay()) {
// Restart discoverable_off_timer_ if new timeout is greater
OnSetDiscoverable(true, true, timeout);
} else {
// Just send message to Android if new timeout is lower.
OnSetAdapterProperty(mojom::BluetoothStatus::SUCCESS,
GetDiscoveryTimeoutProperty(timeout));
}
return;
}
bluetooth_adapter_->SetDiscoverable(
discoverable,
base::BindOnce(&ArcBluetoothBridge::OnSetDiscoverable,
weak_factory_.GetWeakPtr(), discoverable, true, timeout),
base::BindOnce(&ArcBluetoothBridge::OnSetDiscoverable,
weak_factory_.GetWeakPtr(), discoverable, false, timeout));
}
void ArcBluetoothBridge::OnSetAdapterProperty(
mojom::BluetoothStatus status,
mojom::BluetoothPropertyPtr property) {
auto* bluetooth_instance = ARC_GET_INSTANCE_FOR_METHOD(
arc_bridge_service_->bluetooth(), OnAdapterProperties);
if (!bluetooth_instance)
return;
std::vector<arc::mojom::BluetoothPropertyPtr> properties;
properties.push_back(std::move(property));
bluetooth_instance->OnAdapterProperties(status, std::move(properties));
}
void ArcBluetoothBridge::SetAdapterProperty(
mojom::BluetoothPropertyPtr property) {
DCHECK(bluetooth_adapter_);
if (property->is_discovery_timeout()) {
uint32_t discovery_timeout = property->get_discovery_timeout();
discoverable_off_timeout_ = std::make_optional(discovery_timeout);
OnSetAdapterProperty(mojom::BluetoothStatus::SUCCESS, std::move(property));
} else if (property->is_bdname()) {
auto property_clone = property.Clone();
const std::string bdname = property->get_bdname();
bluetooth_adapter_->SetName(
bdname,
base::BindOnce(&ArcBluetoothBridge::OnSetAdapterProperty,
weak_factory_.GetWeakPtr(),
mojom::BluetoothStatus::SUCCESS, std::move(property)),
base::BindOnce(&ArcBluetoothBridge::OnSetAdapterProperty,
weak_factory_.GetWeakPtr(), mojom::BluetoothStatus::FAIL,
std::move(property_clone)));
} else if (property->is_adapter_scan_mode()) {
// Only set the BT scan mode to discoverable if requested and Android has
// set a discovery timeout previously.
if (property->get_adapter_scan_mode() ==
mojom::BluetoothScanMode::CONNECTABLE_DISCOVERABLE &&
discoverable_off_timeout_.has_value()) {
SetDiscoverable(/*discoverable=*/true, discoverable_off_timeout_.value());
} else {
SetDiscoverable(/*discoverable=*/false, /*timeout=*/0);
}
OnSetAdapterProperty(mojom::BluetoothStatus::SUCCESS, std::move(property));
} else {
// Android does not set any other property type.
OnSetAdapterProperty(mojom::BluetoothStatus::UNSUPPORTED,
std::move(property));
}
}
void ArcBluetoothBridge::StartDiscovery() {
discovery_queue_.Push(base::BindOnce(&ArcBluetoothBridge::StartDiscoveryImpl,
weak_factory_.GetWeakPtr()));
}
void ArcBluetoothBridge::StartDiscoveryImpl() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
if (!bluetooth_adapter_) {
LOG(DFATAL) << "Bluetooth adapter does not exist.";
return;
}
if (discovery_session_) {
LOG(ERROR) << "Discovery session already running; Reset timeout.";
discovery_off_timer_.Start(
FROM_HERE, kDiscoveryTimeout,
base::BindOnce(&ArcBluetoothBridge::CancelDiscovery,
weak_factory_.GetWeakPtr()));
discovered_devices_.clear();
discovery_queue_.Pop();
return;
}
bluetooth_adapter_->StartDiscoverySession(
kScanClientName,
base::BindOnce(&ArcBluetoothBridge::OnDiscoveryStarted,
weak_factory_.GetWeakPtr()),
base::BindOnce(&ArcBluetoothBridge::OnDiscoveryError,
weak_factory_.GetWeakPtr()));
}
void ArcBluetoothBridge::CancelDiscovery() {
discovery_queue_.Push(base::BindOnce(&ArcBluetoothBridge::CancelDiscoveryImpl,
weak_factory_.GetWeakPtr()));
}
void ArcBluetoothBridge::StartLEScanImpl() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
if (!bluetooth_adapter_) {
LOG(DFATAL) << "Bluetooth adapter does not exist.";
return;
}
if (le_scan_session_) {
LOG(ERROR) << "Discovery session for LE scan already running.";
StartLEScanOffTimer();
scanned_devices_.clear();
discovery_queue_.Pop();
return;
}
bluetooth_adapter_->StartDiscoverySessionWithFilter(
std::make_unique<BluetoothDiscoveryFilter>(
device::BLUETOOTH_TRANSPORT_LE),
kScanClientName,
base::BindOnce(&ArcBluetoothBridge::OnLEScanStarted,
weak_factory_.GetWeakPtr()),
base::BindOnce(&ArcBluetoothBridge::OnLEScanError,
weak_factory_.GetWeakPtr()));
}
void ArcBluetoothBridge::CancelDiscoveryImpl() {
discovery_off_timer_.Stop();
discovery_session_ = nullptr;
auto* bluetooth_instance = ARC_GET_INSTANCE_FOR_METHOD(
arc_bridge_service_->bluetooth(), OnDiscoveryStateChanged);
if (bluetooth_instance != nullptr) {
bluetooth_instance->OnDiscoveryStateChanged(
mojom::BluetoothDiscoveryState::STOPPED);
}
discovery_queue_.Pop();
}
void ArcBluetoothBridge::StartLEScanOffTimer() {
// TODO(b/152463320): Android expects to stop the LE scan by itself but not by
// a timer automatically. We set this timer here due to the potential
// complains about the power consumption since we cannot set scan parameters
// and filters now.
le_scan_off_timer_.Start(
FROM_HERE, kDiscoveryTimeout,
base::BindOnce(&ArcBluetoothBridge::StopLEScanByTimer,
weak_factory_.GetWeakPtr()));
}
void ArcBluetoothBridge::ResetLEScanSession() {
le_scan_session_ = nullptr;
}
bool ArcBluetoothBridge::IsDiscoveringOrScanning() {
return discovery_session_ || le_scan_session_;
}
void ArcBluetoothBridge::StopLEScanImpl() {
le_scan_off_timer_.Stop();
ResetLEScanSession();
discovery_queue_.Pop();
}
void ArcBluetoothBridge::OnPoweredOn(
ArcBluetoothBridge::AdapterStateCallback callback,
bool save_user_pref) {
// Saves the power state to user preference only if Android initiated it.
if (save_user_pref)
SetPrimaryUserBluetoothPowerSetting(true);
std::move(callback).Run(mojom::BluetoothAdapterState::ON);
// Sends cached devices to Android after its Bluetooth stack is ready. We
// should do this after the above callback since Android will clear its
// device cache after receiving the "ON" state of adapter.
SendCachedDevices();
// Allow derived classes to perform additional logic if desired.
HandlePoweredOn();
}
void ArcBluetoothBridge::OnPoweredOff(
ArcBluetoothBridge::AdapterStateCallback callback,
bool save_user_pref) {
// Saves the power state to user preference only if Android initiated it.
if (save_user_pref)
SetPrimaryUserBluetoothPowerSetting(false);
std::move(callback).Run(mojom::BluetoothAdapterState::OFF);
}
void ArcBluetoothBridge::OnPoweredError(
ArcBluetoothBridge::AdapterStateCallback callback) const {
LOG(WARNING) << "failed to change power state";
std::move(callback).Run(bluetooth_adapter_->IsPowered()
? mojom::BluetoothAdapterState::ON
: mojom::BluetoothAdapterState::OFF);
}
void ArcBluetoothBridge::OnDiscoveryStarted(
std::unique_ptr<BluetoothDiscoverySession> session) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
// We need to set timer to turn device discovery off because of the difference
// between Android API (do device discovery once) and Chrome API (do device
// discovery until user turns it off).
discovery_off_timer_.Start(
FROM_HERE, kDiscoveryTimeout,
base::BindOnce(&ArcBluetoothBridge::CancelDiscovery,
weak_factory_.GetWeakPtr()));
discovery_session_ = std::move(session);
discovered_devices_.clear();
auto* bluetooth_instance = ARC_GET_INSTANCE_FOR_METHOD(
arc_bridge_service_->bluetooth(), OnDiscoveryStateChanged);
if (bluetooth_instance != nullptr) {
bluetooth_instance->OnDiscoveryStateChanged(
mojom::BluetoothDiscoveryState::STARTED);
}
discovery_queue_.Pop();
}
void ArcBluetoothBridge::OnLEScanStarted(
std::unique_ptr<BluetoothDiscoverySession> session) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
StartLEScanOffTimer();
le_scan_session_ = std::move(session);
scanned_devices_.clear();
// Android doesn't need a callback for discovery started event for a LE scan.
discovery_queue_.Pop();
}
void ArcBluetoothBridge::CreateBond(mojom::BluetoothAddressPtr addr,
int32_t transport) {
std::string addr_str = addr->To<std::string>();
BluetoothDevice* device = bluetooth_adapter_->GetDevice(addr_str);
if (!device || !device->IsPairable()) {
VLOG(1) << __func__ << ": device " << addr_str
<< " is no longer valid or pairable";
OnPairedError(std::move(addr), BluetoothDevice::ERROR_FAILED);
return;
}
if (device->IsPaired()) {
OnPairedDone(std::move(addr));
return;
}
devices_paired_by_arc_.insert(addr_str);
// BluetoothPairingDialog will automatically pair the device and handle all
// the incoming pairing requests.
ash::BluetoothPairingDialog::ShowDialog(device->GetAddress());
}
void ArcBluetoothBridge::RemoveBond(mojom::BluetoothAddressPtr addr) {
// Forget the device if it is no longer valid or not even paired.
BluetoothDevice* device =
bluetooth_adapter_->GetDevice(addr->To<std::string>());
if (!device || !device->IsPaired()) {
OnForgetDone(std::move(addr));
return;
}
// If unpairing finished successfully, DevicePairedChanged will notify Android
// on paired state change event, so DoNothing is passed as a success callback.
device->Forget(base::DoNothing(),
base::BindOnce(&ArcBluetoothBridge::OnForgetError,
weak_factory_.GetWeakPtr(), std::move(addr)));
}
void ArcBluetoothBridge::CancelBond(mojom::BluetoothAddressPtr addr) {
BluetoothDevice* device =
bluetooth_adapter_->GetDevice(addr->To<std::string>());
if (!device) {
OnForgetDone(std::move(addr));
return;
}
device->CancelPairing();
OnForgetDone(std::move(addr));
}
void ArcBluetoothBridge::GetConnectionState(
mojom::BluetoothAddressPtr addr,
GetConnectionStateCallback callback) {
if (!bluetooth_adapter_) {
std::move(callback).Run(false);
return;
}
BluetoothDevice* device =
bluetooth_adapter_->GetDevice(addr->To<std::string>());
if (!device) {
std::move(callback).Run(false);
return;
}
std::move(callback).Run(device->IsConnected());
}
void ArcBluetoothBridge::StartLEScan() {
discovery_queue_.Push(base::BindOnce(&ArcBluetoothBridge::StartLEScanImpl,
weak_factory_.GetWeakPtr()));
}
void ArcBluetoothBridge::StopLEScan() {
discovery_queue_.Push(base::BindOnce(&ArcBluetoothBridge::StopLEScanImpl,
weak_factory_.GetWeakPtr()));
}
void ArcBluetoothBridge::StopLEScanByTimer() {
// If the scan is stopped by the timer, it is possible that the following scan
// client in Android cannot start the scan successfully but that client will
// not get an error.
LOG(WARNING) << "The discovery session for LE scan is stopped by the timer";
discovery_queue_.Push(base::BindOnce(&ArcBluetoothBridge::StopLEScanImpl,
weak_factory_.GetWeakPtr()));
}
void ArcBluetoothBridge::OnGattConnectStateChanged(
mojom::BluetoothAddressPtr addr,
bool connected) const {
auto* btle_instance = ARC_GET_INSTANCE_FOR_METHOD(
arc_bridge_service_->bluetooth(), OnLEConnectionStateChange);
if (!btle_instance)
return;
DCHECK(addr);
btle_instance->OnLEConnectionStateChange(std::move(addr), connected);
}
void ArcBluetoothBridge::OnGattConnect(
mojom::BluetoothAddressPtr addr,
std::unique_ptr<BluetoothGattConnection> connection,
std::optional<BluetoothDevice::ConnectErrorCode> error_code) {
if (error_code.has_value()) {
LOG(WARNING) << "GattConnectError: error_code = " << error_code.value();
OnGattDisconnected(std::move(addr));
return;
}
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
const std::string addr_str = addr->To<std::string>();
GattConnection& conn = gatt_connections_[addr_str];
conn.state = GattConnection::ConnectionState::CONNECTED;
conn.connection = std::move(connection);
devices_paired_by_arc_.erase(addr_str);
OnGattConnectStateChanged(std::move(addr), true);
}
void ArcBluetoothBridge::OnGattDisconnected(mojom::BluetoothAddressPtr addr) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
if (gatt_connections_.erase(addr->To<std::string>()) == 0) {
LOG(WARNING) << "OnGattDisconnected called, "
<< "but no gatt connection was found";
return;
}
OnGattConnectStateChanged(std::move(addr), false);
}
void ArcBluetoothBridge::ConnectLEDevice(
mojom::BluetoothAddressPtr remote_addr) {
auto* bluetooth_instance = ARC_GET_INSTANCE_FOR_METHOD(
arc_bridge_service_->bluetooth(), OnLEConnectionStateChange);
if (!bluetooth_instance)
return;
std::string addr = remote_addr->To<std::string>();
BluetoothDevice* device = bluetooth_adapter_->GetDevice(addr);
if (!device) {
LOG(ERROR) << "Unknown device " << addr;
OnGattConnect(std::move(remote_addr),
/*connection=*/nullptr,
BluetoothDevice::ConnectErrorCode::ERROR_FAILED);
return;
}
auto it = gatt_connections_.find(addr);
if (it != gatt_connections_.end()) {
if (it->second.state == GattConnection::ConnectionState::CONNECTED) {
bluetooth_instance->OnLEConnectionStateChange(std::move(remote_addr),
true);
} else {
OnGattConnect(std::move(remote_addr),
/*connection=*/nullptr,
BluetoothDevice::ConnectErrorCode::ERROR_INPROGRESS);
}
return;
}
bool need_hard_disconnect =
devices_paired_by_arc_.find(addr) != devices_paired_by_arc_.end() ||
!device->IsConnected();
// Also pass disconnect callback in error case since it would be disconnected
// anyway.
gatt_connections_.emplace(
addr, GattConnection(GattConnection::ConnectionState::CONNECTING, nullptr,
need_hard_disconnect));
device->CreateGattConnection(
base::BindOnce(&ArcBluetoothBridge::OnGattConnect,
weak_factory_.GetWeakPtr(), std::move(remote_addr)));
}
void ArcBluetoothBridge::DisconnectLEDevice(
mojom::BluetoothAddressPtr remote_addr) {
auto* bluetooth_instance = ARC_GET_INSTANCE_FOR_METHOD(
arc_bridge_service_->bluetooth(), OnLEConnectionStateChange);
if (!bluetooth_instance)
return;
const std::string addr_str = remote_addr->To<std::string>();
BluetoothDevice* device = bluetooth_adapter_->GetDevice(addr_str);
const auto conn_itr = gatt_connections_.find(remote_addr->To<std::string>());
if (!device || !device->IsConnected() ||
conn_itr == gatt_connections_.end()) {
bluetooth_instance->OnLEConnectionStateChange(std::move(remote_addr),
false);
return;
}
if (conn_itr->second.need_hard_disconnect)
device->Disconnect(base::DoNothing(), base::DoNothing());
// Removes the connection object held by us and notifies Android.
OnGattDisconnected(std::move(remote_addr));
}
void ArcBluetoothBridge::SearchService(mojom::BluetoothAddressPtr remote_addr) {
auto* bluetooth_instance = ARC_GET_INSTANCE_FOR_METHOD(
arc_bridge_service_->bluetooth(), OnSearchComplete);
if (!bluetooth_instance)
return;
BluetoothDevice* device =
bluetooth_adapter_->GetDevice(remote_addr->To<std::string>());
if (!device) {
LOG(ERROR) << "Unknown device " << remote_addr->To<std::string>();
bluetooth_instance->OnSearchComplete(
std::move(remote_addr), mojom::BluetoothGattStatus::GATT_FAILURE);
return;
}
// Call the callback if discovery is completed
if (device->IsGattServicesDiscoveryComplete()) {
bluetooth_instance->OnSearchComplete(
std::move(remote_addr), mojom::BluetoothGattStatus::GATT_SUCCESS);
return;
}
// Discard result. Will call the callback when discovery is completed.
device->GetGattServices();
}
void ArcBluetoothBridge::GetGattDB(mojom::BluetoothAddressPtr remote_addr) {
auto* bluetooth_instance = ARC_GET_INSTANCE_FOR_METHOD(
arc_bridge_service_->bluetooth(), OnGetGattDB);
if (!bluetooth_instance)
return;
BluetoothDevice* device =
bluetooth_adapter_->GetDevice(remote_addr->To<std::string>());
std::vector<mojom::BluetoothGattDBElementPtr> db;
if (!device) {
LOG(ERROR) << "Unknown device " << remote_addr->To<std::string>();
bluetooth_instance->OnGetGattDB(std::move(remote_addr), std::move(db));
return;
}
for (auto* service : device->GetGattServices()) {
mojom::BluetoothGattDBElementPtr service_element = CreateGattDBElement(
service->IsPrimary()
? mojom::BluetoothGattDBAttributeType::BTGATT_DB_PRIMARY_SERVICE
: mojom::BluetoothGattDBAttributeType::BTGATT_DB_SECONDARY_SERVICE,
service);
if (!service_element)
continue;
const auto& characteristics = service->GetCharacteristics();
if (characteristics.size() > 0) {
const auto& descriptors = characteristics.back()->GetDescriptors();
const std::optional<uint16_t> start_handle =
ConvertGattIdentifierToId(characteristics.front()->GetIdentifier());
if (!start_handle)
continue;
const std::optional<uint16_t> end_handle = ConvertGattIdentifierToId(
descriptors.size() > 0 ? descriptors.back()->GetIdentifier()
: characteristics.back()->GetIdentifier());
if (!end_handle)
continue;
service_element->start_handle = *start_handle;
service_element->end_handle = *end_handle;
}
db.push_back(std::move(service_element));
for (auto* characteristic : characteristics) {
mojom::BluetoothGattDBElementPtr characteristic_element =
CreateGattDBElement(
mojom::BluetoothGattDBAttributeType::BTGATT_DB_CHARACTERISTIC,
characteristic);
if (!characteristic_element)
continue;
characteristic_element->properties = characteristic->GetProperties();
db.push_back(std::move(characteristic_element));
for (auto* descriptor : characteristic->GetDescriptors()) {
mojom::BluetoothGattDBElementPtr descriptor_element =
CreateGattDBElement(
mojom::BluetoothGattDBAttributeType::BTGATT_DB_DESCRIPTOR,
descriptor);
if (!descriptor_element)
continue;
db.push_back(std::move(descriptor_element));
}
}
}
bluetooth_instance->OnGetGattDB(std::move(remote_addr), std::move(db));
}
BluetoothRemoteGattCharacteristic* ArcBluetoothBridge::FindGattCharacteristic(
mojom::BluetoothAddressPtr remote_addr,
mojom::BluetoothGattServiceIDPtr service_id,
mojom::BluetoothGattIDPtr char_id) const {
DCHECK(remote_addr);
DCHECK(service_id);
DCHECK(char_id);
BluetoothDevice* device =
bluetooth_adapter_->GetDevice(remote_addr->To<std::string>());
if (!device)
return nullptr;
BluetoothRemoteGattService* service =
FindGattAttributeByUuid(device->GetGattServices(), service_id->id->uuid);
if (!service)
return nullptr;
return FindGattAttributeByUuid(service->GetCharacteristics(), char_id->uuid);
}
BluetoothRemoteGattDescriptor* ArcBluetoothBridge::FindGattDescriptor(
mojom::BluetoothAddressPtr remote_addr,
mojom::BluetoothGattServiceIDPtr service_id,
mojom::BluetoothGattIDPtr char_id,
mojom::BluetoothGattIDPtr desc_id) const {
BluetoothRemoteGattCharacteristic* characteristic = FindGattCharacteristic(
std::move(remote_addr), std::move(service_id), std::move(char_id));
if (!characteristic)
return nullptr;
return FindGattAttributeByUuid(characteristic->GetDescriptors(),
desc_id->uuid);
}
void ArcBluetoothBridge::SendBluetoothPoweredStateBroadcast(
AdapterPowerState powered) const {
auto* intent_instance = ARC_GET_INSTANCE_FOR_METHOD(
arc_bridge_service_->intent_helper(), SendBroadcast);
if (!intent_instance)
return;
base::Value::Dict extras;
extras.Set("enable", powered == AdapterPowerState::TURN_ON);
std::string extras_json;
bool write_success = base::JSONWriter::Write(extras, &extras_json);
DCHECK(write_success);
BLUETOOTH_LOG(EVENT) << "Sending Android intent to set power: "
<< (powered == AdapterPowerState::TURN_ON);
intent_instance->SendBroadcast(
ArcIntentHelperBridge::AppendStringToIntentHelperPackageName(
"SET_BLUETOOTH_STATE"),
kArcIntentHelperPackageName,
ArcIntentHelperBridge::AppendStringToIntentHelperPackageName(
"SettingsReceiver"),
extras_json);
}
void ArcBluetoothBridge::ReadGattCharacteristic(
mojom::BluetoothAddressPtr remote_addr,
mojom::BluetoothGattServiceIDPtr service_id,
mojom::BluetoothGattIDPtr char_id,
ReadGattCharacteristicCallback callback) {
BluetoothRemoteGattCharacteristic* characteristic = FindGattCharacteristic(
std::move(remote_addr), std::move(service_id), std::move(char_id));
if (!characteristic) {
// TODO(b/201737474): Investigate in what case this could happen.
LOG(ERROR) << "Requested GATT characteristic does not exist";
OnGattRead(std::move(callback),
device::BluetoothGattService::GattErrorCode::kFailed,
/*result=*/{});
return;
}
characteristic->ReadRemoteCharacteristic(
base::BindOnce(&OnGattRead, std::move(callback)));
}
void ArcBluetoothBridge::WriteGattCharacteristic(
mojom::BluetoothAddressPtr remote_addr,
mojom::BluetoothGattServiceIDPtr service_id,
mojom::BluetoothGattIDPtr char_id,
mojom::BluetoothGattValuePtr value,
bool prepare,
WriteGattCharacteristicCallback callback) {
BluetoothRemoteGattCharacteristic* characteristic = FindGattCharacteristic(
std::move(remote_addr), std::move(service_id), std::move(char_id));
if (!characteristic) {
BLUETOOTH_LOG(ERROR) << __func__
<< " failed to write GATT characteristic, "
"characteristic does not exist.";
std::move(callback).Run(mojom::BluetoothGattStatus::GATT_FAILURE);
return;
}
auto split_callback = base::SplitOnceCallback(std::move(callback));
if (prepare) {
characteristic->PrepareWriteRemoteCharacteristic(
value->value,
base::BindOnce(&OnGattOperationDone, std::move(split_callback.first)),
base::BindOnce(&OnGattOperationError,
std::move(split_callback.second)));
} else {
characteristic->DeprecatedWriteRemoteCharacteristic(
value->value,
base::BindOnce(&OnGattOperationDone, std::move(split_callback.first)),
base::BindOnce(&OnGattOperationError,
std::move(split_callback.second)));
}
}
void ArcBluetoothBridge::ReadGattDescriptor(
mojom::BluetoothAddressPtr remote_addr,
mojom::BluetoothGattServiceIDPtr service_id,
mojom::BluetoothGattIDPtr char_id,
mojom::BluetoothGattIDPtr desc_id,
ReadGattDescriptorCallback callback) {
BluetoothRemoteGattDescriptor* descriptor =
FindGattDescriptor(std::move(remote_addr), std::move(service_id),
std::move(char_id), std::move(desc_id));
if (!descriptor) {
BLUETOOTH_LOG(ERROR)
<< __func__
<< " failed to read GATT descriptor, descriptor does not exist.";
arc::mojom::BluetoothGattValuePtr gatt_value =
mojom::BluetoothGattValue::New();
gatt_value->status = mojom::BluetoothGattStatus::GATT_FAILURE;
std::move(callback).Run(std::move(gatt_value));
return;
}
descriptor->ReadRemoteDescriptor(
base::BindOnce(&OnGattRead, std::move(callback)));
}
void ArcBluetoothBridge::WriteGattDescriptor(
mojom::BluetoothAddressPtr remote_addr,
mojom::BluetoothGattServiceIDPtr service_id,
mojom::BluetoothGattIDPtr char_id,
mojom::BluetoothGattIDPtr desc_id,
mojom::BluetoothGattValuePtr value,
WriteGattDescriptorCallback callback) {
BluetoothRemoteGattDescriptor* descriptor =
FindGattDescriptor(std::move(remote_addr), std::move(service_id),
std::move(char_id), std::move(desc_id));
if (!descriptor) {
BLUETOOTH_LOG(ERROR)
<< __func__
<< " failed to write GATT descriptor, descriptor does not exist.";
std::move(callback).Run(mojom::BluetoothGattStatus::GATT_FAILURE);
return;
}
if (value->value.empty()) {
std::move(callback).Run(mojom::BluetoothGattStatus::GATT_FAILURE);
return;
}
if (descriptor->GetUUID() !=
BluetoothGattDescriptor::ClientCharacteristicConfigurationUuid()) {
auto split_callback = base::SplitOnceCallback(std::move(callback));
descriptor->WriteRemoteDescriptor(
value->value,
base::BindOnce(&OnGattOperationDone, std::move(split_callback.first)),
base::BindOnce(&OnGattOperationError,
std::move(split_callback.second)));
return;
}
BluetoothRemoteGattCharacteristic* characteristic =
descriptor->GetCharacteristic();
std::string char_id_str = characteristic->GetIdentifier();
auto it = notification_session_.find(char_id_str);
if (it != notification_session_.end()) {
// Stop the previous session while keeping this client registered.
it->second.reset();
}
// If notification session does not exist, a write to gatt descriptor will
// only enable peer device to notify us, but our clients won't hear the change
// events. Though this use case is not typical, we should still allow the API
// to succeed since the public API doesn't disallow this
// (https://developer.android.com/reference/android/bluetooth/BluetoothGatt#writeDescriptor(android.bluetooth.BluetoothGattDescriptor)).
switch (value->value[0]) {
case DISABLE_NOTIFICATION_VALUE:
std::move(callback).Run(mojom::BluetoothGattStatus::GATT_SUCCESS);
return;
case ENABLE_NOTIFICATION_VALUE: {
auto split_callback = base::SplitOnceCallback(std::move(callback));
characteristic->StartNotifySession(
device::BluetoothGattCharacteristic::NotificationType::kNotification,
base::BindOnce(&ArcBluetoothBridge::OnGattNotifyStartDone,
weak_factory_.GetWeakPtr(),
std::move(split_callback.first),
std::move(char_id_str)),
base::BindOnce(&OnGattOperationError,
std::move(split_callback.second)));
return;
}
case ENABLE_INDICATION_VALUE: {
auto split_callback = base::SplitOnceCallback(std::move(callback));
characteristic->StartNotifySession(
device::BluetoothGattCharacteristic::NotificationType::kIndication,
base::BindOnce(&ArcBluetoothBridge::OnGattNotifyStartDone,
weak_factory_.GetWeakPtr(),
std::move(split_callback.first),
std::move(char_id_str)),
base::BindOnce(&OnGattOperationError,
std::move(split_callback.second)));
return;
}
default:
std::move(callback).Run(mojom::BluetoothGattStatus::GATT_FAILURE);
}
}
void ArcBluetoothBridge::ExecuteWrite(mojom::BluetoothAddressPtr remote_addr,
bool execute,
ExecuteWriteCallback callback) {
device::BluetoothDevice* device =
bluetooth_adapter_->GetDevice(remote_addr->To<std::string>());
if (device == nullptr) {
std::move(callback).Run(mojom::BluetoothGattStatus::GATT_FAILURE);
return;
}
auto split_callback = base::SplitOnceCallback(std::move(callback));
if (execute) {
device->ExecuteWrite(
base::BindOnce(&OnGattOperationDone, std::move(split_callback.first)),
base::BindOnce(&OnGattOperationError,
std::move(split_callback.second)));
} else {
device->AbortWrite(
base::BindOnce(&OnGattOperationDone, std::move(split_callback.first)),
base::BindOnce(&OnGattOperationError,
std::move(split_callback.second)));
}
}
void ArcBluetoothBridge::OnGattNotifyStartDone(
ArcBluetoothBridge::GattStatusCallback callback,
std::string char_string_id,
std::unique_ptr<BluetoothGattNotifySession> notify_session) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
// Hold on to |notify_session|. Destruction of |notify_session| is equivalent
// to stopping this session.
notification_session_[char_string_id] = std::move(notify_session);
std::move(callback).Run(mojom::BluetoothGattStatus::GATT_SUCCESS);
}
void ArcBluetoothBridge::RegisterForGattNotification(
mojom::BluetoothAddressPtr remote_addr,
mojom::BluetoothGattServiceIDPtr service_id,
mojom::BluetoothGattIDPtr char_id,
RegisterForGattNotificationCallback callback) {
BluetoothRemoteGattCharacteristic* characteristic = FindGattCharacteristic(
std::move(remote_addr), std::move(service_id), std::move(char_id));
if (characteristic == nullptr) {
LOG(WARNING) << __func__ << " Characteristic is not existed.";
std::move(callback).Run(mojom::BluetoothGattStatus::GATT_FAILURE);
return;
}
std::string char_id_str = characteristic->GetIdentifier();
// Create an empty notification session object - which will be fully
// instantiated by a future call to WriteGattDescriptor - if one does not yet
// exist. Note that the notification session object may have been created as
// a result of a previous call to WriteGattDescriptor, which can be left
// as-is.
if (!base::Contains(notification_session_, char_id_str)) {
notification_session_.emplace(char_id_str, nullptr);
}
std::move(callback).Run(mojom::BluetoothGattStatus::GATT_SUCCESS);
}
void ArcBluetoothBridge::DeregisterForGattNotification(
mojom::BluetoothAddressPtr remote_addr,
mojom::BluetoothGattServiceIDPtr service_id,
mojom::BluetoothGattIDPtr char_id,
DeregisterForGattNotificationCallback callback) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
BluetoothRemoteGattCharacteristic* characteristic = FindGattCharacteristic(
std::move(remote_addr), std::move(service_id), std::move(char_id));
if (characteristic == nullptr) {
LOG(WARNING) << __func__ << " Characteristic is not existed.";
std::move(callback).Run(mojom::BluetoothGattStatus::GATT_FAILURE);
return;
}
std::string char_id_str = characteristic->GetIdentifier();
auto it = notification_session_.find(char_id_str);
if (it == notification_session_.end()) {
LOG(WARNING) << "Notification session not found " << char_id_str;
std::move(callback).Run(mojom::BluetoothGattStatus::GATT_FAILURE);
return;
}
notification_session_.erase(it);
std::move(callback).Run(mojom::BluetoothGattStatus::GATT_SUCCESS);
}
void ArcBluetoothBridge::ReadRemoteRssi(mojom::BluetoothAddressPtr remote_addr,
ReadRemoteRssiCallback callback) {
BluetoothDevice* device =
bluetooth_adapter_->GetDevice(remote_addr->To<std::string>());
if (!device) {
std::move(callback).Run(mojom::kUnknownPower);
return;
}
if (device->IsConnected()) {
device->GetConnectionInfo(
base::BindOnce(&SendRssiOnGetConnectionInfoDone, std::move(callback)));
} else {
std::move(callback).Run(
device->GetInquiryRSSI().value_or(mojom::kUnknownPower));
}
}
bool ArcBluetoothBridge::IsGattServerAttributeHandleAvailable(int need) {
return gatt_server_attribute_next_handle_ + need <= kMaxGattAttributeHandle;
}
int32_t ArcBluetoothBridge::GetNextGattServerAttributeHandle() {
return IsGattServerAttributeHandleAvailable(1)
? ++gatt_server_attribute_next_handle_
: kInvalidGattAttributeHandle;
}
template <class LocalGattAttribute>
int32_t ArcBluetoothBridge::CreateGattAttributeHandle(
LocalGattAttribute* attribute) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
if (!attribute)
return kInvalidGattAttributeHandle;
int32_t handle = GetNextGattServerAttributeHandle();
if (handle == kInvalidGattAttributeHandle)
return kInvalidGattAttributeHandle;
const std::string& identifier = attribute->GetIdentifier();
gatt_identifier_[handle] = identifier;
gatt_handle_[identifier] = handle;
return handle;
}
void ArcBluetoothBridge::AddService(mojom::BluetoothGattServiceIDPtr service_id,
int32_t num_handles,
AddServiceCallback callback) {
if (!IsGattServerAttributeHandleAvailable(num_handles)) {
std::move(callback).Run(kInvalidGattAttributeHandle);
return;
}
base::WeakPtr<BluetoothLocalGattService> service =
bluetooth_adapter_->CreateLocalGattService(
service_id->id->uuid, service_id->is_primary, this /* delegate */);
std::move(callback).Run(CreateGattAttributeHandle(service.get()));
}
void ArcBluetoothBridge::AddCharacteristic(int32_t service_handle,
const BluetoothUUID& uuid,
int32_t properties,
int32_t permissions,
AddCharacteristicCallback callback) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
auto gatt_id = gatt_identifier_.find(service_handle);
DCHECK(gatt_id != gatt_identifier_.end());
if (!IsGattServerAttributeHandleAvailable(1)) {
std::move(callback).Run(kInvalidGattAttributeHandle);
return;
}
const auto& [bluez_properties, bluez_permissions] =
floss::BluetoothGattCharacteristicFloss::ConvertPropsAndPermsFromFloss(
static_cast<uint8_t>(properties), static_cast<uint16_t>(permissions));
auto* service = bluetooth_adapter_->GetGattService(gatt_id->second);
if (!service) {
return;
}
base::WeakPtr<BluetoothLocalGattCharacteristic> characteristic =
service->CreateCharacteristic(uuid, bluez_properties, bluez_permissions);
int32_t characteristic_handle =
CreateGattAttributeHandle(characteristic.get());
last_characteristic_[service_handle] = characteristic_handle;
std::move(callback).Run(characteristic_handle);
}
void ArcBluetoothBridge::AddDescriptor(int32_t service_handle,
const BluetoothUUID& uuid,
int32_t permissions,
AddDescriptorCallback callback) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
if (!IsGattServerAttributeHandleAvailable(1)) {
std::move(callback).Run(kInvalidGattAttributeHandle);
return;
}
DCHECK(gatt_identifier_.find(service_handle) != gatt_identifier_.end());
BluetoothLocalGattService* service =
bluetooth_adapter_->GetGattService(gatt_identifier_[service_handle]);
DCHECK(service);
// Since the Android API does not give information about which characteristic
// is the parent of the new descriptor, we assume that it would be the last
// characteristic that was added to the given service. This matches the
// Android framework code at android/bluetooth/BluetoothGattServer.java#594.
// https://android.googlesource.com/platform/frameworks/base/+/android-6.0.1_r55/core/java/android/bluetooth/BluetoothGattServer.java#586
DCHECK(last_characteristic_.find(service_handle) !=
last_characteristic_.end());
int32_t last_characteristic_handle = last_characteristic_[service_handle];
DCHECK(gatt_identifier_.find(last_characteristic_handle) !=
gatt_identifier_.end());
BluetoothLocalGattCharacteristic* characteristic =
service->GetCharacteristic(gatt_identifier_[last_characteristic_handle]);
DCHECK(characteristic);
const auto& [unused, bluez_permissions] =
floss::BluetoothGattCharacteristicFloss::ConvertPropsAndPermsFromFloss(
/*properties=*/0, static_cast<uint16_t>(permissions));
base::WeakPtr<BluetoothLocalGattDescriptor> descriptor =
BluetoothLocalGattDescriptor::Create(uuid, bluez_permissions,
characteristic);
std::move(callback).Run(CreateGattAttributeHandle(descriptor.get()));
}
void ArcBluetoothBridge::StartService(int32_t service_handle,
StartServiceCallback callback) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
DCHECK(gatt_identifier_.find(service_handle) != gatt_identifier_.end());
BluetoothLocalGattService* service =
bluetooth_adapter_->GetGattService(gatt_identifier_[service_handle]);
DCHECK(service);
auto split_callback = base::SplitOnceCallback(std::move(callback));
service->Register(
base::BindOnce(&OnGattOperationDone, std::move(split_callback.first)),
base::BindOnce(&OnGattOperationError, std::move(split_callback.second)));
}
void ArcBluetoothBridge::StopService(int32_t service_handle,
StopServiceCallback callback) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
DCHECK(gatt_identifier_.find(service_handle) != gatt_identifier_.end());
BluetoothLocalGattService* service =
bluetooth_adapter_->GetGattService(gatt_identifier_[service_handle]);
DCHECK(service);
auto split_callback = base::SplitOnceCallback(std::move(callback));
service->Unregister(
base::BindOnce(&OnGattOperationDone, std::move(split_callback.first)),
base::BindOnce(&OnGattOperationError, std::move(split_callback.second)));
}
void ArcBluetoothBridge::DeleteService(int32_t service_handle,
DeleteServiceCallback callback) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
auto itr = gatt_identifier_.find(service_handle);
if (itr == gatt_identifier_.end()) {
LOG(WARNING) << "DeleteService called with invalid service handle.";
return;
}
BluetoothLocalGattService* service =
bluetooth_adapter_->GetGattService(itr->second);
DCHECK(service);
gatt_identifier_.erase(itr);
gatt_handle_.erase(service->GetIdentifier());
service->Delete();
OnGattOperationDone(std::move(callback));
}
void ArcBluetoothBridge::SendIndication(int32_t attribute_handle,
mojom::BluetoothAddressPtr address,
bool confirm,
const std::vector<uint8_t>& value,
SendIndicationCallback callback) {
BluetoothDevice* device =
bluetooth_adapter_->GetDevice(address->To<std::string>());
auto identifier = gatt_identifier_.find(attribute_handle);
if (device == nullptr || identifier == gatt_identifier_.end()) {
std::move(callback).Run(mojom::BluetoothGattStatus::GATT_FAILURE);
return;
}
for (const auto& service_handle : last_characteristic_) {
auto it = gatt_identifier_.find(service_handle.first);
if (it == gatt_identifier_.end())
continue;
BluetoothLocalGattService* service =
bluetooth_adapter_->GetGattService(it->second);
if (service == nullptr)
continue;
BluetoothLocalGattCharacteristic* characteristic =
service->GetCharacteristic(identifier->second);
if (characteristic == nullptr)
continue;
characteristic->NotifyValueChanged(device, value, confirm);
std::move(callback).Run(mojom::BluetoothGattStatus::GATT_SUCCESS);
return;
}
std::move(callback).Run(mojom::BluetoothGattStatus::GATT_FAILURE);
}
bool ArcBluetoothBridge::GetAdvertisementHandle(int32_t* adv_handle) {
for (int i = 0; i < kMaxAdvertisements; i++) {
if (advertisements_.find(i) == advertisements_.end()) {
*adv_handle = i;
return true;
}
}
return false;
}
void ArcBluetoothBridge::ReserveAdvertisementHandle(
ReserveAdvertisementHandleCallback callback) {
advertisement_queue_.Push(
base::BindOnce(&ArcBluetoothBridge::ReserveAdvertisementHandleImpl,
weak_factory_.GetWeakPtr(), std::move(callback)));
}
void ArcBluetoothBridge::ReserveAdvertisementHandleImpl(
ReserveAdvertisementHandleCallback callback) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
// Find an empty advertisement slot.
int32_t adv_handle;
if (!GetAdvertisementHandle(&adv_handle)) {
LOG(WARNING) << "Out of space for advertisement data";
std::move(callback).Run(mojom::BluetoothGattStatus::GATT_FAILURE,
kInvalidAdvertisementHandle);
advertisement_queue_.Pop();
return;
}
// We have a handle. Put an entry in the map to reserve it.
advertisements_[adv_handle] = nullptr;
// The advertisement will be registered when we get the call
// to SetAdvertisingData. For now, just return the adv_handle.
std::move(callback).Run(mojom::BluetoothGattStatus::GATT_SUCCESS, adv_handle);
advertisement_queue_.Pop();
}
void ArcBluetoothBridge::EnableAdvertisement(
int32_t adv_handle,
std::unique_ptr<device::BluetoothAdvertisement::Data> advertisement,
EnableAdvertisementCallback callback) {
advertisement_queue_.Push(base::BindOnce(
&ArcBluetoothBridge::EnableAdvertisementImpl, weak_factory_.GetWeakPtr(),
adv_handle, std::move(advertisement), std::move(callback)));
}
void ArcBluetoothBridge::EnableAdvertisementImpl(
int32_t adv_handle,
std::unique_ptr<device::BluetoothAdvertisement::Data> advertisement,
EnableAdvertisementCallback callback) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
auto split_callback = base::SplitOnceCallback(std::move(callback));
base::OnceClosure done_callback = base::BindOnce(
&ArcBluetoothBridge::OnReadyToRegisterAdvertisement,
weak_factory_.GetWeakPtr(), std::move(split_callback.first), adv_handle,
std::move(advertisement));
base::OnceCallback<void(BluetoothAdvertisement::ErrorCode)> error_callback =
base::BindOnce(&ArcBluetoothBridge::OnRegisterAdvertisementError,
weak_factory_.GetWeakPtr(),
std::move(split_callback.second), adv_handle);
auto it = advertisements_.find(adv_handle);
if (it == advertisements_.end()) {
std::move(error_callback)
.Run(BluetoothAdvertisement::ErrorCode::
ERROR_ADVERTISEMENT_DOES_NOT_EXIST);
return;
}
if (it->second == nullptr) {
std::move(done_callback).Run();
return;
}
it->second->Unregister(std::move(done_callback), std::move(error_callback));
}
void ArcBluetoothBridge::DisableAdvertisement(
int32_t adv_handle,
EnableAdvertisementCallback callback) {
advertisement_queue_.Push(base::BindOnce(
&ArcBluetoothBridge::DisableAdvertisementImpl, weak_factory_.GetWeakPtr(),
adv_handle, std::move(callback)));
}
void ArcBluetoothBridge::DisableAdvertisementImpl(
int32_t adv_handle,
EnableAdvertisementCallback callback) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
auto split_callback = base::SplitOnceCallback(std::move(callback));
base::OnceClosure done_callback = base::BindOnce(
&ArcBluetoothBridge::OnUnregisterAdvertisementDone,
weak_factory_.GetWeakPtr(), std::move(split_callback.first), adv_handle);
base::OnceCallback<void(BluetoothAdvertisement::ErrorCode)> error_callback =
base::BindOnce(&ArcBluetoothBridge::OnUnregisterAdvertisementError,
weak_factory_.GetWeakPtr(),
std::move(split_callback.second), adv_handle);
auto it = advertisements_.find(adv_handle);
if (it == advertisements_.end()) {
std::move(error_callback)
.Run(BluetoothAdvertisement::ErrorCode::
ERROR_ADVERTISEMENT_DOES_NOT_EXIST);
return;
}
if (it->second == nullptr) {
std::move(done_callback).Run();
return;
}
it->second->Unregister(std::move(done_callback), std::move(error_callback));
}
void ArcBluetoothBridge::ReleaseAdvertisementHandle(
int32_t adv_handle,
ReleaseAdvertisementHandleCallback callback) {
advertisement_queue_.Push(base::BindOnce(
&ArcBluetoothBridge::ReleaseAdvertisementHandleImpl,
weak_factory_.GetWeakPtr(), adv_handle, std::move(callback)));
}
void ArcBluetoothBridge::ReleaseAdvertisementHandleImpl(
int32_t adv_handle,
ReleaseAdvertisementHandleCallback callback) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
if (advertisements_.find(adv_handle) == advertisements_.end()) {
std::move(callback).Run(mojom::BluetoothGattStatus::GATT_FAILURE);
advertisement_queue_.Pop();
return;
}
if (!advertisements_[adv_handle]) {
advertisements_.erase(adv_handle);
std::move(callback).Run(mojom::BluetoothGattStatus::GATT_SUCCESS);
advertisement_queue_.Pop();
return;
}
auto split_callback = base::SplitOnceCallback(std::move(callback));
advertisements_[adv_handle]->Unregister(
base::BindOnce(&ArcBluetoothBridge::OnReleaseAdvertisementHandleDone,
weak_factory_.GetWeakPtr(),
std::move(split_callback.first), adv_handle),
base::BindOnce(&ArcBluetoothBridge::OnReleaseAdvertisementHandleError,
weak_factory_.GetWeakPtr(),
std::move(split_callback.second), adv_handle));
}
void ArcBluetoothBridge::OnReadyToRegisterAdvertisement(
ArcBluetoothBridge::GattStatusCallback callback,
int32_t adv_handle,
std::unique_ptr<device::BluetoothAdvertisement::Data> data) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
auto split_callback = base::SplitOnceCallback(std::move(callback));
bluetooth_adapter_->RegisterAdvertisement(
std::move(data),
base::BindOnce(&ArcBluetoothBridge::OnRegisterAdvertisementDone,
weak_factory_.GetWeakPtr(),
std::move(split_callback.first), adv_handle),
base::BindOnce(&ArcBluetoothBridge::OnRegisterAdvertisementError,
weak_factory_.GetWeakPtr(),
std::move(split_callback.second), adv_handle));
}
void ArcBluetoothBridge::OnRegisterAdvertisementDone(
ArcBluetoothBridge::GattStatusCallback callback,
int32_t adv_handle,
scoped_refptr<BluetoothAdvertisement> advertisement) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
advertisements_[adv_handle] = std::move(advertisement);
std::move(callback).Run(mojom::BluetoothGattStatus::GATT_SUCCESS);
advertisement_queue_.Pop();
}
void ArcBluetoothBridge::OnRegisterAdvertisementError(
ArcBluetoothBridge::GattStatusCallback callback,
int32_t adv_handle,
BluetoothAdvertisement::ErrorCode error_code) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
LOG(WARNING) << "Failed to register advertisement for handle " << adv_handle
<< ", error code = " << error_code;
advertisements_[adv_handle] = nullptr;
std::move(callback).Run(mojom::BluetoothGattStatus::GATT_FAILURE);
advertisement_queue_.Pop();
}
void ArcBluetoothBridge::OnUnregisterAdvertisementDone(
ArcBluetoothBridge::GattStatusCallback callback,
int32_t adv_handle) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
advertisements_[adv_handle] = nullptr;
std::move(callback).Run(mojom::BluetoothGattStatus::GATT_SUCCESS);
advertisement_queue_.Pop();
}
void ArcBluetoothBridge::OnUnregisterAdvertisementError(
ArcBluetoothBridge::GattStatusCallback callback,
int32_t adv_handle,
BluetoothAdvertisement::ErrorCode error_code) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
LOG(WARNING) << "Failed to unregister advertisement for handle " << adv_handle
<< ", error code = " << error_code;
advertisements_[adv_handle] = nullptr;
std::move(callback).Run(mojom::BluetoothGattStatus::GATT_FAILURE);
advertisement_queue_.Pop();
}
void ArcBluetoothBridge::OnReleaseAdvertisementHandleDone(
ArcBluetoothBridge::GattStatusCallback callback,
int32_t adv_handle) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
advertisements_.erase(adv_handle);
std::move(callback).Run(mojom::BluetoothGattStatus::GATT_SUCCESS);
advertisement_queue_.Pop();
}
void ArcBluetoothBridge::OnReleaseAdvertisementHandleError(
ArcBluetoothBridge::GattStatusCallback callback,
int32_t adv_handle,
BluetoothAdvertisement::ErrorCode error_code) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
LOG(WARNING) << "Failed to relase advertisement handle " << adv_handle
<< ", error code = " << error_code;
advertisements_.erase(adv_handle);
std::move(callback).Run(mojom::BluetoothGattStatus::GATT_FAILURE);
advertisement_queue_.Pop();
}
void ArcBluetoothBridge::OnDiscoveryError() {
LOG(WARNING) << "failed to change discovery state";
discovery_queue_.Pop();
}
void ArcBluetoothBridge::OnLEScanError() {
LOG(WARNING) << "failed to start LE scan";
discovery_queue_.Pop();
}
void ArcBluetoothBridge::OnPairing(mojom::BluetoothAddressPtr addr) const {
auto* bluetooth_instance = ARC_GET_INSTANCE_FOR_METHOD(
arc_bridge_service_->bluetooth(), OnBondStateChanged);
if (!bluetooth_instance)
return;
bluetooth_instance->OnBondStateChanged(mojom::BluetoothStatus::SUCCESS,
std::move(addr),
mojom::BluetoothBondState::BONDING);
}
void ArcBluetoothBridge::OnPairedDone(mojom::BluetoothAddressPtr addr) const {
auto* bluetooth_instance = ARC_GET_INSTANCE_FOR_METHOD(
arc_bridge_service_->bluetooth(), OnBondStateChanged);
if (!bluetooth_instance)
return;
bluetooth_instance->OnBondStateChanged(mojom::BluetoothStatus::SUCCESS,
std::move(addr),
mojom::BluetoothBondState::BONDED);
}
void ArcBluetoothBridge::OnPairedError(
mojom::BluetoothAddressPtr addr,
BluetoothDevice::ConnectErrorCode error_code) const {
auto* bluetooth_instance = ARC_GET_INSTANCE_FOR_METHOD(
arc_bridge_service_->bluetooth(), OnBondStateChanged);
if (!bluetooth_instance)
return;
bluetooth_instance->OnBondStateChanged(mojom::BluetoothStatus::FAIL,
std::move(addr),
mojom::BluetoothBondState::NONE);
}
void ArcBluetoothBridge::OnForgetDone(mojom::BluetoothAddressPtr addr) {
devices_paired_by_arc_.erase(addr->To<std::string>());
auto* bluetooth_instance = ARC_GET_INSTANCE_FOR_METHOD(
arc_bridge_service_->bluetooth(), OnBondStateChanged);
if (!bluetooth_instance)
return;
bluetooth_instance->OnBondStateChanged(mojom::BluetoothStatus::SUCCESS,
std::move(addr),
mojom::BluetoothBondState::NONE);
}
void ArcBluetoothBridge::OnForgetError(mojom::BluetoothAddressPtr addr) const {
auto* bluetooth_instance = ARC_GET_INSTANCE_FOR_METHOD(
arc_bridge_service_->bluetooth(), OnBondStateChanged);
if (!bluetooth_instance)
return;
BluetoothDevice* device =
bluetooth_adapter_->GetDevice(addr->To<std::string>());
mojom::BluetoothBondState bond_state = mojom::BluetoothBondState::NONE;
if (device && device->IsPaired()) {
bond_state = mojom::BluetoothBondState::BONDED;
}
bluetooth_instance->OnBondStateChanged(mojom::BluetoothStatus::FAIL,
std::move(addr), bond_state);
}
bool ArcBluetoothBridge::IsPowerChangeInitiatedByRemote(
ArcBluetoothBridge::AdapterPowerState powered) const {
return !remote_power_changes_.empty() &&
remote_power_changes_.front() == powered;
}
bool ArcBluetoothBridge::IsPowerChangeInitiatedByLocal(
ArcBluetoothBridge::AdapterPowerState powered) const {
return !local_power_changes_.empty() &&
local_power_changes_.front() == powered;
}
void ArcBluetoothBridge::OnConnectionReady() {
if (!bluetooth_adapter_ || !bluetooth_adapter_->IsPowered()) {
// The default power state of Bluetooth on Android is off, so there is no
// need to send an intent to turn off Bluetooth if the initial power state
// is off.
return;
}
// Send initial power state in case both, Intent Helper and App instances are
// present. Intent Helper is required to dispatch this event and App is sign
// that ARC is fully started. In case of initial boot, App instance is started
// after the Intent Helper instance. In case of next boot Intent Helper and
// App instances are started at almost the same time and order of start is not
// determined.
if (!arc_bridge_service_->app()->IsConnected() ||
!arc_bridge_service_->intent_helper()->IsConnected()) {
return;
}
EnqueueLocalPowerChange(AdapterPowerState::TURN_ON);
}
void ArcBluetoothBridge::EnqueueLocalPowerChange(
ArcBluetoothBridge::AdapterPowerState powered) {
local_power_changes_.push(powered);
if (power_intent_timer_.IsRunning())
return;
SendBluetoothPoweredStateBroadcast(local_power_changes_.front());
power_intent_timer_.Start(
FROM_HERE, kPowerIntentTimeout,
base::BindOnce(&ArcBluetoothBridge::DequeueLocalPowerChange,
weak_factory_.GetWeakPtr(), powered));
}
void ArcBluetoothBridge::DequeueLocalPowerChange(
ArcBluetoothBridge::AdapterPowerState powered) {
power_intent_timer_.Stop();
if (!IsPowerChangeInitiatedByLocal(powered))
return;
AdapterPowerState current_change = local_power_changes_.front();
AdapterPowerState last_change = local_power_changes_.back();
// Compress the queue for power intent to reduce the amount of intents being
// sent to Android so that the powered state will be synced between Android
// and Chrome even if the state is toggled repeatedly on Chrome.
base::queue<AdapterPowerState> empty_queue;
std::swap(local_power_changes_, empty_queue);
if (last_change == current_change)
return;
local_power_changes_.push(last_change);
SendBluetoothPoweredStateBroadcast(last_change);
power_intent_timer_.Start(
FROM_HERE, kPowerIntentTimeout,
base::BindOnce(&ArcBluetoothBridge::DequeueLocalPowerChange,
weak_factory_.GetWeakPtr(), last_change));
}
void ArcBluetoothBridge::EnqueueRemotePowerChange(
ArcBluetoothBridge::AdapterPowerState powered,
ArcBluetoothBridge::AdapterStateCallback callback) {
remote_power_changes_.push(powered);
bool turn_on = (powered == AdapterPowerState::TURN_ON);
auto split_callback = base::SplitOnceCallback(std::move(callback));
BLUETOOTH_LOG(EVENT) << "ARC bluetooth set power: " << turn_on;
bluetooth_adapter_->SetPowered(
turn_on,
base::BindOnce(turn_on ? &ArcBluetoothBridge::OnPoweredOn
: &ArcBluetoothBridge::OnPoweredOff,
weak_factory_.GetWeakPtr(),
std::move(split_callback.first),
/*save_user_pref=*/true),
base::BindOnce(&ArcBluetoothBridge::OnPoweredError,
weak_factory_.GetWeakPtr(),
std::move(split_callback.second)));
}
void ArcBluetoothBridge::DequeueRemotePowerChange(
ArcBluetoothBridge::AdapterPowerState powered) {
remote_power_changes_.pop();
}
void ArcBluetoothBridge::SendCachedDevices() const {
auto* bluetooth_instance = ARC_GET_INSTANCE_FOR_METHOD(
arc_bridge_service_->bluetooth(), OnDevicePropertiesChanged);
if (!bluetooth_instance)
return;
for (const auto* device : bluetooth_adapter_->GetDevices()) {
// Since a cached device may not be a currently available device, we use
// OnDevicePropertiesChanged() instead of OnDeviceFound() to avoid trigger
// the logic of device found in Android.
bluetooth_instance->OnDevicePropertiesChanged(
mojom::BluetoothAddress::From(device->GetAddress()),
GetDeviceProperties(mojom::BluetoothPropertyType::ALL, device));
}
}
std::vector<mojom::BluetoothPropertyPtr>
ArcBluetoothBridge::GetDeviceProperties(mojom::BluetoothPropertyType type,
const BluetoothDevice* device) const {
std::vector<mojom::BluetoothPropertyPtr> properties;
if (!device) {
return properties;
}
if (type == mojom::BluetoothPropertyType::ALL ||
type == mojom::BluetoothPropertyType::BDNAME) {
properties.push_back(mojom::BluetoothProperty::NewBdname(
device->GetName() ? device->GetName().value() : ""));
}
if (type == mojom::BluetoothPropertyType::ALL ||
type == mojom::BluetoothPropertyType::BDADDR) {
properties.push_back(mojom::BluetoothProperty::NewBdaddr(
mojom::BluetoothAddress::From(device->GetAddress())));
}
if (type == mojom::BluetoothPropertyType::ALL ||
type == mojom::BluetoothPropertyType::UUIDS) {
BluetoothDevice::UUIDSet uuids = device->GetUUIDs();
if (uuids.size() > 0) {
properties.push_back(mojom::BluetoothProperty::NewUuids(
std::vector<BluetoothUUID>(uuids.begin(), uuids.end())));
}
}
if (type == mojom::BluetoothPropertyType::ALL ||
type == mojom::BluetoothPropertyType::CLASS_OF_DEVICE) {
properties.push_back(
mojom::BluetoothProperty::NewDeviceClass(device->GetBluetoothClass()));
}
if (type == mojom::BluetoothPropertyType::ALL ||
type == mojom::BluetoothPropertyType::TYPE_OF_DEVICE) {
properties.push_back(
mojom::BluetoothProperty::NewDeviceType(device->GetType()));
}
if (type == mojom::BluetoothPropertyType::ALL ||
type == mojom::BluetoothPropertyType::REMOTE_FRIENDLY_NAME) {
properties.push_back(mojom::BluetoothProperty::NewRemoteFriendlyName(
base::UTF16ToUTF8(device->GetNameForDisplay())));
}
if (type == mojom::BluetoothPropertyType::ALL ||
type == mojom::BluetoothPropertyType::REMOTE_RSSI) {
std::optional<int8_t> rssi = device->GetInquiryRSSI();
if (rssi.has_value()) {
properties.push_back(
mojom::BluetoothProperty::NewRemoteRssi(rssi.value()));
}
}
// TODO(smbarber): Add remote version info
return properties;
}
std::vector<mojom::BluetoothPropertyPtr>
ArcBluetoothBridge::GetAdapterProperties(
mojom::BluetoothPropertyType type) const {
// TODO(crbug.com/40189401): Since this function is invoked from ARC side, it
// is possible that adapter is not present or powered here. It's not
// meaningful to return any property when that happens.
const std::string adapter_address = bluetooth_adapter_->GetAddress();
if (adapter_address.empty()) {
LOG(ERROR) << "Bluetooth adapter does not have a valid address";
return {};
}
std::vector<mojom::BluetoothPropertyPtr> properties;
if (type == mojom::BluetoothPropertyType::ALL ||
type == mojom::BluetoothPropertyType::BDNAME) {
properties.push_back(
mojom::BluetoothProperty::NewBdname(bluetooth_adapter_->GetName()));
}
if (type == mojom::BluetoothPropertyType::ALL ||
type == mojom::BluetoothPropertyType::BDADDR) {
properties.push_back(mojom::BluetoothProperty::NewBdaddr(
mojom::BluetoothAddress::From(adapter_address)));
}
if (type == mojom::BluetoothPropertyType::ALL ||
type == mojom::BluetoothPropertyType::UUIDS) {
properties.push_back(
mojom::BluetoothProperty::NewUuids(bluetooth_adapter_->GetUUIDs()));
}
if (type == mojom::BluetoothPropertyType::ALL ||
type == mojom::BluetoothPropertyType::CLASS_OF_DEVICE) {
properties.push_back(
mojom::BluetoothProperty::NewDeviceClass(kBluetoothComputerClass));
}
if (type == mojom::BluetoothPropertyType::ALL ||
type == mojom::BluetoothPropertyType::TYPE_OF_DEVICE) {
// Assume that all ChromeOS devices are dual mode Bluetooth device.
properties.push_back(mojom::BluetoothProperty::NewDeviceType(
device::BLUETOOTH_TRANSPORT_DUAL));
}
if (type == mojom::BluetoothPropertyType::ALL ||
type == mojom::BluetoothPropertyType::ADAPTER_SCAN_MODE) {
mojom::BluetoothScanMode scan_mode = mojom::BluetoothScanMode::CONNECTABLE;
if (bluetooth_adapter_->IsDiscoverable())
scan_mode = mojom::BluetoothScanMode::CONNECTABLE_DISCOVERABLE;
properties.push_back(
mojom::BluetoothProperty::NewAdapterScanMode(scan_mode));
}
if (type == mojom::BluetoothPropertyType::ALL ||
type == mojom::BluetoothPropertyType::ADAPTER_BONDED_DEVICES) {
BluetoothAdapter::DeviceList devices = bluetooth_adapter_->GetDevices();
std::vector<mojom::BluetoothAddressPtr> bonded_devices;
for (auto* device : devices) {
if (!device->IsPaired())
continue;
mojom::BluetoothAddressPtr addr =
mojom::BluetoothAddress::From(device->GetAddress());
bonded_devices.push_back(std::move(addr));
}
properties.push_back(
mojom::BluetoothProperty::NewBondedDevices(std::move(bonded_devices)));
}
if (type == mojom::BluetoothPropertyType::ALL ||
type == mojom::BluetoothPropertyType::ADAPTER_DISCOVERY_TIMEOUT) {
properties.push_back(
mojom::BluetoothProperty::NewDiscoveryTimeout(static_cast<uint32_t>(
bluetooth_adapter_->GetDiscoverableTimeout().InSeconds())));
}
if (type == mojom::BluetoothPropertyType::ALL ||
type == mojom::BluetoothPropertyType::LOCAL_LE_FEATURES) {
// TODO(crbug.com/40480399) Investigate all the le_features.
mojom::BluetoothLocalLEFeaturesPtr le_features =
mojom::BluetoothLocalLEFeatures::New();
le_features->version_supported = kAndroidMBluetoothVersionNumber;
le_features->local_privacy_enabled = 0;
le_features->max_adv_instance = kMaxAdvertisements;
le_features->rpa_offload_supported = 0;
le_features->max_irk_list_size = 0;
le_features->max_adv_filter_supported = 0;
le_features->activity_energy_info_supported = 0;
le_features->scan_result_storage_size = 0;
le_features->total_trackable_advertisers = 0;
le_features->extended_scan_support = false;
le_features->debug_logging_supported = false;
properties.push_back(
mojom::BluetoothProperty::NewLocalLeFeatures(std::move(le_features)));
}
return properties;
}
// Android support 6 types of Advertising Data which are Advertising Data Flags,
// Local Name, Service UUIDs, Tx Power Level, Service Data, and Manufacturer
// Data. Note that we need to use 16-bit UUID in Service Data section because
// Android does not support 128-bit UUID there.
std::vector<mojom::BluetoothAdvertisingDataPtr>
ArcBluetoothBridge::GetAdvertisingData(const BluetoothDevice* device) const {
std::vector<mojom::BluetoothAdvertisingDataPtr> advertising_data;
// Advertising Data Flags
if (device->GetAdvertisingDataFlags().has_value()) {
advertising_data.push_back(mojom::BluetoothAdvertisingData::NewFlags(
device->GetAdvertisingDataFlags().value()));
}
// Local Name
advertising_data.push_back(mojom::BluetoothAdvertisingData::NewLocalName(
device->GetName() ? device->GetName().value() : ""));
// Service UUIDs
BluetoothDevice::UUIDSet uuid_set = device->GetUUIDs();
for (const BluetoothRemoteGattService* gatt_service :
device->GetGattServices()) {
uuid_set.erase(gatt_service->GetUUID());
}
if (uuid_set.size() > 0) {
advertising_data.push_back(mojom::BluetoothAdvertisingData::NewServiceUuids(
std::vector<BluetoothUUID>(uuid_set.begin(), uuid_set.end())));
}
// Tx Power Level
if (device->GetInquiryTxPower().has_value()) {
advertising_data.push_back(mojom::BluetoothAdvertisingData::NewTxPowerLevel(
device->GetInquiryTxPower().value()));
}
// Service Data
for (const BluetoothUUID& uuid : device->GetServiceDataUUIDs()) {
std::optional<uint16_t> uuid16 = GetUUID16(uuid);
if (!uuid16)
continue;
mojom::BluetoothServiceDataPtr service_data =
mojom::BluetoothServiceData::New();
// Android only supports UUID 16 bit here.
service_data->uuid_16bit = *uuid16;
const std::vector<uint8_t>* data = device->GetServiceDataForUUID(uuid);
DCHECK(data != nullptr);
service_data->data = *data;
advertising_data.push_back(mojom::BluetoothAdvertisingData::NewServiceData(
std::move(service_data)));
}
// Manufacturer Data
if (!device->GetManufacturerData().empty()) {
std::vector<uint8_t> manufacturer_data;
for (const auto& pair : device->GetManufacturerData()) {
uint16_t id = pair.first;
// Use little endian here.
manufacturer_data.push_back(id & 0xff);
manufacturer_data.push_back(id >> 8);
manufacturer_data.insert(manufacturer_data.end(), pair.second.begin(),
pair.second.end());
}
advertising_data.push_back(
mojom::BluetoothAdvertisingData::NewManufacturerData(
std::move(manufacturer_data)));
}
return advertising_data;
}
void ArcBluetoothBridge::SetPrimaryUserBluetoothPowerSetting(
bool enabled) const {
const user_manager::User* const user =
user_manager::UserManager::Get()->GetPrimaryUser();
Profile* profile = ash::ProfileHelper::Get()->GetProfileByUser(user);
DCHECK(profile);
profile->GetPrefs()->SetBoolean(ash::prefs::kUserBluetoothAdapterEnabled,
enabled);
}
ArcBluetoothBridge::GattConnection::GattConnection(
ArcBluetoothBridge::GattConnection::ConnectionState state,
std::unique_ptr<device::BluetoothGattConnection> connection,
bool need_hard_disconnect)
: state(state),
connection(std::move(connection)),
need_hard_disconnect(need_hard_disconnect) {}
ArcBluetoothBridge::GattConnection::GattConnection()
: connection(nullptr), need_hard_disconnect(false) {}
ArcBluetoothBridge::GattConnection::~GattConnection() = default;
ArcBluetoothBridge::GattConnection::GattConnection(
ArcBluetoothBridge::GattConnection&&) = default;
ArcBluetoothBridge::GattConnection&
ArcBluetoothBridge::GattConnection::operator=(
ArcBluetoothBridge::GattConnection&&) = default;
namespace {
bool IsValidPort(mojom::BluetoothSocketType sock_type, int port) {
switch (sock_type) {
case mojom::BluetoothSocketType::TYPE_RFCOMM:
return port <= ArcBluetoothBridge::kMaxRfcommChannel &&
port >= ArcBluetoothBridge::kMinRfcommChannel;
case mojom::BluetoothSocketType::TYPE_L2CAP_LE:
return port <= ArcBluetoothBridge::kMaxL2capLePsm &&
port >= ArcBluetoothBridge::kMinL2capLePsm;
}
}
} // namespace
void ArcBluetoothBridge::BluetoothSocketListen(
mojom::BluetoothSocketType sock_type,
mojom::BluetoothSocketFlagsPtr sock_flags,
int32_t port,
BluetoothSocketListenCallback callback) {
if (!mojom::IsKnownEnumValue(sock_type)) {
LOG(ERROR) << "Unsupported sock type " << sock_type;
std::move(callback).Run(
mojom::BluetoothStatus::UNSUPPORTED, /*port=*/0,
mojo::PendingReceiver<mojom::BluetoothListenSocketClient>());
return;
}
if (port != kAutoSockPort && !IsValidPort(sock_type, port)) {
LOG(ERROR) << "Invalid port number " << port;
std::move(callback).Run(
mojom::BluetoothStatus::FAIL, /*port=*/0,
mojo::PendingReceiver<mojom::BluetoothListenSocketClient>());
return;
}
CreateBluetoothListenSocket(sock_type, std::move(sock_flags), port,
std::move(callback));
}
void ArcBluetoothBridge::BluetoothSocketConnect(
mojom::BluetoothSocketType sock_type,
mojom::BluetoothSocketFlagsPtr sock_flags,
mojom::BluetoothAddressPtr remote_addr,
int32_t port,
BluetoothSocketConnectCallback callback) {
if (!mojom::IsKnownEnumValue(sock_type)) {
LOG(ERROR) << "Unsupported sock type " << sock_type;
std::move(callback).Run(
mojom::BluetoothStatus::UNSUPPORTED,
mojo::PendingReceiver<arc::mojom::BluetoothConnectSocketClient>());
return;
}
if (!IsValidPort(sock_type, port)) {
LOG(ERROR) << "Invalid port number " << port;
std::move(callback).Run(
mojom::BluetoothStatus::FAIL,
mojo::PendingReceiver<arc::mojom::BluetoothConnectSocketClient>());
return;
}
CreateBluetoothConnectSocket(sock_type, std::move(sock_flags),
std::move(remote_addr), port,
std::move(callback));
}
// static
void ArcBluetoothBridge::EnsureFactoryBuilt() {
ArcBluezBridgeFactory::GetInstance();
ArcFlossBridgeFactory::GetInstance();
}
ArcBluetoothBridge::BluetoothListeningSocket::BluetoothListeningSocket() =
default;
ArcBluetoothBridge::BluetoothListeningSocket::~BluetoothListeningSocket() =
default;
ArcBluetoothBridge::BluetoothConnectingSocket::BluetoothConnectingSocket() =
default;
ArcBluetoothBridge::BluetoothConnectingSocket::~BluetoothConnectingSocket() =
default;
ArcBluetoothBridge::BluetoothArcConnectionObserver::
BluetoothArcConnectionObserver(ArcBluetoothBridge* arc_bluetooth_bridge)
: arc_bluetooth_bridge_(arc_bluetooth_bridge) {
arc_bluetooth_bridge_->arc_bridge_service_->bluetooth()->AddObserver(this);
}
ArcBluetoothBridge::BluetoothArcConnectionObserver::
~BluetoothArcConnectionObserver() {
arc_bluetooth_bridge_->arc_bridge_service_->bluetooth()->RemoveObserver(this);
}
void ArcBluetoothBridge::BluetoothArcConnectionObserver::OnConnectionClosed() {
// Stops the ongoing discovery sessions.
arc_bluetooth_bridge_->CancelDiscovery();
arc_bluetooth_bridge_->StopLEScan();
// Cleanup for CreateBond().
for (const auto& addr : arc_bluetooth_bridge_->devices_paired_by_arc_) {
BluetoothDevice* device =
arc_bluetooth_bridge_->bluetooth_adapter_->GetDevice(addr);
if (!device)
continue;
if (device->IsPaired()) {
device->Disconnect(base::DoNothing(), base::DoNothing());
} else {
device->CancelPairing();
}
}
arc_bluetooth_bridge_->devices_paired_by_arc_.clear();
arc_bluetooth_bridge_->devices_pairing_.clear();
// Cleanup for GATT connections.
// TODO(b/151573141): Remove the following loops when Chrome can perform hard
// disconnect on a paired device correctly.
for (const auto& addr_conn : arc_bluetooth_bridge_->gatt_connections_) {
BluetoothDevice* device =
arc_bluetooth_bridge_->bluetooth_adapter_->GetDevice(addr_conn.first);
if (!device || !device->IsPaired() || !device->IsConnected())
continue;
device->Disconnect(base::DoNothing(), base::DoNothing());
}
arc_bluetooth_bridge_->gatt_connections_.clear();
}
} // namespace arc
|