import { logError } from './log.js' import store from '../store' // 可在utils.js或common.js等公共文件中创建此方法 /** * 公共日志错误转态码逻辑处理方法 * @param {Object} code * @param {Object} msg * @param {Object} 上下文this * 0: '正常', 10000: '未初始化蓝牙适配器', 10001: '当前蓝牙适配器不可用', 10002: '没有找到指定设备', 10003: '连接失败', 10004: '没有找到指定服务', 10005: '没有找到指定特征值', 10006: '当前连接已断开', 10007: '当前特征值不支持此操作', 10008: '其余所有系统上报的异常', 10009: 'Android 系统特有,系统版本低于 4.3 不支持 BLE', 10010: '已连接', 10011: '配对设备需要配对码', 10012: '连接超时', 10013: '连接 deviceId 为空或者是格式不正确', 2: '信息日志', */ var commonStateCodeDeal = async (code, msg, contextThis) => { // console.log('this', contextThis) if (code === 10000) { // 未初始化蓝牙适配器 /** * 如果是蓝牙未初始化,且已经有了deviceid和name直接蓝牙初始化处理 * 没有deviceId证明还没有连过蓝牙设备,则进入蓝牙搜索页面重新选择蓝牙 */ contextThis.setConnected(false) if (contextThis.deviceId) { await contextThis.openBluetoothAdapter() await contextThis.startLink() } else { contextThis.unlinkModalShow({ tipContent: '未初始化蓝牙适配器', }) } popuper.hideLoading() } else if (code === 10001) { // 当前蓝牙适配器不可用(手机没开启蓝牙) contextThis.setConnected(false) contextThis.unlinkModalShow({ tipContent: '请开启手机蓝牙后重试', successCb: (res) => { // 点击确认按钮的逻辑处理 contextThis.initLink() } }) popuper.hideLoading() } else if (code === 10002) { // showCustomToast({ // title: '没有找到指定设备' // }) contextThis.setConnected(false) contextThis.setNavBarTitle('没有找到指定设备-10002') popuper.hideLoading() } else if (code === 10003) { // showCustomToast({ // title: '连接失败' // }) contextThis.stopLink() contextThis.setConnected(false) contextThis.setNavBarTitle('连接失败-10003【请检查蓝牙是否正确连接】') popuper.hideLoading() } else if (code === 10004) { // showCustomToast({ // title: '没有找到指定服务' // }) contextThis.setConnected(false) contextThis.setNavBarTitle('没有找到指定服务-10004【请检查蓝牙是否正确连接】') popuper.hideLoading() } else if (code === 10005) { // showCustomToast({ // title: '没有找到指定特征值' // }) contextThis.setNavBarTitle('没有找到指定特征值-10005【请检查蓝牙是否正确连接】') popuper.hideLoading() } else if (code === 10006) { // showCustomToast({ // title: '当前连接已断开' // }) contextThis.setConnected(false) contextThis.setNavBarTitle('当前连接已断开-10006') popuper.hideLoading() } else if (code === 10007) { // showCustomToast({ // title: '当前特征值不支持此操作' // }) contextThis.setConnected(false) contextThis.setNavBarTitle('当前特征值不支持此操作-10007【请检查蓝牙是否正确连接】') popuper.hideLoading() } else if (code === 10008) { // showCustomToast({ // title: '当前特征值不支持此操作' // }) contextThis.setNavBarTitle('其余所有系统上报的异常-10008【请检查蓝牙是否正确连接】') popuper.hideLoading() } else if (code === 10009) { // showCustomToast({ // title: 'Android系统版本低于4.3 不支持BLE' // }) contextThis.setConnected(false) contextThis.setNavBarTitle('Android系统版本低于4.3 不支持BLE-10009') popuper.hideLoading() } else if (code === 10012) { // contextThis.unlinkModalShow({ // tipContent: '蓝牙连接超时,请尝试重新连接', // }) contextThis.setNavBarTitle('蓝牙连接超时,请尝试重新连接-10012【请检查蓝牙是否正确连接】') popuper.hideLoading() } else if (code === 10013) { // deviceId为空,重新选择蓝牙设备 // contextThis.unlinkModalShow({ // tipContent: 'deviceId 为空,请确认设备是否正确连接', // }) contextThis.setConnected(false) contextThis.setNavBarTitle('deviceId 为空,请确认设备是否正确连接-10013') popuper.hideLoading() } else if (code === -1) { // 蓝牙连接中再次重连,导致报错 popuper.hideLoading() /** * 1、连接后断开蓝牙返回首页再次进入该页面,提醒开启蓝牙后,开启蓝牙后开始连接时产生的问题处理 * 1-1该情况与未连接成功直接迅速推出然后进入进行连接操作的情况几乎一致,平台连接api报异常。 * */ if(msg === 'startLink=>连接失败'){ // await contextThis.openBluetoothAdapter() // await contextThis.startLink() showCustomModal({ content: '蓝牙连接服务繁忙,请稍后重试' }) } contextThis.stopLink() contextThis.setConnected(false) contextThis.setNavBarTitle('未知error--1') // showCustomToast({ // title: '蓝牙连接意外中段,重连失败' // }) // showCustomModal({ // content: '网络错误,请确认后重试', // 内容 // success: function() { // uni.reLaunch({ // 冲刷新当前页面 // url: getCurrentPage() // }) // } // }) } logError(code, msg) }; function getCurrentPage() { // 返回 /pages/home/blueTest // 获取当前页面栈数组 const pages = getCurrentPages(); // 获取数组中最后一个元素,即当前页面的实例 const currentPage = pages[pages.length - 1]; // 获取当前页面的路由路径 route: pages/home/blueTest const route = currentPage.route; return '/' + route } function showCustomModal(options) { // 默认配置项 const defaults = { title: '信息提示', // 标题 content: '', // 内容 showCancel: false, // 是否显示取消按钮 cancelText: '取消', // 取消按钮文字 confirmText: '确定', // 确定按钮文字 success: () => {}, // 成功后的回调函数 fail: () => {} // 失败后的回调函数(如点击取消) }; // 合并默认配置和传入的配置项 const config = Object.assign({}, defaults, options); // 使用uni.showModal显示模态弹窗 uni.showModal({ title: config.title, content: config.content, showCancel: config.showCancel, cancelText: config.cancelText, confirmText: config.confirmText, success: (res) => { if (res.confirm) { // 点击确定后的处理逻辑 config.success(); } else if (res.cancel) { // 点击取消后的处理逻辑 config.fail(); } } }); } function showCustomToast(options) { const defaults = { title: '', // 提示内容 icon: 'none', // 图标类型,如 'success', 'loading' 等 duration: 2000, // 显示时长,单位毫秒 successCallback: () => {} // 显示成功后执行的回调 }; // 合并默认配置和传入的配置项 const config = Object.assign({}, defaults, options); // 使用 uni.showToast 显示提示信息 uni.showToast({ title: config.title, icon: config.icon, duration: config.duration, success: () => { // 执行成功后的回调函数(如果有) config.successCallback(); } }); } function formatTime(time) { if (typeof time !== 'number' || time < 0) { return time } var hour = parseInt(time / 3600) time = time % 3600 var minute = parseInt(time / 60) time = time % 60 var second = time return ([hour, minute, second]).map(function(n) { n = n.toString() return n[1] ? n : '0' + n }).join(':') } function formatLocation(longitude, latitude) { if (typeof longitude === 'string' && typeof latitude === 'string') { longitude = parseFloat(longitude) latitude = parseFloat(latitude) } longitude = longitude.toFixed(2) latitude = latitude.toFixed(2) return { longitude: longitude.toString().split('.'), latitude: latitude.toString().split('.') } } function getCurrentTime() { // 获取当前系统时间 let now = new Date(); // 格式化时间 let year = now.getFullYear(); // 获取年份 let month = (now.getMonth() + 1).toString().padStart(2, '0'); // 获取月份,月份是从0开始的,所以加1后填充前导零(当为一位时) let date = now.getDate().toString().padStart(2, '0'); // 获取日期,也进行同样的填充前导零处理 let hours = now.getHours().toString().padStart(2, '0'); // 获取小时 let minutes = now.getMinutes().toString().padStart(2, '0'); // 获取分钟 // 拼接年月日时分格式的字符串 let formattedTime = `${year}-${month}-${date} ${hours}:${minutes}`; } function ab2Str(arrayBuffer) { let unit8Arr = new Uint8Array(arrayBuffer); let encodedString = String.fromCharCode.apply(null, unit8Arr); return encodedString; } function stringToBytes(str) { var ch; var st; var re = []; for (var i = 0; i < str.length; i++) { ch = str.charCodeAt(i); // get char st = []; // set up "stack" do { st.push(ch & 255); // push byte to stack ch = ch >> 8; // shift value down by 1 byte } while (ch); // add stack contents to result // done because chars have "wrong" endianness re = re.concat(st.reverse()); } // return an array of bytes return re; } var dater = { getDate: function(type) { const date = new Date(); let year = date.getFullYear(); let month = date.getMonth() + 1; let day = date.getDate(); if (type === 'start') { year = year - 60; } else if (type === 'end') { year = year + 2; } month = month > 9 ? month : '0' + month; day = day > 9 ? day : '0' + day; return `${year}-${month}-${day}`; }, } var storager = { set: function(key, content){ uni.setStorageSync(key, content) }, get: function(key){ return uni.getStorageSync(key) } } var popuper = { showLoading: function(obj={}){ store.commit('setBlueConnectLoading', true) uni.showLoading({ title: obj.title || '加载中...', mask: true }) }, hideLoading: function(){ store.commit('setBlueConnectLoading', false) uni.hideLoading() } } var pager = { navTo: function(url){ uni.navigateTo({ url }) }, relaunchTo: function(url){ console.log('relaunch', url) uni.reLaunch({ url }) } } var blueToother = { serviceId: '0000FFE0-0000-1000-8000-00805F9B34FB', characteristicId_WRITE: '0000FFE1-0000-1000-8000-00805F9B34FB', // 写特征值 characteristicId_NOTIFY: '0000FFE1-0000-1000-8000-00805F9B34FB', // 通知特征值 writeBLECharacteristicValue: function(value){ // value: 'GETDATA' var strbuf = new Uint8Array(stringToBytes(value)); var buffer1 = strbuf.buffer; uni.writeBLECharacteristicValue({ deviceId: storager.get('deviceInfo').deviceId, serviceId: this.serviceId, characteristicId: this.characteristicId_WRITE, value: buffer1, success: (res) => { console.log('writeBLECharacteristicValue-success:res1=>'+value, res) }, fail: (res) => { console.log('writeBLECharacteristicValue-fail:res1=>'+value, res) // commonStateCodeDeal(res.errCode || res, 'gosend -> writeBLECharacteristicValue', // this) }, }); }, openBluetoothAdapter: function() { return new Promise((resolve, reject) => { setTimeout(() => { uni.openBluetoothAdapter({ success: (res) => { resolve(res); // 成功时调用 }, fail: (res) => { logError(res.errCode, res.errMsg) reject(res); // 成功时调用 } }); }, 200) }) }, closeBluetoothAdapter: function() { return new Promise((resolve, reject) => { setTimeout(() => { uni.closeBluetoothAdapter({ success: (res) => { logError(2, '关闭适配器成功') resolve(res); // 成功时调用 }, fail: (res) => { logError(res.errCode, res.errMsg) reject(res); // 成功时调用 } }) }, 200) }) }, createBLEConnection: function(deviceId) { return new Promise((resolve, reject) => { setTimeout(() => { uni.createBLEConnection({ deviceId, success: (res) => { resolve(res); // 成功时调用 }, fail: (res) => { logError(res.errCode, res.errMsg) reject(res); // 成功时调用 } }); }, 200) }); }, closeBLEConnection: function(deviceId) { return new Promise((resolve, reject) => { setTimeout(() => { uni.closeBLEConnection({ deviceId, success: (res) => { logError(2, '关闭连接成功') resolve(res); // 成功时调用 }, fail: (res) => { logError(res.errCode, res.errMsg) reject(res); // 成功时调用 } }); }, 200) }); }, getBLEDeviceServices: function(deviceId) { return new Promise((resolve, reject) => { setTimeout(() => { uni.getBLEDeviceServices({ deviceId, success: (res) => { console.log(res) resolve(res); // 成功时调用 }, fail: (res) => { logError(res.errCode, res.errMsg) reject(res); // 成功时调用 } }); }, 3000) }); }, getBLEDeviceCharacteristics: function(deviceId, serviceId) { return new Promise((resolve, reject) => { setTimeout(() => { uni.getBLEDeviceCharacteristics({ deviceId, serviceId, success: (res) => { resolve(res); // 成功时调用 }, fail: (res) => { logError(res.errCode, res.errMsg) reject(res); // 成功时调用 } }); }, 200) }); }, readBLECharacteristicValue: function(deviceId, serviceId, characteristicId) { return new Promise((resolve, reject) => { setTimeout(() => { uni.readBLECharacteristicValue({ deviceId, serviceId, // 蓝牙特征值对应服务的UUID (固定值) characteristicId, // 蓝牙特征值的UUID success: (res) => { resolve(res); // 成功时调用 }, fail: (res) => { logError(res.errCode, res.errMsg) reject(res); // 成功时调用 } }); }, 200) }); }, notifyBLECharacteristicValueChange: function(deviceId, serviceId, characteristicId, state) { return new Promise((resolve, reject) => { setTimeout(() => { uni.notifyBLECharacteristicValueChange({ //开启通知 deviceId, serviceId, characteristicId, state, success: (res) => { resolve(res); // 成功时调用 }, fail: (res) => { logError(res.errCode, res.errMsg) reject(res); // 成功时调用 } }); }, 200) }); }, } var dateUtils = { UNITS: { '年': 31557600000, '月': 2629800000, '天': 86400000, '小时': 3600000, '分钟': 60000, '秒': 1000 }, humanize: function(milliseconds) { var humanize = ''; for (var key in this.UNITS) { if (milliseconds >= this.UNITS[key]) { humanize = Math.floor(milliseconds / this.UNITS[key]) + key + '前'; break; } } return humanize || '刚刚'; }, format: function(dateStr) { var date = this.parse(dateStr) var diff = Date.now() - date.getTime(); if (diff < this.UNITS['天']) { return this.humanize(diff); } var _format = function(number) { return (number < 10 ? ('0' + number) : number); }; return date.getFullYear() + '/' + _format(date.getMonth() + 1) + '/' + _format(date.getDate()) + '-' + _format(date.getHours()) + ':' + _format(date.getMinutes()); }, parse: function(str) { //将"yyyy-mm-dd HH:MM:ss"格式的字符串,转化为一个Date对象 var a = str.split(/[^0-9]/); return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]); } }; export { formatTime, formatLocation, dateUtils, stringToBytes, ab2Str, getCurrentTime, showCustomModal, showCustomToast, commonStateCodeDeal, blueToother, getCurrentPage, popuper, storager, dater, pager }