File size: 172,672 Bytes
4a5ef51 | 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 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 | import {createAudioPlayer, setAudioModeAsync, type AudioPlayer} from 'expo-audio';
import {File, Paths} from 'expo-file-system';
import {useEffect, useRef, useState} from 'react';
import {Clipboard, Linking, PermissionsAndroid, Platform} from 'react-native';
import WifiManager from 'react-native-wifi-reborn';
import BluetoothSdk, {
DeviceModels,
type AudioConnectedEvent,
type ButtonPressEvent,
type BluetoothSdkEventMap,
type CameraFovResult,
type CameraRoiPosition,
type CompatibleGlassesSearchStopEvent,
type LogEvent,
type Device,
type DeviceModel,
type MicLc3Event,
type MicPcmEvent,
type PhotoRequestParams,
type PhotoSuccessResponseEvent,
type PhotoStatusEvent,
type SettingsAckEvent,
type SpeakingStatusEvent,
type StreamStatusEvent,
type TouchEvent,
type VersionInfoEvent,
type VersionInfoResult,
type VideoRecordingStatusEvent,
type VoiceActivityDetectionStatusEvent,
} from '@mentra/engine/bluetooth-sdk';
import {
useMentraBluetooth,
type DefaultDeviceStorage,
type GlassesRuntimeState,
type PhoneSdkRuntimeState,
} from '@mentra/engine/bluetooth-sdk/react';
import MentraBarcodeScanner, {
type BarcodeScanResult,
type ImageFovEstimate,
} from '@mentra/react-native-barcode-scanner';
import MentraPhotoReceiver, {
type PhotoReceiverResult,
type PhotoReceiverStatusEvent,
type PhotoReceiverUploadEvent,
} from '@mentra/engine/bluetooth-sdk/photo-receiver';
import MentraVideoStreamReceiver, {
type VideoStreamFrameEvent,
type VideoStreamFirstFrameEvent,
type VideoStreamReceiverStatusEvent,
} from '@mentra/react-native-video-stream-receiver';
import {
galleryHotspotPasswordLabel,
galleryHotspotSsidLabel,
galleryServerUrl,
connectedWifiStatus,
enabledHotspotStatus,
isDisconnectedStatus,
isGlassesConnected,
isGlassesWifiConnected,
supportsDisplay,
} from './sdkFormat';
import {
applyTouchGestureDefault,
initialTouchGestureDefaults,
type TouchGesture,
type TouchGestureDefaults,
} from './touchGestureDefaults';
export type ExampleTabKey = 'device' | 'camera' | 'stream' | 'system' | 'console';
export type BluetoothSdkExampleOptions = {
activeTab?: ExampleTabKey;
};
export type StreamProtocol = 'rtmp' | 'srt' | 'webrtc';
export type StreamPreviewTarget = {
kind: 'hls' | 'web';
url: string;
};
type MediaUploadSuccessEvent = BluetoothSdkEventMap['media_success'];
type MediaUploadErrorEvent = BluetoothSdkEventMap['media_error'];
type PhotoCaptureOptions = {
scanBarcode: boolean;
textMode: boolean;
};
// The SDK gives up waiting for a wifi connect ack after 15s, but the glasses
// often finish associating shortly after; keep the connecting state alive a
// little longer before declaring failure.
const WIFI_CONNECT_GRACE_MS = 20_000;
function versionValue(value: string | null | undefined) {
return typeof value === 'string' && value.trim().length > 0 ? value.trim() : null;
}
function resolveMentraLiveVersions(
glasses: GlassesRuntimeState,
versionInfo: VersionInfoResult | null,
): MentraLiveVersions {
if (!glasses.connected) {
return {
appVersion: null,
besFirmwareVersion: null,
mtkFirmwareVersion: null,
};
}
return {
appVersion:
versionValue(versionInfo?.appVersion) ??
versionValue(glasses.device.appVersion) ??
versionValue(glasses.firmware.appVersion),
besFirmwareVersion:
versionValue(versionInfo?.besFirmwareVersion) ??
(glasses.firmware.source === 'bes' ? versionValue(glasses.firmware.version) : null),
mtkFirmwareVersion:
versionValue(versionInfo?.mtkFirmwareVersion) ??
(glasses.firmware.source === 'mtk' ? versionValue(glasses.firmware.version) : null),
};
}
export function isMentraLiveRuntime(
glasses: GlassesRuntimeState,
): glasses is Extract<GlassesRuntimeState, {connected: true}> {
if (!glasses.connected) {
return false;
}
const model = [
glasses.device.deviceModel,
glasses.device.bluetoothName,
].filter(Boolean).join(' ').toLowerCase();
return glasses.device.deviceModel === DeviceModels.MentraLive || model.includes('mentra live');
}
export type StreamResolvedConfig = {
transport?: 'rtmp' | 'srt' | 'whip';
video?: {
width: number;
height: number;
captureWidth?: number;
captureHeight?: number;
bitrate: number;
fps: number;
};
audio?: {
bitrate?: number;
sampleRate?: number;
echoCancellation?: boolean;
noiseSuppression?: boolean;
};
};
export type PhotoRequestedCaptureConfigDetails = {
manual?: boolean;
exposureTimeNs?: number;
iso?: number;
frameDurationNs?: number;
aeMode?: number;
aeLock?: boolean;
aeExposureCompensation?: number;
aeTargetFpsRange?: {min?: number; max?: number};
noiseReductionMode?: number;
edgeMode?: number;
afMode?: number;
zsl?: boolean;
};
export type PhotoMeteredPreviewDetails = {
exposureTimeNs?: number;
iso?: number;
totalLightProxy?: number;
};
export type PhotoCaptureMetadataDetails = {
manual?: boolean;
exposureTimeNs?: number;
iso?: number;
frameDurationNs?: number;
aeMode?: number;
aeState?: number;
aeStateName?: string;
noiseReductionMode?: number;
edgeMode?: number;
zsl?: boolean;
sensorTimestampNs?: number;
totalLightProxy?: number;
mfnrLikely?: boolean;
};
export type PhotoTimelineEvent = {
source: 'request' | 'photo_status' | 'photo_response';
status?: string;
timestamp: number;
};
export type PhotoPreviewDetails = {
bleFallbackMessage?: string;
bleFallbackUsed?: boolean;
byteCount?: number;
contentType?: string;
error?: string;
estimatedFov?: ImageFovEstimate | null;
fileName?: string;
focalLength35mm?: number | null;
height?: number;
previewUrl?: string;
requestId?: string | null;
resolvedConfig?: PhotoStatusEvent['resolvedConfig'];
requestedCaptureConfig?: PhotoRequestedCaptureConfigDetails;
meteredPreview?: PhotoMeteredPreviewDetails;
captureMetadata?: PhotoCaptureMetadataDetails;
source: 'Cloud server' | 'Phone receiver' | 'Action button' | 'Glasses gallery';
state: 'acknowledged' | 'error' | 'preview' | 'saved';
timestamp?: number;
timeline?: PhotoTimelineEvent[];
uploadUrl?: string;
uploadedAt?: string;
width?: number;
};
export type VideoPreviewDetails = {
byteCount?: number;
contentType?: string;
durationMs?: number;
error?: string;
mediaUrl?: string;
previewUrl?: string;
requestId?: string | null;
source: 'Cloud server';
state: 'recording' | 'uploading' | 'preview' | 'error';
status?: string;
timestamp?: number;
uploadUrl?: string;
uploadedAt?: string;
};
export type BarcodeScanDetails = {
barcodes: BarcodeScanResult[];
error?: string;
expectedValue?: string;
scannedAt?: string;
sourceUri?: string;
state: 'idle' | 'scanning' | 'found' | 'none' | 'error';
};
export type LedMode = 'Off' | 'Solid' | 'Pulse' | 'Blink';
type RgbLedAction = 'on' | 'off';
export type LedColor = 'red' | 'green' | 'blue' | 'orange' | 'white';
export type PhotoSize = 'low' | 'medium' | 'high' | 'max';
export type PhotoCompression = NonNullable<PhotoRequestParams['compress']>;
export type PhotoTransferMethod = 'auto' | 'direct' | 'ble';
export type PhotoDestination = 'phone' | 'cloud' | 'glasses';
export type PhotoAeExposureDivisor = 2 | 3 | 5;
export type PhotoIsoCap = 400 | 800 | 1600;
export type PhotoIspDigitalGain = 0 | 1 | 2 | 4;
export type PhotoIspAnalogGain = 'low';
export type PhotoTuningFlag = 'unset' | 'on' | 'off';
export const SCAN_MODELS = [DeviceModels.MentraLive, DeviceModels.G2] as const;
export type ScanModel = (typeof SCAN_MODELS)[number];
type StreamStartRequest = {
streamId: string;
streamUrl: string;
type: 'start_stream';
video: {
fps: number;
};
};
type PersistedDefaultDevice = Device & {
savedAt: number;
version: 1;
};
type PersistedCloudUrls = {
streamProtocol?: StreamProtocol;
savedAt: number;
streamUrl?: string;
version: 1;
webhookUrl?: string;
};
export const RGB_LED_COLORS: LedColor[] = ['red', 'green', 'blue', 'orange', 'white'];
export const PHOTO_SIZES: PhotoSize[] = ['low', 'medium', 'high', 'max'];
export const PHOTO_COMPRESSIONS: PhotoCompression[] = ['none', 'low', 'medium', 'high'];
export const PHOTO_TRANSFER_METHODS: PhotoTransferMethod[] = ['auto', 'direct', 'ble'];
export const PHOTO_AE_EXPOSURE_DIVISOR_OPTIONS: PhotoAeExposureDivisor[] = [2, 3, 5];
export const PHOTO_ISO_CAP_OPTIONS: PhotoIsoCap[] = [400, 800, 1600];
export const PHOTO_ISP_DIGITAL_GAIN_OPTIONS: PhotoIspDigitalGain[] = [0, 1, 2, 4];
export const PHOTO_ISP_ANALOG_GAIN_OPTIONS: PhotoIspAnalogGain[] = ['low'];
export const PHOTO_TUNING_FLAG_OPTIONS: PhotoTuningFlag[] = ['unset', 'on', 'off'];
export const STREAM_MIN_FPS = 1;
export const STREAM_MAX_FPS = 24;
export const STREAM_DEFAULT_FPS = 15;
export const PHOTO_EXPOSURE_MIN_NS = 1_000_000;
export const PHOTO_EXPOSURE_MAX_NS = 33_333_333;
export const PHOTO_EXPOSURE_DEFAULT_NS = 8_333_333;
export const PHOTO_ISO_MIN = 100;
export const PHOTO_ISO_MAX = 6400;
export const PHOTO_ISO_DEFAULT = 200;
export const CAMERA_FOV_MIN = 62;
export const CAMERA_FOV_MAX = 118;
export const CAMERA_FOV_DEFAULT = 102;
const CAMERA_WARM_UP_DURATION_MS = 30_000;
const CAMERA_WARM_UP_REFRESH_MS = 20_000;
const CAMERA_WARM_UP_DISCONNECTED_RETRY_MS = 2_000;
export const CAMERA_ROI_POSITIONS = [
{label: 'Center', value: 'center'},
{label: 'Bottom', value: 'bottom'},
{label: 'Top', value: 'top'},
] as const satisfies ReadonlyArray<{label: string; value: CameraRoiPosition}>;
export const STREAM_DEFAULT_URLS: Record<StreamProtocol, string> = {
rtmp: 'rtmp://<computer-ip>:1935/live/mentra-live',
srt: 'srt://<computer-ip>:8890?streamid=publish:mentra-live',
webrtc: 'http://<computer-ip>:8889/mentra-live/whip',
};
export const PHOTO_UPLOAD_DEFAULT_URL = 'http://<computer-ip>:8787/upload';
const STREAM_DEFAULT_URL_VALUES = new Set(Object.values(STREAM_DEFAULT_URLS));
const CAMERA_BUTTON_GALLERY_MODE_NOTICE =
'Gallery mode is on. Photo stays on glasses and is not previewed.';
const CAMERA_ACTION_BUTTON_IDS = new Set(['action', 'camera', 'main', 'primary']);
type MicPcmChunk = {
data: Uint8Array;
index: number;
};
export type SdkConsoleEvent = {
tag: 'LIVE' | 'STORE' | 'BLE' | 'TX';
text: string;
time: string;
};
export type MentraLiveVersions = {
appVersion: string | null;
besFirmwareVersion: string | null;
mtkFirmwareVersion: string | null;
};
export type BluetoothSdkExampleState = {
activeAction: string | null;
barcodeScan: BarcodeScanDetails;
cameraButtonNotice: string | null;
cameraStatus: string;
/** Stable for one BLE connection; advances after disconnect before reconnect. */
glassesConnectionGeneration: number;
defaultDevice: Device | null;
discoveredDevices: Device[];
events: SdkConsoleEvent[];
galleryModeEnabled: boolean;
touchGestureDefaults: TouchGestureDefaults;
touchGesturePending: TouchGesture | null;
setTouchGestureDefaultBehaviorEnabled: (gesture: TouchGesture, enabled: boolean) => Promise<void>;
galleryServerReachable: boolean | null;
galleryServerStatus: string;
glasses: GlassesRuntimeState;
hotspotEnabled: boolean;
/** Optimistic local toggle — glasses do not report Wi-Fi ADB status. */
wifiAdbEnabled: boolean;
lastAction: string;
lastMicBytes: number;
lastMicDurationSeconds: number | null;
mentraLiveVersions: MentraLiveVersions;
micAudioRouteStatus: string;
ledColor: LedColor;
ledMode: LedMode;
micElapsedSeconds: number;
micPlaybackHint: string | null;
micPlaying: boolean;
micRecording: boolean;
pcmBytes: number;
pcmFrames: number;
speaking: boolean | null;
voiceActivityDetectionEnabled: boolean;
wifiConnectError: string | null;
wifiConnectingSsid: string | null;
permissionStatus: string;
phonePhotoReceiverRunning: boolean;
phonePhotoUploadUrl: string | null;
photoCompression: PhotoCompression;
photoCloudServerEnabled: boolean;
photoGlassesStorageEnabled: boolean;
photoAeExposureDivisor: PhotoAeExposureDivisor | null;
photoIsoCap: PhotoIsoCap | null;
photoNoiseReduction: PhotoTuningFlag;
photoEdgeEnhancement: PhotoTuningFlag;
photoMfnr: PhotoTuningFlag;
photoZsl: PhotoTuningFlag;
photoIspDigitalGain: PhotoIspDigitalGain | null;
photoIspAnalogGain: PhotoIspAnalogGain | null;
photoExposureManual: boolean;
photoIso: number;
photoExposureTimeNs: number;
photoPreviewDetails: PhotoPreviewDetails | null;
photoPreviewUrl: string | null;
photoStatus: PhotoStatusEvent | null;
photoSize: PhotoSize;
photoTransferMethod: PhotoTransferMethod;
barcodeScanningEnabled: boolean;
textMode: boolean;
videoPreviewDetails: VideoPreviewDetails | null;
videoPreviewUrl: string | null;
videoRecording: boolean;
videoStatus: VideoRecordingStatusEvent | null;
cameraFov: number;
cameraRoiPosition: CameraRoiPosition;
cameraSettingsApplying: boolean;
cameraSettingsStatus: string;
rawJsonExpanded: boolean;
scanActive: boolean;
scanHint: string | null;
selectedDiscoveredDevice: Device | null;
selectedScanModel: ScanModel;
directStreamReceiverRunning: boolean;
directStreamWhipUrl: string | null;
streamCloudServerEnabled: boolean;
streamFps: number;
streamProtocol: StreamProtocol;
streamPreviewReady: boolean;
streamRequested: boolean;
streamResolvedConfig: StreamResolvedConfig | null;
streamStartPending: boolean;
streamStartedAt: number | null;
streamStatus: string;
streamUrl: string;
webhookUrl: string;
phone: PhoneSdkRuntimeState;
};
export type BluetoothSdkExampleActions = {
captureAndUpload: () => Promise<void>;
clearDefaultDevice: () => Promise<void>;
clearDisplay: () => Promise<void>;
connect: () => Promise<void>;
connectDevice: (device: Device) => Promise<void>;
disconnect: () => Promise<void>;
displayHello: () => Promise<void>;
forgetCurrentWifiNetwork: () => Promise<void>;
copyGalleryHotspotPassword: () => Promise<void>;
copyGalleryServerUrl: () => Promise<void>;
openBluetoothSettings: () => Promise<void>;
openGalleryServer: () => Promise<void>;
openPhotoPreview: () => Promise<void>;
openWifiSettings: () => Promise<void>;
prepareGlassesPhotoPreview: () => Promise<void>;
requestWifiScan: () => Promise<void>;
playMicRecording: () => Promise<void>;
selectDiscoveredDevice: (device: Device) => void;
selectScanModel: (model: ScanModel) => void;
selectLedColor: (color: LedColor) => Promise<void>;
selectLedMode: (mode: LedMode) => Promise<void>;
selectProtocol: (protocol: StreamProtocol) => void;
sendWifiCredentials: (ssid: string, password: string, requiresPassword: boolean) => Promise<void>;
setGalleryModeEnabled: (enabled: boolean) => Promise<void>;
setPhotoCompression: (compression: PhotoCompression) => void;
setPhotoCloudServerEnabled: (enabled: boolean) => Promise<void>;
setPhotoGlassesStorageEnabled: (enabled: boolean) => Promise<void>;
setPhotoAeExposureDivisor: (divisor: PhotoAeExposureDivisor | null) => void;
setPhotoIsoCap: (isoCap: PhotoIsoCap | null) => void;
setPhotoNoiseReduction: (value: PhotoTuningFlag) => void;
setPhotoEdgeEnhancement: (value: PhotoTuningFlag) => void;
setPhotoMfnr: (value: PhotoTuningFlag) => void;
setPhotoZsl: (value: PhotoTuningFlag) => void;
setPhotoIspDigitalGain: (gain: PhotoIspDigitalGain | null) => void;
setPhotoIspAnalogGain: (gain: PhotoIspAnalogGain | null) => void;
setPhotoExposureManual: (enabled: boolean) => void;
setPhotoIso: (iso: number) => void;
setPhotoExposureTimeNs: (exposureTimeNs: number) => void;
setPhotoSize: (size: PhotoSize) => void;
setPhotoTransferMethod: (transferMethod: PhotoTransferMethod) => void;
setBarcodeScanningEnabled: (enabled: boolean) => void;
setTextMode: (enabled: boolean) => void;
setCameraFov: (fov: number) => void;
setCameraRoiPosition: (roiPosition: CameraRoiPosition) => void;
applyCameraSettings: () => Promise<void>;
setRawJsonExpanded: (expanded: boolean) => void;
setStreamCloudServerEnabled: (enabled: boolean) => Promise<void>;
setStreamFps: (fps: number) => void;
setStreamUrl: (url: string) => void;
setWebhookUrl: (url: string) => void;
setVoiceActivityDetectionEnabled: (enabled: boolean) => Promise<void>;
startScan: () => Promise<void>;
testWebhook: () => Promise<void>;
toggleHotspot: () => Promise<void>;
setWifiAdbState: (enabled: boolean) => Promise<void>;
toggleMic: () => Promise<void>;
toggleVideoRecording: () => Promise<void>;
toggleStream: () => Promise<void>;
};
export type BluetoothSdkExampleModel = BluetoothSdkExampleState & BluetoothSdkExampleActions;
const PHOTO_APP_ID = 'com.mentra.examples.reactnative';
const PHOTO_POLL_ATTEMPTS = 45;
const GLASSES_PHOTO_POLL_ATTEMPTS = 120;
const GLASSES_GALLERY_FAILURE_THRESHOLD = 3;
const VIDEO_POLL_ATTEMPTS = 180;
const DIRECT_PHOTO_UPLOAD_TIMEOUT_MS = 75_000;
export const PHOTO_BLE_FALLBACK_TRANSFER_MESSAGE =
'Photo is transferred over Bluetooth, which takes longer than Wi-Fi.';
const PHOTO_BLE_FALLBACK_COMPRESSION_MESSAGE =
'Preparing the photo for Bluetooth transfer.';
const DIRECT_WEBRTC_RECEIVER_WARMUP_MS = 1000;
const BARCODE_SCAN_VISIBLE_TIMEOUT_MS = 2_500;
const ANDROID_12_API_LEVEL = 31;
const MIC_SAMPLE_RATE = 16000;
const MIC_CHANNEL_COUNT = 1;
const MIC_BITS_PER_SAMPLE = 16;
const DEFAULT_DEVICE_FILE = 'mentra-default-device.json';
const CLOUD_URLS_FILE = 'mentra-cloud-urls.json';
const IOS_AUDIO_ROUTE_HINT =
'Audio output: iOS cannot pair audio from the app. Open Settings > Bluetooth and connect/select the glasses before playback.';
const defaultDeviceStorage: DefaultDeviceStorage = {
load: loadPersistedDefaultDevice,
save: savePersistedDefaultDevice,
};
declare const process: {
env?: {
EXPO_PUBLIC_MENTRA_PHOTO_WEBHOOK_URL?: string;
EXPO_PUBLIC_MENTRA_STREAM_URL?: string;
};
};
export function useBluetoothSdkExample(options: BluetoothSdkExampleOptions = {}): BluetoothSdkExampleModel {
const activeTab = options.activeTab ?? 'device';
const [events, setEvents] = useState<SdkConsoleEvent[]>([
event('LIVE', 'SDK ready. Scan to discover glasses.'),
]);
const [activeAction, setActiveAction] = useState<string | null>(null);
const [lastAction, setLastAction] = useState('No actions yet.');
const [permissionStatus, setPermissionStatus] = useState(
Platform.OS === 'android'
? 'Permissions: not requested'
: 'Permissions: iOS prompts as needed',
);
const [webhookUrl, setWebhookUrlState] = useState(
process.env?.EXPO_PUBLIC_MENTRA_PHOTO_WEBHOOK_URL ?? PHOTO_UPLOAD_DEFAULT_URL,
);
const [photoDestination, setPhotoDestination] = useState<PhotoDestination>('phone');
const photoCloudServerEnabled = photoDestination === 'cloud';
const photoGlassesStorageEnabled = photoDestination === 'glasses';
const [phonePhotoReceiverRunning, setPhonePhotoReceiverRunning] = useState(false);
const [phonePhotoUploadUrl, setPhonePhotoUploadUrl] = useState<string | null>(null);
const [cameraStatus, setCameraStatus] = useState('Camera: ready to capture to phone');
const [cameraButtonNotice, setCameraButtonNotice] = useState<string | null>(null);
const [barcodeScan, setBarcodeScan] = useState<BarcodeScanDetails>({
barcodes: [],
state: 'idle',
});
const barcodeScanRef = useRef<BarcodeScanDetails>({
barcodes: [],
state: 'idle',
});
const [photoPreviewDetails, setPhotoPreviewDetails] =
useState<PhotoPreviewDetails | null>(null);
const [photoPreviewUrl, setPhotoPreviewUrl] = useState<string | null>(null);
const [photoStatus, setPhotoStatus] = useState<PhotoStatusEvent | null>(null);
const [videoPreviewDetails, setVideoPreviewDetails] =
useState<VideoPreviewDetails | null>(null);
const [videoPreviewUrl, setVideoPreviewUrl] = useState<string | null>(null);
const [videoRecording, setVideoRecording] = useState(false);
const [videoStatus, setVideoStatus] = useState<VideoRecordingStatusEvent | null>(null);
const [photoSize, setPhotoSize] = useState<PhotoSize>('max');
const [photoCompression, setPhotoCompression] = useState<PhotoCompression>('none');
const [photoTransferMethod, setPhotoTransferMethod] = useState<PhotoTransferMethod>('auto');
const [barcodeScanningEnabled, setBarcodeScanningEnabled] = useState(false);
const [textMode, setTextMode] = useState(false);
const [photoAeExposureDivisor, setPhotoAeExposureDivisor] =
useState<PhotoAeExposureDivisor | null>(null);
const [photoIsoCap, setPhotoIsoCap] = useState<PhotoIsoCap | null>(null);
const [photoNoiseReduction, setPhotoNoiseReduction] = useState<PhotoTuningFlag>('unset');
const [photoEdgeEnhancement, setPhotoEdgeEnhancement] = useState<PhotoTuningFlag>('unset');
const [photoMfnr, setPhotoMfnr] = useState<PhotoTuningFlag>('unset');
const [photoZsl, setPhotoZsl] = useState<PhotoTuningFlag>('unset');
const [photoIspDigitalGain, setPhotoIspDigitalGain] =
useState<PhotoIspDigitalGain | null>(null);
const [photoIspAnalogGain, setPhotoIspAnalogGain] =
useState<PhotoIspAnalogGain | null>(null);
const [photoExposureManual, setPhotoExposureManual] = useState(false);
const [photoExposureTimeNs, setPhotoExposureTimeNsState] = useState(PHOTO_EXPOSURE_DEFAULT_NS);
const [photoIso, setPhotoIsoState] = useState(PHOTO_ISO_DEFAULT);
const [cameraFov, setCameraFovState] = useState(CAMERA_FOV_DEFAULT);
const [cameraRoiPosition, setCameraRoiPositionState] = useState<CameraRoiPosition>('center');
const [cameraSettingsApplying, setCameraSettingsApplying] = useState(false);
const cameraSettingsApplyingRef = useRef(false);
const [cameraSettingsStatus, setCameraSettingsStatus] = useState('Camera settings: default');
const [streamCloudServerEnabled, setStreamCloudServerEnabledState] = useState(false);
const [directStreamReceiverRunning, setDirectStreamReceiverRunning] = useState(false);
const [directStreamWhipUrl, setDirectStreamWhipUrl] = useState<string | null>(null);
const [streamProtocol, setStreamProtocol] =
useState<StreamProtocol>('webrtc');
const [streamUrl, setStreamUrlState] = useState(
process.env?.EXPO_PUBLIC_MENTRA_STREAM_URL ?? STREAM_DEFAULT_URLS.webrtc,
);
const [streamFps, setStreamFps] = useState(STREAM_DEFAULT_FPS);
const [streamStartedAt, setStreamStartedAt] = useState<number | null>(null);
const [streamRequested, setStreamRequested] = useState(false);
const [streamStartPending, setStreamStartPending] = useState(false);
const [streamPreviewReady, setStreamPreviewReady] = useState(false);
const [streamResolvedConfig, setStreamResolvedConfig] =
useState<StreamResolvedConfig | null>(null);
const [streamStatus, setStreamStatus] = useState('Ready to stream WebRTC to phone');
const [micRecording, setMicRecording] = useState(false);
const [micPlaying, setMicPlaying] = useState(false);
const [micElapsedSeconds, setMicElapsedSeconds] = useState(0);
const [pcmFrames, setPcmFrames] = useState(0);
const [pcmBytes, setPcmBytes] = useState(0);
const [speaking, setSpeaking] = useState<boolean | null>(null);
const [voiceActivityDetectionEnabled, setVoiceActivityDetectionEnabledState] = useState(false);
const [lastMicBytes, setLastMicBytes] = useState(0);
const [lastMicDurationSeconds, setLastMicDurationSeconds] = useState<number | null>(null);
const [micPlaybackHint, setMicPlaybackHint] = useState<string | null>(null);
const [wifiConnectingSsid, setWifiConnectingSsid] = useState<string | null>(null);
const [wifiConnectError, setWifiConnectError] = useState<string | null>(null);
const [micAudioRouteStatus, setMicAudioRouteStatus] = useState(
Platform.OS === 'ios'
? IOS_AUDIO_ROUTE_HINT
: 'Audio output: waiting for Bluetooth audio status',
);
const [galleryServerReachable, setGalleryServerReachable] = useState<boolean | null>(null);
const [galleryServerStatus, setGalleryServerStatus] = useState(
'Gallery server: enable hotspot to check',
);
const [touchGestureDefaults, setTouchGestureDefaults] = useState(initialTouchGestureDefaults);
const [touchGesturePending, setTouchGesturePending] = useState<TouchGesture | null>(null);
const touchGesturePendingRef = useRef<TouchGesture | null>(null);
const [ledColor, setLedColor] = useState<LedColor>('green');
const [ledMode, setLedMode] = useState<LedMode>('Off');
const [rawJsonExpanded, setRawJsonExpanded] = useState(false);
const activePhotoRequestIdRef = useRef<string | null>(null);
const activeVideoRequestIdRef = useRef<string | null>(null);
const activeStreamIdRef = useRef<string | null>(null);
const videoRecordingRef = useRef(false);
const streamStartPendingRef = useRef(false);
const pollGenerationRef = useRef(0);
const videoPollGenerationRef = useRef(0);
const photoDestinationRef = useRef<PhotoDestination>('phone');
const photoDestinationBeforeGlassesRef = useRef<Exclude<PhotoDestination, 'glasses'>>('phone');
const galleryConnectionGenerationRef = useRef(0);
/** BLE session generation — advances only on glasses disconnect/reconnect. */
const glassesConnectionGenerationRef = useRef(0);
const galleryConnectionPromiseRef = useRef<Promise<void> | null>(null);
const galleryServerReachableRef = useRef<boolean | null>(null);
const galleryBaseUrlRef = useRef<string | null>(null);
const galleryHotspotSsidRef = useRef<string | null>(null);
const barcodeScanningEnabledRef = useRef(false);
const textModeRef = useRef(false);
const cameraWarmUpFailureLoggedRef = useRef(false);
const streamCloudServerEnabledRef = useRef(false);
const activeTabRef = useRef<ExampleTabKey>('device');
const galleryModeEnabledRef = useRef(false);
const captureAndUploadRef = useRef<() => Promise<void>>(async () => undefined);
const photoUploadTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const previewHealthTimerRef = useRef<ReturnType<typeof setInterval> | null>(null);
const directStreamFrameStaleTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const barcodeScanTokenRef = useRef(0);
const barcodeScanRequestIdsRef = useRef(new Set<string>());
const photoPreviewOpeningRef = useRef(false);
const galleryModePhotoRequestIdsRef = useRef(new Set<string>());
const phonePhotoReceiverRef = useRef<PhotoReceiverResult | null>(null);
const phonePhotoReceiverStartPromiseRef = useRef<Promise<PhotoReceiverResult> | null>(null);
const lastCameraInputCaptureAtRef = useRef(0);
const lastMicFileUriRef = useRef<string | null>(null);
const micElapsedSecondsRef = useRef(0);
const micElapsedTimerRef = useRef<ReturnType<typeof setInterval> | null>(null);
const micPcmChunksRef = useRef<MicPcmChunk[]>([]);
const micPcmChunkIndexRef = useRef(0);
const micPcmStatsRef = useRef({bytes: 0, frames: 0});
const micPlayerRef = useRef<AudioPlayer | null>(null);
const micPlayerSubscriptionRef = useRef<{remove: () => void} | null>(null);
const micPlayingRef = useRef(false);
const micRecordingRef = useRef(false);
const micStartedAtRef = useRef<number | null>(null);
const didAutoConnectDefaultRef = useRef(false);
const wasConnectedRef = useRef(false);
const glassesConnectedRef = useRef(false);
const wifiConnectAttemptRef = useRef(0);
const wifiConnectGraceTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const wifiConnectingSsidRef = useRef<string | null>(null);
const [latestVersionInfo, setLatestVersionInfo] = useState<VersionInfoResult | null>(null);
const bluetooth = useMentraBluetooth({
defaultDeviceStorage,
defaultModel: DeviceModels.MentraLive,
onError: (error: unknown) => {
addEvent('TX', `SDK lifecycle error: ${formatError(error)}`);
},
scanTimeoutMs: 10_000,
});
const defaultDevice = bluetooth.defaultDevice;
const discoveredDevices = bluetooth.scan.devices;
const glasses = bluetooth.glasses;
const glassesConnected = glasses.connected;
const connectedDeviceKey = glassesConnected
? [
glasses.device.bluetoothName,
glasses.device.serialNumber,
glasses.device.deviceModel,
].filter(Boolean).join('|') || 'connected'
: null;
const phone = bluetooth.sdk;
const scanActive = bluetooth.scan.active;
const galleryModeEnabled = phone.galleryMode.enabled;
const hotspotEnabled = enabledHotspotStatus(glasses) !== null;
const [wifiAdbEnabled, setWifiAdbEnabled] = useState(false);
const selectedDiscoveredDevice = bluetooth.scan.selectedDevice;
const selectedScanModel = scanModelFromDeviceModel(bluetooth.scan.model);
activeTabRef.current = activeTab;
galleryModeEnabledRef.current = galleryModeEnabled;
glassesConnectedRef.current = glassesConnected;
galleryServerReachableRef.current = galleryServerReachable;
// Optimistic Wi-Fi ADB UI only — reset on disconnect. Do not key off the full
// connectedDeviceKey: late-arriving identity fields (serial/model) rewrite that
// string mid-session and would clear a successful toggle.
useEffect(() => {
if (connectedDeviceKey === null) {
setWifiAdbEnabled(false);
}
}, [connectedDeviceKey]);
useEffect(() => {
let cancelled = false;
void loadPersistedCloudUrls().then((persisted) => {
if (cancelled || !persisted) {
return;
}
if (!process.env?.EXPO_PUBLIC_MENTRA_PHOTO_WEBHOOK_URL && typeof persisted.webhookUrl === 'string') {
setWebhookUrlState(persisted.webhookUrl);
}
const streamUrlOverride = process.env?.EXPO_PUBLIC_MENTRA_STREAM_URL;
if (!streamUrlOverride && persisted.streamProtocol) {
setStreamProtocol(persisted.streamProtocol);
}
if (!streamUrlOverride && typeof persisted.streamUrl === 'string') {
setStreamUrlState(persisted.streamUrl);
} else if (!streamUrlOverride && persisted.streamProtocol) {
setStreamUrlState(STREAM_DEFAULT_URLS[persisted.streamProtocol]);
}
}).catch((error) => {
addEvent('LIVE', `cloud URL restore failed: ${formatError(error)}`);
});
return () => {
cancelled = true;
};
}, []);
function applyVersionInfo(payload: VersionInfoResult) {
if (!glassesConnectedRef.current) {
return;
}
setLatestVersionInfo(payload);
}
useEffect(() => {
setLatestVersionInfo(null);
if (!glassesConnected || !isMentraLiveRuntime(glasses)) {
return;
}
let cancelled = false;
void BluetoothSdk.requestVersionInfo()
.then((payload) => {
if (!cancelled) {
applyVersionInfo(payload);
}
})
.catch((error) => {
if (!cancelled && glassesConnectedRef.current) {
addEvent('LIVE', `version info refresh failed: ${formatError(error)}`);
}
});
return () => {
cancelled = true;
};
}, [connectedDeviceKey, glassesConnected]); // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => {
if (didAutoConnectDefaultRef.current || glassesConnected) {
return;
}
if (!defaultDevice) {
return;
}
didAutoConnectDefaultRef.current = true;
void runAction('Auto-connect default', async () => {
if (!(await ensureAndroidPermissions('connect'))) {
throw new Error('Bluetooth permissions are required to connect.');
}
await bluetooth.connectDefault();
});
}, [defaultDevice, glassesConnected]);
useEffect(() => {
const subscriptions = [
BluetoothSdk.addListener('button_press', handleButtonPress),
BluetoothSdk.addListener('touch_event', handleTouchEvent),
BluetoothSdk.addListener('voice_activity_detection_status', (payload: VoiceActivityDetectionStatusEvent) => {
setVoiceActivityDetectionEnabledState(payload.voiceActivityDetectionEnabled);
if (!payload.voiceActivityDetectionEnabled) {
setSpeaking(null);
}
addEvent('LIVE', `voice activity detection ${payload.voiceActivityDetectionEnabled ? 'enabled' : 'disabled'}`);
}),
BluetoothSdk.addListener('speaking_status', (payload: SpeakingStatusEvent) => {
setSpeaking(payload.speaking);
}),
BluetoothSdk.addListener('battery_status', (payload) => {
addEvent('STORE', `battery ${payload.level}%${payload.charging ? ' charging' : ''}`);
}),
BluetoothSdk.addListener('wifi_status_change', (payload) => {
if (payload.state === 'connected') {
const targetSsid = wifiConnectingSsidRef.current;
if (!targetSsid || payload.ssid === targetSsid) {
// A connect that outlived the SDK request timeout resolved late,
// or the glasses (re)connected with no attempt pending.
settleWifiConnectAttempt();
setWifiConnectError(null);
} else {
// Re-associating with a different network while a join is
// pending means the join failed (e.g. wrong password).
settleWifiConnectAttempt();
setWifiConnectError(`Could not connect to ${targetSsid}. Check the password and try again.`);
}
}
addEvent('STORE', `Wi-Fi ${payload.state === 'connected' ? payload.ssid : payload.state}`);
}),
BluetoothSdk.addListener('hotspot_status_change', (payload) => {
galleryBaseUrlRef.current = payload.state === 'enabled'
? `http://${payload.localIp}:8089`
: null;
galleryHotspotSsidRef.current = payload.state === 'enabled' ? payload.ssid : null;
setGalleryServerReachable((current) =>
payload.state === 'enabled'
? current
: photoDestinationRef.current === 'glasses'
? false
: null,
);
setGalleryServerStatus(
payload.state === 'enabled'
? `Gallery server: http://${payload.localIp}:8089`
: 'Gallery server: hotspot off',
);
addEvent('STORE', `hotspot ${summarizeMap(payload)}`);
}),
BluetoothSdk.addListener('hotspot_error', (payload) => {
setGalleryServerReachable(false);
setGalleryServerStatus('Gallery server: hotspot error');
addEvent('TX', `hotspot error ${summarizeMap(payload)}`);
}),
MentraPhotoReceiver.addListener('photoUpload', handleDirectPhotoUpload),
MentraPhotoReceiver.addListener('receiverStatus', handlePhotoReceiverStatus),
MentraVideoStreamReceiver.addListener('receiverStatus', handleVideoStreamReceiverStatus),
MentraVideoStreamReceiver.addListener('streamFrame', handleDirectStreamFrame),
MentraVideoStreamReceiver.addListener('streamFirstFrame', handleDirectStreamFirstFrame),
BluetoothSdk.addListener('photo_status', handlePhotoStatus),
BluetoothSdk.addListener('video_recording_status', handleVideoRecordingStatus),
BluetoothSdk.addListener('media_success', handleMediaUpload),
BluetoothSdk.addListener('media_error', handleMediaUpload),
BluetoothSdk.addListener('stream_status', (payload: StreamStatusEvent) => {
applyStreamStatus(payload);
if (streamCloudServerEnabledRef.current) {
setStreamStatus(JSON.stringify(payload));
}
addEvent('LIVE', `stream status ${summarizeMap(payload)}`);
}),
BluetoothSdk.addListener('version_info', (payload: VersionInfoEvent) => {
applyVersionInfo(payload);
}),
BluetoothSdk.addListener('mic_pcm', (payload: MicPcmEvent) => {
if (!micRecordingRef.current) {
return;
}
const frame = copyPcmFrame(payload.pcm);
if (frame.byteLength === 0) {
return;
}
const isFirstFrame = micPcmStatsRef.current.frames === 0;
micPcmChunksRef.current.push({
data: frame,
index: micPcmChunkIndexRef.current,
});
micPcmChunkIndexRef.current += 1;
micPcmStatsRef.current.frames += 1;
micPcmStatsRef.current.bytes += frame.byteLength;
if (isFirstFrame) {
addEvent('LIVE', `recording ${formatMicPcmMetadata(payload)}`);
}
}),
BluetoothSdk.addListener('mic_lc3', (payload: MicLc3Event) => {
if (micRecordingRef.current) {
addEvent('LIVE', `received LC3 mic frame while PCM recording is enabled (${formatMicLc3Metadata(payload)})`);
}
}),
BluetoothSdk.addListener('audio_connected', (payload: AudioConnectedEvent) => {
const deviceName = payload.deviceName || 'Bluetooth audio';
setMicAudioRouteStatus(`Audio output: connected to ${deviceName}`);
setMicPlaybackHint(null);
addEvent('LIVE', `audio connected ${deviceName}`);
}),
BluetoothSdk.addListener('audio_disconnected', () => {
setMicAudioRouteStatus(
Platform.OS === 'ios'
? IOS_AUDIO_ROUTE_HINT
: 'Audio output: Bluetooth audio is not connected',
);
addEvent('LIVE', 'audio disconnected');
}),
BluetoothSdk.addListener(
'compatible_glasses_search_stop',
(payload: CompatibleGlassesSearchStopEvent) => {
addEvent('BLE', `scan stopped for ${payload.deviceModel ?? 'glasses'}`);
},
),
BluetoothSdk.addListener('log', (payload: LogEvent) => {
addEvent('LIVE', payload.message);
}),
];
if (webhookUrl) {
addEvent('LIVE', 'Loaded webhook URL from env.');
}
void ensureAndroidPermissions('startup');
return () => {
subscriptions.forEach((subscription) => subscription.remove());
clearPhotoUploadTimeout();
stopPreviewHealthPoll();
stopDirectStreamFrameWatchdog();
void stopPhonePhotoReceiver().catch(() => undefined);
void MentraVideoStreamReceiver.stopWebRtcReceiver().catch(() => undefined);
activeStreamIdRef.current = null;
activeVideoRequestIdRef.current = null;
videoRecordingRef.current = false;
streamStartPendingRef.current = false;
activePhotoRequestIdRef.current = null;
barcodeScanRequestIdsRef.current.clear();
pollGenerationRef.current += 1;
videoPollGenerationRef.current += 1;
stopMicElapsedTimer();
stopMicPlaybackSync();
};
}, []);
useEffect(() => {
if (activeTab !== 'camera' || photoDestination !== 'phone' || !glassesConnected) {
return;
}
void ensurePhonePhotoReceiver('camera tab').catch((error) => {
addEvent('TX', `photo receiver prewarm failed: ${formatError(error)}`);
});
}, [activeTab, photoDestination, glassesConnected]);
useEffect(() => {
if (activeTab !== 'camera') {
return;
}
let cancelled = false;
let timer: ReturnType<typeof setTimeout> | null = null;
function scheduleNext(delayMs: number) {
timer = setTimeout(() => {
void warmUpCamera();
}, delayMs);
}
async function warmUpCamera() {
if (cancelled || activeTabRef.current !== 'camera') {
return;
}
if (!glassesConnectedRef.current) {
scheduleNext(CAMERA_WARM_UP_DISCONNECTED_RETRY_MS);
return;
}
try {
await BluetoothSdk.warmUpCamera({
size: photoSize,
exposureTimeNs: photoExposureManual ? photoExposureTimeNs : null,
durationMs: CAMERA_WARM_UP_DURATION_MS,
});
cameraWarmUpFailureLoggedRef.current = false;
} catch (error) {
if (!cancelled && glassesConnectedRef.current && !cameraWarmUpFailureLoggedRef.current) {
cameraWarmUpFailureLoggedRef.current = true;
addEvent('TX', `camera warm-up failed: ${formatError(error)}`);
}
}
if (!cancelled) {
scheduleNext(CAMERA_WARM_UP_REFRESH_MS);
}
}
cameraWarmUpFailureLoggedRef.current = false;
void warmUpCamera();
return () => {
cancelled = true;
if (timer != null) {
clearTimeout(timer);
}
};
}, [activeTab, photoExposureManual, photoExposureTimeNs, photoSize]);
useEffect(() => {
if (glassesConnected) {
if (bluetooth.scan.diagnostic) bluetooth.scan.clear();
if (!wasConnectedRef.current && photoDestinationRef.current === 'glasses') {
void prepareGlassesPhotoPreviewAction();
}
wasConnectedRef.current = true;
return;
}
// Reset on any connected -> not-connected transition. During an
// auto-reconnect (e.g. the post-BES-update reboot) the SDK publishes
// 'disconnected' and 'connecting' in the same bridge flush, so the app
// never renders the 'disconnected' state.
if (wasConnectedRef.current) {
wasConnectedRef.current = false;
applyDisconnectedState(isDisconnectedStatus(glasses) ? 'Disconnected' : 'Reconnecting');
}
}, [glassesConnected, glasses]); // eslint-disable-line react-hooks/exhaustive-deps
function addEvent(tag: SdkConsoleEvent['tag'], text: string) {
setEvents((current) => [event(tag, text), ...current].slice(0, 30));
}
function handleButtonPress(payload: ButtonPressEvent) {
addEvent('LIVE', `button ${payload.buttonId}: ${payload.pressType}`);
if (activeTabRef.current !== 'camera' || !isCameraActionButtonPress(payload)) {
return;
}
triggerCameraInputCapture('button');
}
function handleTouchEvent(payload: TouchEvent) {
const gesture = payload.gestureName ?? payload.deviceModel ?? 'event';
addEvent(
'LIVE',
`${gesture.toLowerCase().includes('swipe') ? 'swipe' : 'touch'} ${gesture}`,
);
if (activeTabRef.current !== 'camera' || !isCameraActionTouchEvent(payload)) {
return;
}
triggerCameraInputCapture(gesture);
}
function triggerCameraInputCapture(source: string) {
if (galleryModeEnabledRef.current) {
showCameraButtonNotice(CAMERA_BUTTON_GALLERY_MODE_NOTICE);
addEvent('TX', 'gallery mode kept button photo on glasses');
return;
}
if (activePhotoRequestIdRef.current) {
addEvent('LIVE', `ignoring ${source}; photo already in progress`);
return;
}
const now = Date.now();
if (now - lastCameraInputCaptureAtRef.current < 1000) {
addEvent('LIVE', `ignoring duplicate camera input ${source}`);
return;
}
lastCameraInputCaptureAtRef.current = now;
addEvent('TX', `camera input capture ${source}`);
void captureAndUploadRef.current();
}
async function runAction(label: string, action: () => Promise<void> | void) {
setActiveAction(label);
setLastAction(`Running: ${label}`);
addEvent('TX', label);
try {
await action();
setLastAction(`Requested: ${label}`);
} catch (error) {
const message = formatError(error);
setLastAction(`Failed: ${label} - ${message}`);
addEvent('TX', `${label} failed: ${message}`);
} finally {
setActiveAction((current) => (current === label ? null : current));
}
}
async function ensureAndroidPermissions(reason: string) {
if (Platform.OS !== 'android') {
return true;
}
const permissions = androidRuntimePermissions();
const results = await PermissionsAndroid.requestMultiple(permissions);
const denied = permissions.filter(
(permission) =>
results[permission] !== PermissionsAndroid.RESULTS.GRANTED,
);
if (denied.length > 0) {
setPermissionStatus(`Permissions: missing ${denied.length}`);
addEvent('BLE', `permissions denied for ${reason}: ${denied.join(', ')}`);
return false;
}
setPermissionStatus('Permissions: granted');
return true;
}
async function startScan() {
const model = selectedScanModel;
await runAction(`Scan ${scanModelLabel(model)}`, async () => {
if (!(await ensureAndroidPermissions('scan'))) {
throw new Error('Bluetooth permissions are required to scan.');
}
bluetooth.scan.selectDevice(null);
const devices = await bluetooth.scan.start(model);
addEvent('BLE', `scan completed with ${devices.length} result${devices.length === 1 ? '' : 's'}`);
});
}
async function connect() {
await runAction('Connect', async () => {
if (!(await ensureAndroidPermissions('connect'))) {
throw new Error('Bluetooth permissions are required to connect.');
}
await bluetooth.scan.stop();
if (selectedDiscoveredDevice) {
await bluetooth.connect(selectedDiscoveredDevice);
return;
}
if (discoveredDevices.length === 0 && defaultDevice) {
await bluetooth.connectDefault();
return;
}
if (discoveredDevices.length > 0) {
throw new Error('Choose one of the discovered glasses first.');
}
throw new Error('Scan first to choose nearby glasses.');
});
}
async function connectDevice(device: Device) {
bluetooth.scan.selectDevice(device);
await runAction(`Connect ${device.name}`, async () => {
if (!(await ensureAndroidPermissions('connect'))) {
throw new Error('Bluetooth permissions are required to connect.');
}
await bluetooth.scan.stop();
await bluetooth.connect(device);
});
}
async function disconnect() {
await runAction('Disconnect', async () => {
stopDirectStreamFrameWatchdog();
await bluetooth.disconnect();
applyDisconnectedState('Disconnected');
});
}
async function clearDefaultDevice() {
await runAction('Clear default', async () => {
await bluetooth.clearDefaultDevice();
});
}
function selectDiscoveredDevice(device: Device) {
bluetooth.scan.selectDevice(device);
setLastAction(`Selected: ${device.name}`);
}
function selectScanModel(model: ScanModel) {
if (selectedScanModel === model) {
return;
}
bluetooth.scan.setModel(model);
setLastAction(`Selected scan model: ${scanModelLabel(model)}`);
}
async function displayHello() {
await runAction('Display Hello', async () => {
requireDisplaySupport('display text');
await BluetoothSdk.displayText('Hello from Mentra Bluetooth SDK', 0, 0, 24);
});
}
async function clearDisplay() {
await runAction('Clear Display', async () => {
requireDisplaySupport('clear the display');
await BluetoothSdk.clearDisplay();
});
}
async function setGalleryModeEnabledAction(enabled: boolean) {
await runAction(enabled ? 'Save in gallery mode' : 'Report button events', async () => {
requireConnected('change gallery mode');
await bluetooth.setGalleryModeEnabled(enabled);
});
}
async function setTouchGestureDefaultBehaviorEnabledAction(gesture: TouchGesture, enabled: boolean) {
if (touchGesturePendingRef.current !== null) return;
const generation = glassesConnectionGenerationRef.current;
touchGesturePendingRef.current = gesture;
setTouchGesturePending(gesture);
try {
await runAction(`${enabled ? 'Enable' : 'Disable'} ${gesture} default action`, async () => {
requireConnected('change touchpad default actions');
if (!isMentraLiveRuntime(glasses)) throw new Error('Touchpad default actions require Mentra Live.');
await applyTouchGestureDefault(BluetoothSdk as Parameters<typeof applyTouchGestureDefault>[0], gesture, enabled);
if (generation !== glassesConnectionGenerationRef.current) return;
setTouchGestureDefaults((current) => ({...current, [gesture]: enabled}));
});
} finally {
if (generation === glassesConnectionGenerationRef.current) {
touchGesturePendingRef.current = null;
setTouchGesturePending(null);
}
}
}
function setTextModeAction(enabled: boolean) {
textModeRef.current = enabled;
setTextMode(enabled);
if (enabled) {
barcodeScanningEnabledRef.current = false;
setBarcodeScanningEnabled(false);
resetBarcodeScan();
}
}
function setBarcodeScanningEnabledAction(enabled: boolean) {
barcodeScanningEnabledRef.current = enabled;
setBarcodeScanningEnabled(enabled);
if (enabled) {
textModeRef.current = false;
setTextMode(false);
} else {
resetBarcodeScan();
}
}
function optionalTuningFlag(value: PhotoTuningFlag) {
if (value === 'unset') {
return undefined;
}
return value === 'on';
}
function addRequestTuningFields(
fields: Omit<PhotoRequestParams, 'requestId' | 'webhookUrl' | 'authToken'>,
) {
if (!photoExposureManual && photoAeExposureDivisor !== null) {
fields.aeExposureDivisor = photoAeExposureDivisor;
}
if (!photoExposureManual && photoIsoCap !== null) {
fields.isoCap = photoIsoCap;
}
const noiseReduction = optionalTuningFlag(photoNoiseReduction);
if (noiseReduction !== undefined) {
fields.noiseReduction = noiseReduction;
}
const edgeEnhancement = optionalTuningFlag(photoEdgeEnhancement);
if (edgeEnhancement !== undefined) {
fields.edgeEnhancement = edgeEnhancement;
}
const mfnr = optionalTuningFlag(photoMfnr);
if (mfnr !== undefined) {
fields.mfnr = mfnr;
}
const zsl = optionalTuningFlag(photoZsl);
if (zsl !== undefined) {
fields.zsl = zsl;
}
if (photoIspDigitalGain !== null) {
fields.ispDigitalGain = photoIspDigitalGain;
}
if (photoIspAnalogGain !== null) {
fields.ispAnalogGain = photoIspAnalogGain;
}
return fields;
}
function buildPhotoRequestFields(textModeEnabled: boolean): Omit<
PhotoRequestParams,
'requestId' | 'webhookUrl' | 'authToken'
> {
return addRequestTuningFields({
size: photoSize,
mode: textModeEnabled ? 'text' : 'photo',
transferMethod: photoTransferMethod,
compress: photoCompression,
sound: true,
exposureTimeNs: photoExposureManual ? photoExposureTimeNs : null,
iso: photoExposureManual ? photoIso : null,
});
}
function registerPhotoCaptureOptions(requestId: string, options: PhotoCaptureOptions) {
if (options.scanBarcode) {
barcodeScanRequestIdsRef.current.add(requestId);
}
}
function scanPreviewBarcodeForRequest(requestId: string | null | undefined, sourceUri: string) {
if (!requestId || !barcodeScanRequestIdsRef.current.delete(requestId)) {
return;
}
void scanPreviewBarcode(sourceUri);
}
async function captureAndUpload() {
clearCameraButtonNotice();
resetBarcodeScan();
const captureOptions: PhotoCaptureOptions = {
scanBarcode: !textModeRef.current && barcodeScanningEnabledRef.current,
textMode: textModeRef.current,
};
const captureLabel = captureOptions.textMode ? 'Capture text photo' : 'Capture & upload';
await runAction(captureLabel, async () => {
requireConnected('capture photos');
if (!(await ensureAndroidPermissions('photo'))) {
throw new Error('Camera and Bluetooth permissions are required for photos.');
}
barcodeScanRequestIdsRef.current.clear();
if (photoDestinationRef.current === 'glasses') {
if (galleryServerReachableRef.current !== true) {
throw new Error('Connect to the glasses hotspot before capturing.');
}
await captureToGlassesStorage(captureOptions);
return;
}
// Without glasses Wi-Fi the photo is delivered over the Bluetooth
// transfer path instead of the network upload.
if (photoDestinationRef.current === 'phone') {
await captureAndUploadToPhone(captureOptions);
return;
}
await captureAndUploadToCloud(captureOptions);
});
}
captureAndUploadRef.current = captureAndUpload;
async function toggleVideoRecording() {
clearCameraButtonNotice();
resetBarcodeScan();
if (videoRecordingRef.current || activeVideoRequestIdRef.current) {
await stopVideoRecording();
return;
}
await startVideoRecording();
}
async function startVideoRecording() {
await runAction('Start video recording', async () => {
requireConnected('record video');
requireGlassesWifi('record video');
const uploadUrlText = webhookUrl.trim();
const validationMessage = photoUploadValidationMessage(uploadUrlText);
if (validationMessage) {
setCameraStatus(`Camera: ${validationMessage}`);
throw new Error(validationMessage);
}
try {
photoStatusUrl(uploadUrlText, '');
} catch {
setCameraStatus('Camera: enter a valid http:// or https:// media upload URL');
throw new Error('Enter a valid http:// or https:// media upload URL.');
}
setCameraStatus('Camera: checking this app can reach the media server before video');
try {
const reachability = await checkWebhookReachable(uploadUrlText);
setCameraStatus(`Camera: this app reached media server (${reachability.host}); starting video`);
addEvent('LIVE', `app reached media server for video ${reachability.uploadUrl ?? reachability.healthUrl}`);
} catch (error) {
const message = formatError(error);
setCameraStatus(`Camera: media server check failed: ${message}`);
setVideoPreviewDetails({
error: message,
source: 'Cloud server',
state: 'error',
uploadUrl: uploadUrlText,
});
throw new Error(`Media server check failed: ${message}`);
}
const requestId = `video-${Date.now()}`;
activeVideoRequestIdRef.current = requestId;
videoRecordingRef.current = true;
videoPollGenerationRef.current += 1;
setVideoRecording(true);
setVideoStatus(null);
setVideoPreviewUrl(null);
setVideoPreviewDetails({
requestId,
source: 'Cloud server',
state: 'recording',
uploadUrl: uploadUrlText,
});
setCameraStatus(`Camera: recording video (${requestId})`);
try {
const response = await BluetoothSdk.startVideoRecording(requestId, true, true, {
maxRecordingTimeMinutes: 1,
});
handleVideoRecordingStatus(response);
} catch (error) {
activeVideoRequestIdRef.current = null;
videoRecordingRef.current = false;
setVideoRecording(false);
setVideoPreviewDetails({
error: formatError(error),
requestId,
source: 'Cloud server',
state: 'error',
uploadUrl: uploadUrlText,
});
throw error;
}
});
}
async function stopVideoRecording() {
await runAction('Stop & upload video', async () => {
const requestId = activeVideoRequestIdRef.current;
if (!requestId) {
const message = 'No active video recording to stop.';
setCameraStatus(`Camera: ${message}`);
throw new Error(message);
}
const uploadUrlText = webhookUrl.trim();
const validationMessage = photoUploadValidationMessage(uploadUrlText);
if (validationMessage) {
setCameraStatus(`Camera: ${validationMessage}`);
throw new Error(validationMessage);
}
const statusUrl = photoStatusUrl(uploadUrlText, requestId);
videoPollGenerationRef.current += 1;
const pollGeneration = videoPollGenerationRef.current;
videoRecordingRef.current = false;
setVideoRecording(false);
setVideoPreviewDetails((current) => ({
...current,
requestId,
source: 'Cloud server',
state: 'uploading',
uploadUrl: uploadUrlText,
}));
setCameraStatus(`Camera: stopping video and uploading (${requestId})`);
try {
const response = await BluetoothSdk.stopVideoRecording(requestId, uploadUrlText);
handleVideoRecordingStatus(response);
} catch (error) {
activeVideoRequestIdRef.current = null;
setVideoPreviewDetails((current) => ({
...current,
error: formatError(error),
requestId,
source: 'Cloud server',
state: 'error',
uploadUrl: uploadUrlText,
}));
throw error;
}
await pollVideoPreview(requestId, statusUrl, pollGeneration);
});
}
async function captureAndUploadToCloud(options: PhotoCaptureOptions) {
const uploadUrlText = webhookUrl.trim();
const validationMessage = photoUploadValidationMessage(uploadUrlText);
if (validationMessage) {
setCameraStatus(`Camera: ${validationMessage}`);
throw new Error(validationMessage);
}
let statusUrl = '';
try {
statusUrl = photoStatusUrl(uploadUrlText, '');
} catch {
setCameraStatus('Camera: enter a valid http:// or https:// media upload URL');
throw new Error('Enter a valid http:// or https:// media upload URL.');
}
const requestedAt = Date.now();
const requestId = `photo-${requestedAt}`;
statusUrl = photoStatusUrl(uploadUrlText, requestId);
activePhotoRequestIdRef.current = requestId;
registerPhotoCaptureOptions(requestId, options);
pollGenerationRef.current += 1;
const pollGeneration = pollGenerationRef.current;
setPhotoPreviewUrl(null);
setPhotoPreviewDetails(null);
markPhotoRequestStarted(requestId, 'Cloud server', requestedAt);
resetBarcodeScan();
setCameraStatus(`Camera: webhook upload requested (${requestId})`);
try {
const response = await BluetoothSdk.requestPhoto({
requestId,
webhookUrl: uploadUrlText,
authToken: null,
...buildPhotoRequestFields(options.textMode),
});
handlePhotoResponse(response);
} catch (error) {
if (isRequestTimeoutError(error) && activePhotoRequestIdRef.current === requestId) {
markPhotoRequestStillWaiting(requestId, 'Cloud server', error);
void pollPhotoPreview(requestId, statusUrl, pollGeneration);
return;
}
if (activePhotoRequestIdRef.current === requestId) {
activePhotoRequestIdRef.current = null;
}
barcodeScanRequestIdsRef.current.delete(requestId);
markPhotoRequestFailed(requestId, 'REQUEST_FAILED', formatError(error));
throw error;
}
void pollPhotoPreview(requestId, statusUrl, pollGeneration);
}
async function captureAndUploadToPhone(options: PhotoCaptureOptions) {
const receiver = await ensurePhonePhotoReceiver('capture');
const requestedAt = Date.now();
const requestId = `photo-${requestedAt}`;
activePhotoRequestIdRef.current = requestId;
registerPhotoCaptureOptions(requestId, options);
pollGenerationRef.current += 1;
setPhotoPreviewUrl(null);
setPhotoPreviewDetails(null);
markPhotoRequestStarted(requestId, 'Phone receiver', requestedAt);
resetBarcodeScan();
setCameraStatus(`Camera: phone upload requested (${requestId})`);
startPhonePhotoUploadTimeout(requestId);
let response: PhotoSuccessResponseEvent;
try {
response = await BluetoothSdk.requestPhoto({
requestId,
webhookUrl: receiver.uploadUrl,
authToken: null,
...buildPhotoRequestFields(options.textMode),
});
handlePhotoResponse(response);
} catch (error) {
if (isRequestTimeoutError(error) && activePhotoRequestIdRef.current === requestId) {
markPhotoRequestStillWaiting(requestId, 'Phone receiver', error);
startPhonePhotoUploadTimeout(requestId);
return;
}
clearPhotoUploadTimeout();
if (activePhotoRequestIdRef.current === requestId) {
activePhotoRequestIdRef.current = null;
}
barcodeScanRequestIdsRef.current.delete(requestId);
markPhotoRequestFailed(requestId, 'REQUEST_FAILED', formatError(error));
throw error;
}
}
async function captureToGlassesStorage(options: PhotoCaptureOptions) {
const requestedAt = Date.now();
const requestId = `photo-${requestedAt}`;
activePhotoRequestIdRef.current = requestId;
registerPhotoCaptureOptions(requestId, options);
pollGenerationRef.current += 1;
const generation = pollGenerationRef.current;
setPhotoPreviewUrl(null);
setPhotoPreviewDetails(null);
markPhotoRequestStarted(requestId, 'Glasses gallery', requestedAt);
resetBarcodeScan();
setCameraStatus(`Camera: saving photo on glasses (${requestId})`);
let response: PhotoSuccessResponseEvent;
try {
response = await BluetoothSdk.requestPhoto({
requestId,
webhookUrl: null,
authToken: null,
save: true,
...buildPhotoRequestFields(options.textMode),
});
} catch (error) {
if (activePhotoRequestIdRef.current === requestId) {
activePhotoRequestIdRef.current = null;
}
barcodeScanRequestIdsRef.current.delete(requestId);
markPhotoRequestFailed(requestId, 'GLASSES_PHOTO_FAILED', formatError(error));
throw error;
}
handlePhotoResponse(response);
setCameraStatus('Camera: photo saved on glasses; loading preview');
setPhotoPreviewDetails((current) =>
current
? {...current, state: 'saved'}
: {requestId, source: 'Glasses gallery', state: 'saved'},
);
void downloadGlassesPhotoPreview(requestId, generation).catch((error) => {
if (
activePhotoRequestIdRef.current !== requestId ||
pollGenerationRef.current !== generation
) {
return;
}
activePhotoRequestIdRef.current = null;
const message = formatError(error);
setCameraStatus(`Camera: ${message}`);
setPhotoPreviewDetails((current) => ({
...current,
error: message,
requestId,
source: 'Glasses gallery',
state: 'saved',
}));
});
}
async function testWebhook() {
await runAction('Test webhook', async () => {
const uploadUrlText = webhookUrl.trim();
const validationMessage = photoUploadValidationMessage(uploadUrlText);
if (validationMessage) {
setCameraStatus(`Camera: ${validationMessage}`);
throw new Error(validationMessage);
}
let healthUrl = '';
try {
healthUrl = webhookHealthUrl(uploadUrlText);
} catch {
setCameraStatus('Camera: enter a valid http:// or https:// media upload URL');
throw new Error('Enter a valid http:// or https:// media upload URL.');
}
setCameraStatus('Camera: testing local webhook');
try {
const reachability = await checkWebhookReachable(uploadUrlText);
setCameraStatus(`Camera: webhook reachable (${reachability.host})`);
addEvent('LIVE', `webhook reachable ${reachability.uploadUrl ?? reachability.healthUrl}`);
} catch (error) {
const message = formatError(error);
setCameraStatus(`Camera: webhook test failed: ${message}`);
throw error;
}
});
}
async function checkWebhookReachable(uploadUrlText: string) {
const healthUrl = webhookHealthUrl(uploadUrlText);
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 3000);
try {
const response = await fetch(cacheBustedUrl(healthUrl), {
cache: 'no-store',
headers: {'Cache-Control': 'no-cache', Pragma: 'no-cache'},
signal: controller.signal,
});
if (!response.ok) {
throw new Error(`This app reached ${healthUrl}, but the media server returned HTTP ${response.status}.`);
}
const json = (await response.json().catch(() => ({}))) as {uploadUrl?: string};
return {
healthUrl,
host: new URL(healthUrl).host,
uploadUrl: json.uploadUrl,
};
} catch (error) {
throw new Error(webhookReachabilityErrorMessage(error, healthUrl));
} finally {
clearTimeout(timeout);
}
}
function handleDirectPhotoUpload(payload: PhotoReceiverUploadEvent) {
const activeRequestId = activePhotoRequestIdRef.current;
if (activeRequestId && payload.requestId && payload.requestId !== activeRequestId) {
addEvent('LIVE', `ignoring stale phone photo ${payload.requestId}`);
return;
}
const deliveredAt = Date.now();
clearPhotoUploadTimeout();
activePhotoRequestIdRef.current = null;
setPhonePhotoReceiverRunning(true);
setPhotoPreviewUrl(payload.fileUri);
setPhotoStatus(null);
setPhotoPreviewDetails((current) => ({
...current,
bleFallbackMessage: current?.bleFallbackUsed
? PHOTO_BLE_FALLBACK_TRANSFER_MESSAGE
: current?.bleFallbackMessage,
byteCount: payload.byteCount,
previewUrl: payload.fileUri,
requestId: payload.requestId ?? activeRequestId ?? current?.requestId ?? null,
source: 'Phone receiver',
state: 'preview',
timestamp: deliveredAt,
timeline: appendPhotoResponseTimeline(current?.timeline, {timestamp: deliveredAt}),
}));
void updatePhotoPreviewMetadata(payload.fileUri);
scanPreviewBarcodeForRequest(payload.requestId ?? activeRequestId, payload.fileUri);
setCameraStatus(`Camera: phone photo ready (${Math.round(payload.byteCount / 1024)} KB)`);
addEvent('LIVE', `phone photo ready ${payload.fileUri}`);
}
function handlePhotoReceiverStatus(payload: PhotoReceiverStatusEvent) {
if (payload.message.toLowerCase().includes('ready at')) {
setPhonePhotoReceiverRunning(true);
}
if (payload.message.toLowerCase().includes('stopped')) {
phonePhotoReceiverRef.current = null;
phonePhotoReceiverStartPromiseRef.current = null;
setPhonePhotoReceiverRunning(false);
}
addEvent('LIVE', `photo receiver ${payload.message}`);
}
async function ensurePhonePhotoReceiver(reason: 'camera tab' | 'capture'): Promise<PhotoReceiverResult> {
if (phonePhotoReceiverRef.current && reason !== 'capture') {
return phonePhotoReceiverRef.current;
}
if (phonePhotoReceiverStartPromiseRef.current) {
return phonePhotoReceiverStartPromiseRef.current;
}
const startedAt = Date.now();
if (reason === 'capture') {
setCameraStatus('Camera: preparing phone photo receiver');
}
addEvent('LIVE', `${phonePhotoReceiverRef.current ? 'refreshing' : 'starting'} phone photo receiver (${reason})`);
const promise = MentraPhotoReceiver.startPhotoReceiver()
.then((receiver) => {
const previousUploadUrl = phonePhotoReceiverRef.current?.uploadUrl;
phonePhotoReceiverRef.current = receiver;
setPhonePhotoReceiverRunning(true);
setPhonePhotoUploadUrl(receiver.uploadUrl);
if (previousUploadUrl && previousUploadUrl !== receiver.uploadUrl) {
addEvent('LIVE', `phone photo receiver URL changed ${previousUploadUrl} -> ${receiver.uploadUrl}`);
}
addEvent('LIVE', `phone photo receiver ready ${receiver.uploadUrl} (${Date.now() - startedAt}ms)`);
return receiver;
})
.finally(() => {
phonePhotoReceiverStartPromiseRef.current = null;
});
phonePhotoReceiverStartPromiseRef.current = promise;
return promise;
}
async function stopPhonePhotoReceiver() {
phonePhotoReceiverRef.current = null;
phonePhotoReceiverStartPromiseRef.current = null;
await MentraPhotoReceiver.stopPhotoReceiver();
setPhonePhotoReceiverRunning(false);
setPhonePhotoUploadUrl(null);
}
function markPhotoRequestStarted(
requestId: string,
source: PhotoPreviewDetails['source'],
requestedAt: number,
) {
setPhotoStatus({
type: 'photo_status',
requestId,
status: 'accepted',
timestamp: requestedAt,
});
setPhotoPreviewDetails({
requestId,
source,
state: 'acknowledged',
timestamp: requestedAt,
timeline: [{source: 'request', timestamp: requestedAt}],
});
}
// A delivery timeout may still be followed by a late receiver event.
// Callers remove barcode intent only for definitive capture failures.
function markPhotoRequestFailed(
requestId: string,
errorCode: string,
errorMessage: string,
) {
const failedAt = Date.now();
setPhotoStatus({
type: 'photo_status',
requestId,
status: 'failed',
timestamp: failedAt,
errorCode,
errorMessage,
});
setPhotoPreviewDetails((current) => ({
...current,
error: errorMessage || errorCode,
requestId,
source: current?.source ?? currentPhotoSource(photoDestinationRef.current),
state: 'error',
timestamp: failedAt,
timeline: appendPhotoTimeline(current?.timeline, {
source: 'photo_status',
status: 'failed',
timestamp: failedAt,
}),
}));
}
function markPhotoRequestStillWaiting(
requestId: string,
source: PhotoPreviewDetails['source'],
error: unknown,
) {
const waitingAt = Date.now();
setPhotoStatus({
type: 'photo_status',
requestId,
status: 'uploading',
timestamp: waitingAt,
});
setPhotoPreviewDetails((current) => ({
...current,
error: undefined,
requestId,
source,
state: current?.state === 'preview' ? 'preview' : 'acknowledged',
timestamp: waitingAt,
timeline: appendPhotoTimeline(current?.timeline, {
source: 'photo_status',
status: 'uploading',
timestamp: waitingAt,
}),
}));
setCameraStatus('Camera: still waiting for photo delivery');
addEvent(
'LIVE',
`photo request still waiting after SDK timeout ${requestId}: ${formatError(error)}`,
);
}
function startPhonePhotoUploadTimeout(requestId: string) {
clearPhotoUploadTimeout();
photoUploadTimeoutRef.current = setTimeout(() => {
if (activePhotoRequestIdRef.current === requestId) {
activePhotoRequestIdRef.current = null;
setCameraStatus('Camera: timed out waiting for phone upload');
markPhotoRequestFailed(requestId, 'UPLOAD_TIMEOUT', 'Timed out waiting for phone upload');
addEvent('TX', `phone photo upload timed out ${requestId}`);
}
}, DIRECT_PHOTO_UPLOAD_TIMEOUT_MS);
}
function handlePhotoStatus(payload: PhotoStatusEvent) {
const activeRequestId = activePhotoRequestIdRef.current;
if (activeRequestId && payload.requestId !== activeRequestId) {
addEvent('LIVE', `ignoring stale photo status ${payload.requestId}`);
return;
}
const isGalleryModeButtonPhoto =
galleryModePhotoRequestIdsRef.current.has(payload.requestId) ||
(galleryModeEnabledRef.current &&
!activeRequestId &&
payload.resolvedConfig?.source === 'button');
if (isGalleryModeButtonPhoto) {
galleryModePhotoRequestIdsRef.current.add(payload.requestId);
showCameraButtonNotice(CAMERA_BUTTON_GALLERY_MODE_NOTICE);
}
if (!activeRequestId && !isGalleryModeButtonPhoto) {
addEvent('LIVE', `ignoring external photo status ${payload.requestId}`);
return;
}
setPhotoStatus(payload);
const label = photoStatusLabel(payload, isGalleryModeButtonPhoto);
setCameraStatus(`Camera: ${label}`);
if (photoStatusStartsNewCapture(payload.status)) {
setPhotoPreviewDetails((current) => {
if (!current || current.requestId === payload.requestId) {
return current;
}
return clearPhotoBleFallbackWarning(current);
});
}
const payloadWithExtras = payload as PhotoStatusEvent & PhotoStatusExtras;
const fallbackMessage = photoBleFallbackMessage(payload.status);
const bleTransferStatus =
payload.status === 'ready_for_transfer' || payload.status === 'transferring';
const statusPhoneTimestamp = Date.now();
setPhotoPreviewDetails((current) => {
const bleFallbackUsed =
current?.bleFallbackUsed || payload.status === 'ble_fallback_compression';
return {
...current,
bleFallbackMessage:
fallbackMessage ??
(bleFallbackUsed
? photoBleFallbackProgressMessage(payload.status, current?.bleFallbackMessage)
: current?.bleFallbackMessage),
bleFallbackUsed,
requestId: payload.requestId,
source:
isGalleryModeButtonPhoto
? 'Glasses gallery'
: payload.resolvedConfig?.source === 'button'
? 'Action button'
: current?.source ?? currentPhotoSource(photoDestinationRef.current),
state:
current?.state === 'preview' || current?.state === 'saved'
? current.state
: 'acknowledged',
timestamp: statusPhoneTimestamp,
timeline: appendPhotoTimeline(current?.timeline, {
source: 'photo_status',
status: payload.status,
timestamp: statusPhoneTimestamp,
}),
resolvedConfig: payload.resolvedConfig ?? current?.resolvedConfig,
requestedCaptureConfig:
payloadWithExtras.requestedCaptureConfig ?? current?.requestedCaptureConfig,
meteredPreview: payloadWithExtras.meteredPreview ?? current?.meteredPreview,
captureMetadata: payloadWithExtras.captureMetadata ?? current?.captureMetadata,
};
});
if (payload.status === 'failed') {
galleryModePhotoRequestIdsRef.current.delete(payload.requestId);
barcodeScanRequestIdsRef.current.delete(payload.requestId);
clearPhotoUploadTimeout();
activePhotoRequestIdRef.current = null;
setPhotoPreviewDetails((current) => ({
...current,
error: payload.errorCode ?? payload.errorMessage,
requestId: payload.requestId,
source: current?.source ?? currentPhotoSource(photoDestinationRef.current),
state: 'error',
timestamp: statusPhoneTimestamp,
timeline: current?.timeline ?? [{
source: 'photo_status',
status: payload.status,
timestamp: statusPhoneTimestamp,
}],
}));
resetBarcodeScan();
}
const configSummary = photoStatusDetailSummary(payload);
addEvent(
'LIVE',
`photo status ${payload.status}${configSummary ? ` · ${configSummary}` : ''}`,
);
}
function handleVideoRecordingStatus(payload: VideoRecordingStatusEvent) {
const activeRequestId = activeVideoRequestIdRef.current;
if (activeRequestId && payload.requestId && payload.requestId !== activeRequestId) {
addEvent('LIVE', `ignoring stale video status ${payload.requestId}`);
return;
}
if (!activeRequestId && payload.requestId) {
addEvent('LIVE', `external video status ${payload.status}`);
}
setVideoStatus(payload);
const requestId = payload.requestId ?? activeRequestId;
const durationMs = typeof payload.data?.duration_ms === 'number'
? payload.data.duration_ms
: undefined;
const failed = !payload.success || videoStatusIsFailure(payload.status);
if (payload.status === 'recording_started' || payload.data?.recording === true) {
videoRecordingRef.current = true;
setVideoRecording(true);
setVideoPreviewDetails((current) => ({
...current,
requestId,
source: 'Cloud server',
state: 'recording',
status: payload.status,
timestamp: payload.timestamp,
}));
setCameraStatus('Camera: recording video');
} else if (payload.status === 'recording_stopped') {
videoRecordingRef.current = false;
setVideoRecording(false);
setVideoPreviewDetails((current) => ({
...current,
durationMs,
requestId,
source: 'Cloud server',
state: 'uploading',
status: payload.status,
timestamp: payload.timestamp,
}));
setCameraStatus('Camera: video stopped; waiting for upload preview');
} else if (failed) {
videoRecordingRef.current = false;
setVideoRecording(false);
activeVideoRequestIdRef.current = null;
setVideoPreviewDetails((current) => ({
...current,
durationMs,
error: payload.details ?? payload.status,
requestId,
source: 'Cloud server',
state: 'error',
status: payload.status,
timestamp: payload.timestamp,
}));
setCameraStatus(`Camera: video failed (${payload.details ?? payload.status})`);
} else {
setVideoPreviewDetails((current) => ({
...current,
durationMs,
requestId,
source: 'Cloud server',
state: current?.state ?? 'recording',
status: payload.status,
timestamp: payload.timestamp,
}));
setCameraStatus(`Camera: video ${payload.status.replace(/_/g, ' ')}`);
}
addEvent('LIVE', `video status ${payload.status}`);
}
function handleMediaUpload(payload: MediaUploadSuccessEvent | MediaUploadErrorEvent) {
const activeRequestId = activeVideoRequestIdRef.current;
const isVideo = payload.mediaType === 2;
if (!isVideo) {
return;
}
if (activeRequestId && payload.requestId !== activeRequestId) {
addEvent('LIVE', `ignoring stale video upload ${payload.requestId}`);
return;
}
if (payload.type === 'media_error') {
activeVideoRequestIdRef.current = null;
videoRecordingRef.current = false;
setVideoRecording(false);
setVideoPreviewDetails((current) => ({
...current,
error: payload.errorMessage,
requestId: payload.requestId,
source: 'Cloud server',
state: 'error',
timestamp: payload.timestamp,
}));
setCameraStatus(`Camera: video upload failed (${payload.errorMessage})`);
addEvent('LIVE', `video upload failed ${payload.errorMessage}`);
return;
}
setVideoPreviewDetails((current) => ({
...current,
mediaUrl: payload.mediaUrl,
requestId: payload.requestId,
source: 'Cloud server',
state: current?.state === 'preview' ? 'preview' : 'uploading',
timestamp: payload.timestamp,
}));
setCameraStatus('Camera: video uploaded; loading preview');
addEvent('LIVE', `video uploaded ${payload.mediaUrl}`);
}
function handleVideoStreamReceiverStatus(payload: VideoStreamReceiverStatusEvent) {
if (payload.kind === 'stream') {
if (payload.message.toLowerCase().includes('ready at')) {
setDirectStreamReceiverRunning(true);
}
if (payload.message.toLowerCase().includes('stopped')) {
setDirectStreamReceiverRunning(false);
stopDirectStreamFrameWatchdog();
}
if (payload.message.startsWith('Rendered ')) {
markDirectStreamFrameReceived();
}
}
addEvent('LIVE', `${payload.kind} receiver ${payload.message}`);
}
function handleDirectStreamFirstFrame(_payload: VideoStreamFirstFrameEvent) {
markDirectStreamFrameReceived();
}
function handleDirectStreamFrame(_payload: VideoStreamFrameEvent) {
markDirectStreamFrameReceived();
}
function markDirectStreamFrameReceived() {
if (!activeStreamIdRef.current || streamCloudServerEnabledRef.current) {
return;
}
setStreamPreviewReady(true);
setStreamStartedAt((current) => current ?? Date.now());
setStreamStatus('WebRTC phone preview ready');
stopDirectStreamFrameWatchdog();
directStreamFrameStaleTimerRef.current = setTimeout(() => {
if (!activeStreamIdRef.current || streamCloudServerEnabledRef.current) {
return;
}
setStreamPreviewReady(false);
setStreamStatus('WebRTC preview stalled: no video frames received from glasses');
addEvent('TX', 'WebRTC preview stalled');
}, 7000);
}
function handlePhotoResponse(response: PhotoSuccessResponseEvent) {
const activeRequestId = activePhotoRequestIdRef.current;
if (activeRequestId && response.requestId !== activeRequestId) {
addEvent('LIVE', `ignoring stale photo ${response.requestId}`);
return;
}
const previewUrl = response.photoUrl;
const destination = photoDestinationRef.current;
const source: PhotoPreviewDetails['source'] =
destination === 'cloud'
? 'Cloud server'
: destination === 'glasses'
? 'Glasses gallery'
: 'Phone receiver';
const responsePhoneTimestamp = Date.now();
const responseDeviceTimestamp = response.timestamp ?? responsePhoneTimestamp;
if (previewUrl) {
setPhotoPreviewUrl(previewUrl);
setPhotoStatus(null);
activePhotoRequestIdRef.current = null;
}
setCameraStatus(
previewUrl
? 'Camera: loaded photo preview'
: destination === 'cloud'
? 'Camera: photo delivered to cloud webhook'
: destination === 'glasses'
? 'Camera: photo saved on glasses; loading preview'
: 'Camera: photo delivered to phone receiver',
);
setPhotoPreviewDetails((current) => ({
...current,
byteCount: typeof response.fileSizeBytes === 'number' ? response.fileSizeBytes : current?.byteCount,
contentType: response.contentType ?? current?.contentType,
previewUrl: previewUrl ?? current?.previewUrl,
requestId: response.requestId,
source,
state:
current?.state === 'preview' || previewUrl
? 'preview'
: current?.state === 'saved'
? 'saved'
: 'acknowledged',
timestamp: responseDeviceTimestamp,
timeline: appendPhotoResponseTimeline(current?.timeline, {timestamp: responsePhoneTimestamp}),
uploadUrl: response.uploadUrl,
}));
if (previewUrl) {
void updatePhotoPreviewMetadata(previewUrl);
scanPreviewBarcodeForRequest(response.requestId, previewUrl);
}
addEvent('LIVE', `photo response ${response.requestId}`);
}
async function downloadGlassesPhotoPreview(
requestId: string,
generation: number,
) {
const baseUrl = galleryBaseUrlRef.current ?? galleryServerUrl(glasses, hotspotEnabled);
if (!baseUrl || galleryServerReachableRef.current !== true) {
throw new Error('The glasses hotspot is not ready for preview downloads.');
}
const galleryGeneration = galleryConnectionGenerationRef.current;
const localFile = new File(Paths.cache, `mentra-gallery-${requestId}.jpg`);
setGalleryServerStatus(`Gallery server: finding ${requestId}`);
let consecutiveFailures = 0;
for (let attempt = 0; attempt < GLASSES_PHOTO_POLL_ATTEMPTS; attempt += 1) {
if (
activePhotoRequestIdRef.current !== requestId ||
pollGenerationRef.current !== generation ||
galleryConnectionGenerationRef.current !== galleryGeneration
) {
return;
}
try {
const galleryResponse = await fetchWithTimeout(
cacheBustedUrl(`${baseUrl}/api/gallery?limit=100`),
{cache: 'no-store', headers: {'Cache-Control': 'no-cache', Pragma: 'no-cache'}},
3000,
);
if (galleryConnectionGenerationRef.current !== galleryGeneration) return;
if (!galleryResponse.ok) {
throw new Error(`Gallery server returned HTTP ${galleryResponse.status}.`);
}
const gallery = (await galleryResponse.json()) as {
data?: {
photos?: Array<{
mime_type?: string;
name?: string;
request_id?: string;
size?: number;
url?: string;
}>;
};
};
if (galleryConnectionGenerationRef.current !== galleryGeneration) return;
const photo = gallery.data?.photos?.find((item) => item.request_id === requestId);
consecutiveFailures = 0;
setGalleryServerReachable(true);
if (!photo?.name) {
setGalleryServerStatus(`Gallery server: connected; finding ${requestId}`);
await delay(1000);
continue;
}
const fileName = photo.name;
const remoteUrl = new URL(photo.url ?? '/api/photo', baseUrl);
if (!photo.url) {
remoteUrl.searchParams.set('file', fileName);
}
const downloaded = await File.downloadFileAsync(remoteUrl.toString(), localFile, {idempotent: true});
if (galleryConnectionGenerationRef.current !== galleryGeneration) return;
const deliveredAt = Date.now();
setPhotoPreviewUrl(downloaded.uri);
setPhotoStatus(null);
setPhotoPreviewDetails((current) => ({
...current,
byteCount: photo.size ?? (downloaded.size || current?.byteCount),
contentType: photo.mime_type ?? downloaded.type ?? current?.contentType ?? 'image/jpeg',
fileName,
previewUrl: remoteUrl.toString(),
requestId,
source: 'Glasses gallery',
state: 'preview',
timestamp: current?.timestamp ?? deliveredAt,
}));
setGalleryServerReachable(true);
setGalleryServerStatus(`Gallery server: downloaded ${fileName}`);
setCameraStatus('Camera: loaded photo preview from glasses');
activePhotoRequestIdRef.current = null;
void updatePhotoPreviewMetadata(downloaded.uri);
scanPreviewBarcodeForRequest(requestId, downloaded.uri);
addEvent('LIVE', `glasses photo downloaded ${fileName}`);
return;
} catch (error) {
if (galleryConnectionGenerationRef.current !== galleryGeneration) return;
consecutiveFailures += 1;
const transportUnavailable =
consecutiveFailures >= GLASSES_GALLERY_FAILURE_THRESHOLD;
if (attempt === 0 || attempt % 10 === 9) {
setGalleryServerStatus(
transportUnavailable
? `Gallery server: ${formatError(error)}`
: `Gallery server: connected; waiting for ${requestId}.`,
);
setCameraStatus(
transportUnavailable
? 'Camera: reconnect to the glasses hotspot to load the saved photo'
: 'Camera: photo saved on glasses; waiting for preview',
);
addEvent('LIVE', `waiting for glasses photo ${requestId}: ${formatError(error)}`);
}
if (transportUnavailable) {
setGalleryServerReachable(false);
}
}
await delay(1000);
}
throw new Error(
`Photo was saved on the glasses, but the preview could not be downloaded from ${baseUrl}.`,
);
}
async function pollPhotoPreview(
requestId: string,
statusUrl: string,
pollGeneration: number,
) {
for (let attempt = 0; attempt < PHOTO_POLL_ATTEMPTS; attempt += 1) {
if (
activePhotoRequestIdRef.current !== requestId ||
pollGenerationRef.current !== pollGeneration
) {
return;
}
try {
const response = await fetch(cacheBustedUrl(statusUrl), {
cache: 'no-store',
headers: {'Cache-Control': 'no-cache', Pragma: 'no-cache'},
});
if (response.ok) {
const json = (await response.json()) as {
contentType?: string;
fileSizeBytes?: number;
photoUrl?: string;
requestId?: string;
uploadedAt?: string;
};
if (json.photoUrl) {
const deliveredAt = Date.now();
setPhotoPreviewUrl(json.photoUrl);
setPhotoStatus(null);
setPhotoPreviewDetails((current) => ({
...current,
bleFallbackMessage: current?.bleFallbackUsed
? PHOTO_BLE_FALLBACK_TRANSFER_MESSAGE
: current?.bleFallbackMessage,
byteCount: typeof json.fileSizeBytes === 'number' ? json.fileSizeBytes : current?.byteCount,
contentType: json.contentType ?? current?.contentType,
previewUrl: json.photoUrl,
requestId: json.requestId ?? requestId,
source: 'Cloud server',
state: 'preview',
timestamp: deliveredAt,
timeline: appendPhotoResponseTimeline(current?.timeline, {timestamp: deliveredAt}),
uploadedAt: json.uploadedAt ?? current?.uploadedAt,
}));
void updatePhotoPreviewMetadata(json.photoUrl);
scanPreviewBarcodeForRequest(json.requestId ?? requestId, json.photoUrl);
setCameraStatus('Camera: loaded photo preview');
addEvent('LIVE', `local photo ready ${json.photoUrl}`);
activePhotoRequestIdRef.current = null;
return;
}
}
if (attempt === 0 || attempt % 10 === 9) {
addEvent('LIVE', `waiting for upload ${requestId}: ${response.status}`);
}
} catch (error) {
if (attempt === 0 || attempt % 10 === 9) {
addEvent('LIVE', `waiting for local photo server: ${formatError(error)}`);
}
}
await delay(1000);
}
if (activePhotoRequestIdRef.current === requestId) {
setCameraStatus('Camera: timed out waiting for local server upload');
}
}
async function pollVideoPreview(
requestId: string,
statusUrl: string,
pollGeneration: number,
) {
for (let attempt = 0; attempt < VIDEO_POLL_ATTEMPTS; attempt += 1) {
if (
activeVideoRequestIdRef.current !== requestId ||
videoPollGenerationRef.current !== pollGeneration
) {
return;
}
try {
const response = await fetch(cacheBustedUrl(statusUrl), {
cache: 'no-store',
headers: {'Cache-Control': 'no-cache', Pragma: 'no-cache'},
});
if (response.ok) {
const json = (await response.json()) as {
contentType?: string;
fileSizeBytes?: number;
mediaType?: string;
mediaUrl?: string;
requestId?: string;
uploadedAt?: string;
url?: string;
videoUrl?: string;
};
const previewUrl = json.videoUrl ?? (json.mediaType === 'video' ? json.mediaUrl ?? json.url : undefined);
if (previewUrl) {
setVideoPreviewUrl(previewUrl);
setVideoPreviewDetails((current) => ({
...current,
byteCount: typeof json.fileSizeBytes === 'number' ? json.fileSizeBytes : current?.byteCount,
contentType: json.contentType ?? current?.contentType,
mediaUrl: json.mediaUrl ?? json.url ?? current?.mediaUrl,
previewUrl,
requestId: json.requestId ?? requestId,
source: 'Cloud server',
state: 'preview',
uploadedAt: json.uploadedAt ?? current?.uploadedAt,
}));
setCameraStatus('Camera: loaded video preview');
addEvent('LIVE', `local video ready ${previewUrl}`);
activeVideoRequestIdRef.current = null;
return;
}
}
if (attempt === 0 || attempt % 10 === 9) {
addEvent('LIVE', `waiting for video upload ${requestId}: ${response.status}`);
}
} catch (error) {
if (attempt === 0 || attempt % 10 === 9) {
addEvent('LIVE', `waiting for local video server: ${formatError(error)}`);
}
}
await delay(1000);
}
if (activeVideoRequestIdRef.current === requestId) {
activeVideoRequestIdRef.current = null;
setVideoPreviewDetails((current) => ({
...current,
error: 'Timed out waiting for local server upload',
requestId,
source: 'Cloud server',
state: 'error',
}));
setCameraStatus('Camera: timed out waiting for local server video upload');
}
}
async function updatePhotoPreviewMetadata(uri: string) {
try {
const metadata = await MentraBarcodeScanner.getImageMetadata(uri);
setPhotoPreviewDetails((current) =>
current?.previewUrl === uri
? {
...current,
estimatedFov: metadata.estimatedFov,
focalLength35mm: metadata.focalLength35mm,
height: metadata.height ?? current.height,
width: metadata.width ?? current.width,
}
: current,
);
} catch (error) {
addEvent('TX', `photo metadata failed: ${formatError(error)}`);
}
}
async function openPhotoPreview() {
if (photoPreviewOpeningRef.current) {
return;
}
photoPreviewOpeningRef.current = true;
resetBarcodeScan();
await runAction('Open photo preview', async () => {
try {
if (!photoPreviewUrl) {
throw new Error('Capture or load a photo preview first.');
}
await MentraBarcodeScanner.openImage(photoPreviewUrl);
} finally {
photoPreviewOpeningRef.current = false;
}
});
}
function resetBarcodeScan() {
barcodeScanTokenRef.current += 1;
updateBarcodeScan({barcodes: [], state: 'idle'});
}
function showCameraButtonNotice(message: string) {
setCameraButtonNotice(message);
}
function clearCameraButtonNotice() {
setCameraButtonNotice(null);
}
async function scanPreviewBarcode(sourceUri: string, expectedValue?: string) {
const currentScan = barcodeScanRef.current;
if (
currentScan.sourceUri === sourceUri &&
(currentScan.state === 'scanning' || currentScan.state === 'found')
) {
return;
}
const token = barcodeScanTokenRef.current + 1;
barcodeScanTokenRef.current = token;
updateBarcodeScan({
barcodes: [],
expectedValue,
sourceUri,
state: 'scanning',
});
const visibleTimeout = setTimeout(() => {
if (barcodeScanTokenRef.current !== token) {
return;
}
const latestScan = barcodeScanRef.current;
if (latestScan.sourceUri !== sourceUri || latestScan.state !== 'scanning') {
return;
}
updateBarcodeScan({
barcodes: [],
expectedValue,
scannedAt: new Date().toISOString(),
sourceUri,
state: 'none',
});
addEvent('LIVE', 'barcode scan timed out');
}, BARCODE_SCAN_VISIBLE_TIMEOUT_MS);
await waitForNextFrame();
if (barcodeScanTokenRef.current !== token) {
clearTimeout(visibleTimeout);
return;
}
try {
const barcodes = dedupeBarcodeResults(await MentraBarcodeScanner.scanImage(sourceUri));
clearTimeout(visibleTimeout);
if (barcodeScanTokenRef.current !== token) {
return;
}
const scannedAt = new Date().toISOString();
const latestScan = barcodeScanRef.current;
if (
barcodes.length === 0 &&
latestScan.sourceUri === sourceUri &&
latestScan.state === 'found' &&
latestScan.barcodes.length > 0
) {
addEvent('LIVE', 'ignored empty duplicate barcode scan');
return;
}
updateBarcodeScan({
barcodes,
expectedValue,
scannedAt,
sourceUri,
state: barcodes.length > 0 ? 'found' : 'none',
});
if (barcodes.length > 0) {
addEvent('LIVE', `barcode scan ${barcodeScanSummary(barcodes)}`);
} else {
addEvent('LIVE', 'no barcode found in photo preview');
}
} catch (error) {
clearTimeout(visibleTimeout);
if (barcodeScanTokenRef.current !== token) {
return;
}
const message = formatError(error);
updateBarcodeScan({
barcodes: [],
error: message,
expectedValue,
scannedAt: new Date().toISOString(),
sourceUri,
state: 'error',
});
addEvent('TX', `barcode scan failed: ${message}`);
}
}
function updateBarcodeScan(next: BarcodeScanDetails) {
barcodeScanRef.current = next;
setBarcodeScan(next);
}
function setPhotoExposureTimeNsAction(exposureTimeNs: number) {
setPhotoExposureTimeNsState(clampRounded(exposureTimeNs, PHOTO_EXPOSURE_MIN_NS, PHOTO_EXPOSURE_MAX_NS));
}
function setPhotoIsoAction(iso: number) {
setPhotoIsoState(clampRounded(iso, PHOTO_ISO_MIN, PHOTO_ISO_MAX));
}
function setPhotoSizeAction(size: PhotoSize) {
setPhotoSize(size);
}
function setPhotoCompressionAction(compression: PhotoCompression) {
setPhotoCompression(compression);
}
function setPhotoAeExposureDivisorAction(divisor: PhotoAeExposureDivisor | null) {
setPhotoAeExposureDivisor(divisor);
}
function setPhotoIsoCapAction(isoCap: PhotoIsoCap | null) {
setPhotoIsoCap(isoCap);
}
function setPhotoNoiseReductionAction(value: PhotoTuningFlag) {
setPhotoNoiseReduction(value);
}
function setPhotoEdgeEnhancementAction(value: PhotoTuningFlag) {
setPhotoEdgeEnhancement(value);
}
function setPhotoMfnrAction(value: PhotoTuningFlag) {
setPhotoMfnr(value);
}
function setPhotoZslAction(value: PhotoTuningFlag) {
setPhotoZsl(value);
}
function setPhotoIspDigitalGainAction(gain: PhotoIspDigitalGain | null) {
setPhotoIspDigitalGain(gain);
}
function setPhotoIspAnalogGainAction(gain: PhotoIspAnalogGain | null) {
setPhotoIspAnalogGain(gain);
}
function setCameraFovAction(fov: number) {
const nextFov = clampRounded(fov, CAMERA_FOV_MIN, CAMERA_FOV_MAX);
setCameraFovState(nextFov);
if (nextFov === CAMERA_FOV_MAX) {
setCameraRoiPositionState('center');
}
}
function setCameraRoiPositionAction(roiPosition: CameraRoiPosition) {
setCameraRoiPositionState(cameraFov === CAMERA_FOV_MAX ? 'center' : roiPosition);
}
async function applyCameraSettings() {
if (cameraSettingsApplyingRef.current) {
addEvent('TX', 'camera_fov already applying');
return;
}
await runAction('Apply camera settings', async () => {
requireConnected('apply camera settings');
const fov = clampRounded(cameraFov, CAMERA_FOV_MIN, CAMERA_FOV_MAX);
const roiPosition = fov === CAMERA_FOV_MAX ? 'center' : cameraRoiPosition;
cameraSettingsApplyingRef.current = true;
setCameraSettingsApplying(true);
setCameraSettingsStatus('Camera settings: applying FOV/ROI on glasses');
try {
const result = await BluetoothSdk.setCameraFov({fov, roiPosition});
addEvent('LIVE', `camera_fov ${describeCameraFovResult(result)}`);
setCameraSettingsStatus(
`Camera settings: applied; field of view ${result.fov}°, ${roiPositionLabel(result.roiPosition)} crop`,
);
} catch (error) {
setCameraSettingsStatus(`Camera settings: failed - ${formatError(error)}`);
throw error;
} finally {
cameraSettingsApplyingRef.current = false;
setCameraSettingsApplying(false);
}
});
}
function selectProtocol(protocol: StreamProtocol) {
if (streamRequested || streamStartedAt !== null) {
void stopActiveStream('Stream stopped because protocol changed');
}
setStreamResolvedConfig(null);
setStreamProtocol(protocol);
const trimmed = streamUrl.trim();
const nextUrl = !trimmed || STREAM_DEFAULT_URL_VALUES.has(trimmed)
? STREAM_DEFAULT_URLS[protocol]
: streamUrl;
setStreamUrlState(nextUrl);
void savePersistedCloudUrls({
streamProtocol: protocol,
streamUrl: nextUrl,
webhookUrl,
});
}
function setWebhookUrlAction(url: string) {
setWebhookUrlState(url);
void savePersistedCloudUrls({
streamProtocol,
streamUrl,
webhookUrl: url,
});
}
async function setPhotoCloudServerEnabledAction(enabled: boolean) {
await runAction(enabled ? 'Use photo cloud server' : 'Capture photos to phone', async () => {
if (photoDestinationRef.current === 'glasses') {
await disableGlassesPhotoPreviewConnection();
}
const destination: PhotoDestination = enabled ? 'cloud' : 'phone';
photoDestinationBeforeGlassesRef.current = destination;
photoDestinationRef.current = destination;
setPhotoDestination(destination);
activePhotoRequestIdRef.current = null;
barcodeScanRequestIdsRef.current.clear();
clearPhotoUploadTimeout();
setPhotoStatus(null);
pollGenerationRef.current += 1;
if (enabled) {
await stopPhonePhotoReceiver().catch(() => undefined);
setCameraStatus('Camera: enter the cloud media upload URL');
return;
}
setCameraStatus('Camera: ready to capture to phone');
});
}
async function setPhotoGlassesStorageEnabledAction(enabled: boolean) {
const restoredDestination = photoDestinationBeforeGlassesRef.current;
await runAction(
enabled
? 'Save photos on glasses'
: restoredDestination === 'cloud'
? 'Restore photo cloud server'
: 'Capture photos to phone',
async () => {
if (enabled && photoDestinationRef.current !== 'glasses') {
photoDestinationBeforeGlassesRef.current = photoDestinationRef.current;
}
const destination: PhotoDestination = enabled
? 'glasses'
: photoDestinationBeforeGlassesRef.current;
photoDestinationRef.current = destination;
setPhotoDestination(destination);
activePhotoRequestIdRef.current = null;
barcodeScanRequestIdsRef.current.clear();
clearPhotoUploadTimeout();
setPhotoStatus(null);
pollGenerationRef.current += 1;
if (!enabled) {
await disableGlassesPhotoPreviewConnection();
setCameraStatus(
destination === 'cloud'
? 'Camera: enter the cloud media upload URL'
: 'Camera: ready to capture to phone',
);
return;
}
await stopPhonePhotoReceiver().catch(() => undefined);
if (!glassesConnected) {
setCameraStatus('Camera: connect glasses to save photos on them');
return;
}
await prepareGlassesPhotoPreviewConnection();
},
);
}
async function prepareGlassesPhotoPreviewAction() {
await runAction('Connect to glasses hotspot', () => prepareGlassesPhotoPreviewConnection(true));
}
async function disableGlassesPhotoPreviewConnection() {
galleryConnectionGenerationRef.current += 1;
galleryConnectionPromiseRef.current = null;
const hotspotSsid = galleryHotspotSsidRef.current ?? galleryHotspotSsidLabel(glasses);
galleryBaseUrlRef.current = null;
galleryHotspotSsidRef.current = null;
setGalleryServerReachable(null);
setGalleryServerStatus('Gallery server: hotspot off');
await disconnectGlassesHotspotWifi(hotspotSsid).catch((error) => {
addEvent('LIVE', `hotspot Wi-Fi disconnect: ${formatError(error)}`);
});
if (hotspotEnabled) {
const status = await BluetoothSdk.setHotspotState(false);
addEvent('LIVE', `hotspot ${status.state}`);
}
}
async function prepareGlassesPhotoPreviewConnection(restart = false) {
if (restart) {
galleryConnectionGenerationRef.current += 1;
const staleConnection = galleryConnectionPromiseRef.current;
galleryConnectionPromiseRef.current = null;
const hotspotSsid = galleryHotspotSsidRef.current;
if (hotspotSsid) {
await disconnectGlassesHotspotWifi(hotspotSsid).catch((error) => {
addEvent('LIVE', `hotspot retry cleanup: ${formatError(error)}`);
});
}
void staleConnection?.catch(() => undefined);
addEvent('LIVE', 'restarting glasses hotspot connection');
}
if (galleryConnectionPromiseRef.current) {
return galleryConnectionPromiseRef.current;
}
const generation = ++galleryConnectionGenerationRef.current;
const connection = (async () => {
requireConnected('prepare saved-photo previews');
setGalleryServerReachable(null);
setGalleryServerStatus('Gallery server: starting glasses hotspot');
setCameraStatus('Camera: preparing glasses hotspot');
const currentHotspot = enabledHotspotStatus(glasses);
const hotspot = currentHotspot ?? await BluetoothSdk.setHotspotState(true);
if (hotspot.state !== 'enabled') {
throw new Error('The glasses hotspot did not turn on.');
}
if (generation !== galleryConnectionGenerationRef.current) return;
const baseUrl = `http://${hotspot.localIp}:8089`;
galleryBaseUrlRef.current = baseUrl;
galleryHotspotSsidRef.current = hotspot.ssid;
const alreadyReady = await waitForGalleryServer(baseUrl, 3, 400);
if (generation !== galleryConnectionGenerationRef.current) return;
if (alreadyReady) {
markGalleryServerReady(baseUrl);
return;
}
setGalleryServerStatus(`Gallery server: connecting to ${hotspot.ssid}`);
setCameraStatus(`Camera: connecting to ${hotspot.ssid}`);
let connectionError: unknown = null;
try {
await WifiManager.connectToProtectedSSID(
hotspot.ssid,
hotspot.password,
false,
false,
);
} catch (error) {
connectionError = error;
}
if (generation !== galleryConnectionGenerationRef.current) return;
const ready = await waitForGalleryServer(baseUrl, 20, 500);
if (generation !== galleryConnectionGenerationRef.current) return;
if (ready) {
markGalleryServerReady(baseUrl);
return;
}
const reason = connectionError ? ` ${formatError(connectionError)}` : '';
setGalleryServerReachable(false);
setGalleryServerStatus(`Gallery server: connection required for ${hotspot.ssid}`);
setCameraStatus('Camera: connect to the glasses hotspot to enable capture');
throw new Error(`Could not reach the glasses gallery.${reason}`);
})();
galleryConnectionPromiseRef.current = connection;
try {
await connection;
} finally {
if (galleryConnectionPromiseRef.current === connection) {
galleryConnectionPromiseRef.current = null;
}
}
}
function markGalleryServerReady(baseUrl: string) {
setGalleryServerReachable(true);
setGalleryServerStatus(`Gallery server: ready at ${baseUrl}`);
setCameraStatus('Camera: ready to save and preview from glasses');
addEvent('LIVE', `gallery server ready ${baseUrl}`);
}
async function setStreamCloudServerEnabledAction(enabled: boolean) {
await runAction(enabled ? 'Use stream cloud server' : 'Stream to phone', async () => {
if (streamRequested || streamStartedAt !== null) {
await stopActiveStream('Stream stopped because destination changed');
}
streamCloudServerEnabledRef.current = enabled;
setStreamCloudServerEnabledState(enabled);
setStreamPreviewReady(false);
setStreamResolvedConfig(null);
if (enabled) {
setStreamStatus('Ready to stream to a cloud server');
return;
}
setStreamProtocol('webrtc');
setStreamStatus('Ready to stream WebRTC to phone');
});
}
function setStreamUrlAction(url: string) {
if (streamRequested || streamStartedAt !== null) {
void stopActiveStream('Stream stopped because URL changed');
}
setStreamResolvedConfig(null);
setStreamUrlState(url);
void savePersistedCloudUrls({
streamProtocol,
streamUrl: url,
webhookUrl,
});
}
function setStreamFpsAction(fps: number) {
if (streamRequested || streamStartedAt !== null) {
return;
}
const nextFps = Math.max(STREAM_MIN_FPS, Math.min(STREAM_MAX_FPS, Math.round(fps)));
setStreamFps(nextFps);
}
function setStreamStartPendingValue(pending: boolean) {
streamStartPendingRef.current = pending;
setStreamStartPending(pending);
}
async function toggleStream() {
if (streamStartPendingRef.current) {
setStreamStatus('Stream start already in progress');
addEvent('TX', 'duplicate stream start ignored');
return;
}
if (streamRequested || streamStartedAt) {
await runAction('Stop stream', () => stopActiveStream('Stopped'));
return;
}
setStreamStartPendingValue(true);
setStreamStatus(
streamCloudServerEnabledRef.current
? `Starting ${streamProtocol.toUpperCase()} stream`
: 'Starting WebRTC stream to phone',
);
await runAction('Start stream', async () => {
try {
requireConnected('start streaming');
requireGlassesWifi('start streaming');
if (streamCloudServerEnabledRef.current) {
await startCloudStream();
return;
}
await startPhoneWebRtcStream();
} finally {
setStreamStartPendingValue(false);
}
});
}
async function startCloudStream() {
const url = streamUrl.trim();
const validationMessage = streamUrlValidationMessage(url);
if (validationMessage) {
setStreamStatus(validationMessage);
throw new Error(validationMessage);
}
if (streamProtocol === 'rtmp' || streamProtocol === 'srt' || streamProtocol === 'webrtc') {
setStreamStatus(`Checking local ${streamProtocol.toUpperCase()} server`);
const reachabilityMessage =
streamProtocol === 'rtmp'
? await localRtmpReachabilityMessage(url)
: streamProtocol === 'srt'
? await localSrtReachabilityMessage(url)
: await localWebrtcReachabilityMessage(url);
if (reachabilityMessage) {
setStreamStatus(reachabilityMessage);
throw new Error(reachabilityMessage);
}
}
const streamId = `rn-${Date.now()}`;
const params = {
streamId,
streamUrl: url,
type: 'start_stream',
video: {fps: streamFps},
} satisfies StreamStartRequest;
const status = await BluetoothSdk.startStream(params);
addEvent('LIVE', `stream ${status.status}`);
activeStreamIdRef.current = streamId;
setStreamRequested(true);
setStreamPreviewReady(false);
setStreamStatus(`Starting ${streamProtocol.toUpperCase()} stream; waiting for preview`);
void startPreviewReadinessPoll(url, streamProtocol, streamId);
}
async function startPhoneWebRtcStream() {
const receiver = await MentraVideoStreamReceiver.startWebRtcReceiver();
setDirectStreamReceiverRunning(true);
setDirectStreamWhipUrl(receiver.streamUrl);
setStreamPreviewReady(false);
setStreamStatus('Phone WebRTC receiver ready; starting glasses stream');
await delay(DIRECT_WEBRTC_RECEIVER_WARMUP_MS);
const streamId = `rn-${Date.now()}`;
const params = {
streamId,
streamUrl: receiver.streamUrl,
type: 'start_stream',
video: {fps: streamFps},
} satisfies StreamStartRequest;
try {
const status = await BluetoothSdk.startStream(params);
addEvent('LIVE', `stream ${status.status}`);
activeStreamIdRef.current = streamId;
setStreamRequested(true);
setStreamPreviewReady(false);
setStreamStatus('Starting WebRTC stream to phone; waiting for preview');
} catch (error) {
await MentraVideoStreamReceiver.stopWebRtcReceiver().catch(() => undefined);
setDirectStreamReceiverRunning(false);
setDirectStreamWhipUrl(null);
throw error;
}
}
async function stopActiveStream(status: string) {
stopPreviewHealthPoll();
stopDirectStreamFrameWatchdog();
activeStreamIdRef.current = null;
setStreamStartPendingValue(false);
if (isGlassesConnected(glasses)) {
const status = await BluetoothSdk.stopStream();
addEvent('LIVE', `stream ${status.status}`);
}
await MentraVideoStreamReceiver.stopWebRtcReceiver().catch(() => undefined);
setDirectStreamReceiverRunning(false);
setDirectStreamWhipUrl(null);
setStreamRequested(false);
setStreamPreviewReady(false);
setStreamStartedAt(null);
setStreamStatus(status);
}
async function startPreviewReadinessPoll(
url: string,
protocol: StreamProtocol,
streamId: string,
) {
for (let attempt = 0; attempt < 30; attempt += 1) {
await delay(1000);
if (activeStreamIdRef.current !== streamId) {
return;
}
if (await streamPreviewIsReady(url, protocol)) {
if (activeStreamIdRef.current === streamId) {
setStreamPreviewReady(true);
setStreamStatus(`${protocol.toUpperCase()} preview ready`);
addEvent('LIVE', `${protocol.toUpperCase()} preview ready`);
startPreviewHealthPoll(url, protocol, streamId);
}
return;
}
}
if (activeStreamIdRef.current === streamId) {
setStreamStatus('Stream requested; preview is still starting');
addEvent('TX', `${protocol.toUpperCase()} preview did not become ready`);
}
}
function startPreviewHealthPoll(
url: string,
protocol: StreamProtocol,
streamId: string,
) {
stopPreviewHealthPoll();
let lastReady = true;
previewHealthTimerRef.current = setInterval(() => {
void (async () => {
if (activeStreamIdRef.current !== streamId) {
stopPreviewHealthPoll();
return;
}
const ready = await streamPreviewIsReady(url, protocol);
if (activeStreamIdRef.current !== streamId) {
return;
}
if (ready && !lastReady) {
setStreamPreviewReady(true);
setStreamStatus(`${protocol.toUpperCase()} preview ready`);
addEvent('LIVE', `${protocol.toUpperCase()} preview ready`);
} else if (!ready && lastReady) {
setStreamPreviewReady(false);
setStreamStatus(`${protocol.toUpperCase()} media path lost; preview may be frozen`);
addEvent('TX', `${protocol.toUpperCase()} media path lost`);
}
lastReady = ready;
})();
}, 3000);
}
function stopPreviewHealthPoll() {
if (previewHealthTimerRef.current) {
clearInterval(previewHealthTimerRef.current);
previewHealthTimerRef.current = null;
}
}
function clearPhotoUploadTimeout() {
if (photoUploadTimeoutRef.current) {
clearTimeout(photoUploadTimeoutRef.current);
photoUploadTimeoutRef.current = null;
}
}
function stopDirectStreamFrameWatchdog() {
if (directStreamFrameStaleTimerRef.current) {
clearTimeout(directStreamFrameStaleTimerRef.current);
directStreamFrameStaleTimerRef.current = null;
}
}
async function requestWifiScan() {
await runAction('Scan Wi-Fi', async () => {
requireConnected('scan Wi-Fi');
const networks = await BluetoothSdk.requestWifiScan();
addEvent('LIVE', `Wi-Fi scan returned ${networks.length} network${networks.length === 1 ? '' : 's'}`);
});
}
function settleWifiConnectAttempt() {
wifiConnectAttemptRef.current += 1;
wifiConnectingSsidRef.current = null;
if (wifiConnectGraceTimerRef.current) {
clearTimeout(wifiConnectGraceTimerRef.current);
wifiConnectGraceTimerRef.current = null;
}
setWifiConnectingSsid(null);
}
async function sendWifiCredentials(ssid: string, password: string, requiresPassword: boolean) {
await runAction(`Connect Wi-Fi ${ssid}`, async () => {
requireConnected('send Wi-Fi credentials');
if (requiresPassword && !password) {
throw new Error(`Enter the Wi-Fi password before connecting to ${ssid}.`);
}
const attempt = ++wifiConnectAttemptRef.current;
if (wifiConnectGraceTimerRef.current) {
clearTimeout(wifiConnectGraceTimerRef.current);
wifiConnectGraceTimerRef.current = null;
}
wifiConnectingSsidRef.current = ssid;
setWifiConnectingSsid(ssid);
setWifiConnectError(null);
try {
const status = await BluetoothSdk.sendWifiCredentials(ssid, requiresPassword ? password : '');
if (wifiConnectAttemptRef.current === attempt) {
settleWifiConnectAttempt();
}
addEvent('LIVE', `Wi-Fi ${status.state === 'connected' ? status.ssid : status.state}`);
} catch (error) {
if (wifiConnectAttemptRef.current !== attempt) {
return;
}
// iOS loses the 'request_timeout' code in the Expo bridge, so also
// match on the message like isRequestTimeoutError does.
if ((error as {code?: string})?.code === 'request_timeout' || isRequestTimeoutError(error)) {
// The glasses often finish associating after the SDK stops
// waiting; keep the connecting state during a grace window and
// let a late wifi_status_change resolve it.
wifiConnectGraceTimerRef.current = setTimeout(() => {
wifiConnectGraceTimerRef.current = null;
if (wifiConnectAttemptRef.current === attempt) {
wifiConnectingSsidRef.current = null;
setWifiConnectingSsid(null);
setWifiConnectError(`Could not connect to ${ssid}. Check the password and try again.`);
}
}, WIFI_CONNECT_GRACE_MS);
addEvent('LIVE', `Wi-Fi connect to ${ssid} still pending`);
return;
}
settleWifiConnectAttempt();
setWifiConnectError(formatError(error));
throw error;
}
});
}
async function forgetCurrentWifiNetwork() {
await runAction('Forget current Wi-Fi', async () => {
requireConnected('forget Wi-Fi network');
const wifi = connectedWifiStatus(glasses);
if (!wifi) {
throw new Error('No connected Wi-Fi network to forget.');
}
const result = await BluetoothSdk.forgetWifiNetwork(wifi.ssid);
addEvent('LIVE', `Wi-Fi forget ${result.outcome}: ${result.ssid}`);
});
}
async function toggleHotspot() {
await runAction(hotspotEnabled ? 'Disable hotspot' : 'Enable hotspot', async () => {
requireConnected('toggle hotspot');
const next = !hotspotEnabled;
const status = await BluetoothSdk.setHotspotState(next);
addEvent('LIVE', `hotspot ${status.state}`);
});
}
async function setWifiAdbState(enabled: boolean) {
await runAction(enabled ? 'Enable Wi-Fi ADB' : 'Disable Wi-Fi ADB', async () => {
requireConnected('toggle Wi-Fi ADB');
const requestGeneration = glassesConnectionGenerationRef.current;
const rebuildHint =
Platform.OS === 'ios'
? 'bun run ios (link MentraOS bluetooth-sdk and define MENTRA_SDK_HAS_WIFI_ADB)'
: 'bun run android';
const sdkWithWifiAdb = BluetoothSdk as typeof BluetoothSdk & {
setWifiAdbState?: (value: boolean) => Promise<void>;
};
if (typeof sdkWithWifiAdb.setWifiAdbState !== 'function') {
throw new Error(
`BluetoothSdk.setWifiAdbState is missing from JS. Use an SDK version that provides it and rebuild via: ${rebuildHint}`,
);
}
try {
await sdkWithWifiAdb.setWifiAdbState(enabled);
} catch (error) {
const message = formatError(error);
const isCompatGap =
/unavailable|not implemented|NoSuchMethod|does not exist|MENTRA_SDK_HAS_WIFI_ADB|predates OS-1627/i.test(
message,
);
if (isCompatGap) {
throw new Error(
`${message} — native SDK likely predates OS-1627. Rebuild with MentraOS bluetooth-sdk (auto-picked when nested under MentraOS) via: ${rebuildHint}`,
);
}
throw error instanceof Error ? error : new Error(message);
}
// Ignore completions from a prior BLE session after disconnect/reconnect.
// Do not use galleryConnectionGeneration — hotspot/gallery flows bump that while BLE stays up.
if (requestGeneration !== glassesConnectionGenerationRef.current) {
return;
}
setWifiAdbEnabled(enabled);
addEvent('LIVE', `Wi-Fi ADB ${enabled ? 'enabled' : 'disabled'}`);
});
}
async function openGalleryServer() {
await runAction('Open gallery server', async () => {
const baseUrl = requireGalleryServerUrl(glasses, hotspotEnabled);
setGalleryServerReachable(null);
setGalleryServerStatus(`Gallery server: checking ${baseUrl}`);
const result = await checkGalleryServerReachability(baseUrl, glasses);
setGalleryServerReachable(result.reachable);
setGalleryServerStatus(result.status);
addEvent(result.eventTag, result.eventText);
if (result.reachable) {
await Linking.openURL(baseUrl);
}
});
}
async function copyGalleryServerUrl() {
await runAction('Copy gallery URL', async () => {
const baseUrl = requireGalleryServerUrl(glasses, hotspotEnabled);
Clipboard.setString(baseUrl);
setGalleryServerStatus(`Gallery server: copied ${baseUrl}`);
});
}
async function copyGalleryHotspotPassword() {
await runAction('Copy hotspot password', async () => {
const password = galleryHotspotPasswordLabel(glasses);
Clipboard.setString(password);
setGalleryServerStatus(`Hotspot password copied: ${password}`);
});
}
async function openWifiSettings() {
await runAction('Open Wi-Fi settings', async () => {
if (Platform.OS === 'android') {
const androidLinking = Linking as typeof Linking & {
sendIntent?: (action: string) => Promise<void>;
};
if (androidLinking.sendIntent) {
await androidLinking.sendIntent('android.settings.WIFI_SETTINGS');
return;
}
}
const ssid = galleryHotspotSsidLabel(glasses);
setGalleryServerStatus(`Join ${ssid} from system Wi-Fi settings, then tap Retry.`);
addEvent('LIVE', `Join ${ssid} from system Wi-Fi settings, then tap Retry.`);
});
}
async function toggleMic() {
await runAction(micRecording ? 'Stop microphone' : 'Start microphone', async () => {
if (micRecordingRef.current) {
await stopMicRecording();
} else {
await startMicRecording();
}
});
}
async function playMicRecording() {
await runAction(micPlaying ? 'Stop mic playback' : 'Play mic recording', async () => {
if (micPlayingRef.current) {
await stopMicPlayback();
return;
}
await startMicPlayback();
});
}
async function setVoiceActivityDetectionEnabledAction(enabled: boolean) {
await runAction(enabled ? 'Enable voice activity detection' : 'Disable voice activity detection', async () => {
requireConnected('change voice activity detection');
setVoiceActivityDetectionEnabledState(enabled);
await BluetoothSdk.setVoiceActivityDetectionEnabled(enabled);
});
}
async function openBluetoothSettings() {
await runAction('Open Bluetooth settings', async () => {
if (Platform.OS === 'android') {
const androidLinking = Linking as typeof Linking & {
sendIntent?: (action: string) => Promise<void>;
};
if (androidLinking.sendIntent) {
await androidLinking.sendIntent('android.settings.BLUETOOTH_SETTINGS');
return;
}
}
if (Platform.OS === 'ios') {
setMicPlaybackHint('Open iOS Settings > Bluetooth and connect/select the glasses for audio playback.');
addEvent('LIVE', 'iOS blocks reliable Bluetooth Settings deep links. Open Settings > Bluetooth manually.');
return;
}
await Linking.openSettings();
});
}
async function startMicRecording() {
requireConnected('stream microphone audio');
await stopMicPlayback();
micPcmChunksRef.current = [];
micPcmChunkIndexRef.current = 0;
micPcmStatsRef.current = {bytes: 0, frames: 0};
lastMicFileUriRef.current = null;
micElapsedSecondsRef.current = 0;
micStartedAtRef.current = Date.now();
setLastMicBytes(0);
setLastMicDurationSeconds(null);
setMicPlaybackHint(null);
setMicElapsedSeconds(0);
setPcmBytes(0);
setPcmFrames(0);
micRecordingRef.current = true;
setMicRecording(true);
startMicElapsedTimer();
try {
await BluetoothSdk.setMicState(true, true);
} catch (error) {
micRecordingRef.current = false;
setMicRecording(false);
stopMicElapsedTimer();
throw error;
}
}
async function stopMicRecording() {
micRecordingRef.current = false;
setMicRecording(false);
stopMicElapsedTimer();
flushMicStats();
if (isGlassesConnected(glasses)) {
await BluetoothSdk.setMicState(false);
}
const pcm = concatChunks(micPcmChunksRef.current);
micPcmChunksRef.current = [];
if (pcm.byteLength === 0) {
lastMicFileUriRef.current = null;
setLastMicBytes(0);
setLastMicDurationSeconds(null);
setMicPlaybackHint('No speech audio captured. Keep the glasses connected, speak while recording, and try again.');
addEvent('LIVE', 'microphone stopped with no PCM data');
return;
}
const file = new File(Paths.cache, 'mentra-mic-last.wav');
file.create({intermediates: true, overwrite: true});
file.write(wavBytes(pcm));
lastMicFileUriRef.current = file.uri;
setLastMicBytes(pcm.byteLength);
setLastMicDurationSeconds(
Math.max(micElapsedSecondsRef.current, estimatedMicDurationSeconds(pcm.byteLength)),
);
setMicPlaybackHint(null);
addEvent('LIVE', `saved microphone WAV ${pcm.byteLength} bytes`);
}
async function startMicPlayback(restart = false) {
const uri = lastMicFileUriRef.current;
if (!uri || lastMicBytes <= 0) {
throw new Error('Record microphone audio before playback.');
}
await stopMicPlayback();
await setAudioModeAsync({interruptionMode: 'duckOthers', playsInSilentMode: true});
if (Platform.OS === 'ios') {
setMicPlaybackHint('If playback is silent, open iOS Settings > Bluetooth and connect/select the glasses.');
addEvent('LIVE', 'iOS playback uses the selected system audio output. Pair/select the glasses in Settings > Bluetooth first.');
} else if (Platform.OS === 'android') {
addEvent('LIVE', 'Android playback uses the bonded Bluetooth audio route. Accept the pairing dialog after BLE connects.');
}
try {
const player = createAudioPlayer({uri}, {updateInterval: 250});
micPlayerRef.current = player;
micPlayerSubscriptionRef.current = player.addListener(
'playbackStatusUpdate',
(status) => {
if (status.didJustFinish) {
void stopMicPlayback();
}
},
);
if (restart) {
await player.seekTo(0);
}
await BluetoothSdk.setOwnAppAudioPlaying(true);
micPlayingRef.current = true;
setMicPlaybackHint(null);
setMicPlaying(true);
player.play();
} catch (error) {
await stopMicPlayback();
setMicPlaybackHint(formatError(error));
throw error;
}
}
async function stopMicPlayback() {
const wasPlaying = releaseMicPlayer();
if (wasPlaying) {
await BluetoothSdk.setOwnAppAudioPlaying(false);
}
}
function stopMicPlaybackSync() {
const wasPlaying = releaseMicPlayer();
if (wasPlaying) {
void BluetoothSdk.setOwnAppAudioPlaying(false).catch(() => undefined);
}
}
function releaseMicPlayer() {
micPlayerSubscriptionRef.current?.remove();
micPlayerSubscriptionRef.current = null;
if (micPlayerRef.current) {
try {
micPlayerRef.current.pause();
micPlayerRef.current.remove();
} catch {
// The player may already be torn down after a native completion callback.
}
}
micPlayerRef.current = null;
const wasPlaying = micPlayingRef.current;
micPlayingRef.current = false;
setMicPlaying(false);
return wasPlaying;
}
function startMicElapsedTimer() {
stopMicElapsedTimer();
micElapsedTimerRef.current = setInterval(() => {
const startedAt = micStartedAtRef.current;
if (!startedAt) {
return;
}
const elapsed = Math.max(0, Math.floor((Date.now() - startedAt) / 1000));
micElapsedSecondsRef.current = elapsed;
setMicElapsedSeconds(elapsed);
flushMicStats();
}, 250);
}
function stopMicElapsedTimer() {
if (micElapsedTimerRef.current) {
clearInterval(micElapsedTimerRef.current);
micElapsedTimerRef.current = null;
}
micStartedAtRef.current = null;
}
function flushMicStats() {
setPcmFrames(micPcmStatsRef.current.frames);
setPcmBytes(micPcmStatsRef.current.bytes);
}
async function selectLedMode(mode: LedMode) {
await runAction(`RGB LED ${mode}`, async () => {
requireConnected('control the RGB LED');
setLedMode(mode);
await sendRgbLedRequest(mode, ledColor);
});
}
async function selectLedColor(color: LedColor) {
await runAction(`RGB LED color ${color.toUpperCase()}`, async () => {
requireConnected('control the RGB LED');
if (!RGB_LED_COLORS.includes(color)) {
throw new Error(`Unsupported RGB LED color: ${color}`);
}
setLedColor(color);
if (ledMode !== 'Off') {
await sendRgbLedRequest(ledMode, color);
}
});
}
async function sendRgbLedRequest(mode: LedMode, color: LedColor) {
const requestId = `rgb-${Date.now()}`;
const request = rgbLedRequestFor(mode, color);
const response = await BluetoothSdk.rgbLedControl(
requestId,
PHOTO_APP_ID,
request.action,
request.color,
request.ontime,
request.offtime,
request.count,
);
addEvent('LIVE', `RGB LED ack ${response.requestId}`);
}
function rgbLedRequestFor(mode: LedMode, color: LedColor): { action: RgbLedAction; color: LedColor | null; ontime: number; offtime: number; count: number } {
switch (mode) {
case 'Solid':
return { action: 'on', color, ontime: 30_000, offtime: 0, count: 1 };
case 'Pulse':
return { action: 'on', color, ontime: 900, offtime: 900, count: 6 };
case 'Blink':
return { action: 'on', color, ontime: 250, offtime: 250, count: 12 };
default:
return { action: 'off', color: null, ontime: 0, offtime: 0, count: 0 };
}
}
function requireConnected(feature: string) {
if (isGlassesConnected(glasses)) {
return;
}
const message = `Connect glasses first to ${feature}.`;
if (feature.includes('photo') || feature.includes('capture') || feature.includes('video')) {
setCameraStatus(message);
}
if (feature.includes('stream')) {
setStreamStatus(message);
}
addEvent('TX', message);
throw new Error(message);
}
function requireGlassesWifi(feature: string) {
if (isGlassesWifiConnected(glasses)) {
return;
}
const message = `Connect the glasses to Wi-Fi from the System tab before you ${feature}.`;
if (feature.includes('photo') || feature.includes('capture') || feature.includes('video')) {
setCameraStatus(`Camera: ${message}`);
}
if (feature.includes('stream')) {
setStreamStatus(message);
}
addEvent('TX', message);
throw new Error(message);
}
function requireDisplaySupport(feature: string) {
requireConnected(feature);
if (!supportsDisplay(glasses)) {
throw new Error('This glasses model has no display, so display commands are unavailable.');
}
}
function applyDisconnectedState(status: string) {
setTouchGestureDefaults(initialTouchGestureDefaults());
touchGesturePendingRef.current = null;
setTouchGesturePending(null);
stopPreviewHealthPoll();
stopDirectStreamFrameWatchdog();
clearPhotoUploadTimeout();
void MentraVideoStreamReceiver.stopWebRtcReceiver().catch(() => undefined);
activeStreamIdRef.current = null;
setStreamStartPendingValue(false);
const disconnectedPhotoRequestId = activePhotoRequestIdRef.current;
const disconnectedVideoRequestId = activeVideoRequestIdRef.current;
const hadPhotoRequest = disconnectedPhotoRequestId !== null;
const hadVideoRequest = disconnectedVideoRequestId !== null || videoRecordingRef.current;
activePhotoRequestIdRef.current = null;
barcodeScanRequestIdsRef.current.clear();
activeVideoRequestIdRef.current = null;
videoRecordingRef.current = false;
setVideoRecording(false);
if (hadPhotoRequest) {
pollGenerationRef.current += 1;
setCameraStatus('Disconnected before photo upload completed');
setPhotoStatus({
type: 'photo_status',
requestId: disconnectedPhotoRequestId ?? 'disconnected',
status: 'failed',
timestamp: Date.now(),
errorCode: 'DISCONNECTED',
errorMessage: 'Disconnected before photo upload completed',
});
}
if (hadVideoRequest) {
videoPollGenerationRef.current += 1;
setCameraStatus('Disconnected before video upload completed');
setVideoStatus({
type: 'video_recording_status',
requestId: disconnectedVideoRequestId ?? 'disconnected',
success: false,
status: 'error',
timestamp: Date.now(),
details: 'Disconnected before video upload completed',
});
setVideoPreviewDetails((current) => ({
...current,
error: 'Disconnected before video upload completed',
requestId: disconnectedVideoRequestId ?? current?.requestId ?? null,
source: 'Cloud server',
state: 'error',
}));
}
setStreamRequested(false);
setDirectStreamReceiverRunning(false);
setDirectStreamWhipUrl(null);
setStreamPreviewReady(false);
setStreamStartedAt(null);
setStreamStatus(status);
setGalleryServerReachable(null);
setGalleryServerStatus('Gallery server: connect glasses first');
galleryConnectionGenerationRef.current += 1;
glassesConnectionGenerationRef.current += 1;
galleryConnectionPromiseRef.current = null;
const hotspotSsid = galleryHotspotSsidRef.current;
galleryBaseUrlRef.current = null;
galleryHotspotSsidRef.current = null;
if (hotspotSsid) {
void disconnectGlassesHotspotWifi(hotspotSsid).catch(() => undefined);
}
settleWifiConnectAttempt();
setWifiConnectError(null);
setMicRecording(false);
micRecordingRef.current = false;
stopMicElapsedTimer();
void stopMicPlayback();
}
function applyStreamStatus(payload: StreamStatusEvent) {
const resolvedConfig = (payload as {resolvedConfig?: StreamResolvedConfig})
.resolvedConfig;
const summary = summarizeMap(payload);
const status = payload.status;
if (
status === 'streaming' ||
status === 'initializing' ||
status === 'reconnecting' ||
status === 'reconnected'
) {
if (typeof payload.streamId === 'string') {
activeStreamIdRef.current = payload.streamId;
}
setStreamRequested(true);
setStreamStartedAt((current) => current ?? Date.now());
if (resolvedConfig) {
setStreamResolvedConfig(resolvedConfig);
}
return;
}
if (
status === 'stopped' ||
status === 'stopping' ||
status === 'error' ||
status === 'reconnect_failed'
) {
stopPreviewHealthPoll();
stopDirectStreamFrameWatchdog();
activeStreamIdRef.current = null;
setStreamStartPendingValue(false);
void MentraVideoStreamReceiver.stopWebRtcReceiver().catch(() => undefined);
setDirectStreamReceiverRunning(false);
setDirectStreamWhipUrl(null);
setStreamRequested(false);
setStreamPreviewReady(false);
stopDirectStreamFrameWatchdog();
if (!resolvedConfig) {
setStreamResolvedConfig(null);
}
setStreamStartedAt(null);
setStreamStatus(
status === 'error'
? `Stream error: ${payload.errorDetails ?? summary}`
: status === 'reconnect_failed'
? `Stream reconnect failed: ${summary}`
: status === 'stopping'
? 'Stopping stream'
: 'Stream stopped',
);
}
if (resolvedConfig) {
setStreamResolvedConfig(resolvedConfig);
}
}
return {
activeAction,
barcodeScan,
cameraButtonNotice,
phone,
cameraStatus,
cameraFov,
cameraRoiPosition,
cameraSettingsApplying,
cameraSettingsStatus,
captureAndUpload,
clearDefaultDevice,
clearDisplay,
connect,
connectDevice,
copyGalleryHotspotPassword,
copyGalleryServerUrl,
disconnect,
defaultDevice,
directStreamReceiverRunning,
directStreamWhipUrl,
discoveredDevices,
displayHello,
events,
forgetCurrentWifiNetwork,
galleryModeEnabled,
touchGestureDefaults,
touchGesturePending,
setTouchGestureDefaultBehaviorEnabled: setTouchGestureDefaultBehaviorEnabledAction,
galleryServerReachable,
galleryServerStatus,
glasses,
glassesConnectionGeneration: glassesConnectionGenerationRef.current,
hotspotEnabled,
lastAction,
lastMicBytes,
lastMicDurationSeconds,
mentraLiveVersions: resolveMentraLiveVersions(glasses, latestVersionInfo),
ledColor,
ledMode,
micAudioRouteStatus,
micElapsedSeconds,
micPlaybackHint,
micPlaying,
micRecording,
openBluetoothSettings,
openGalleryServer,
openPhotoPreview,
openWifiSettings,
prepareGlassesPhotoPreview: prepareGlassesPhotoPreviewAction,
applyCameraSettings,
pcmBytes,
pcmFrames,
speaking,
permissionStatus,
phonePhotoReceiverRunning,
phonePhotoUploadUrl,
photoCompression,
photoCloudServerEnabled,
photoGlassesStorageEnabled,
photoAeExposureDivisor,
photoIsoCap,
photoNoiseReduction,
photoEdgeEnhancement,
photoMfnr,
photoZsl,
photoIspDigitalGain,
photoIspAnalogGain,
photoExposureManual,
photoIso,
photoExposureTimeNs,
photoPreviewDetails,
photoPreviewUrl,
photoStatus,
photoSize,
photoTransferMethod,
barcodeScanningEnabled,
textMode,
videoPreviewDetails,
videoPreviewUrl,
videoRecording,
videoStatus,
playMicRecording,
rawJsonExpanded,
requestWifiScan,
scanActive,
scanHint: bluetooth.scan.diagnostic?.message ?? null,
selectDiscoveredDevice,
selectLedColor,
selectLedMode,
selectedScanModel,
selectScanModel,
selectProtocol,
sendWifiCredentials,
setGalleryModeEnabled: setGalleryModeEnabledAction,
setPhotoCompression: setPhotoCompressionAction,
setPhotoCloudServerEnabled: setPhotoCloudServerEnabledAction,
setPhotoGlassesStorageEnabled: setPhotoGlassesStorageEnabledAction,
setPhotoAeExposureDivisor: setPhotoAeExposureDivisorAction,
setPhotoIsoCap: setPhotoIsoCapAction,
setPhotoNoiseReduction: setPhotoNoiseReductionAction,
setPhotoEdgeEnhancement: setPhotoEdgeEnhancementAction,
setPhotoMfnr: setPhotoMfnrAction,
setPhotoZsl: setPhotoZslAction,
setPhotoIspDigitalGain: setPhotoIspDigitalGainAction,
setPhotoIspAnalogGain: setPhotoIspAnalogGainAction,
setPhotoExposureManual,
setPhotoIso: setPhotoIsoAction,
setPhotoExposureTimeNs: setPhotoExposureTimeNsAction,
setPhotoSize: setPhotoSizeAction,
setPhotoTransferMethod,
setBarcodeScanningEnabled: setBarcodeScanningEnabledAction,
setTextMode: setTextModeAction,
setCameraFov: setCameraFovAction,
setCameraRoiPosition: setCameraRoiPositionAction,
setRawJsonExpanded,
setStreamCloudServerEnabled: setStreamCloudServerEnabledAction,
setStreamFps: setStreamFpsAction,
setStreamUrl: setStreamUrlAction,
setWebhookUrl: setWebhookUrlAction,
setVoiceActivityDetectionEnabled: setVoiceActivityDetectionEnabledAction,
selectedDiscoveredDevice,
startScan,
streamCloudServerEnabled,
streamFps,
streamProtocol,
streamPreviewReady,
streamRequested,
streamResolvedConfig,
streamStartPending,
streamStartedAt,
streamStatus,
streamUrl,
testWebhook,
toggleHotspot,
setWifiAdbState,
toggleMic,
toggleVideoRecording,
toggleStream,
wifiAdbEnabled,
voiceActivityDetectionEnabled,
webhookUrl,
wifiConnectError,
wifiConnectingSsid,
};
}
export function scanModelLabel(model: ScanModel) {
return model === DeviceModels.G2 ? 'Even G2' : 'Mentra Live';
}
function scanModelFromDeviceModel(model: DeviceModel): ScanModel {
return SCAN_MODELS.includes(model as ScanModel)
? (model as ScanModel)
: DeviceModels.MentraLive;
}
function event(tag: SdkConsoleEvent['tag'], text: string): SdkConsoleEvent {
return {
tag,
text,
time: new Date().toLocaleTimeString([], {
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
}),
};
}
function barcodeScanSummary(barcodes: BarcodeScanResult[]) {
return barcodes
.map((barcode) => {
const value = barcode.rawValue ?? barcode.displayValue ?? 'unreadable';
return `${barcode.format}: ${value}`;
})
.join(' · ');
}
function dedupeBarcodeResults(barcodes: BarcodeScanResult[]) {
const seen = new Set<string>();
return barcodes.filter((barcode) => {
const value = barcode.rawValue ?? barcode.displayValue;
if (!value) {
return true;
}
const key = `${barcode.format ?? 'unknown'}:${value}`;
if (seen.has(key)) {
return false;
}
seen.add(key);
return true;
});
}
function waitForNextFrame() {
return new Promise<void>((resolve) => {
requestAnimationFrame(() => resolve());
});
}
async function loadPersistedDefaultDevice() {
const file = new File(Paths.document, DEFAULT_DEVICE_FILE);
if (!file.exists) {
return null;
}
return parseDefaultDevice(JSON.parse(await file.text()));
}
async function savePersistedDefaultDevice(device: Device | null) {
const file = new File(Paths.document, DEFAULT_DEVICE_FILE);
if (!device) {
if (file.exists) {
file.delete();
}
return;
}
const persisted: PersistedDefaultDevice = {
...device,
savedAt: Date.now(),
version: 1,
};
file.create({intermediates: true, overwrite: true});
file.write(JSON.stringify(persisted, null, 2));
}
async function loadPersistedCloudUrls(): Promise<PersistedCloudUrls | null> {
const file = new File(Paths.document, CLOUD_URLS_FILE);
if (!file.exists) {
return null;
}
return parsePersistedCloudUrls(JSON.parse(await file.text()));
}
async function savePersistedCloudUrls(urls: {
streamProtocol: StreamProtocol;
streamUrl: string;
webhookUrl: string;
}) {
const file = new File(Paths.document, CLOUD_URLS_FILE);
const persisted: PersistedCloudUrls = {
savedAt: Date.now(),
streamProtocol: urls.streamProtocol,
streamUrl: urls.streamUrl,
version: 1,
webhookUrl: urls.webhookUrl,
};
file.create({intermediates: true, overwrite: true});
file.write(JSON.stringify(persisted, null, 2));
}
function parsePersistedCloudUrls(value: unknown): PersistedCloudUrls | null {
if (!value || typeof value !== 'object') {
return null;
}
const values = value as Record<string, unknown>;
const version = values.version;
if (version !== 1) {
return null;
}
return {
savedAt: typeof values.savedAt === 'number' ? values.savedAt : 0,
streamProtocol: streamProtocolValue(values, 'streamProtocol') ?? undefined,
streamUrl: stringValue(values, 'streamUrl') ?? undefined,
version,
webhookUrl: stringValue(values, 'webhookUrl') ?? undefined,
};
}
function parseDefaultDevice(value: unknown): Device | null {
if (!value || typeof value !== 'object') {
return null;
}
const values = value as Record<string, unknown>;
const model = deviceModelValue(values, 'model');
const name = stringValue(values, 'name');
if (!model || !name) {
return null;
}
const address = stringValue(values, 'address');
return {
id: stringValue(values, 'id') ?? address ?? `${model}:${name}`,
model,
name,
...(address ? {address} : {}),
};
}
function discoveredDeviceKey(device: Device) {
return device.id;
}
function stringValue(values: Record<string, unknown>, key: string) {
const value = (values as Record<string, unknown>)[key];
return typeof value === 'string' && value.length > 0 ? value : undefined;
}
function deviceModelValue(
values: Record<string, unknown>,
key: string,
): DeviceModel | undefined {
const value = stringValue(values, key);
if (!value) {
return undefined;
}
return (Object.values(DeviceModels) as string[]).includes(value) ? (value as DeviceModel) : undefined;
}
function streamProtocolValue(
values: Record<string, unknown>,
key: string,
): StreamProtocol | undefined {
const value = stringValue(values, key);
return value === 'rtmp' || value === 'srt' || value === 'webrtc' ? value : undefined;
}
export function durationText(seconds: number) {
const safeSeconds = Math.max(0, Math.floor(seconds));
const hours = Math.floor(safeSeconds / 3600);
const minutes = Math.floor((safeSeconds % 3600) / 60);
const remainder = safeSeconds % 60;
return [hours, minutes, remainder]
.map((value) => String(value).padStart(2, '0'))
.join(':');
}
function clamp(value: number, min: number, max: number) {
return Math.min(max, Math.max(min, value));
}
function copyPcmFrame(pcm: MicPcmEvent['pcm'] | ArrayBufferView | ArrayLike<number>) {
const raw = pcm as unknown;
if (raw instanceof ArrayBuffer) {
return new Uint8Array(raw).slice();
}
if (ArrayBuffer.isView(raw)) {
const view = raw as ArrayBufferView;
return new Uint8Array(view.buffer, view.byteOffset, view.byteLength).slice();
}
return Uint8Array.from(raw as ArrayLike<number>);
}
function formatMicPcmMetadata(event: MicPcmEvent) {
return `${event.sampleRate}Hz ${event.bitsPerSample}-bit ${event.channels}ch ${event.encoding}`;
}
function formatMicLc3Metadata(event: MicLc3Event) {
return `${event.lc3.byteLength} bytes, ${event.frameDurationMs}ms, ${event.sampleRate}Hz ${event.channels}ch, ${event.bitrate}bps`;
}
function concatChunks(chunks: MicPcmChunk[]) {
const orderedChunks = [...chunks].sort((left, right) => left.index - right.index);
const totalBytes = orderedChunks.reduce((sum, chunk) => sum + chunk.data.byteLength, 0);
const merged = new Uint8Array(totalBytes);
let offset = 0;
for (const chunk of orderedChunks) {
merged.set(chunk.data, offset);
offset += chunk.data.byteLength;
}
return merged;
}
function estimatedMicDurationSeconds(byteCount: number) {
const bytesPerSecond = (MIC_SAMPLE_RATE * MIC_CHANNEL_COUNT * MIC_BITS_PER_SAMPLE) / 8;
return byteCount <= 0 ? 0 : Math.ceil(byteCount / bytesPerSecond);
}
function wavBytes(pcm: Uint8Array) {
const buffer = new ArrayBuffer(44 + pcm.byteLength);
const view = new DataView(buffer);
const bytes = new Uint8Array(buffer);
let offset = 0;
function writeAscii(value: string) {
for (let index = 0; index < value.length; index += 1) {
bytes[offset + index] = value.charCodeAt(index);
}
offset += value.length;
}
function writeUInt16(value: number) {
view.setUint16(offset, value, true);
offset += 2;
}
function writeUInt32(value: number) {
view.setUint32(offset, value, true);
offset += 4;
}
writeAscii('RIFF');
writeUInt32(36 + pcm.byteLength);
writeAscii('WAVE');
writeAscii('fmt ');
writeUInt32(16);
writeUInt16(1);
writeUInt16(MIC_CHANNEL_COUNT);
writeUInt32(MIC_SAMPLE_RATE);
writeUInt32((MIC_SAMPLE_RATE * MIC_CHANNEL_COUNT * MIC_BITS_PER_SAMPLE) / 8);
writeUInt16((MIC_CHANNEL_COUNT * MIC_BITS_PER_SAMPLE) / 8);
writeUInt16(MIC_BITS_PER_SAMPLE);
writeAscii('data');
writeUInt32(pcm.byteLength);
bytes.set(pcm, offset);
return bytes;
}
function photoStatusUrl(uploadUrlText: string, requestId: string) {
const uploadUrl = new URL(uploadUrlText);
if (uploadUrl.protocol !== 'http:' && uploadUrl.protocol !== 'https:') {
throw new Error('Only http and https webhook URLs are supported.');
}
return `${uploadUrl.protocol}//${uploadUrl.host}/uploads/${requestId}.json`;
}
function webhookHealthUrl(uploadUrlText: string) {
const uploadUrl = new URL(uploadUrlText);
if (uploadUrl.protocol !== 'http:' && uploadUrl.protocol !== 'https:') {
throw new Error('Only http and https webhook URLs are supported.');
}
return `${uploadUrl.protocol}//${uploadUrl.host}/`;
}
export function streamPreviewTarget(protocol: StreamProtocol, streamUrl: string): StreamPreviewTarget | null {
try {
if (protocol === 'rtmp') {
const url = rtmpHlsPreviewUrl(streamUrl);
return url ? {kind: 'hls', url} : null;
}
if (protocol === 'srt') {
const url = srtHlsPreviewUrl(streamUrl);
return url ? {kind: 'hls', url} : null;
}
return {kind: 'web', url: webrtcPreviewUrl(streamUrl)};
} catch {
return null;
}
}
function photoUploadValidationMessage(uploadUrlText: string) {
const value = uploadUrlText.trim();
if (value.length === 0) {
return 'Paste the media upload URL printed by local demo cloud.';
}
if (value.includes('<computer-ip>')) {
return 'Replace <computer-ip> with the IP printed by local demo cloud.';
}
return null;
}
async function localWebrtcReachabilityMessage(whipUrlText: string) {
let previewUrl = '';
try {
previewUrl = webrtcPreviewUrl(whipUrlText);
} catch {
return 'Enter a valid http:// or https:// WHIP URL.';
}
return localHttpPreviewReachabilityMessage(previewUrl, localWebrtcSetupMessage);
}
async function localRtmpReachabilityMessage(rtmpUrlText: string) {
let previewUrl = '';
try {
previewUrl = rtmpHlsPreviewUrl(rtmpUrlText) ?? '';
} catch {
return 'Enter a valid rtmp:// or rtmps:// publish URL.';
}
if (!previewUrl) {
return null;
}
return localHttpPreviewReachabilityMessage(previewUrl, localRtmpSetupMessage);
}
async function localSrtReachabilityMessage(srtUrlText: string) {
let previewUrl = '';
try {
previewUrl = srtHlsPreviewUrl(srtUrlText) ?? '';
} catch {
return 'Enter a valid srt:// publish URL.';
}
if (!previewUrl) {
return null;
}
return localHttpPreviewReachabilityMessage(previewUrl, localSrtSetupMessage);
}
async function localHttpPreviewReachabilityMessage(
previewUrl: string,
setupMessage: (detail: string) => string,
) {
try {
const response = await fetch(cacheBustedUrl(previewUrl), {
cache: 'no-store',
headers: {'Cache-Control': 'no-cache', Pragma: 'no-cache'},
});
// MediaMTX may return 404 before a stream exists; any HTTP response means it is reachable.
void response.status;
return null;
} catch (error) {
return setupMessage(formatError(error));
}
}
async function streamPreviewIsReady(streamUrl: string, protocol: StreamProtocol) {
try {
if (protocol === 'rtmp') {
const previewUrl = rtmpHlsPreviewUrl(streamUrl);
return previewUrl ? hlsPreviewIsReady(previewUrl) : false;
}
if (protocol === 'srt') {
const previewUrl = srtHlsPreviewUrl(streamUrl);
return previewUrl ? hlsPreviewIsReady(previewUrl) : false;
}
return webPreviewIsReady(webrtcPreviewUrl(streamUrl));
} catch {
return false;
}
}
async function webPreviewIsReady(previewUrl: string) {
try {
const response = await fetch(cacheBustedUrl(previewUrl), {
cache: 'no-store',
headers: {'Cache-Control': 'no-cache', Pragma: 'no-cache'},
});
return response.ok;
} catch {
return false;
}
}
async function hlsPreviewIsReady(previewUrl: string) {
try {
const response = await fetch(cacheBustedUrl(previewUrl), {
cache: 'no-store',
headers: {'Cache-Control': 'no-cache', Pragma: 'no-cache'},
});
if (!response.ok) {
return false;
}
return (await response.text()).includes('#EXTM3U');
} catch {
return false;
}
}
function rtmpHlsPreviewUrl(rtmpUrlText: string) {
const rtmpUrl = new URL(rtmpUrlText);
if (rtmpUrl.protocol !== 'rtmp:' && rtmpUrl.protocol !== 'rtmps:') {
throw new Error('Only rtmp and rtmps URLs are supported.');
}
if (!isLocalPreviewHost(rtmpUrl.hostname)) {
return null;
}
const streamPath = rtmpUrl.pathname.replace(/^\/+|\/+$/g, '');
rtmpUrl.protocol = rtmpUrl.protocol === 'rtmps:' ? 'https:' : 'http:';
rtmpUrl.port = '8888';
rtmpUrl.pathname = streamPath.length === 0 ? '/index.m3u8' : `/${streamPath}/index.m3u8`;
rtmpUrl.search = '';
return rtmpUrl.toString();
}
function srtHlsPreviewUrl(srtUrlText: string) {
const srtUrl = new URL(srtUrlText);
if (srtUrl.protocol !== 'srt:') {
throw new Error('Only srt URLs are supported.');
}
if (!isLocalPreviewHost(srtUrl.hostname)) {
return null;
}
const path = srtStreamPath(srtUrl.searchParams.get('streamid'));
if (!path) {
return null;
}
return `http://${srtUrl.hostname}:8888/${path}/index.m3u8`;
}
function srtStreamPath(streamId: string | null) {
if (!streamId) {
return null;
}
const parts = streamId.split(':');
const path = parts[0] === 'publish' || parts[0] === 'read' ? parts[1] : streamId;
return path?.replace(/^\/+|\/+$/g, '') || null;
}
function isLocalPreviewHost(host: string) {
const normalized = host.toLowerCase();
if (
normalized === 'localhost' ||
normalized.endsWith('.local') ||
normalized.startsWith('192.168.') ||
normalized.startsWith('10.') ||
normalized.startsWith('169.254.')
) {
return true;
}
const parts = normalized.split('.').map((part) => Number(part));
return (
parts.length === 4 &&
parts.every(Number.isInteger) &&
parts[0] === 172 &&
parts[1] >= 16 &&
parts[1] <= 31
);
}
function webrtcPreviewUrl(whipUrlText: string) {
const whipUrl = new URL(whipUrlText);
if (whipUrl.protocol !== 'http:' && whipUrl.protocol !== 'https:') {
throw new Error('Only http and https WHIP URLs are supported.');
}
if (whipUrl.pathname.endsWith('/whip')) {
whipUrl.pathname = whipUrl.pathname.slice(0, -'/whip'.length) || '/';
}
whipUrl.search = '';
return whipUrl.toString();
}
function localWebrtcSetupMessage(detail: string) {
return `Local WebRTC server not reachable (${detail}). Run python3 local-demo-cloud/server.py and paste the printed WHIP publish URL.`;
}
function localRtmpSetupMessage(detail: string) {
return `Local RTMP/HLS server not reachable (${detail}). Run python3 local-demo-cloud/server.py and paste the printed RTMP publish URL.`;
}
function localSrtSetupMessage(detail: string) {
return `Local SRT/HLS server not reachable (${detail}). Run python3 local-demo-cloud/server.py and paste the printed SRT publish URL.`;
}
function streamUrlValidationMessage(streamUrl: string) {
if (!streamUrl) {
return 'Stream URL is required.';
}
if (streamUrl.includes('<computer-ip>')) {
return 'Replace <computer-ip> with the matching publish URL printed by local demo cloud.';
}
if (streamUrl.includes('<') || streamUrl.includes('>') || streamUrl.includes('YOUR_')) {
return 'Replace the placeholder stream URL before starting.';
}
const rtmpSegmentCount = rtmpPathSegmentCount(streamUrl);
if (rtmpSegmentCount !== null && rtmpSegmentCount < 2) {
return 'RTMP URL must include an app and stream key, for example rtmp://<computer-ip>:1935/live/mentra-live.';
}
return null;
}
function rtmpPathSegmentCount(streamUrl: string) {
try {
const url = new URL(streamUrl);
if (url.protocol !== 'rtmp:' && url.protocol !== 'rtmps:') {
return null;
}
return url.pathname.split('/').filter(Boolean).length;
} catch {
return null;
}
}
function cacheBustedUrl(url: string) {
return `${url}${url.includes('?') ? '&' : '?'}poll=${Date.now()}`;
}
function currentPhotoSource(destination: PhotoDestination): PhotoPreviewDetails['source'] {
if (destination === 'cloud') {
return 'Cloud server';
}
if (destination === 'glasses') {
return 'Glasses gallery';
}
return 'Phone receiver';
}
function requireGalleryServerUrl(status: GlassesRuntimeState, fallbackEnabled: boolean) {
const baseUrl = galleryServerUrl(status, fallbackEnabled);
if (!baseUrl) {
throw new Error('Enable the glasses hotspot first.');
}
return baseUrl;
}
async function checkGalleryServerReachability(
baseUrl: string,
status: GlassesRuntimeState,
) {
try {
const response = await fetch(cacheBustedUrl(`${baseUrl}/api/status`), {
cache: 'no-store',
headers: {'Cache-Control': 'no-cache', Pragma: 'no-cache'},
});
const body = await response.text();
if (response.ok) {
const totalPhotos = /"total_photos"\s*:\s*(\d+)/.exec(body)?.[1];
return {
reachable: true,
status: totalPhotos
? `Gallery server: reachable · ${totalPhotos} items`
: 'Gallery server: reachable',
eventTag: 'LIVE' as const,
eventText: `gallery server reachable ${baseUrl}`,
};
}
return {
reachable: false,
status: `Gallery server: HTTP ${response.status}`,
eventTag: 'TX' as const,
eventText: `gallery server HTTP ${response.status}`,
};
} catch (error) {
return {
reachable: false,
status: `Gallery server: not reachable. Join ${galleryHotspotSsidLabel(status)} and retry.`,
eventTag: 'TX' as const,
eventText: `gallery server unreachable: ${formatError(error)}`,
};
}
}
async function waitForGalleryServer(baseUrl: string, attempts: number, delayMs: number) {
for (let attempt = 0; attempt < attempts; attempt += 1) {
try {
const response = await fetchWithTimeout(
cacheBustedUrl(`${baseUrl}/api/health`),
{cache: 'no-store', headers: {'Cache-Control': 'no-cache', Pragma: 'no-cache'}},
1000,
);
if (response.status > 0) {
return true;
}
} catch {
// The hotspot can take a few seconds to become routable after the OS joins it.
}
if (attempt < attempts - 1) {
await delay(delayMs);
}
}
return false;
}
async function disconnectGlassesHotspotWifi(ssid: string) {
if (Platform.OS === 'ios') {
await WifiManager.disconnectFromSSID(ssid);
return;
}
await WifiManager.disconnect();
}
function androidRuntimePermissions() {
const permissions = [
PermissionsAndroid.PERMISSIONS.CAMERA,
PermissionsAndroid.PERMISSIONS.RECORD_AUDIO,
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
];
if (Number(Platform.Version) >= ANDROID_12_API_LEVEL) {
permissions.push(
PermissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN,
PermissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT,
);
} else {
permissions.push(PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION);
}
if (Number(Platform.Version) >= 33) {
permissions.push(
PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS,
'android.permission.NEARBY_WIFI_DEVICES',
);
}
return permissions;
}
type PhotoStatusExtras = {
requestedCaptureConfig?: PhotoRequestedCaptureConfigDetails;
meteredPreview?: PhotoMeteredPreviewDetails;
captureMetadata?: PhotoCaptureMetadataDetails;
};
function photoStatusLabel(event: PhotoStatusEvent, galleryModeButtonPhoto = false) {
const base = (() => {
if (galleryModeButtonPhoto) {
switch (event.status) {
case 'accepted':
case 'queued':
return 'gallery photo queued on glasses';
case 'configuring':
return 'gallery camera configured';
case 'capturing':
return 'saving photo on glasses';
case 'captured':
case 'uploading':
case 'uploaded':
return 'photo saved on glasses';
case 'failed':
return event.errorCode ?? event.errorMessage ?? 'gallery photo failed';
default:
return String(event.status).replace(/_/g, ' ');
}
}
switch (event.status) {
case 'accepted':
return 'photo request started';
case 'queued':
return 'photo queued on glasses';
case 'configuring':
return 'camera configured';
case 'capturing':
return 'capturing photo';
case 'captured':
return 'photo captured';
case 'compressing':
return 'compressing photo';
case 'ble_fallback_compression':
return 'Wi-Fi upload failed; Bluetooth fallback compression';
case 'uploading':
return 'uploading photo';
case 'uploaded':
return 'photo uploaded';
case 'ready_for_transfer':
return 'photo ready for transfer';
case 'transferring':
return 'transferring photo';
case 'failed':
return event.errorCode ?? event.errorMessage ?? 'photo failed';
default:
return String(event.status).replace(/_/g, ' ');
}
})();
const configSummary = photoStatusDetailSummary(event);
return configSummary ? `${base} (${configSummary})` : base;
}
function photoBleFallbackMessage(status: string) {
return status === 'ble_fallback_compression'
? PHOTO_BLE_FALLBACK_COMPRESSION_MESSAGE
: null;
}
function photoBleFallbackProgressMessage(status: string, currentMessage?: string) {
switch (status) {
case 'ready_for_transfer':
return PHOTO_BLE_FALLBACK_TRANSFER_MESSAGE;
case 'transferring':
return PHOTO_BLE_FALLBACK_TRANSFER_MESSAGE;
default:
return currentMessage;
}
}
function photoStatusStartsNewCapture(status: string) {
return status === 'accepted' || status === 'queued' || status === 'configuring';
}
function appendPhotoTimeline(
timeline: PhotoTimelineEvent[] | undefined,
event: PhotoTimelineEvent,
) {
const entries = timeline ?? [];
const duplicate = entries.some(
(entry) =>
entry.source === event.source &&
entry.status === event.status &&
entry.timestamp === event.timestamp,
);
return duplicate ? entries : [...entries, event];
}
function appendPhotoResponseTimeline(
timeline: PhotoTimelineEvent[] | undefined,
event: Pick<PhotoTimelineEvent, 'timestamp'>,
) {
return appendPhotoTimeline(timeline, {
source: 'photo_response',
timestamp: event.timestamp,
});
}
function videoStatusIsFailure(status: string) {
return [
'already_recording',
'not_recording',
'request_id_mismatch',
'service_unavailable',
'json_error',
'battery_low',
'camera_busy',
'storage_unavailable',
'integrity_failed',
'error',
].includes(status);
}
function isCameraActionButtonPress(payload: ButtonPressEvent) {
return payload.pressType === 'short' && CAMERA_ACTION_BUTTON_IDS.has(payload.buttonId.toLowerCase());
}
function isCameraActionTouchEvent(payload: TouchEvent) {
const gestureName = payload.gestureName?.trim();
if (!gestureName) {
return false;
}
const normalized = gestureName.toLowerCase().replace(/[\s-]+/g, '_');
return normalized === 'tap' || normalized === 'single_tap';
}
function clearPhotoBleFallbackWarning(details: PhotoPreviewDetails) {
if (!details.bleFallbackUsed && !details.bleFallbackMessage) {
return details;
}
return {
...details,
bleFallbackMessage: undefined,
bleFallbackUsed: false,
};
}
function photoStatusDetailSummary(event: PhotoStatusEvent) {
const eventWithExtras = event as PhotoStatusEvent & PhotoStatusExtras;
return [
photoResolvedConfigSummary(event.resolvedConfig),
photoRequestedCaptureSummary(eventWithExtras.requestedCaptureConfig),
photoMeteredPreviewSummary(eventWithExtras.meteredPreview),
photoCaptureMetadataSummary(eventWithExtras.captureMetadata),
].filter(Boolean).join(' · ') || null;
}
function photoResolvedConfigSummary(config: PhotoStatusEvent['resolvedConfig']) {
if (!config) {
return null;
}
const values = [
config.width && config.height ? `${config.width}x${config.height}` : null,
config.quality ? `q${config.quality}` : null,
config.requestedSize ? `requested ${config.requestedSize}` : null,
config.transferMethod ? config.transferMethod : null,
config.compression ? `compress ${config.compression}` : null,
config.exposureTimeNs ? exposureTimeSummary(config.exposureTimeNs) : null,
config.iso ? `ISO ${config.iso}` : null,
].filter(Boolean);
return values.length > 0 ? values.join(' · ') : null;
}
function photoRequestedCaptureSummary(config: PhotoStatusExtras['requestedCaptureConfig']) {
if (!config) {
return null;
}
const fps = config.aeTargetFpsRange?.min != null && config.aeTargetFpsRange?.max != null
? `${config.aeTargetFpsRange.min}-${config.aeTargetFpsRange.max}fps`
: null;
const values = [
config.manual != null ? (config.manual ? 'manual request' : 'auto request') : null,
config.exposureTimeNs ? `request ${exposureTimeSummary(config.exposureTimeNs)}` : null,
config.iso ? `request ISO ${config.iso}` : null,
config.frameDurationNs ? `frame ${exposureTimeSummary(config.frameDurationNs)}` : null,
fps,
].filter(Boolean);
return values.length > 0 ? values.join(' · ') : null;
}
function photoMeteredPreviewSummary(config: PhotoStatusExtras['meteredPreview']) {
if (!config) {
return null;
}
const values = [
config.exposureTimeNs ? `metered ${exposureTimeSummary(config.exposureTimeNs)}` : null,
config.iso ? `metered ISO ${config.iso}` : null,
].filter(Boolean);
return values.length > 0 ? values.join(' · ') : null;
}
function photoCaptureMetadataSummary(config: PhotoStatusExtras['captureMetadata']) {
if (!config) {
return null;
}
const values = [
config.exposureTimeNs ? `actual ${exposureTimeSummary(config.exposureTimeNs)}` : null,
config.iso ? `actual ISO ${config.iso}` : null,
config.frameDurationNs ? `actual frame ${exposureTimeSummary(config.frameDurationNs)}` : null,
config.aeStateName ? `AE ${config.aeStateName}` : null,
].filter(Boolean);
return values.length > 0 ? values.join(' · ') : null;
}
function exposureTimeSummary(exposureTimeNs: number) {
const seconds = exposureTimeNs / 1_000_000_000;
if (seconds <= 0) {
return `${Math.round(exposureTimeNs)} ns`;
}
return `1/${Math.round(1 / seconds)}s`;
}
function summarizeMap(values: object) {
const record = values as Record<string, unknown>;
const keys = Object.keys(record);
if (keys.length === 0) {
return 'empty update';
}
return keys
.slice(0, 3)
.map((key) => `${key}: ${String(record[key])}`)
.join(', ');
}
function describeSettingsAck(ack: SettingsAckEvent) {
const parts = [`${ack.setting} ${ack.status}`];
if (ack.fov !== undefined) {
parts.push(`fov=${ack.fov}`);
}
if (ack.roiPosition !== undefined) {
parts.push(`roi=${ack.roiPosition}`);
}
if (ack.errorCode) {
parts.push(ack.errorCode);
}
return parts.join(' ');
}
function describeCameraFovResult(result: CameraFovResult) {
return `applied fov=${result.fov} roi=${result.roiPosition} request=${result.requestId}`;
}
function delay(ms: number) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
async function fetchWithTimeout(
input: string,
init: RequestInit,
timeoutMs: number,
) {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), timeoutMs);
try {
return await fetch(input, {...init, signal: controller.signal});
} finally {
clearTimeout(timeout);
}
}
function clampRounded(value: number, min: number, max: number) {
return Math.max(min, Math.min(max, Math.round(value)));
}
function roiPositionLabel(roiPosition: CameraRoiPosition) {
return CAMERA_ROI_POSITIONS.find((option) => option.value === roiPosition)?.label ?? 'Center';
}
function formatError(error: unknown) {
return error instanceof Error ? error.message : String(error);
}
function isRequestTimeoutError(error: unknown) {
const message = formatError(error).toLowerCase();
return (
message.includes('request_timeout') ||
message.includes('timed out waiting for glasses response')
);
}
function webhookReachabilityErrorMessage(error: unknown, healthUrl: string) {
if (isAbortError(error)) {
return `Timed out after 3s while this app tried to GET ${healthUrl}. This only checks app-device-to-media-server reachability.`;
}
const message = formatError(error);
if (message === 'Network request failed' || error instanceof TypeError) {
return `This app could not GET ${healthUrl}. Check that the media server is running and that this device can reach that host on the local network.`;
}
return message;
}
function isAbortError(error: unknown) {
return error instanceof Error && error.name === 'AbortError';
}
|