91 lines
2.9 KiB
TypeScript
91 lines
2.9 KiB
TypeScript
import { View } from "@tarojs/components";
|
|
import { memo, useEffect, useMemo, useState } from "react";
|
|
import Taro from "@tarojs/taro";
|
|
import { useBluetooth } from "@/use/contextBlueTooth"
|
|
import SearchInput from "@/components/searchInput";
|
|
import Popup from "./Popup"
|
|
import classnames from "classnames";
|
|
import styles from "../../css/linkBlueTooth.module.scss"
|
|
|
|
export default memo(() => {
|
|
const { state, init, startScan, connect, disconnect } = useBluetooth()
|
|
|
|
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)
|
|
}
|
|
console.log('aaa:::', state.connected)
|
|
}, [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 onFindDevice = () => {
|
|
if (linkStatus == 1) {
|
|
Taro.showToast({
|
|
title: '请打开蓝牙',
|
|
icon: 'none'
|
|
})
|
|
} else {
|
|
setPopupShow(true)
|
|
onFindEven()
|
|
}
|
|
|
|
}
|
|
const onFindEven = () => {
|
|
if (!state.discovering && !state.connected && !state.connecting)
|
|
startScan()
|
|
}
|
|
|
|
//断开链接
|
|
const onDisconnect = () => {
|
|
disconnect()
|
|
setPopupShow(false)
|
|
}
|
|
|
|
return (
|
|
<>
|
|
<View className={styles.main}>
|
|
<SearchInput title="蓝牙设备" showIcon={true} showBorder={false}>
|
|
<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>
|
|
}
|
|
</View>
|
|
</SearchInput>
|
|
<Popup
|
|
state={state}
|
|
show={popupShow}
|
|
onClose={() => setPopupShow(false)}
|
|
onLink={item => onLinkListen(item)}
|
|
onOff={onDisconnect}
|
|
onFind={onFindEven}
|
|
/>
|
|
</View>
|
|
</>
|
|
|
|
);
|
|
|
|
})
|