123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433 |
- <template>
- <view>
- <h2 class='hTitle'>匹配蓝牙设备</h2>
- <view class="bottomBox">
- <button @click="refreshBlue" class="refreshBlueTooth">刷新蓝牙设备</button>
- <view class="equipmentTitle">
- 设备名称
- </view>
-
- <view class="blueListBox">
- <scroll-view scroll-y class="box">
- <view class="item" v-for="item in blueDeviceList" @click="connect(item)">
- <view>
- <text>id: {{ item.deviceId }}</text>
- </view>
- <view>
- <text>name: {{ item.name }}</text>
- </view>
- </view>
- </scroll-view>
- </view>
- <view class="equipmentTitle">
- 已配对的设备
- </view>
- <view class="alreadyBlue">
- {{deviceId}}
- </view>
- <view class="bottom-btn">
- <button :loading='characteristicId==""' @click="confirmEdit" class="refreshBlueToothNot"
- :class="{refreshBlueTooth:characteristicId?true:false}">{{characteristicId?'确定编辑设备':'获取服务中'}}</button>
- </view>
- </view>
- </view>
- </template>
- <script>
- export default {
- data() {
- return {
- blueDeviceList: [],
- deviceId: '',
- serviceId: '',
- characteristicId: '',
- connected: false,
- isUpdateData:false,
- };
- },
- created() {
-
- this.openBlue()
-
- this.stateChange()
- },
- onShow() {
- let that = this
- uni.$on('updateData', function(data) {
- if (data) {
- this.isUpdateData = true
-
-
- if (that.deviceId) {
- that.closeBLEConnection(that.deviceId)
- }
- that.deviceId = ''
- that.serviceId = ''
- that.characteristicId = ''
- }
- })
- },
- onHide() {
-
- uni.$on('updateData', function(data) {
- uni.$off('updateData');
- this.isUpdateData = false
- })
- },
- methods: {
-
- blueError(code) {
- switch (code) {
- case 10000:
- this.errorToast('未初始化蓝牙适配器')
- break
- case 10001:
- this.errorToast('当前蓝牙适配器不可用')
- break
- case 10002:
- this.errorToast('没有找到指定设备')
- break
- case 10003:
- this.errorToast('连接失败')
- break
- case 10004:
- this.errorToast('没有找到指定服务')
- break
- case 10005:
- this.errorToast('没有找到指定特征值')
- break
- case 10006:
- this.errorToast('当前连接已断开')
- break
- case 10007:
- this.errorToast('当前特征值不支持此操作')
- break
- case 10008:
- this.errorToast('其余所有系统上报的异常')
- break
- case 10009:
- this.errorToast('Android 系统特有,系统版本低于 4.3 不支持 BLE')
- break
- case 10010:
- this.errorToast('已连接')
- break
- case 10011:
- this.errorToast('配对设备需要配对码')
- break
- case 10012:
- this.errorToast('连接超时')
- break
- case 10013:
- this.errorToast('连接 deviceld 为空或者是格式不正确')
- break
- }
- },
-
- errorToast(err) {
- uni.showToast({
- title: `${err}`,
- icon: 'none',
- duration: 2500
- })
- },
-
- refreshBlue() {
- uni.showLoading({
- title: '正在刷新',
- mask: true
- })
- this.discovery('refresh')
- },
-
- confirmEdit() {
- if (!this.characteristicId) {
- return
- }
- uni.navigateTo({
- url: `/pages/edit/edit?deviceId=${this.deviceId}&serviceId=${this.serviceId}&characteristicId=${this.characteristicId}`
- })
- },
-
- openBlue() {
- let that = this
- uni.showLoading({
- title: '初始化中',
- mask: true
- })
- uni.openBluetoothAdapter({
- success(res) {
- uni.hideLoading()
- uni.showToast({
- title: '初始化成功',
- duration: 2500
- })
- that.discovery()
- },
- fail(err) {
- uni.hideLoading()
- that.blueError(err.errCode)
- console.log('初始化蓝牙失败')
- console.error(err)
- }
- })
- },
-
- discovery(msg) {
- let that = this
- that.blueDeviceList = []
- uni.startBluetoothDevicesDiscovery({
- success(res) {
- if (msg = 'refresh') {
- uni.hideLoading()
- }
-
- uni.onBluetoothDeviceFound((res) => {
- if (res.devices[0].name) {
- that.found(res)
- }
- })
- },
- fail(err) {
- console.log('搜索失败')
- console.error(err)
- }
- })
- },
-
- found(res) {
- if (res.devices[0].name.includes('BT24')) {
- this.blueDeviceList.push(res.devices[0])
- }
-
- if (this.connected) {
- return
- }
-
- let deviceId = uni.getStorageSync('deviceId')
- if (deviceId) {
- let list = []
- this.blueDeviceList.forEach(item => {
- list.push(item.deviceId)
- })
- if (list.includes(deviceId)) {
-
- this.deviceId = ''
- let data = {
- deviceId
- }
- this.connect(data)
- }
- }
- },
-
- stateChange() {
- uni.onBLEConnectionStateChange(function(res) {
-
- let connected = res.connected
- console.log(`device ${res.deviceId} state has changed, connected: ${res.connected}`,
- '监听到蓝牙设备变化')
- if (!res.connected&&!this.isUpdateData) {
- console.log(111111, '断开重连操作');
- let data = {
- deviceId: this.deviceId
- }
-
- this.deviceId = ''
- this.connect(data)
- }
- })
- },
-
- closeBLEConnection(deviceId) {
- console.log(deviceId, '断开蓝牙设备ID');
- uni.closeBLEConnection({
- deviceId,
- success(res) {
- console.log('断开蓝牙成功', res)
- },
- fail(err) {
- console.log('断开蓝牙失败', err);
- }
- })
- },
-
- connect(data) {
-
- if (data.deviceId == this.deviceId) {
- uni.showToast({
- title: '您已经连接该蓝牙',
- duration: 2500,
- icon: 'none'
- })
- return
- } else if (this.deviceId) {
- this.closeBLEConnection(this.deviceId)
- }
- wx.showLoading({
- title: '正在连接',
- mask: true
- })
- let that = this
- that.deviceId = data.deviceId
- uni.createBLEConnection({
- deviceId: that.deviceId,
- timeout: 20000,
- success(res) {
- wx.hideLoading()
- uni.showToast({
- title: '连接成功',
- duration: 2500
- })
- console.log('连接成功');
-
- uni.setStorageSync('deviceId', that.deviceId);
-
- that.stopDiscovery()
-
- setTimeout(() => {
-
- that.getLyService(that.deviceId)
- }, 1000)
- },
- fail(err) {
- wx.hideLoading()
- switch (err.errMsg) {
- default:
- that.blueError(err.errCode)
- that.deviceId = ''
- }
- console.log('连接失败')
- console.error(err)
- }
- })
- },
-
- stopDiscovery() {
- uni.stopBluetoothDevicesDiscovery({
- success(res) {
- console.log('停止成功')
- console.log(res)
- },
- fail(err) {
- console.log('停止失败')
- console.error(err)
- }
- })
- },
-
- getLyService(deviceId) {
- uni.getBLEDeviceServices({
- deviceId: deviceId,
- success: async (res) => {
- console.log('蓝牙服务', JSON.stringify(res))
- if (res.services.length < 1) {
- setTimeout(() => {
- this.getLyService(deviceId)
- }, 1000)
- return;
- }
- for (var i = 0; i < res.services.length; i++) {
-
- var characteristic = await this.getLyCharacteristic(deviceId, res.services[i].uuid)
- if (!characteristic) continue;
- this.serviceId = res.services[i].uuid
- this.characteristicId = characteristic
- console.log('ok:', this.serviceId + ',' + this.characteristicId)
- this.notifyLy();
- break;
- }
- },
- fail: (err) => {
- console.error(JSON.stringify(err))
- }
- })
- },
-
- getLyCharacteristic(deviceId, serviceId) {
- return new Promise((resolve, reject) => {
- uni.getBLEDeviceCharacteristics({
- deviceId: deviceId,
- serviceId: serviceId,
- success: (res) => {
- var result = '';
- for (var i = 0; i < res.characteristics.length; i++) {
- var properties = res.characteristics[i].properties;
- if (properties.read && properties.write && properties.notify) {
- console.log('可用特征值', JSON.stringify(res.characteristics[i].uuid))
- result = res.characteristics[i].uuid;
- break;
- }
- }
- resolve(result)
- },
- fail: (err) => {
- console.log('特征值', JSON.stringify(err))
- reject('')
- }
- })
- })
- },
- }
- }
- </script>
- <style lang="less" scoped>
- .hTitle {
- margin-left: 10px;
- }
- .bottomBox {
- margin-left: 40px;
- margin-top: 50px;
- // 蓝牙按钮
- .refreshBlueTooth {
- width: 140px;
- background-color: #1e98d7;
- color: #fff;
- margin: 0;
- }
- .refreshBlueToothNot {
- width: 140px;
- margin: 0;
- }
- .equipmentTitle {
- font-size: 18px;
- margin-top: 20px;
- }
- .blueListBox {
- margin-top: 20px;
- width: 90%;
- height: 300px;
- border: 1px solid #1e98d7;
- border-radius: 12px;
- padding: 8px;
- background-color: #eee;
- .box {
- margin-bottom: 20px;
- height: 100%;
- width: 100%;
- }
- .item:nth-child(2n) {
- background-color: #1e98d7;
- }
- }
- .alreadyBlue {
- margin-top: 16px;
- font-size: 16px;
- }
- .bottom-btn {
- width: 90%;
- margin-top: 20px;
- display: flex;
- justify-content: flex-end;
- }
- }
- </style>
|