import store from '../store/index.js'; export const serviceId = "6E400001-B5A3-F393-E0A9-E50E24DCCA9E"; //6E400001-0000-1000-8000-00805F9B34FB export const writeCharacteristicId = "6E400002-B5A3-F393-E0A9-E50E24DCCA9E"; // export const readCharacteristicId = "6E400003-B5A3-F393-E0A9-E50E24DCCA9E"; // //循环获取当前蓝牙状态 let timer = uni.getStorageSync("blueStateTime"); let maxConnectNum = 3; let isModalShown = false; let oneMac = ""; //蓝牙连接状态 export const blueConnectState = () => { uni.getConnectedBluetoothDevices({ services: [serviceId], success(res) { //console.log('获取链接状态成功:', res.devices); store.commit('setConnectState', true); // if (res.devices.length > 0) { // store.commit('setConnectDev', res.devices[0]); // } }, fail(res) { //console.log('获取连接状态失败:', res); store.commit('setConnectDev', ""); store.commit("setConnectState", false); } }); } blueConnectState(); if (timer) clearInterval(timer) timer = setInterval(() => { blueConnectState(); }, 5000); uni.setStorageSync("blueStateTime", timer) //结束循环 export const blueStopConnectState = () => { if (timer) { clearInterval(timer) uni.setStorageSync("blueStateTime", "") } } let isConnecting = false; const CONNECT_TIMEOUT = 10000; // 10秒超时 let connectTimeout = null; //链接蓝牙 export const connectBlue = (mac) => { return new Promise((resolve, reject) => { if (isConnecting) { uni.showToast({ title: '已有连接正在进行中', icon: 'none' }); return reject(new Error('已有连接正在进行中')); } isConnecting = true; connectTimeout = setTimeout(() => { handleConnectError(new Error('连接超时'), 'timeout'); }, CONNECT_TIMEOUT); uni.showLoading({ title: '连接中' }); oneMac = mac; maxConnectNum = 3; const tryConnect = () => { closeBlue().then(() => { console.log("尝试连接", uni.getStorageSync('connectNum'), oneMac); uni.createBLEConnection({ deviceId: mac.deviceId, success: function(res) { uni.setStorageSync('otherUnconnect',false) clearTimeout(connectTimeout); handleConnectionSuccess(resolve); }, fail: function(err) { handleConnectError(err, 1); } }); // 监听蓝牙连接状态变化 uni.onBLEConnectionStateChange(function(res) { if (!res.connected && !isConnecting && uni.getStorageSync('connectNum') == 0) { uni.setStorageSync('otherUnconnect',true) store.commit('setConnectDev', ""); uni.setStorageSync('connectNum', 1); handleConnectError({errMsg: "蓝牙连接断开"}, 2); } }); }); } const handleConnectionSuccess = (resolve) => { isConnecting = false; uni.hideLoading(); if (uni.getSystemInfoSync().platform === "ios") { setupIOSConnection(resolve); } else { completeConnection(resolve); } } const setupIOSConnection = (resolve) => { uni.getBLEDeviceServices({ deviceId: oneMac.deviceId, success(res) { uni.getBLEDeviceCharacteristics({ deviceId: oneMac.deviceId, serviceId: serviceId, success() { completeConnection(resolve); }, fail(err) { handleConnectError(err, 4); } }); }, fail(err) { handleConnectError(err, 3); } }); } const completeConnection = (resolve) => { isModalShown = false; uni.setStorageSync('connectNum', 0); setNotification(); store.commit('setConnectDev', oneMac); store.commit('setConnectState', true); resolve(); } const handleConnectError = (err, type) => { clearTimeout(connectTimeout); uni.hideLoading(); if (uni.getStorageSync('connectNum') <= maxConnectNum && uni.getStorageSync('connectNum') > 0) { console.log(`第${uni.getStorageSync('connectNum')}次重试`); if (!store.state.connectDev) { uni.setStorageSync('connectNum', uni.getStorageSync('connectNum') + 1); tryConnect(); } } else { isConnecting = false; showReconnectModal(); } } tryConnect(); }); } const showReconnectModal = () => { if (isModalShown) return; isModalShown = true; uni.hideLoading(); uni.showModal({ title: '连接失败', content: '蓝牙连接失败,前往手动连接?', success: (res) => { isModalShown = false; if (res.confirm) { uni.redirectTo({ url: '/pages/bluetooth/detail' }) } else { isConnecting = false; uni.setStorageSync('connectNum', 4); store.commit('setConnectDev', ''); store.commit('setConnectState', false); } }, fail: () => { isModalShown = false; isConnecting = false; } }); } //通知消息检测 export const setNotification = () => { return new Promise((reslove, rejcts) => { let mac = store.state.connectDev /*保存本地*/ let list = uni.getStorageSync("connectDevList") ? uni.getStorageSync("connectDevList") : [] let isHav = false; list.filter(v => { if (v.deviceId == mac.deviceId) isHav = true; }) if (!isHav) { list.push({name : mac.name,deviceId : mac.deviceId}); uni.setStorageSync("connectDevList", list); } /*保存本地结束*/ uni.notifyBLECharacteristicValueChange({ deviceId: oneMac.deviceId, serviceId: serviceId, characteristicId: readCharacteristicId, state: true, success(res) { uni.setStorageSync('connectNum', 0); console.log("接收通知成功", res); reslove() }, fail(res) { console.log("接收通知失败", res); closeBlue(); rejcts(); } }); }) } export const closeBlue = () => { return new Promise((reslove, rejcts) => { let connectDev = store.state.connectDev if (connectDev) { uni.closeBLEConnection({ deviceId: connectDev.deviceId, success(res) { console.log('蓝牙关闭成功:', res); reslove(); }, fail(res) { console.log('蓝牙关闭失败:', res); reslove(); } }) } else { reslove(); } }) } //发送数据 export const sendData = (dataArray) => { return new Promise((reslove, rejcts) => { let connectDev = store.state.connectDev if (!connectDev) { uni.showModal({ title: "提示", content: "蓝牙未连接" }) rejcts() } console.log("数据发送", dataArray); let uint8Array = new Uint8Array(dataArray); wx.writeBLECharacteristicValue({ deviceId: connectDev.deviceId, serviceId: serviceId, characteristicId: writeCharacteristicId, value: uint8Array.buffer, success(res) { console.log('数据发送成功:', res); setTimeout(() => { reslove(); }, 200) }, fail(res) { console.log('数据发送失败:', res); uni.hideLoading(); if (res.errCode == 10006) { store.commit('setConnectDev', ""); store.commit("setConnectState", false); } rejcts() } }); }) } //关闭蓝牙 export const closeBlueAdapter = () => { isModalShown = true; uni.closeBluetoothAdapter({ success: (res) => { blueConnectState(); isModalShown = false; }, fail: (error) => { isModalShown = false; console.log("关闭蓝牙模块失败", error); } }); } //返回数据反解析 export const ab2hex = (buffer, num = 2) => { var hexArr = Array.prototype.map.call( new Uint8Array(buffer), function (bit) { return ('00' + bit.toString(16)).slice(-2) } ) var hexString = ""; var hexResArr = []; hexArr.filter((v, i) => { if (i > num) { hexString += v; } else { hexResArr.push(v); } }); let string = hexToString(hexString); var data = { pre: hexResArr, value: string }; return data; } //不弹弹窗 export const changeIsModalShown = () => { isModalShown = true; } export const strToHex = (str) => { var result = []; for (var i = 0; i < str.length; i++) { result.push("0x" + str.charCodeAt(i).toString(16)); } return result; } function hexToString(hex) { var rawString = ""; for (var i = 0; i < hex.length; i += 2) { rawString += String.fromCharCode(parseInt(hex.substr(i, 2), 16)); } return rawString; }