- 创建 bluetooth.js 文件
function ble_com(readCallBack, statusCallBack) {
this.readCallBack = readCallBack;
this.statusCallBack = statusCallBack;
this.characteristicObj = {
read: '',
write: '',
notify: ''
}
this.writeserveObjUuid = ''
this.readServerObjUuid = ''
this.characteristics = ''
this.waiweiId = ''
this.advertisData = ''
this.asciiRes = ''
this.asciiCode = ''
this.asciiSuc = ''
this.asciiStep = ''
this.asciiHex = ''
this.instruct = ''
this.blueToothconnected = ''
this.readVal = ''
this.writeState = false
this.callBackState = false
}
ble_com.prototype = {
onLoad: function(tableNumber) {
uni.openBluetoothAdapter({
success: (e) => {
uni.showLoading({
title: '连接中',
mask: true
});
this.startBluetoothDeviceDiscovery(tableNumber)
},
fail: res => {
uni.showToast({
icon: "none",
title: "请检查蓝牙是否开启!",
duration: 2000
})
}
});
this.onBLEConnectionStateChange()
},
startBluetoothDeviceDiscovery: function(tableNumber) {
uni.startBluetoothDevicesDiscovery({
success: res => {
this.onBluetoothDeviceFound(tableNumber);
},
fail: res => {
uni.showToast({
icon: "none",
title: "查找设备失败!",
duration: 3000
})
}
});
},
ab2hex: function(buffer) {
const hexArr = Array.prototype.map.call(
new Uint8Array(buffer),
function(bit) {
return ('00' + bit.toString(16)).slice(-2)
}
)
return hexArr.join('')
},
onBluetoothDeviceFound: function(tableNumber) {
uni.onBluetoothDeviceFound(devices => {
if (devices.devices[0].localName) {
if (devices.devices[0].localName.indexOf('JNM-' + tableNumber) != -1 && devices
.devices[0].advertisData) {
this.advertisData = this.ab2hex(devices.devices[0].advertisData)
this.stopBluetoothDevicesDiscovery();
this.waiweiId = devices.devices[0].deviceId
this.createBLEConnection(devices.devices[0].deviceId)
return;
}
}
});
},
stopBluetoothDevicesDiscovery: function() {
uni.stopBluetoothDevicesDiscovery({
success: e => {
console.log('停止搜索蓝牙设备:' + e.errMsg);
},
fail: e => {
console.log('停止搜索蓝牙设备失败,错误码:' + e.errCode);
}
});
},
closeBLEConnection: function() {
uni.closeBLEConnection({
deviceId: this.waiweiId,
success: res => {}
})
},
createBLEConnection: function(deviceId) {
uni.createBLEConnection({
deviceId: deviceId,
success: res => {
this.stopBluetoothDevicesDiscovery();
this.getBLEDeviceServices(deviceId);
},
fail: res => {
console.log(res)
}
})
},
getBLEDeviceServices: function(deviceId) {
setTimeout(() => {
uni.getBLEDeviceServices({
deviceId: deviceId,
success: (res) => {
this.writeState = false
console.log(res, '126');
res.services.forEach(item => {
this.getBLEDeviceCharacteristics(deviceId, item.uuid)
})
}
})
}, 1000)
},
getBLEDeviceCharacteristics: function(deviceId, serviceId) {
setTimeout(() => {
uni.getBLEDeviceCharacteristics({
deviceId: deviceId,
serviceId: serviceId,
success: (res) => {
let state = 0
console.log(res, '129');
this.characteristics = res.characteristics
res.characteristics.forEach(item => {
if (item.properties.read) {
this.characteristicObj.read = item.uuid
this.readServerObjUuid = serviceId
this.readBLECharacteristicValue(deviceId, serviceId,
item.uuid
);
}
if (item.properties.write && !this.writeState) {
this.characteristicObj.write = item.uuid
this.writeserveObjUuid = serviceId
this.writeState = true
}
if (item.properties.notify && state === 0) {
this.characteristicObj.notify = serviceId
state = 1
this.notifyBLECharacteristicValueChange(deviceId, item
.uuid, serviceId)
}
})
},
fail: (res) => {
console.log(res, '153')
}
})
}, 2000)
},
readBLECharacteristicValue: function(deviceId, serviceId, characteristicId) {
uni.readBLECharacteristicValue({
deviceId: deviceId,
serviceId: serviceId,
characteristicId: characteristicId,
success: (res) => {
console.log(res, '167');
},
fail: (res) => {
console.log(res, '170');
}
})
},
notifyBLECharacteristicValueChange: function(deviceId, characteristicId, serviceId) {
uni.notifyBLECharacteristicValueChange({
state: true,
deviceId: deviceId,
serviceId: serviceId,
characteristicId: characteristicId,
success: (res) => {
uni.hideLoading();
console.log('初始化完成');
this.onBLECharacteristicValueChange(deviceId);
},
fail: (res) => {
console.log('notifyBLECharacteristicValueChange success', res.errMsg)
}
})
},
onBLEConnectionStateChange: function() {
uni.onBLEConnectionStateChange((res) => {
this.statusCallBack({
advertisData: this.advertisData,
connected: res.connected
})
if (res.connected) {
uni.hideLoading();
uni.showToast({
title: '连接成功!等待初始化!',
duration: 2000
});
uni.showLoading({
title: '初始化中 请等待',
mask: true
});
} else {
}
})
},
onBLECharacteristicValueChange: function(deviceId) {
uni.onBLECharacteristicValueChange((res) => {
this.callBackState = true
let hex = this.ab2hex(res.value)
this.readVal += hex;
console.log(this.readVal, '232');
if (this.instruct === 'writeTable') {
this.readCallBack({
data: this.readVal,
cmd: this.instruct,
})
} else {
this.readCallBack({
data: this.readVal,
cmd: 'connectState',
})
}
})
},
ab2hex: function(buffer) {
const hexArr = Array.prototype.map.call(
new Uint8Array(buffer),
function(bit) {
return ('00' + bit.toString(16)).slice(-2)
}
)
return hexArr.join('')
},
writeBLECharacteristicValue: function(value) {
let buffer = this.stringToBytes(value)
uni.writeBLECharacteristicValue({
deviceId: this.waiweiId,
writeType: 'write',
serviceId: this.writeserveObjUuid,
characteristicId: this.characteristicObj.write,
value: buffer,
success: (res) => {
console.log('writeBLECharacteristicValue success', res)
},
fail: (res) => {
console.log('writeBLECharacteristicValue success', res)
}
})
},
multipleWriteBLECharacteristicValue: function(values) {
console.log(values);
values.forEach(item => {
let buffer = this.stringToBytes(item)
uni.writeBLECharacteristicValue({
deviceId: this.waiweiId,
writeType: 'writeNoResponse',
serviceId: this.writeserveObjUuid,
characteristicId: this.characteristicObj.write,
value: buffer,
success: (res) => {
console.log('writeBLECharacteristicValue success', res)
},
fail: (res) => {
console.log('writeBLECharacteristicValue success', res)
}
})
})
},
stringToBytes: function(hex) {
var typedArray = new Uint8Array(hex.match(/[\da-f]{2}/gi).map(function(h) {
return parseInt(h, 16)
}))
return typedArray.buffer
},
writeTable: function(data) {
console.log(data);
this.resetState()
this.instruct = 'writeTable'
this.writeBLECharacteristicValue(data)
},
xorSum: function(hex) {
var sum = 0;
for (var i = 0; i < hex.length / 2; i++) {
if (i == 0) {
sum = parseInt(hex.substr(i * 2, 2), 16);
} else {
sum ^= parseInt(hex.substr(i * 2, 2), 16);
}
}
var sumHex = sum.toString(16)
if (sumHex.length < 2) {
sumHex = '0' + sumHex;
}
return sumHex.toUpperCase();
},
hex2ascii: function(hex) {
let str = '';
for (let i = 0; i < hex.length / 2; i++) {
str += String.fromCharCode(parseInt(hex.substr(i * 2, 2), 16));
}
return str;
},
resetState: function() {
this.asciiRes = ''
this.asciiCode = ''
this.asciiSuc = ''
this.asciiStep = ''
this.asciiHex = ''
this.callBackState = false;
}
}
export default {
ble_com
}
- 在main.js 添加
import {
createSSRApp
} from "vue";
import App from "./App.vue";
import uviewPlus from 'uview-plus'
import bluetooth from '@/utils/bluetooth.js'
export function createApp() {
const app = createSSRApp(App);
var ble_com = new bluetooth.ble_com((e) => {}, (e) => {})
app.config.globalProperties.$global = {
bleCom: ble_com
}
app.use(uviewPlus)
uni.$u.setConfig({
config: {
unit: 'rpx'
},
props: {
radio: {
size: 15
}
}
})
return {
app,
};
}
- 在vue 页面使用
data() {
return {
searchForm: {
meterNo: "",
notifyData: "",
areaCode: "",
}
};
},
onLoad() {
let _this = this
this.proxy = getCurrentInstance().proxy
this.proxy.$global.bleCom.readCallBack = (res) => {
if (res.cmd === 'connectState') {
_this.searchForm.notifyData = res.data
}
if (res.cmd === 'writeTable') {
_this.onCallBack(res.data)
}
}
this.proxy.$global.bleCom.statusCallBack = (res) => {
if (uni.getSystemInfoSync().platform === 'ios') {
_this.searchForm.notifyData = res.advertisData
}
if (res.connected) {
}
}
},
- 注意:安卓与ios的 notifyData 值是不同方法取的 原因自行百度
ab2hex: function(buffer) {
const hexArr = Array.prototype.map.call(
new Uint8Array(buffer),
function(bit) {
return ('00' + bit.toString(16)).slice(-2)
}
)
return hexArr.join('')
},