uniapp html5+ plus蓝牙连接电子秤

news/2024/12/28 9:02:34/

uniapp /html5+ 蓝牙连接电子秤

<template><view class="container"><uni-nav-bar title="设备管理" left-icon="back" fixed backgroundColor='#fff' color='#000' :border='false'></uni-nav-bar><view class="ul"><view class="li" v-for="(item, index) in bluetooth" :key="index" :title="item.name"@click="createBLEConnection(item.deviceId, index)"><view class="li-left"><view class="blueImg"><image src="../../static/img/user/icon_weigh.png" mode="widthFix"></image></view><view class="eqName">{{ item.name }}</view></view><view class="status"><view v-if="isLink[index]==0" class="ft-color-999999"></view><view v-if="isLink[index]==1" class="ft-color-999999">连接中...</view><view v-if="isLink[index]==2" class="ft-color-007FFF">已连接</view><view v-if="isLink[index]==3" class="ft-color-999999">连接失败</view><view v-if="isLink[index]==4" class="ft-color-999999">已断开</view><view v-if="isLink[index]==2" @click.stop="closeBLEConnection(item.deviceId,index)"class="ft-color-green iconfont icon-info m-lt20 ft-40 ft-color-999999"> 断开连接</view></view></view></view><view style="display: flex;"><button @click="startBluetoothDevicesDiscovery" class="foot-btn-g">搜索周围设备</button></view><!-- <button type="default" @click="readBLECharacteristicValue">获取</button> --></view>
</template>
<script>export default {data() {return {isSearch: false,bluetooth: [],isLink: [],// 调试数据serverList: [],characteristics: [],readCode: '',readCodeMsg: '',serviceId: '',characteristicId: '',value: '0102',returnMessage: '',macAddress: "",macValue: '', //获取的重量}},onShow() {this.getBlueInfo()},methods: {// 监听蓝牙设备连接状态listenerConnection() {console.log('监听蓝牙设备连接状态')let _this = this;plus.bluetooth.onBLEConnectionStateChange(function(e) {console.log('connection state changed: ' + JSON.stringify(e));_this.deviceId = e.deviceId;_this.createBLEConnection(_this.deviceId)});},// 蓝牙手机初始化getBlueInfo() {console.log('getBlueInfo')const _this = thisplus.bluetooth.openBluetoothAdapter({success(res) {console.log(JSON.stringify(res))_this.startBluetoothDevicesDiscovery()},fail(err) {console.log('fail', err)uni.showToast({title: '未检测到蓝牙',icon: 'none'})}});},// 搜索周围蓝牙设备startBluetoothDevicesDiscovery() {console.log('开始搜索蓝牙设备')const _this = thisthis.isSearch = truethis.bluetooth = []this.searchNoNameBluetooths = []plus.bluetooth.startBluetoothDevicesDiscovery({// services:['FE7D','FFF0'],//可选 要获取设备的uuid列表success(res) {console.log(JSON.stringify(res))plus.bluetooth.onBluetoothDeviceFound(res => {console.log(JSON.stringify(res))_this.getBluetoothDevices();})},fail(err) {console.log('错误信息', JSON.stringify(err))uni.showToast({title: '蓝牙未初始化',icon: 'none',duration: 2000});}})},// 停止搜索stopBluetoothDevicesDiscovery() {plus.bluetooth.stopBluetoothDevicesDiscovery({success: e => {console.log('停止搜索蓝牙设备:' + e.errMsg);},fail: e => {console.log('停止搜索蓝牙设备失败,错误码:' + e.errCode);}});},// 获取已发现的蓝牙设备getBluetoothDevices() {console.log('获取已发现的蓝牙设备')const _this = thisplus.bluetooth.getBluetoothDevices({success(res) {// console.log(' 获取已发现的蓝牙设备',res)// _this.stopBluetoothDevicesDiscovery()_this.bluetooth = res.devices.filter(item => {return item.name})_this.isLink = []_this.bluetooth.forEach(e => {_this.isLink.push(0)})}})},// 获取蓝牙适配器状态getBluetoothAdapterState() {plus.bluetooth.getBluetoothAdapterState({success(res) {console.log('获取蓝牙适配器状态', res)}})},// 连接蓝牙createBLEConnection(deviceId, index) {console.log('连接蓝牙', deviceId, index)const _this = thisthis.deviceId = deviceId;if (this.isLink[index] == 2) {return;}this.isLink.splice(index, 1, 1)plus.bluetooth.createBLEConnection({deviceId: _this.deviceId,success: res => {console.log(res)_this.isLink.splice(index, 1, 2)_this.stopBluetoothDevicesDiscovery();_this.getBLEDeviceServices(_this.deviceId);uni.showLoading({title: '连接中...',mask: true});},fail: res => {if (res.message == 'already connect') {_this.isLink[index] = 2;_this.stopBluetoothDevicesDiscovery();_this.getBLEDeviceServices(_this.deviceId);} else {_this.isLink.splice(index, 1, 3)}console.log(JSON.stringify(res))}})},//获取蓝牙设备所有服务(service)。getBLEDeviceServices(deviceId) {const _this = thisconsole.log(deviceId)setTimeout(() => {plus.bluetooth.getBLEDeviceServices({// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接deviceId: deviceId,success: (res) => {console.log('获取蓝牙设备所有服务:', JSON.stringify(res.services))_this.serverList = res.servicesvar findItem = res.services.find(item => {//FE7D FFF0if (item.uuid != '00001800-0000-1000-8000-00805F9B34FB' && item.uuid != '00001801-0000-1000-8000-00805F9B34FB' &&item.uuid != '0000180A-0000-1000-8000-00805F9B34FB') {return item;}})console.log(JSON.stringify(findItem))_this.serviceId = findItem.uuid;_this.getBLEDeviceCharacteristics(_this.deviceId)},fail: res => {console.log(res)}})}, 4000)},// 获取蓝牙特征值getBLEDeviceCharacteristics(deviceId) {console.log("进入特征");const _this = thissetTimeout(() => {plus.bluetooth.getBLEDeviceCharacteristics({// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接deviceId: deviceId,// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取serviceId: this.serviceId,success: (res) => {_this.characteristics = res.characteristicsconsole.log('characteristics', JSON.stringify(_this.characteristics))let findItem = res.characteristics.find(item => {let uuid = item.uuidconsole.log(uuid)return item.properties.notify})_this.characteristicId = findItem.uuid;console.log('当前使用的特征characteristicId:', _this.characteristicId)_this.notifyBLECharacteristicValueChange(_this.deviceId)let bluetoothData = {deviceId: _this.deviceId,serviceId: _this.serviceId,characteristicId: _this.characteristicId}uni.setStorageSync('bluetoothData', bluetoothData)uni.hideLoading();},fail: (res) => {uni.hideLoading();console.log(res)}})}, 4000)},// 启用 notify 功能notifyBLECharacteristicValueChange(deviceId) {const _this = this;plus.bluetooth.notifyBLECharacteristicValueChange({state: true, // 启用 notify 功能// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接deviceId: deviceId,// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取serviceId: _this.serviceId,// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取characteristicId: _this.characteristicId,success: (res) => {_this.$api.msg('连接成功', 'success')},fail: (res) => {_this.$api.msg('连接失败')}})},ab2hex(buffer) {const hexArr = Array.prototype.map.call(new Uint8Array(buffer),function(bit) {return ('00' + bit.toString(16)).slice(-2)})return hexArr.join('')},//十六进制转字符串,调整高低位hexCharCodeToStr(hexCharCodeStr) {let trimedStr = hexCharCodeStr.trim();let rawStr =trimedStr.substr(0, 2).toLowerCase() === "0x" ?trimedStr.substr(2) :trimedStr;let len = rawStr.length;if (len % 2 !== 0) {alert("Illegal Format ASCII Code!");return "";}let curCharCode;let resultStr = [];for (let i = 0; i < len; i = i + 2) {curCharCode = parseInt(rawStr.substr(i, 2), 16); // ASCII Code ValueresultStr.unshift(String.fromCharCode(curCharCode));}return Math.round(parseFloat(resultStr.join("")) * 100) / 100;},// 监听低功耗蓝牙设备的特征值变化onBLECharacteristicValueChange(deviceId) {const _this = this;plus.bluetooth.onBLECharacteristicValueChange((res) => {_this.macAddress = res.deviceId;let val = _this.ab2hex(res.value);let resValue = _this.hexCharCodeToStr(val)_this.macValue = resValueconsole.log(resValue + '千克')})},// 读取设备二进制数据readBLECharacteristicValue() {let _this = this;plus.bluetooth.readBLECharacteristicValue({// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接deviceId: _this.deviceId,// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取serviceId: _this.serviceId,// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取characteristicId: _this.characteristicId,success: (res) => {console.log('readBLECharacteristicValue:', res)this.readCode = res.errCode;this.readCodeMsg = res.errMsg;this.onBLECharacteristicValueChange(this.deviceId);},fail: (res) => {console.log('readBLECharacteristicValue:', res)this.readCode = res.errCode;this.readCodeMsg = res.errMsg;this.onBLECharacteristicValueChange(this.deviceId);}})},// 写入低功耗蓝牙设备的特征值writeBLECharacteristicValue(value) {const _this = this;console.log('写入低功耗蓝牙设备的特征值')// const data = new Uint8Array(_this.write.qp).buffer;//2let codeLength = value.length / 2;let buffer = new ArrayBuffer(codeLength)const dataView = new DataView(buffer)let data = [];//在这里解析将要写入的值  for (let i = 0; i < codeLength; i++) {dataView.setUint8(i, '0X' + value.substring(i * 2, i * 2 + 2));data.push(value.substring(2 * i, 2 * i + 2))}plus.bluetooth.writeBLECharacteristicValue({deviceId: _this.deviceId,serviceId: _this.serviceId,characteristicId: _this.characteristicId,value: buffer,success: function(e) {console.log('发送成功', data.join(','))console.log('write characteristics success: ' + JSON.stringify(e));},fail: function(e) {console.log('write characteristics failed: ' + JSON.stringify(e));}});},//断开蓝牙连接closeBLEConnection(deviceId, index) {const _this = thisplus.bluetooth.closeBLEConnection({deviceId: deviceId,success: res => {console.log('断开蓝牙连接')_this.isLink.splice(index, 1, 4)}})},}}
</script><style scoped lang="scss">.ul {margin: 10px;.li {display: flex;justify-content: space-between;background: #FFFFFF;margin-top: 13upx;align-items: center;font-size: 30upx;border-radius: 20upx;height: 160upx;padding-left: 43upx;.li-left {display: flex;.blueImg {width: 77upx;height: 74upx;margin-right: 40upx;image {width: 100%;height: 100%;}}.eqName {color: #000000;font-size: 30upx;width: 250upx;word-break: break-all;display: flex;align-items: center;}}.status {display: flex;view {margin-right: 48upx;}}}}.search {width: 358upx;height: 70upx;border-radius: 35upx;border: 1px solid #5CA3F9;margin-top: 131upx;color: #5CA3F9;font-size: 24upx;line-height: 70upx;text-align: center;}.foot-btn-g {color: #007FFF;margin-top: 80upx;}.ft-color-999999 {color: #999999;}.ft-color-007FFF {color: #007FFF;}
</style>

http://www.ppmy.cn/news/162307.html

相关文章

计算机机箱的dvd结构,天天都在用电脑,你知道电脑主机的组成结构吗?

原标题&#xff1a;天天都在用电脑&#xff0c;你知道电脑主机的组成结构吗&#xff1f; 电脑主机通常包括 CPU、内存、硬盘、光驱、电源、以及其他输入输出控制器和接口。如 USB 控制器、显卡、网卡、声卡等等。 中央处理器(CPU&#xff0c;Central Processing Unit)是一块超大…

计算机主机包括寄存器吗,计算机主机包括什么

大家好&#xff0c;我是时间财富网智能客服时间君&#xff0c;上述问题将由我为大家进行解答。 计算机主机包括CPU、内存、 硬盘、 光驱、 电源、以及其他输入输出控制器和接口。 中央处理器(Central Processing Unit)&#xff0c;简称CPU&#xff0c;是1971年推出的一个计算机…

3分钟手写TCP连接池,并基于Socket通信模拟康宝和桐哥的微信在线聊天

文章目录 TCP连接池客户端服务端 TCP连接池 设计 用ConcurrentHashMap<Integer, Socket>作为连接池声明连接池的数量、端口和ip、TCP连接的状态&#xff08;boolean数组&#xff09;初始化连接池使用Socket只需要找到状态是未连接的即可使用之后将此时连接状态设为未连…

前端里最帅的2016年终总结

年底了&#xff0c;我奋战到最后一刻&#xff0c;虽说我很帅&#xff0c;但是 免不了俗。 人人都写各种年终总结&#xff0c;年终告白&#xff0c;虽说大部分人是在应付公司&#xff08;我不揭穿你们额&#xff09;&#xff0c;但如果是自己真心实意的想写&#xff0c;确实是有…

【HMS Core】运动健康服务发起授权失败

【问题描述】 集成运动健康服务&#xff0c;按照官方文档Demo发起授权&#xff0c;提示授权失败&#xff0c;错误码{"mData":{"mExtras":{"mMap":{"HEALTHKIT_AUTH_RESULT":"{\"status\":{\"statusCode\":1…

什么是康宝光驱

COMBO在英文里的意思是“结合物”&#xff0c;而康宝&#xff08;COMBO&#xff09;驱动器就是把CD—RW刻录机和DVD光驱结合在一起的“复合型一体化”驱动器。简单的说&#xff0c; COMBO就是集CD—ROM、DVD—ROM、CD-RW三位一体的一种光存储设备。 康宝光驱的倡导者&#xff…

pc机

PC (personal computer)&#xff0c;个人 计算机一词源自于1981年 IBM的第一部桌上型 计算机型号 PC&#xff0c;在此之前有 Apple II的个人用计算机。能独立运行、完成特定功能的个人计算机。个人计算机不需要 共享其他计算机的处理、 磁盘和打印机等资源也可以独立工作。今天…

为什么刻盘显示计算机内存不够,dvd刻录机在刻录时显示内存不足需终结cd怎么办...

肯定是你没刻录进去 1、不要超容量刻,特别是DVD+-R和CD-R,因为一旦刻出问题,DVD+-R和CD-R盘的特性将导致刻在其上的数据无法擦除,该盘就只能作废处理,所以即使是与刻录机同品牌的盘也最好不要超容量刻。如要关闭NERO中的超容量刻功能,运行NERO BURNING ROM,点"文件…