上代代码
蓝牙类
import {
storage,
keys
} from '../utils/js/storage.js'
import store from '../store/index.js'
export default class ble {
constructor() {
let that = this;
// 用户绑定了的设备
this.userBind = [];
// 蓝牙开启状态
this.startFlag = false
// 蓝牙是否开启适配器
this.startAdapter = false
//搜索到的所有的设备的数组
this.deviceArray = [];
// 正在连接的智能尺id
this.deviceId = ''
this.serviceId = "6E400001-B5A3-F393-E0A9-E50E54DCCAA9";
this.readCharacteristicId = "6E400003-B5A3-F393-E0A9-E50E54DCCAA9";
this.writeCharacteristicId = "6E400002-B5A3-F393-E0A9-E50E54DCCAA9";
// 开启蓝牙
this.openBluetooth()
// this.openBluetoothAdapter()
// 监听客户是否主动打开蓝牙
setInterval(() => {
this.intervalBluStart()
}, 1200)
}
openBluetooth() {
let that = this
let main, BluetoothAdapter, BAdapter, Context, BManager;
switch (uni.getSystemInfoSync().platform) {
case 'android':
main = plus.android.runtimeMainActivity()
BluetoothAdapter = plus.android.importClass('android.bluetooth.BluetoothAdapter')
BAdapter = BluetoothAdapter.getDefaultAdapter()
if (!BAdapter.isEnabled()) {
let a = BAdapter.enable()
console.log(a)
if (a) {
let checkedNum = 5
let b = setInterval(() => {
checkedNum--
if (checkedNum < 0) {
clearInterval(b)
// 适配器开启失败
uni.showToast({
title: '蓝牙未打开,请打开蓝牙!',
icon: 'none',
duration: 3000
})
} else {
if (BAdapter.isEnabled()) {
that.openBluetoothAdapter()
clearInterval(b)
}
}
}, 1000)
} else {
// 适配器开启失败
let b = setTimeout(() => {
uni.showToast({
title: '蓝牙未打开,请打开蓝牙!',
icon: 'none',
duration: 3000
})
clearTimeout(b)
}, 1600)
}
}
break
}
}
// 定时监听蓝牙是否开启
intervalBluStart() {
let that = this
let main, BluetoothAdapter, BAdapter, Context, BManager;
switch (uni.getSystemInfoSync().platform) {
case 'android':
main = plus.android.runtimeMainActivity()
BluetoothAdapter = plus.android.importClass('android.bluetooth.BluetoothAdapter')
BAdapter = BluetoothAdapter.getDefaultAdapter()
if (BAdapter.isEnabled()) {
//console.log('startAdapter',that.startAdapter)
// 蓝牙以打开,并且没有开启适配器
if (!that.startAdapter) {
that.openBluetoothAdapter()
}
}
break
}
}
//添加事件监听器
addEvent() {
let that = this;
/**
* 开始搜索设备
* @param {String} data 已经绑定了的设备id
* */
uni.$on("scanEquipment", function(data) {
that.startBluetoothDevicesDiscovery();
})
/**
* 创建连接
* @param {String} deviceId 需要连接的设备id
* */
uni.$on("createCon", function(deviceId) {
console.log('收到创建事件:', deviceId)
that.createBLEConnection(deviceId)
})
// 断开蓝牙连接
uni.$on('closeBLEConnection', (deviceId) => {
that.closeBLEConnection(deviceId)
})
/**
* 向蓝牙发送数据
* @param {buffArray} 数组 需要发送的数据
* */
uni.$on("writeTodevice", function(buffArray) {
that.writeBLECharacteristicValue(buffArray)
})
/**
* 停止扫描蓝牙设备
* */
uni.$on("stopScan", function() {
that.stopBluetoothDevicesDiscovery();
})
/**
* 搜索并连接已经绑定的设备
* */
uni.$on("bindCreateCon", function(list) {
console.log("已绑定的设备调用连接");
console.log(list);
console.log(storage.getStorageSync("devicelist"))
that.startBluetoothDevicesDiscovery();
})
console.log('开始监听蓝牙事件')
}
openBluetoothAdapter() {
console.log('打开蓝牙适配器')
let that = this
uni.openBluetoothAdapter({
success() {
console.log("openBluetoothAdapter success")
that.startAdapter = true
that.startFlag = false
that.addEvent();
//监听寻找到新设备
that.onBluetoothDeviceFound()
//监听连接状态
that.onBLEConnectionStateChange();
//监听值的变化
that.onBLECharacteristicValueChange();
// 主动连接已绑定过得设备
that.getBluetoothDevices()
uni.$emit("bindCreateCon",null)
},
fail() {
this.startFlag = false
console.log("openBluetoothAdapter fail")
uni.showToast({
title: '蓝牙未打开,请打开蓝牙!',
icon: 'none',
duration: 3000
})
}
})
}
// 获取在蓝牙模块生效期间所有已发现的蓝牙设备
getBluetoothDevices(){
uni.getBluetoothDevices({
success(res) {
console.log(JSON.stringify(res))
if (res.devices[0]) {
}
}
})
}
/**
* 开始搜寻附近的蓝牙外围设备。此操作比较耗费系统资源
* @param {String} data 要过滤的id
* */
startBluetoothDevicesDiscovery(data) {
uni.startBluetoothDevicesDiscovery({
// services: [],
allowDuplicatesKey: true,
interval: 0,
success(e) {
console.log("调用搜索设备成功", JSON.stringify(e))
},
fail() {
console.log("调用搜索设备失败")
}
})
}
//监听寻找到新设备的事件
onBluetoothDeviceFound() {
var that = this;
console.log('监听寻找到新设备的事件')
uni.onBluetoothDeviceFound(function(devices) {
//console.log('新设备', JSON.stringify(devices))
if (devices.devices[0].name == "meter") {
let mydevices = devices
mydevices.devices = mydevices.devices.filter(item => {
if (item.name == "meter") {
return item
}
})
uni.$emit("deviceFound", mydevices)
let deviceArray = devices.devices;
for (let i = 0; i < deviceArray.length; i++) {
that.deviceArray.push(deviceArray[i])
}
console.log(JSON.stringify(devices))
let userBind = storage.getStorageSync("devicelist");
console.log(userBind)
for (let i = 0; i < userBind.length; i++) {
if (devices.devices[0].deviceId == userBind[i].devicId) {
console.log("是已经绑定的设备")
that.createBLEConnection(devices.devices[0].deviceId)
break;
}
}
}
},(e)=>{
console.log(JSON.stringify(e))
})
}
// 断开蓝牙连接
closeBLEConnection(deviceId) {
if (!deviceId) return;
uni.closeBLEConnection({
deviceId,
success(res) {
console.log(res)
},
fail() {
}
})
}
/**
* 开始连接设备
* @param {String} deviceId 需要连接的设备id
* */
createBLEConnection(deviceId) {
let that = this
if (deviceId && deviceId == this.deviceId) {
return uni.showToast({
title: '蓝牙已连接',
icon: 'none',
duration: 4000
})
} else if (deviceId && deviceId != this.deviceId) {
let id = this.deviceId
uni.closeBLEConnection({
id,
success(res) {
that.createConnetFunction(deviceId)
},
fail() {
that.createConnetFunction(deviceId)
}
})
return
}
}
createConnetFunction(deviceId) {
let that = this;
let serverArry = that.deviceArray;
let contentStatus = false;
uni.showToast({
title: '连接中...',
icon: 'loading',
duration: 4000
})
uni.createBLEConnection({
deviceId: deviceId,
timeout: 4000,
success: () => {
that.deviceId = deviceId
uni.$emit('deviceConnectChange', deviceId)
// todo修改连接状态
uni.showToast({
title: '蓝牙连接成功',
icon: 'none',
duration: 2000
})
},
fail: (e) => {
uni.showToast({
title: '蓝牙连接失败',
icon: 'none',
duration: 3000
})
}
})
}
//监听低功耗蓝牙连接状态的改变事件。包括开发者主动连接或断开连接,设备丢失,连接异常断开等等
onBLEConnectionStateChange() {
let that = this;
uni.onBLEConnectionStateChange(function(res) {
console.log("监听到设备连接状态" + JSON.stringify(res))
if (res.connected == true) {
that.deviceId = res.deviceId
uni.$emit("ConnectEd", res)
uni.$emit('deviceConnectChange', that.deviceId)
that.stopBluetoothDevicesDiscovery();
let userBind = storage.getStorageSync("devicelist");
for (let i = 0; i < userBind.length; i++) {
if (userBind[i].devicId == res.deviceId) {
userBind[i].is_content = true;
userBind[i].connected = true;
storage.setStorageSync("devicelist", userBind)
}
}
console.log(storage.getStorageSync("devicelist"))
setTimeout(function() {
that.notifyBLECharacteristicValueChange();
}, 2000)
} else {
that.startAdapter = false
that.deviceId = ''
uni.$emit('deviceConnectChange', that.deviceId)
uni.showToast({
title: '蓝牙连接断开',
icon: 'none',
duration: 3000
})
}
})
}
//启用低功耗蓝牙设备特征值变化时的 notify 功能,
notifyBLECharacteristicValueChange() {
uni.notifyBLECharacteristicValueChange({
deviceId: this.deviceId,
serviceId: this.serviceId,
characteristicId: this.readCharacteristicId,
state: true,
success(res) {
console.log("开启notify服务成功" + JSON.stringify(res))
},
fail(ret) {
console.log("开启notify服务失败" + JSON.stringify(ret))
}
})
}
//监听低功耗蓝牙设备的特征值变化事件。必须先启用 notifyBLECharacteristicValueChange 接口才能接收到设备推送的 notification。
onBLECharacteristicValueChange() {
let that = this;
uni.onBLECharacteristicValueChange(function(res) {
let valueInfo = that.ab2hex(res.value);
if (valueInfo.substr(3, 1) != 1) {
console.log("数据变化了" + valueInfo)
uni.$emit("deviceValueChange", valueInfo);
}
if (valueInfo.substr(3, 1) == 2) {
// 确认单次数据
console.log("获取到数据" + valueInfo)
console.log(valueInfo.substr(8, 2) + valueInfo.substr(6, 2))
}
})
}
//写入数据
writeBLECharacteristicValue(ArrayBuff) {
let that = this;
// 向蓝牙设备发送一个0x00的16进制数据
const buffer = new ArrayBuffer(ArrayBuff.length)
const dataView = new DataView(buffer)
for (let i = 0; i < ArrayBuff.length; i++) {
dataView.setUint8(i, ArrayBuff[i])
}
var hex = ArrayBuff //要发送的信息
console.log('要发送的信息是:' + hex)
var typedArray = new Uint8Array(hex.match(/[\da-f]{2}/gi).map(function(h) {
return parseInt(h, 16)
}))
console.log(typedArray)
var buffer1 = typedArray.buffer
console.log("写入数据" + this.ab2hex(buffer) + '-buffer1:' + buffer1 + '-str:' + this.ab2hex(buffer1))
uni.writeBLECharacteristicValue({
deviceId: that.deviceId,
serviceId: that.serviceId,
characteristicId: that.writeCharacteristicId,
value: buffer1,
success(res) {
console.log('writeBLECharacteristicValue success', JSON.stringify(res))
},
fail(res) {
console.log('writeBLECharacteristicValue fail', JSON.stringify(res))
},
complete(res) {
console.log('writeBLECharacteristicValue compe', JSON.stringify(res))
}
})
}
//停止扫描蓝牙设备
stopBluetoothDevicesDiscovery() {
console.log("停止扫描设备");
uni.stopBluetoothDevicesDiscovery({
success(res) {
console.log(res)
}
})
}
// ArrayBuffer转16进度字符串示例
ab2hex(buffer) {
const hexArr = Array.prototype.map.call(
new Uint8Array(buffer),
function(bit) {
return ('00' + bit.toString(16)).slice(-2)
}
)
return hexArr.join('')
}
string2buffer(str) {
// 首先将字符串转为16进制
let val = ""
for (let i = 0; i < str.length; i++) {
if (val === '') {
val = str.charCodeAt(i).toString(16)
} else {
val += ',' + str.charCodeAt(i).toString(16)
}
}
// 将16进制转化为ArrayBuffer
return new Uint8Array(val.match(/[\da-f]{2}/gi).map(function(h) {
return parseInt(h, 16)
})).buffer
}
}
储存类storage.js
export const keys = {
}
class Storage {
constructor() {
}
//存储在本地缓存指定的name中
setStorageSync(name, data) {
try {
data = JSON.stringify(data)
uni.setStorageSync(name, data);
} catch (e) {
console.log(e)
}
}
//存储在本地缓存指定的name中(异步)
setStorage(name, data) {
try {
data = JSON.stringify(data)
uni.setStorage(name, data);
} catch (e) {
console.log(e)
}
}
//从本地缓存中读取置顶name对应的内容(异步)
getStorage(name) {
let data;
try {
data = uni.getStorage(name);
} catch (e) {
console.log(e);
}
return data;
}
//从本地缓存中读取置顶name对应的内容
getStorageSync(name) {
let data;
try {
data = uni.getStorageSync(name);
if (data) {
data = JSON.parse(data)
}
} catch (e) {
console.log(e);
}
return data;
}
//从本地缓存中移出指定key
removeStorageSync(name) {
try {
uni.removeStorageSync(name);
} catch (e) {
//TODO handle the exception
console.log(e);
}
}
//从本地缓存中移出指定key(异步)
removeStorage(name) {
try {
uni.removeStorage(name);
} catch (e) {
//TODO handle the exception
console.log(e);
}
}
//返回一个布尔值,表示name是否在本地缓存之中
checkStorageSync(name) {
let value;
try {
const res = uni.getStorageInfoSync()
value = res.keys.includes(name)
} catch (e) {
console.log(e)
}
return value
}
//返回一个布尔值,表示name是否在本地缓存之中(异步)
checkStorage(name) {
let value;
try {
const res = uni.getStorageInfo()
value = res.keys.includes(name)
} catch (e) {
console.log(e)
}
return value
}
//清除本地数据缓存
clearStorageSync() {
try {
uni.clearStorageSync();
} catch (e) {
console.log(e)
}
}
//清除本地数据缓存(异步)
clearStorage() {
try {
uni.clearStorage();
} catch (e) {
console.log(e)
}
}
}
export const storage = new Storage();