This commit is contained in:
tx 2024-12-17 14:17:42 +08:00
parent 20ae23b88a
commit 55399cd5c1
3 changed files with 672 additions and 1184 deletions

View File

@ -241,32 +241,32 @@ export default {
rings() {
console.log('准备发送响铃命令');
if(!this.hasConnectedDevice || !this.selectedDevice) {
uni.showToast({
title: '请先连接设备',
icon: 'none'
});
return;
}
//
my.getBLEDeviceServices({
deviceId: this.selectedDevice.deviceId,
success: (res) => {
console.log('设备的所有服务:', res.services);
//
xBlufi.notifySendCustomData({
customData: "11play1@"
});
},
fail: (error) => {
console.error('获取服务列表失败:', error);
uni.showToast({
title: '获取服务失败',
icon: 'none'
});
}
});
if (!this.hasConnectedDevice || !this.selectedDevice) {
uni.showToast({
title: '请先连接设备',
icon: 'none'
});
return;
}
console.log(this.selectedDevice.deviceId,'this.selectedDevice.deviceId');
//
my.getBLEDeviceServices({
deviceId: this.selectedDevice.deviceId,
success: (res) => {
console.log('设备的所有服务:', res.services);
//
xBlufi.notifySendCustomData({
customData: "11play1@"
});
},
fail: (error) => {
console.error('获取服务列表失败:', error);
uni.showToast({
title: '获取服务失败',
icon: 'none'
});
}
});
},

View File

@ -41,14 +41,12 @@
确认添加
</view>
<view class="bot_btn">
<view class="btn1" @click="Binddevice()">
蓝牙链接
</view>
<view class="btn1" @click="ring()" v-if="carstause">
响铃寻车
</view>
<view class="btn1" @click="open()" v-if="carstause">
蓝牙开锁
</view>
@ -58,9 +56,6 @@
<view class="btn1" @click="reboot()" v-if="carstause">
设备重启
</view>
<view class="btn1" @click="Binddevice()" v-if="isbands">
接口响铃
</view>
</view>
<u-mask :show="showbind" :z-index='100' />
<view class="tip_box" v-if="showbind">
@ -95,128 +90,265 @@
</template>
<script>
const app = getApp();
var xBlufi = require("@/utils/blufi/xBlufi.js");
let _this = null;
import xBlufi from '@/utils/blufi/xBlufi.js'
export default {
data() {
return {
devicesList: [
// {name:'110000',
// mac:'11111'}
],
searching: false,
texts: '正在扫描蓝牙设备...',
btnflag: true,
tishiflag: false,
option: '',
bluthlist: [], //
// status: 'loading',
statusflag: false,
Bluetoothmac: '',
//
devices: [],
isSearching: false,
isConnecting: false,
bluetoothStatus: '未初始化',
selectedDevice: null,
hasConnectedDevice: false,
serviceId: '000000FF-0000-1000-8000-00805F9B34FB',
characteristicId: '0000FF01-0000-1000-8000-00805F9B34FB',
//
mac: '',
ishave: false,
ver_data: null,
deviceInfoss: {},
gps: {},
isband: false,
// status: false,
deviceIds: '',
name: '',
orderinfo: {},
dl: 0,
czmoney: true,
iscz: true,
bgc: {
backgroundColor: "#F7FAFE",
},
sn: '',
carstause: true,
isbands: false,
carstause: false,
show: false,
list: [],
hardwareInfo: {},
showbind: false,
bgc: {
backgroundColor: "#F7FAFE",
}
}
},
onLoad(e) {
this.mac = e.mac
this.Binddevice()
this.isbands = false
this.carstause = false
this.initBluetooth()
this.getlist()
//
if (this.mac) {
setTimeout(() => {
this.Binddevice()
}, 1000) // 1
}
//
my.onBluetoothAdapterStateChange((res) => {
console.log('蓝牙适配器状态:', res);
if (!res.available) {
this.searching = false;
this.isSearching = false;
uni.showToast({
title: '蓝牙已关闭',
icon: 'none'
});
}
});
my.onBLEConnectionStateChanged(function(res) {
console.log('蓝牙连接状态变化:', res);
if (!res.connected) {
// this.carstause = false
// //
// let obj = {
// 'type': mDeviceEvent.XBLUFI_TYPE.TYPE_CLOSE_CONNECTED,
// 'result': false,
// 'data': ''
// };
// mDeviceEvent.notifyDeviceMsgEvent(obj);
}else{
// this.carstause = true
}
});
},
onShow() {
this.getlist()
},
onUnload: function () {
xBlufi.listenDeviceMsgEvent(false, this.funListenDeviceMsgEvent);
xBlufi.notifyStartDiscoverBle({
'isStart': false
my.onBLEConnectionStateChanged((res) => {
console.log('蓝牙连接状态变化:', res);
if (!res.connected) {
this.carstause = false;
this.hasConnectedDevice = false;
} else {
this.carstause = true;
this.hasConnectedDevice = true;
}
});
},
onUnload() {
this.cleanupBluetooth()
},
onHide() {
xBlufi.listenDeviceMsgEvent(false, this.funListenDeviceMsgEvent);
xBlufi.notifyStartDiscoverBle({
'isStart': false
});
},
onBeforeUnmount() {
xBlufi.listenDeviceMsgEvent(false, this.funListenDeviceMsgEvent);
xBlufi.notifyStartDiscoverBle({
'isStart': false
});
},
watch: {
this.cleanupBluetooth()
},
methods: {
confirm(e) {
// console.log(e);
uni.setStorageSync('hardwareVersionId', e[0].value);
this.hardwareVersionId = e[0].value
const hardwareVersionId = this.hardwareVersionId
initBluetooth() {
xBlufi.initXBlufi(xBlufi.XMQTT_SYSTEM.Alis);
if (hardwareVersionId) {
const matchedVersion = this.Versionlist.find(version => version.id ===
hardwareVersionId);
if (matchedVersion) {
this.hardwareInfo = matchedVersion;
xBlufi.listenDeviceMsgEvent(true, (res) => {
console.log('设备消息:', res);
switch (res.type) {
case xBlufi.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS:
if (res.result && res.data) {
console.log("搜索到设备:", res.data);
const bbleDevices = res.data.filter(device => {
const name = device.name || device.deviceName || '';
return name.startsWith('BBLE');
});
this.devices = bbleDevices;
}
break;
case xBlufi.XBLUFI_TYPE.TYPE_STATUS_CONNECTED:
if (res.result) {
this.carstause = true;
this.hasConnectedDevice = true;
uni.showToast({
title: '连接成功',
icon: 'success',
duration: 1000
});
} else {
this.carstause = false;
this.hasConnectedDevice = false;
uni.showToast({
title: '连接断开',
icon: 'none',
duration: 1000
});
}
break;
case xBlufi.XBLUFI_TYPE.TYPE_SEND_CUSTOM_DATA_RESULT:
console.log('发送自定义数据结果:', res);
if (res.result) {
uni.showToast({
title: '命令发送成功',
icon: 'success',
duration: 1000
});
} else {
uni.showToast({
title: '命令发送失败',
icon: 'none',
duration: 1000
});
}
break;
}
});
},
//
Binddevice() {
uni.showLoading({
title: '连接中..'
});
this.devices = [];
this.isSearching = true;
xBlufi.notifyStartDiscoverBle({
'isStart': true
});
setTimeout(() => {
xBlufi.notifyStartDiscoverBle({
'isStart': false
});
setTimeout(() => {
uni.hideLoading();
if (this.devices.length == 0) {
uni.showToast({
title: '暂无发现对应设备,请靠近设备',
icon: 'none'
});
} else {
const matchedDevice = this.devices.find(device => {
const macFromName = device.name.substring(device.name.length - 12);
return macFromName === this.mac;
});
if (matchedDevice) {
console.log('找到匹配设备:', matchedDevice);
this.selectedDevice = matchedDevice;
//
xBlufi.notifyConnectBle({
connect: true,
deviceId: matchedDevice.deviceId
});
//
xBlufi.notifyInitBleEsp32({
deviceId: matchedDevice.deviceId
});
} else {
console.log('未找到匹配设备');
uni.showToast({
title: '未找到对应设备',
icon: 'none'
});
}
}
}, 200);
}, 2000);
},
//
ring() {
if (!this.hasConnectedDevice || !this.selectedDevice) {
uni.showToast({
title: '请先连接设备',
icon: 'none'
});
return;
}
my.getBLEDeviceServices({
deviceId: this.selectedDevice.deviceId,
success: (res) => {
console.log('设备的所有服务:', res.services);
xBlufi.notifySendCustomData({
customData: "11play1@"
});
},
fail: (error) => {
console.error('获取服务列表失败:', error);
uni.showToast({
title: '获取服务失败',
icon: 'none'
});
}
});
},
//
open() {
if (!this.hasConnectedDevice || !this.selectedDevice) {
uni.showToast({
title: '请先连接设备',
icon: 'none'
});
return;
}
xBlufi.notifySendCustomData({
customData: "11open"
});
},
//
close() {
if (!this.hasConnectedDevice || !this.selectedDevice) {
uni.showToast({
title: '请先连接设备',
icon: 'none'
});
return;
}
xBlufi.notifySendCustomData({
customData: "11close"
});
},
//
reboot() {
if (!this.hasConnectedDevice || !this.selectedDevice) {
uni.showToast({
title: '请先连接设备',
icon: 'none'
});
return;
}
xBlufi.notifySendCustomData({
customData: "11reboot"
});
},
//
getlist() {
this.$u.get('/app/hardwareVersion/list').then((res) => {
if (res.code === 200) {
@ -225,8 +357,7 @@ export default {
if (hardwareVersionId) {
this.hardwareVersionId = hardwareVersionId
const matchedVersion = this.Versionlist.find(version => version.id ===
hardwareVersionId);
const matchedVersion = this.Versionlist.find(version => version.id === hardwareVersionId);
if (matchedVersion) {
this.hardwareInfo = matchedVersion;
}
@ -245,21 +376,59 @@ export default {
}
})
},
send() {
this.$u.post('/app/device/ring?sn=' + this.sn).then((res) => {
if (res.code === 200) {
} else {
uni.showToast({
title: res.msg,
icon: 'none',
duration: 2000
});
//
confirm(e) {
uni.setStorageSync('hardwareVersionId', e[0].value);
this.hardwareVersionId = e[0].value
if (this.hardwareVersionId) {
const matchedVersion = this.Versionlist.find(version => version.id === this.hardwareVersionId);
if (matchedVersion) {
this.hardwareInfo = matchedVersion;
}
})
}
},
changeBind() {
this.$u.post(`/appVerify/updateSn?sn=` + this.sn + '&mac=' + this.mac + '&hardwareVersionId=' + this.hardwareVersionId).then((res) => {
//
bind() {
if (!this.sn || this.sn.length !== 7 || !/^\d+$/.test(this.sn)) {
uni.showToast({
title: '请输入正确的SN码',
icon: 'none'
});
return;
}
this.$u.post(`/appVerify/band?sn=${this.sn}&mac=${this.mac}&hardwareVersionId=${this.hardwareVersionId}`).then((res) => {
if (res.code === 200) {
uni.showToast({
title: '绑定成功',
icon: 'none',
duration: 2000
});
setTimeout(() => {
uni.navigateTo({
url: '/pages_admin/controlDevice?sn=' + this.sn
})
}, 2000)
} else {
if (res.msg === '该MAC号已经存在') {
this.showbind = true;
} else {
uni.showToast({
title: res.msg,
icon: 'none',
duration: 2000
});
}
}
})
},
//
changeBind() {
this.$u.post(`/appVerify/updateSn?sn=${this.sn}&mac=${this.mac}&hardwareVersionId=${this.hardwareVersionId}`).then((res) => {
if (res.code === 200) {
uni.showToast({
title: '绑定成功',
@ -267,9 +436,6 @@ export default {
duration: 2000
});
setTimeout(() => {
// uni.navigateBack({
// delta: 1 // delta1
// });
uni.navigateTo({
url: '/pages_admin/controlDevice?sn=' + this.sn
})
@ -283,54 +449,13 @@ export default {
}
})
},
backpage() {
uni.navigateBack({
delta: 1 // delta1
});
},
bind() {
if (this.sn != '' && this.sn.length === 7 && /^\d+$/.test(this.sn)) {
this.$u.post(`/appVerify/band?sn=` + this.sn + '&mac=' + this.mac + '&hardwareVersionId=' + this.hardwareVersionId).then((res) => {
if (res.code == 200) {
uni.showToast({
title: '绑定成功',
icon: 'none',
duration: 2000
});
setTimeout(() => {
uni.navigateTo({
url: '/pages_admin/controlDevice?sn=' + this.sn
})
// uni.navigateBack({
// delta: 1 // delta1
// });
}, 2000)
} else {
if (res.msg == '该MAC号已经存在') {
this.showbind = true
} else {
uni.showToast({
title: res.msg,
icon: 'none',
duration: 2000
});
}
}
})
}
},
//
qrcode() {
uni.scanCode({
onlyFromCamera: true,
scanType: ['qrCode'],
success: res => {
let sn = null;
let queryParams = res.result.split('?')[1];
if (queryParams) {
@ -343,12 +468,13 @@ export default {
});
}
this.sn = sn
console.log(res.result);
if (this.sn != '') {
this.sn = sn;
if (!this.sn) {
uni.showToast({
title: '无效的二维码',
icon: 'none'
});
}
},
fail: err => {
console.error('扫描失败:', err);
@ -360,430 +486,33 @@ export default {
});
},
Binddevice() {
uni.showLoading({
title: '连接中..'
})
xBlufi.initXBlufi(1);
console.log("xBlufi", xBlufi.XMQTT_SYSTEM);
xBlufi.listenDeviceMsgEvent(true, this.funListenDeviceMsgEvent);
xBlufi.notifyStartDiscoverBle({
'isStart': true
});
//
setTimeout(() => {
xBlufi.notifyStartDiscoverBle({
'isStart': false
});
setTimeout(() => {
uni.hideLoading()
if (this.devicesList.length == 0) {
uni.showToast({
title: '暂无发现对应设备,请靠近设备',
icon: 'none'
});
} else {
let uniqueDevicesList = Array.from(new Set(this.devicesList));
// this.devicesList
this.devicesList = uniqueDevicesList;
// console.log(this.devicesList,'this.devicesListthis.devicesList');
this.devicesList.forEach(device => {
// MAC MAC 6
let macFromName = device.name.substring(device.name.length - 12);
console.log(macFromName, 'macFromNamemacFromName');
// this.mac
if (macFromName == this.mac) {
// this.ishave true
console.log(device);
this.deviceInfoss = device
// this.ishave = true;
this.createBLEConnection(device)
console.log('对比正确1111111111');
} else {
console.log('对比错误');
}
});
}
}, 200)
//
// this.status = true
}, 2000)
},
reboot() {
let vm = this; // this vm
uni.getNetworkType({
success(res) {
if (res.networkType !== 'none') {
uni.getConnectedBluetoothDevices({
success(res) {
console.log('已连接的蓝牙设备信息:', res);
// vm.dl = (vm.orderinfo.deviceAmount / vm.orderinfo.unitPrice).toFixed(2); // 使 vm 访 Vue
xBlufi.notifySendCustomData({
customData: "11reboot"
});
// uni.hideLoading()
// vm.remakr()
},
fail(err) {
uni.hideLoading()
console.error('获取已连接蓝牙设备信息失败:', err);
}
});
} else {
console.log('手机未连接网络');
}
}
//
backpage() {
uni.navigateBack({
delta: 1
});
},
open() {
let vm = this; // this vm
uni.getNetworkType({
success(res) {
if (res.networkType !== 'none') {
uni.getConnectedBluetoothDevices({
success(res) {
console.log('已连接的蓝牙设备信息:', res);
// vm.dl = (vm.orderinfo.deviceAmount / vm.orderinfo.unitPrice).toFixed(2); // 使 vm 访 Vue
xBlufi.notifySendCustomData({
customData: "11open"
});
// uni.hideLoading()
// vm.remakr()
},
fail(err) {
uni.hideLoading()
console.error('获取已连接蓝牙设备信息失败:', err);
}
});
} else {
console.log('手机未连接网络');
}
}
});
},
close() {
let vm = this; // this vm
uni.getNetworkType({
success(res) {
if (res.networkType !== 'none') {
uni.getConnectedBluetoothDevices({
success(res) {
console.log('已连接的蓝牙设备信息:', res);
// vm.dl = (vm.orderinfo.deviceAmount / vm.orderinfo.unitPrice).toFixed(2); // 使 vm 访 Vue
xBlufi.notifySendCustomData({
customData: "11close"
});
// uni.hideLoading()
// vm.remakr()
},
fail(err) {
uni.hideLoading()
console.error('获取已连接蓝牙设备信息失败:', err);
}
});
} else {
console.log('手机未连接网络');
}
}
});
},
ring() {
let vm = this; // this vm
uni.getNetworkType({
success(res) {
if (res.networkType !== 'none') {
uni.getConnectedBluetoothDevices({
success(res) {
console.log('已连接的蓝牙设备信息:', res);
// vm.dl = (vm.orderinfo.deviceAmount / vm.orderinfo.unitPrice).toFixed(2); // 使 vm 访 Vue
xBlufi.notifySendCustomData({
customData: "11play1@"
});
// uni.hideLoading()
// vm.remakr()
},
fail(err) {
uni.hideLoading()
console.error('获取已连接蓝牙设备信息失败:', err);
}
});
} else {
console.log('手机未连接网络');
}
}
});
},
btnyc() {
this.titleflag = false
},
//
funListenDeviceMsgEvent: function (options) {
switch (options.type) {
case xBlufi.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS:
if (options.result) {
let devicesarr = options.data
// this.devicesList = options.data
devicesarr.forEach(device => {
//
// this.$u.get(`/app/device/${mac}/isBind`, data).then((res) => {
// if (res.data == false) {
this.devicesList.push(device);
let uniqueDevicesList = Array.from(new Set(this.devicesList));
// this.devicesList
this.devicesList = uniqueDevicesList;
});
}
break;
case xBlufi.XBLUFI_TYPE.TYPE_CONNECTED:
console.log("连接回调:" + JSON.stringify(options));
if (options.result) {
uni.hideLoading();
uni.showToast({
title: '连接成功',
icon: 'none'
}); {
xBlufi.notifyInitBleEsp32({
deviceId: options.data.deviceId
});
xBlufi.listenDeviceMsgEvent(true, this.funListenDeviceMsgEvents);
this.deviceIds = options.data.deviceId
this.name = options.data.name
//
// let params = {
// mac: this.Bluetoothmac,
// userId: this.$store.state.user.userId
// }
let systemInfo = uni.getSystemInfoSync();
if (systemInfo.platform === 'android') {
// Android
} else if (systemInfo.platform === 'ios') {
// iOS
// uni.navigateTo({
// url: '/pages/wifilist/index?deviceId=' + options
// .data.deviceId + '&name=' + options.data.name
// })
}
}
}
break;
case xBlufi.XBLUFI_TYPE.TYPE_RECIEVE_CUSTON_DATA:
// this.ver_data = this.parseCustomData(options.data)
if (options.data) {
this.carstause = true
}
// console.log("1", this.ver_data);
break;
case xBlufi.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS_STOP:
if (options.result) {
let uniqueDevicesList = Array.from(new Set(this.devicesList));
// "CTPOW"
let filteredDevices = uniqueDevicesList.filter(device => device.name.substring(0, 4) ===
"BBLE");
// this.devicesList
this.devicesList = filteredDevices;
// console.log('ok',this.devicesList);
} else {
//
// console.log('');
}
this.searching = false
// _this.setData({
// searching: false
// });
break;
}
},
createBLEConnection(e) {
this.searching = false;
//
cleanupBluetooth() {
xBlufi.listenDeviceMsgEvent(false);
xBlufi.notifyStartDiscoverBle({
'isStart': false
});
// uni.showLoading({
// title: '...'
// });
const deviceId = e.deviceId;
this.Bluetoothmac = e.localName.substring(5);
xBlufi.notifyConnectBle({
connect: true,
deviceId: deviceId,
name: e.name || ''
});
},
//4
// createBLEConnection(e) {
// console.log('');
// xBlufi.notifyStartDiscoverBle({
// 'isStart': false
// });
// console.log(e, '')
// const deviceId = e.deviceId
// this.Bluetoothmac = e.localName.substring(5) // mac
// console.log(this.Bluetoothmac, '11111');
// let name = e.name;
// console.log('deviceId:' + e.deviceId);
// xBlufi.notifyConnectBle({
// isStart: true,
// deviceId: e.deviceId,
// name
// });
// // for (var i = 0; i < this.devicesList.length; i++) {
// // if (e.deviceId === this.devicesList[i].deviceId) {
// // uni.showLoading({
// // title: '...'
// // });
// // }
// // }
// },
//
Search() {
if (this.status) {
xBlufi.notifyStartDiscoverBle({
'isStart': true
if (this.hasConnectedDevice && this.selectedDevice) {
xBlufi.notifyConnectBle({
connect: false,
deviceId: this.selectedDevice.deviceId
});
//
this.bluthlist = []
this.devicesList = []
//
// this.startBluetoothDevicesDiscovery()
this.statusflag = true
this.status = false
this.texts = '正在扫描蓝牙设备...'
setTimeout(() => {
this.statusflag = false
this.status = true
if (this.searching) {
xBlufi.notifyStartDiscoverBle({
'isStart': false
});
//
if (this.devicesList.length == 0) {
uni.showToast({
title: '暂无发现对应设备,请靠近设备',
icon: 'none'
});
} else {
this.texts = '扫描到以下设备,请点击连接!'
}
} else {
xBlufi.notifyStartDiscoverBle({
'isStart': true
});
}
}, 2000)
}
},
funListenDeviceMsgEvents: function (options) {
let that = this;
switch (options.type) {
case xBlufi.XBLUFI_TYPE.TYPE_STATUS_CONNECTED: {
console.log('状态', options.result)
if (options.result == false) {
this.carstause = false
uni.showToast({
title: '设备断开链接,请重新点击蓝牙链接',
icon: 'none'
});
// uni.showModal({
// title: '',
// content: '',
// showCancel: false,
// success: function(res) {
// // uni.navigateBack({
// // url: '../search/search'
// // });
// }
// });
// this.statusflag = false
uni.hideLoading();
}
}
break;
case xBlufi.XBLUFI_TYPE.TYPE_RECIEVE_MY_DATA:
this.loadPercent = options.data;
this.loadText = '文件读取中'
console.log("文件读取中", options.data);
break;
case xBlufi.XBLUFI_TYPE.TYPE_RECIEVE_CUSTON_DATA:
// this.isband = true
// this.ver_data = this.parseCustomData(options.data)
console.log("1收到设备发来的自定义数据结果", options.data);
if (options.data) {
this.carstause = true
}
break;
case xBlufi.XBLUFI_TYPE.TYPE_INIT_ESP32_RESULT:
uni.hideLoading();
if (options.result) {
console.log('初始化成功');
} else {
console.log('初始化失败');
}
break;
}
},
//
btnhd() {
this.tishiflag = false
},
}
}
}
</script>
<style lang="scss">
page {
overflow-x: hidden;

View File

@ -73,619 +73,378 @@
</template>
<script>
const app = getApp();
var xBlufi = require("@/utils/blufi/xBlufi.js");
let _this = null;
export default {
data() {
return {
titleflag: false, //
bgc: {
backgroundColor: "#F7FAFE",
},
devicesList: [
// {name:'110000',
// mac:'11111'}
],
devicesLists: [],
searching: false,
texts: '正在扫描蓝牙设备...',
btnflag: true,
tishiflag: false,
option: '',
bluthlist: [], //
status: 'loading',
statusflag: false,
Bluetoothmac: '',
gps: {},
mac: '',
status: false,
showConfirmModal: false, //
deviceinfo: null,
sn: ''
}
const app = getApp();
var xBlufi = require("@/utils/blufi/xBlufi.js");
export default {
data() {
return {
titleflag: false,
bgc: {
backgroundColor: "#F7FAFE",
},
devicesList: [], //
devicesLists: [], //
searching: false,
texts: '正在扫描蓝牙设备...',
btnflag: true,
tishiflag: false,
option: '',
bluthlist: [],
statusflag: false,
Bluetoothmac: '',
gps: {},
mac: '',
status: false,
showConfirmModal: false,
deviceinfo: null,
sn: '',
hasConnectedDevice: false,
selectedDevice: null,
serviceId: '000000FF-0000-1000-8000-00805F9B34FB',
characteristicId: '0000FF01-0000-1000-8000-00805F9B34FB'
}
},
onLoad(e) {
if (e.sn) {
this.sn = e.sn;
}
},
onShow() {
this.initBluetooth();
},
onUnload() {
this.cleanupBluetooth();
},
onHide() {
this.cleanupBluetooth();
},
methods: {
//
replay() {
uni.reLaunch({
url: '/pages_admin/worke/bind_sn'
})
},
onLoad(e) {
if (e.sn) {
this.sn = e.sn
}
backPage() {
uni.redirectTo({
url: '/pages_admin/admin_worke'
})
},
onShow: function() {
this.bluthlist = [];
this.devicesList = [];
this.devicesLists = [];
//
this.$forceUpdate();
//
xBlufi.initXBlufi(1);
xBlufi.listenDeviceMsgEvent(true, this.funListenDeviceMsgEvent);
xBlufi.notifyStartDiscoverBle({ 'isStart': true });
setTimeout(() => {
xBlufi.notifyStartDiscoverBle({ 'isStart': false });
if (this.devicesList.length == 0) {
this.tishiflag = true;
this.texts = '扫描完毕,暂无发现电动车设备';
} else {
this.texts = '扫描到以下设备,请点击连接!';
}
this.status = true;
//
this.$forceUpdate();
}, 2000);
toControl() {
uni.redirectTo({
url: '/pages_admin/controlDevice'
})
},
onUnload: function() {
//
initBluetooth() {
//
this.bluthlist = [];
this.devicesList = [];
this.devicesLists = [];
//
xBlufi.initXBlufi(xBlufi.XMQTT_SYSTEM.Alis);
xBlufi.listenDeviceMsgEvent(true, this.funListenDeviceMsgEvent);
//
this.startSearch();
},
//
cleanupBluetooth() {
xBlufi.listenDeviceMsgEvent(false, this.funListenDeviceMsgEvent);
xBlufi.notifyStartDiscoverBle({
'isStart': false
});
xBlufi.notifyStartDiscoverBle({ 'isStart': false });
},
onHide() {
xBlufi.listenDeviceMsgEvent(false, this.funListenDeviceMsgEvent);
xBlufi.notifyStartDiscoverBle({
'isStart': false
});
},
onBeforeUnmount() {
xBlufi.listenDeviceMsgEvent(false, this.funListenDeviceMsgEvent);
xBlufi.notifyStartDiscoverBle({
'isStart': false
});
},
mounted() {
// this.videoContext = uni.createVideoContext('myVideo', this)
},
methods: {
replay(){
uni.reLaunch({
url:'/pages_admin/worke/bind_sn'
})
},
backPage(){
uni.redirectTo({
url:'/pages_admin/admin_worke'
})
},
toControl(){
uni.redirectTo({
url:'/pages_admin/controlDevice'
})
},
fetchDevicesBoundStatus() {
// MAC Set
let uniqueDevices = Array.from(new Set(this.devicesList.map(item => item.localName.substring(5))));
//
startSearch() {
this.searching = true;
this.texts = '正在扫描蓝牙设备...';
xBlufi.notifyStartDiscoverBle({ 'isStart': true });
// devicesList
this.devicesList = uniqueDevices.map(mac => {
return this.devicesList.find(item => item.localName.substring(5) === mac);
});
//
const macs = uniqueDevices.join(',');
//
this.$u.get(`app/getDeviceInfoByMacList?macList=${macs}`).then((res) => {
const resultList = res.data; //
// devicesList mac
this.devicesList.forEach(device => {
const mac = device.localName.substring(5);
// MAC
const matchingResult = resultList.find(result => result.mac === mac);
// MAC sn isBand
if (matchingResult) {
device.sn = matchingResult.sn;
device.isBand = matchingResult.isBand;
}
});
// devicesList isBand false
this.devicesList.sort((a, b) => {
return (a.isBand === false ? -1 : 1) - (b.isBand === false ? -1 : 1);
});
this.$forceUpdate(); //
console.log(this.devicesList, 'Updated devicesList');
}).catch((error) => {
console.error('批量获取设备录入状态失败', error);
});
},
choose(e) {
console.log(e);
let Bluetoothmac = e.name.substring(5)
uni.redirectTo({
url: '/pages_admin/worke/bind_mac?mac=' + Bluetoothmac
})
},
send() {
this.$u.post('/app/device/ring?sn=' + this.sn).then((res) => {
if (res.code === 200) {
} else {
uni.showToast({
title: res.msg,
icon: 'none',
duration: 2000
});
}
})
},
openConfirmModal(e) {
this.deviceinfo = e
this.showConfirmModal = true;
},
closeConfirmModal() {
this.showConfirmModal = false;
},
confirmBind() {
this.closeConfirmModal();
this.createBLEConnection(this.deviceinfo)
},
btnyc() {
this.titleflag = false
},
sing() {
let vm = this; // this vm
uni.getNetworkType({
success(res) {
if (res.networkType !== 'none') {
uni.getConnectedBluetoothDevices({
success(res) {
console.log('已连接的蓝牙设备信息:', res);
// vm.dl = (vm.orderinfo.deviceAmount / vm.orderinfo.unitPrice).toFixed(2); // 使 vm 访 Vue
xBlufi.notifySendCustomData({
customData: "11play1@"
});
uni.hideLoading()
vm.remakr()
},
fail(err) {
uni.hideLoading()
console.error('获取已连接蓝牙设备信息失败:', err);
}
});
} else {
console.log('手机未连接网络');
}
}
});
},
remakr() {
let vm = this; // this vm
uni.getNetworkType({
success(res) {
if (res.networkType !== 'none') {
uni.getConnectedBluetoothDevices({
success(res) {
console.log('已连接的蓝牙设备信息:', res);
// vm.dl = (vm.orderinfo.deviceAmount / vm.orderinfo.unitPrice).toFixed(2); // 使 vm 访 Vue
xBlufi.notifySendCustomData({
customData: "11reboot"
});
uni.navigateBack({
delta: 1 // delta1
});
},
fail(err) {
console.error('获取已连接蓝牙设备信息失败:', err);
}
});
} else {
console.log('手机未连接网络');
}
}
});
},
funListenDeviceMsgEvent: function(options) {
switch (options.type) {
case xBlufi.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS:
if (options.result) {
let devicesarr = options.data
// this.devicesList = options.data
// console.log(devicesarr, 'devicesarrdevicesarr');
devicesarr.forEach(device => {
const mac = device.name.substring(6);
if (device.name.indexOf("BBLE") != -1) {
// this.$u.get(`/app/device/${mac}/isBind`).then((res) => {
// if (res.data == false) {
this.devicesLists.push(device);
let uniqueDevicesList = Array.from(new Set(this.devicesLists));
// this.devicesList
this.devicesLists = uniqueDevicesList;
// }
// })
}
// getisband(mac).then(res => {
// console.log(res);
// if (res.data == true) {
// console.log(`MAC ${mac} `);
// } else {
// this.devicesList.push(device)
// }
// }).catch(error => {
// console.error(` MAC ${mac} :`, error);
// });
});
}
break;
case xBlufi.XBLUFI_TYPE.TYPE_CONNECTED:
console.log("连接回调:" + JSON.stringify(options));
if (options.result) {
uni.hideLoading();
uni.showToast({
title: '连接成功',
icon: 'none'
}); {
console.log("连接回调options.data.deviceId" + options.data.deviceId,
"连接回调options.data.name" + options.data.name);
//
// let params = {
// mac: this.Bluetoothmac,
// userId: this.$store.state.user.userId
// }
xBlufi.notifyInitBleEsp32({
deviceId: options.data.deviceId
});
// xBlufi.listenDeviceMsgEvent(true, this.funListenDeviceMsgEvents);
// setTimeout(() => {
// this.sing()
// }, 3000)
let systemInfo = uni.getSystemInfoSync();
if (systemInfo.platform === 'android') {
// Android
// uni.navigateTo({
// url: '/pages/wifilist/index?deviceId=' + options
// .data.deviceId + '&name=' + options.data.name
// })
} else if (systemInfo.platform === 'ios') {
// iOS
// uni.navigateTo({
// url: '/pages/wifilist/index?deviceId=' + options
// .data.deviceId + '&name=' + options.data.name
// })
}
}
}
break;
case xBlufi.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS_START:
if (!options.result) {
console.log("蓝牙未开启", options);
uni.showToast({
title: '蓝牙未开启,如有疑问请查看查看常见问题',
icon: 'none',
duration: 3000
});
if (this.devicesList.length == 0) {
this.tishiflag = true
this.texts = '扫描完毕,暂无发现电动车设备'
} else {
this.texts = '扫描到以下设备,请点击连接!'
}
} else {
this.searching = true
//
// _this.setData({
// searching: true
// });
}
break;
case xBlufi.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS_STOP:
if (options.result) {
let uniqueDevicesList = Array.from(new Set(this.devicesLists));
// this.devicesList
this.devicesLists = uniqueDevicesList;
let list = []
uniqueDevicesList.forEach(device => {
// MAC MAC 6
let macFromName = device.name.substring(device.name.length - 12);
// console.log(macFromName);
// this.mac
list.push(device)
// this.$u.get(`/app/device/${macFromName}/isBind`).then((res) => {
// if (res.data == false) {
// list.push(device)
// } else {
// }
// })
});
setTimeout(() => {
this.devicesList = list
let uniqueDevicesList = Array.from(new Set(this.devicesList));
// this.devicesList
this.devicesList = uniqueDevicesList;
this.fetchDevicesBoundStatus();
}, 200)
console.log('蓝牙停止搜索ok');
} else {
//
console.log('蓝牙停止搜索失败');
}
this.searching = false
// _this.setData({
// searching: false
// });
break;
setTimeout(() => {
xBlufi.notifyStartDiscoverBle({ 'isStart': false });
if (this.devicesList.length == 0) {
this.tishiflag = true;
this.texts = '扫描完毕,暂无发现电动车设备';
} else {
this.texts = '扫描到以下设备,请点击连接!';
}
},
funListenDeviceMsgEvents: function(options) {
let that = this;
switch (options.type) {
case xBlufi.XBLUFI_TYPE.TYPE_STATUS_CONNECTED: {
// console.log('', options.result)
if (options.result == false) {
// uni.showModal({
// title: '',
// content: '',
// showCancel: false,
// success: function(res) {
// // uni.navigateBack({
// // url: '../search/search'
// // });
// }
// });
this.statusflag = false
uni.hideLoading();
}
this.searching = false;
}, 5000);
},
//
choose(device) {
console.log('选择设备:', device);
let Bluetoothmac = device.name.substring(5);
uni.redirectTo({
url: '/pages_admin/worke/bind_mac?mac=' + Bluetoothmac
});
},
//
funListenDeviceMsgEvent(options) {
switch (options.type) {
case xBlufi.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS:
if (options.result && options.data) {
let devicesarr = options.data;
devicesarr.forEach(device => {
// BBLE
if (device.name && device.name.startsWith('BBLE')) {
//
const existingDevice = this.devicesLists.find(d =>
d.deviceId === device.deviceId
);
if (!existingDevice) {
this.devicesLists.push(device);
//
this.devicesList = [...this.devicesLists];
//
this.fetchDevicesBoundStatus();
}
}
});
}
break;
case xBlufi.XBLUFI_TYPE.TYPE_STATUS_CONNECTED:
this.handleConnectionStatus(options);
break;
case xBlufi.XBLUFI_TYPE.TYPE_RECIEVE_CUSTON_DATA:
console.log("1收到设备发来的自定义数据结果", options.data);
break;
case xBlufi.XBLUFI_TYPE.TYPE_INIT_ESP32_RESULT:
uni.hideLoading();
if (options.result) {
console.log('初始化成功');
} else {
console.log('初始化失败');
uni.showModal({
title: '温馨提示',
content: `设备初始化失败`,
showCancel: false,
//
success: function(res) {
// uni.redirectTo({
// url: '../search/search'
// });
}
});
}
break;
}
},
//4
createBLEConnection(e) {
this.mac = e.localName.substring(5)
let that = this
that.$u.post(`/appVerify/band?sn=` + that.sn + '&mac=' + that.mac).then((res) => {
uni.showLoading({
title: '绑定中'
})
if (res.code == 200) {
case xBlufi.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS_START:
if (!options.result) {
console.log("蓝牙未开启", options);
uni.showToast({
title: '绑定成功',
title: '蓝牙未开启,如有疑问请查看常见问题',
icon: 'none',
duration: 2000
duration: 3000
});
xBlufi.notifyStartDiscoverBle({
'isStart': false
});
const deviceId = that.deviceinfo.deviceId
that.Bluetoothmac = that.deviceinfo.localName.substring(5) // mac
let name = that.deviceinfo.name;
console.log(that.deviceinfo.deviceId, 'that.deviceinfo.deviceId');
xBlufi.notifyConnectBle({
isStart: true,
deviceId: that.deviceinfo.deviceId,
name
});
} else {
uni.showToast({
title: res.msg,
icon: 'none',
duration: 2000
});
setTimeout(() => {
uni.navigateBack({
delta: 1 // delta1
});
}, 2000)
this.searching = true;
}
})
break;
// uni.getLocation({
// type: 'wgs84',
// success: function(lb) {
// console.log('', lb);
// console.log('' + lb.longitude);
// console.log('' + lb.latitude);
// that.gps.lat = lb.latitude;
// that.gps.lon = lb.longitude;
// that.$u.put(`/app/device/bind/${that.mac}`, that.gps).then((res) => {
// if (res.code == 200) {
// uni.showToast({
// title: '',
// icon: 'none',
// duration: 2000
// });
case xBlufi.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS_STOP:
this.searching = false;
break;
// uni.removeStorageSync('mac');
// // setTimeout(()=>{
// // uni.switchTab({
// // url:'/pages/index/index'
// // })
// // },)
// } else {
// uni.showToast({
// title:res.msg,
// icon: 'none',
// duration: 2000
// });
// // setTimeout(()=>{
// // uni.switchTab({
// // url:'/pages/index/index'
// // })
// // },)
// }
// })
// },
// fail: function(error) {
// console.error('', error);
// that.gps.lat = 0;
// that.gps.lon = 0;
// that.$u.put(`/app/device/bind/${that.mac}`, that.gps).then((res) => {
// if (res.code == 200) {
// uni.showToast({
// title: '',
// icon: 'none',
// duration: 2000
// });
// uni.removeStorageSync('mac');
// xBlufi.notifyStartDiscoverBle({
// 'isStart': false
// });
// const deviceId = that.deviceinfo.deviceId
// that.Bluetoothmac = that.deviceinfo.localName.substring(6) // mac
// let name = that.deviceinfo.name;
// xBlufi.notifyConnectBle({
// isStart: true,
// deviceId: that.deviceinfo.deviceId,
// name
// });
// // setTimeout(()=>{
// // uni.switchTab({
// // url:'/pages/index/index'
// // })
// // },)
// } else {
// uni.showToast({
// title:res.msg,
// icon: 'none',
// duration: 2000
// });
// // setTimeout(()=>{
// // uni.switchTab({
// // url:'/pages/index/index'
// // })
// // },)
// }
// })
// //
// }
// })
},
//
Search() {
if (this.status) {
xBlufi.notifyStartDiscoverBle({
'isStart': true
});
//
this.bluthlist = []
this.devicesList = []
this.devicesLists = []
//
// this.startBluetoothDevicesDiscovery()
this.statusflag = true
this.texts = '正在扫描蓝牙设备...'
setTimeout(() => {
this.statusflag = false
if (this.searching) {
//
if (this.devicesList.length == 0) {
this.tishiflag = true
this.texts = '扫描完毕,暂无发现电动车设备'
} else {
this.texts = '扫描到以下设备,请点击连接!'
}
xBlufi.notifyStartDiscoverBle({
'isStart': false
});
} else {
xBlufi.notifyStartDiscoverBle({
'isStart': true
});
}
}, 2000)
}
},
//
btnhd() {
this.tishiflag = false
case xBlufi.XBLUFI_TYPE.TYPE_INIT_ESP32_RESULT:
if (options.result) {
console.log('设备初始化成功');
this.hasConnectedDevice = true;
} else {
console.error('设备初始化失败');
uni.showModal({
title: '温馨提示',
content: '设备初始化失败',
showCancel: false
});
}
break;
}
},
//
handleConnectionStatus(res) {
if (res.result) {
uni.showToast({
title: '连接成功',
icon: 'success'
});
//
xBlufi.notifyInitBleEsp32({
deviceId: res.data.deviceId
});
//
const index = this.devicesList.findIndex(d => d.deviceId === res.data.deviceId);
if (index !== -1) {
this.$set(this.devicesList[index], 'connected', true);
this.hasConnectedDevice = true;
this.selectedDevice = this.devicesList[index];
}
} else {
uni.showToast({
title: '连接断开',
icon: 'none'
});
this.hasConnectedDevice = false;
this.selectedDevice = null;
}
},
//
rings() {
if (!this.hasConnectedDevice || !this.selectedDevice) {
uni.showToast({
title: '请先连接设备',
icon: 'none'
});
return;
}
console.log('准备发送响铃命令');
my.getBLEDeviceServices({
deviceId: this.selectedDevice.deviceId,
success: (res) => {
console.log('设备的所有服务:', res.services);
xBlufi.notifySendCustomData({
customData: "11play1@"
});
},
fail: (error) => {
console.error('获取服务列表失败:', error);
uni.showToast({
title: '获取服务失败',
icon: 'none'
});
}
});
},
//
Search() {
if (this.status) {
//
this.bluthlist = [];
this.devicesList = [];
this.devicesLists = [];
this.statusflag = true;
this.texts = '正在扫描蓝牙设备...';
//
xBlufi.notifyStartDiscoverBle({ 'isStart': true });
setTimeout(() => {
this.statusflag = false;
if (this.searching) {
if (this.devicesList.length == 0) {
this.tishiflag = true;
this.texts = '扫描完毕,暂无发现电动车设备';
} else {
this.texts = '扫描到以下设备,请点击连接!';
}
xBlufi.notifyStartDiscoverBle({ 'isStart': false });
}
}, 2000);
}
},
//
fetchDevicesBoundStatus() {
// MAC
let uniqueDevices = Array.from(new Set(this.devicesList.map(item => item.name.substring(5))));
// devicesList
this.devicesList = uniqueDevices.map(mac => {
return this.devicesList.find(item => item.name.substring(5) === mac);
});
// MAC
const macs = uniqueDevices.join(',');
//
this.$u.get(`app/getDeviceInfoByMacList?macList=${macs}`).then((res) => {
const resultList = res.data;
//
this.devicesList.forEach(device => {
const mac = device.name.substring(5);
const matchingResult = resultList.find(result => result.mac === mac);
if (matchingResult) {
device.sn = matchingResult.sn;
device.isBand = matchingResult.isBand;
}
});
//
this.devicesList.sort((a, b) => {
return (a.isBand === false ? -1 : 1) - (b.isBand === false ? -1 : 1);
});
this.$forceUpdate();
}).catch((error) => {
console.error('获取设备绑定状态失败', error);
});
},
//
openConfirmModal(device) {
this.deviceinfo = device;
this.showConfirmModal = true;
},
//
closeConfirmModal() {
this.showConfirmModal = false;
},
//
confirmBind() {
this.closeConfirmModal();
this.createBLEConnection(this.deviceinfo);
},
//
createBLEConnection(device) {
this.mac = device.name.substring(5);
let that = this;
that.$u.post(`/appVerify/band?sn=${that.sn}&mac=${that.mac}`).then((res) => {
uni.showLoading({
title: '绑定中'
});
if (res.code == 200) {
uni.showToast({
title: '绑定成功',
icon: 'none',
duration: 2000
});
xBlufi.notifyStartDiscoverBle({
'isStart': false
});
xBlufi.notifyConnectBle({
isStart: true,
deviceId: device.deviceId,
name: device.name
});
} else {
uni.showToast({
title: res.msg,
icon: 'none',
duration: 2000
});
setTimeout(() => {
uni.navigateBack({
delta: 1
});
}, 2000);
}
});
}
}
}
</script>
<style lang="scss">
page {
background-color: #F7FAFE !important;