97 lines
2.9 KiB
TypeScript
97 lines
2.9 KiB
TypeScript
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 (
|
|
<>
|
|
<View className={styles.main}>
|
|
<SearchInput title="蓝牙设备" showIcon>
|
|
<View className={styles.bluetooth_link} onClick={onFindDevice}>
|
|
<View className={classnames(styles.link_status, linkStatus == 3 && styles.link_statused, linkStatus == 2 && styles.link_statused_no)}></View>
|
|
{
|
|
linkStatus == 1
|
|
? <View className={classnames(styles.link_name, styles.link_name_no)}>请开启蓝牙</View>
|
|
: linkStatus == 2
|
|
? <View className={classnames(styles.link_name, styles.link_name_no_link)}>未连接设备</View>
|
|
: linkStatus == 3 ? <View className={classnames(styles.link_name)}>{linkName}</View> : null
|
|
}
|
|
</View>
|
|
</SearchInput>
|
|
<Popup
|
|
state={state}
|
|
show={popupShow}
|
|
onClose={() => setPopupShow(false)}
|
|
onLink={item => onLinkListen(item)}
|
|
onOff={onDisconnect}
|
|
onFind={onFindEven}
|
|
/>
|
|
</View>
|
|
</>
|
|
|
|
)
|
|
}
|
|
export default memo(LinkBlueTooth)
|