import { View } from '@tarojs/components' import Taro, { useDidShow } from '@tarojs/taro' import { memo, useEffect, useMemo, useState } from 'react' import classnames from 'classnames' import styles from './css/linkBlueTooth.module.scss' import { useBluetooth } from '@/use/contextBlueTooth' import SearchInput from '@/components/searchInput' import Popup from '@/components/bluetooth/Popup' import useCheckAuthorize from '@/use/useCheckAuthorize' const LinkBlueTooth = () => { const { state, init, startScan, connect, disconnect } = useBluetooth() const { check } = useCheckAuthorize({ scope: 'scope.bluetooth', msg: '请开启小程序蓝牙权限' }) useEffect(() => { init() }, []) const [linkStatus, setLinkStatus] = useState(1) useEffect(() => { if (!state.available) { setLinkStatus(1) } else if (state.available && state.connected?.name) { setLinkStatus(3) } else { setLinkStatus(2) } }, [state.available, state.connected]) const linkName = useMemo(() => { return state.connected?.localName || '' }, [state.connected]) // 链接设备 const onLinkListen = (item) => { if (!state.connected && !state.connecting) { connect(item) } } const [popupShow, setPopupShow] = useState(false) const onFindEven = () => { if (!state.discovering && !state.connected && !state.connecting) { startScan() } } // 显示设备列表 const onFindDevice = () => { check().then((res) => { if (linkStatus == 1) { Taro.showToast({ title: '请打开手机蓝牙', icon: 'none', }) } else { setPopupShow(true) onFindEven() } }) } // 断开链接 const onDisconnect = () => { disconnect() setPopupShow(false) } return ( <> { linkStatus == 1 ? 请开启蓝牙 : linkStatus == 2 ? 未连接设备 : linkStatus == 3 ? {linkName} : null } setPopupShow(false)} onLink={item => onLinkListen(item)} onOff={onDisconnect} onFind={onFindEven} /> ) } export default memo(LinkBlueTooth)