对接的时候厂家应该会给对接文档,类似于
前端代码
<template>
<div class="about">
<el-button type="primary" @click="clickme">测试</el-button>
</div>
</template>
<script>
export default {
name: "HomeView",
data() {
return {
}
},
methods: {
clickme() {
this.readbluetooth()
.then(v => console.log(v))
.catch(e => console.log(e));
},
async readbluetooth() {
let device = await navigator.bluetooth.requestDevice({
optionalServices: ['0783b03e-8535-b5a0-7140-a304d2xxxx']
, acceptAllDevices: true//设置acceptAllDevices代表查询所有蓝牙设备 也是必须配置optionalServices
});
device.addEventListener('gattserverdisconnected', this.onDisconnected);//监听设备断开连接
let server = await device.gatt.connect();
let service = await server.getPrimaryService('0783b03e-8535-b5a0-7140-a304d24xxxx');//这里需要服务UUID 还是可以提供完整的蓝牙UUID或简短的16位或32位形式
let services = await server.getPrimaryServices();
let characteristics = await service.getCharacteristics();//获取设备所有信息特征值
let characteristic = await service.getCharacteristic('0783b03e-8535-b5a0-7140-a304d2xxxx');//这里需要读的特征值UUID 还是可以提供完整的蓝牙UUID或简短的16位或32位形式
characteristic.startNotifications();//开始监听
let array = [];
characteristic.addEventListener(
'characteristicvaluechanged', e => {
let currentArray = [];
Array.prototype.map.call(
new Uint8Array(e.target.value.buffer), function (bit) {
currentArray.push(bit);
}
)
if (JSON.stringify(currentArray) !== JSON.stringify(array)) {
array = currentArray;
const buffer = new Uint8Array(e.target.value.buffer);
const btoaData = btoa(String.fromCharCode.apply(null, buffer));
if (btoaData === "AAAAAAAAAAAAAAAAAAAAAAAAAAA=") {
return;
}
//需要后端解析
this.$api.yunkangbaoTapeMeasure({
result: btoa(String.fromCharCode.apply(null, buffer)),
}).then(res => {
console.log(res)
})
}
}
);
},
onDisconnected(event) {
const device = event.target;
console.log(`设备: ${device.name} 已经断开连接`);
}
},
}
</script>
<style scoped lang="scss"></style>
服务端解析
@ApiOperation("云康宝卷尺")
@PostMapping("/yunkangbaoTapeMeasure")
public AjaxResult yunkangbaoTapeMeasure(@RequestBody ReceiveInfoBo receiveInfoBo) {
byte[] bytes= Base64.getMimeDecoder().decode(receiveInfoBo.getResult());
String result = new String(bytes, Charset.forName("UTF-8"));
System.out.println("卷尺数据"+result);
String data="";
String unit="";
if (result.contains("PM")||result.contains("SM")){
data=result.substring(1,4)+"."+result.substring(4,5);
unit="cm";
}else if(result.contains("PI")||result.contains("SI")){
data=result.substring(1,3)+"."+result.substring(3,5);
unit="in";
}
log.info("卷尺数据"+data);
JSONObject jsonObject=new JSONObject();
jsonObject.set("result",Double.valueOf(data));
jsonObject.set("unit",unit);
return new AjaxResult(200,"成功",jsonObject);
}