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>

uniapp html5+ plus蓝牙连接电子秤相关推荐

  1. Uni-App使用低功耗蓝牙连接血压仪测量

    1.Uni-APP蓝牙使用流程 在阅读这篇内容之前,建议您详细浏览一遍uni-app官方关于蓝牙和低功耗蓝牙(BLE)使用教程文档 uni-app官方低功耗蓝牙接口,如果您有微信小程序方面的开发经验, ...

  2. uniapp 蓝牙连接测温仪

    需求:app通过蓝牙连接硬件测温仪,使用uniapp的ble蓝牙连接 一.连接蓝牙流程 打开蓝牙 → 搜索蓝牙 → 蓝牙连接 → 停止搜索 → 获取蓝牙设备的uuid → 获取蓝牙特性 → 监听接收数 ...

  3. DCloud UniAPP Android 蓝牙连接ESCPOS打印机

    1.蓝牙打印引用文件 btprinter.js import context from "@/common/context.js" //上下文处理 用来保存绑定的蓝牙设备地址fun ...

  4. uniapp蓝牙连接热敏打印机

    uniapp蓝牙连接热敏打印机 需求:通过小程序连接蓝牙,打印指定内容 前提:根据打印机的品牌型号不同,所遵循的打印规范不同(具体询问卖家) 我使用的是佳博的tspl规范 准备:需要几个外部js(具体 ...

  5. android 蓝牙串口自动断开,uni-app 蓝牙连接被自动断开问题

    遍历 快速对两个蓝牙设备(deviceId,mac地址不同)进行连接操作,时间隔为1秒,蓝牙刚进行连接,监听蓝牙连接状态,直接监听到被自动断开,而且断开两次,有知道怎么回事的不?ios ,androi ...

  6. uniapp APP实现通过蓝牙连接打印机打印

    蓝牙连接德佟打印机打印 1.导入插件: 在插件市场中搜索LPAPI,进入之后,点击右侧的"购买for云打包",选择目标项目,按照提示操作即可: 2. 配置插件: 用HBuilder ...

  7. 【uniapp】支付宝小程序蓝牙绑定步骤兼容ios蓝牙连接,并报 10017 写入特征值失败解决方案

    1.问题:安卓手机写入数据的时候一直报10017 写入特征值失败 2.解决方案 安卓手机需要设置低功耗蓝牙设备的最大传输单元my.setBLEMTU 必须在连接完蓝牙my.connectBLEDevi ...

  8. JavaSE + bluecove 蓝牙连接

    最近公司准备将旧系统的.NET部分翻版,项目除了有后台的还有个与设备对接的客户端用蓝牙连接的,所有这周对相关技术做了一个验证. 搜了一下Java 蓝牙相关信息,我去资料也太少了,少也就算了连bluec ...

  9. 在HbuilderX中实现微信小程序下蓝牙连接打印机完整实战案例

    1.基础开发环境,所用到的 Api 以及实现的思路. 应用场景: 商家打印小票,小票包含顾客消费的商品明细信息以及末尾附上二维码,二维码供顾客扫码开票. HbuilderX开发工具: HBuilder ...

最新文章

  1. iBATIS之父:iBATIS框架的成功蜕变
  2. N-LTP:基于预训练模型的中文自然语言处理平台
  3. DFT实训教程笔记3(bibili版本)-SOC Scan Implementtation Scan Practice Session II
  4. c语言存储结构体,c语言结构体的保存和导入
  5. 南通大学16级软嵌班软件工程课程成绩汇总
  6. Mongodb和redis书籍调研
  7. 白硕 | 基于区块链的众包社区激励机制
  8. KMP算法的核心,是一个被称为部分匹配表(Partial Match Table)的数组以及next数组求解
  9. idea java mapper.xml文件sql黄色背景解决
  10. HTTP缓存原理及相关知识(2)-CDN
  11. 张莉python 玩转数据答案_中国大学MOOC(慕课)用Python玩转数据答案大全
  12. 人工智能、区块链、算法...这30个大数据热词你知道吗?
  13. [LeetCode] Reverse Linked List 倒置链表
  14. 通过css和html构建能耗数据分析树状图
  15. 征服 Apache + SSL
  16. watch gt3 鸿蒙,华为matepad pro2和watchGT3系列即将发布!
  17. 牛客网-腾讯编程校招真题 编码 Java
  18. 神经网络理论及应用答案,神经网络理论名词解释
  19. 水平集LevelSet 分割图像
  20. 计算并输出sin(x)、cos(x)、|x|、ex、xy的值

热门文章

  1. [VB.NET源码]销售管理系统
  2. 基于ADS的功分、耦合器的设计
  3. 农行上海研发中心面经
  4. 2011年的赢家和输家
  5. 张钜楷;3.25黄金、原油、磅日、美加、澳美,外汇,今日行情分析及解套
  6. 获国际权威认可 | 云扩科技入选《RPA全球市场格局报告,Q3 2022》
  7. Linux的电源管理-休眠与唤醒
  8. java date只保存年月日_java date 只保留年月日
  9. 关于 电脑分配IP地址可以连接局域网但无法上互联网 的解决方法
  10. 智慧水务,水务自动化无线监控方案