import { NavBar, SpinLoading, Toast } from 'antd-mobile'; import './Bluetooth.scss'; import { useEffect, useState } from 'react'; import { useAppDispatch, useAppSelector } from '../utils/hooks'; import Bridge from '../utils/bridge'; import { updateBleLinkStatus, updateBleList } from '../store/features/contextSlice'; export default function Bluetooth() { const dispatch = useAppDispatch(); const contextState = useAppSelector((state) => state.context); const [connectingMac, setConnectingMac] = useState('') useEffect(() => { Bridge.scanPeripherals().then((res) => { if (!res.success) { Toast.show(res.message); } }); return () => { Bridge.stopScanPeripherals().then((res) => {}); }; }, []); const onConnect = (mac: string) => { setConnectingMac(mac); Bridge.connectPeripheral({ mac }).then((res) => { setConnectingMac(''); if (!res.success) { Toast.show(res.message); } else { dispatch(updateBleLinkStatus({ mac, link: true })); } }); }; const onDisconnect = (mac: string) => { Bridge.disconnectPeripheral().then((res) => { if (!res.success) { Toast.show(res.message); } else { dispatch(updateBleList([])); // 清空列表 // dispatch(updateBleLinkStatus({ mac, link: false })); } }); }; function scanning() { return

扫描中

} return (
蓝牙

附近设备

{contextState.bleList.some((bl) => bl.linked) || connectingMac ? undefined : scanning()}
{contextState.bleList.map((ble) => (
bl.linked) || connectingMac ? undefined : () => onConnect(ble.mac) } >

{ble.name}

{ble.mac}

{ble.linked ? '已连接' : connectingMac === ble.mac ? '正在连接' : ''} {connectingMac === ble.mac &&
} {ble.linked && ( )}
))}
); }