// pages/bluetooth/bluetooth.js
import { BluetoothMode } from '../../models/bluetooth.js'
import {System} from '../../models/system.js'
const bluetooth = new BluetoothMode()
const system = new System()
Page({/*** 页面的初始数据*/data: {devicesData: [],sys: {}},/*** 生命周期函数--监听页面加载*/onLoad: function (options) {const res=system.getSync()this.setData({sys:res})},// 点击连接蓝牙设备connectionBluetooth: function (e) {const deviceId = e.currentTarget.dataset.idbluetooth.connect(deviceId).then(res => {wx.setStorageSync('serviceData', res)// 停止搜索 减少资源
      bluetooth.stop()wx.navigateTo({url: '../device/device?name=' + e.currentTarget.dataset.name,})})},// 扫描设备
  startBluetooth() {this._initBluetooth()},//初始化蓝牙适配器_initBluetooth: function () {// 调用蓝牙子类的初始化事件bluetooth.initBluetooth().then(res => {// 监听发现新的设备bluetooth.on('newDevice',data => {this.setData({devicesData:data})})})},})

1.继上一篇文章中的观察者模式

import {PublishtionModel
} from 'publishtion.js'const tips = {0: '正常',10000: '未初始化蓝牙适配器',10001: '当前蓝牙适配器不可用,请打开手机蓝牙后重试',10002: '没有找到指定设备',10003: '连接失败',10004: '没有找到指定服务',10005: '没有找到指定特征值',10006: '当前连接已断开',10007: '当前特征值不支持此操作',10008: '其余所有系统上报的异常',10009: 'Android 系统特有,系统版本低于 4.3 不支持 BLE',10012: '连接超时',10013: '连接 deviceId 为空或者是格式不正确',20000: '蓝牙适配器不可用,蓝牙可能被关闭',
}class BluetoothMode extends PublishtionModel {//获取搜索到的蓝牙设备data = []//初始化蓝牙适配器
  initBluetooth() {return new Promise((resolve, reject) => {this._initBluetooth().then(res => {this._getBluetoothState()return this._search()}).then(res => {// 开启监听 this._onDFound()resolve(res)})})}_initBluetooth() {return new Promise((resolve, reject) => {wx.openBluetoothAdapter({success: res => {console.log(res)console.log('初始化蓝牙模块成功')resolve()},fail: error => {console.log(error)this._showTips(error.errCode)}})})}// 连接低功耗蓝牙
  connection(deviceId) {return new Promise((resolve, reject) => {wx.createBLEConnection({deviceId,success: res => {console.log(res)this._setDevice(deviceId)// 暂停搜索this.stop()resolve({res,deviceId})},fail: res => {console.log(res)}})})}connect(deviceId) {return new Promise((resolve, reject) => {this.connection(deviceId).then(res => {return this.getServiceList(res.deviceId)}).then(res => {let promiseList = []for (var i in res.services) {promiseList.push(this.getBLEDeviveChar({deviceId,serviceId: res.services[i].uuid}))}return Promise.all(promiseList)}).then(res => {resolve(res)})})}// 启用低功耗蓝牙设备特征值变化时的 notify 功能,订阅特征值。// 注意:必须设备的特征值支持 notify 或者 indicate 才可以成功调用。
  notify({deviceId,serviceId,characteristicId}) {return new Promise((resolve, reject) => {wx.notifyBLECharacteristicValueChange({state: true, // 启用 notify 功能// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
        deviceId,// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
        serviceId,// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
        characteristicId,success(res) {resolve(res)console.log('notifyBLECharacteristicValueChange success', res.errMsg)}})})}// 获取服务列表
  getServiceList(deviceId) {return new Promise((resolve, reject) => {wx.getBLEDeviceServices({// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
        deviceId,success(res) {console.log('device services:', res.services)resolve({services: res.services,deviceId})}})})}// 获取蓝牙设备某个服务中所有特征值 getBLEDeviceCharacteristics
  getBLEDeviveChar({deviceId,serviceId}) {return new Promise((resolve, reject) => {wx.getBLEDeviceCharacteristics({// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
        deviceId,// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
        serviceId,success(res) {resolve(res)console.log('device getBLEDeviceCharacteristics:', res.characteristics)}})})}// 断开与低功耗蓝牙设备的连接。
  closeConnection() {wx.closeBLEConnection({deviceId,success(res) {console.log(res)}})}//向低功耗蓝牙设备特征值中写入二进制数据。
  write({deviceId,serviceId,characteristicId,value}) {//传入String 返回 ArrayBuffer类型let abf = this.__hexStringToArrayBuffer(value)return new Promise((resolve, reject) => {wx.writeBLECharacteristicValue({// 这里的 deviceId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
        deviceId,// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
        serviceId,// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
        characteristicId,// 这里的value是ArrayBuffer类型
        value: abf,success(res) {resolve(res)console.log('writeBLECharacteristicValue success', res.errMsg)}})})}// 停止搜寻附近的蓝牙外围设备
  stop() {return new Promise((resolve, reject) => {wx.stopBluetoothDevicesDiscovery({success(res) {console.log(res)resolve(res)}})})}// 关闭蓝牙适配器
  close() {wx.closeBluetoothAdapter()}// 获取设备Id
  getDevice() {return wx.getStorageSync('deviceId')}// 开启蓝牙搜索
  _search() {wx.showLoading({title: '正在扫描中...',})return new Promise((resolve, reject) => {wx.startBluetoothDevicesDiscovery({success: res => {console.log(res)resolve(res)},fail: err => {console.log(err)},complete: res => {setTimeout(() => {wx.hideLoading()}, 2000)}})})}//返回ArrayBuffe
  _hexStringToArrayBuffer(str) {if (!str) {return new ArrayBuffer(0);}var buffer = new ArrayBuffer(str.length);let dataView = new DataView(buffer)let ind = 0;for (var i = 0, len = str.length; i < len; i += 2) {let code = parseInt(str.substr(i, 2), 16)dataView.setUint8(ind, code)ind++}return buffer;}// 开启监听获取到新的设备
  _onDFound() {wx.onBluetoothDeviceFound(devices =>{this._getDevices().then(res=>{// console.log(this)this.publish(this.data,'newDevice')})// console.dir(devices)
    })}// 获取寻找的所有设备
  _getDevices() {return new Promise((resolve, reject) => {wx.getBluetoothDevices({success: res => {// console.log(res)let array = []for (var x in res.devices) {if (res.devices[x].name != '未知设备') {res.devices[x].advertisData = this._ab2hex(res.devices[x].advertisData)array.push(res.devices[x])}}// console.log(array)this.data = arrayresolve(array)}})})}// 获取蓝牙适配器的状态
  _getBluetoothState() {const that = thiswx.onBluetoothAdapterStateChange(res => {console.log(res)if (res.available) {console.log('蓝牙模块可用')} else {wx.showModal({title: '提示',content: '蓝牙已被关闭',showCancel: false,success(res) {if (res.confirm) {console.log('用户点击确定')} else if (res.cancel) {console.log('用户点击取消')}}})this._showTips(20000)console.log('蓝牙模块不可用')}if (res.discovering) {console.log('蓝牙适配器处于搜索状态')} else {console.log('蓝牙适配器不处于搜索状态')}})}// ArrayBuffer转16进度字符串示例
  _ab2hex(buffer) {var hexArr = Array.prototype.map.call(new Uint8Array(buffer),function(bit) {return ('00' + bit.toString(16)).slice(-2)})return hexArr.join('');}// 错误提示
  _showTips(code) {code && wx.showToast({title: tips[code],icon: 'none'})}// 储存设备Id
  _setDevice(id) {wx.setStorageSync('deviceId', id)}}export {BluetoothMode
}

2.在需要使用的页面中调用

转载于:https://www.cnblogs.com/likewpp/p/11038685.html

promise封装小程序的蓝牙类相关推荐

  1. 小程序公共封装ajax,超简单 Promise封装小程序ajax 超好用 以及封装登录

    //网络类 //封装网络请求 const ajax = (ajaxData, method) => { wx.showLoading({ title: '加载中', mask: true }); ...

  2. promise封装小程序api请求

    在项目中我们使用请求 需要通过api封装 为什么封装api 因为在项目中 请求使用的地方会有很多 不利于后期维护 如果我我们讲api封装出来 只需要维护api文件就可以了 这里以uniapp封装api ...

  3. 详解小程序的蓝牙模块

    刚刚结束了一个项目,其中用到了小程序的蓝牙模块,当时也是遇到了很多的问题,这里就说下其中遇到的一些问题和坑 1 流程 首先是开启蓝牙模块, uni.openBluetoothAdapter({ suc ...

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

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

  5. 蓝牙打印机PHP代码,小程序调用蓝牙打印机完整代码

    [实例简介] 此代码为小程序调用蓝牙打印机完整代码,有蓝牙打印机的情况下可直接扫码进行真机调试 [实例截图] [核心代码] miniprogram-bluetoothprinter-master └─ ...

  6. 支付宝/钉钉小程序实现蓝牙打印

    本文主要是钉钉小程序通过蓝牙进行打印,当然钉钉和支付宝都是相同的.打印机设备佳博M-322便携式打印机,打印效果图在文末 使用到的接口请参照钉钉开发文档 1.连接蓝牙打印机的js Page({data ...

  7. 微信小程序使用蓝牙连接设备流程

    微信小程序使用蓝牙连接设备流程 小程序使用蓝牙连接设备介绍 使用到的api 流程: 初始化蓝牙模块 wx.openBluetoothAdapter wx.openBluetoothAdapter({ ...

  8. 开源一个基于微信小程序的蓝牙室内定位软件(附下载链接)

    文章目录 1. 运行环境要求 2. 软件功能及程序说明 2.1 软件组成 2.2 主要功能 2.3 文件及函数功能说明 3. 软件设计及操作说明 4. 完整版代码获取 1. 运行环境要求 软件运行环境 ...

  9. 微信小程序电商源码:外卖小程序,电商小程序,门店类小程序,展示类小程序,批发商城小程序、分销小程序。

    介绍: 1.naicha 2.xianhua 3.xingbake 4.zhubaoxiao 5.zhubaoxiao 6.majiangshangcheng 7.jiafang 8.huazhuan ...

最新文章

  1. 麻省理工正式宣布人工智能独立设系!人工智能与电子工程、计算机科学系将三分天下...
  2. 15 个 JavaScript Web UI 库 (转)
  3. [昨花今拾]补记昨日
  4. 为什么“ npm install”会重写package-lock.json?
  5. 蓝桥杯---等差数列(C语言)
  6. AI 工程师:他们是做什么的,以及他们值多少钱?
  7. L2TP OVER IPSEC原理详解
  8. CentOS7.6上搭建阿里云OSS的C SDK
  9. 11.高性能MySQL --- 可扩展MySQL
  10. Java中String类型,int类型,double类型相互转换
  11. 饥荒指令代码大全一览
  12. Java8新特性之方法引用
  13. 响应式布局基础知识详解
  14. 二维泊松方程求解--点迭代法
  15. cmd中怎么打开计算机,如何打开命令行窗口?电脑打开cmd命令行窗口5大方法详解...
  16. Redis入门指南之复制
  17. OSM地图瓦片下载器1.0版介绍(win64)
  18. 分布式服务架构的设计方案上—分布式基础理论知识
  19. 笔记本出厂预装Win8改装Win7的操作步骤及常见问题___联想e430c之类可供参考
  20. IFS系统功能清单之七——人力资源(Human Resources)

热门文章

  1. 在CygWin中设置proxy
  2. 数据仓库知识与实战——电信运营商数仓建模
  3. 好评度前五的扫地机器人
  4. 该如何管理我们的知识?
  5. python基础_026__标准库和第三方库
  6. 线性回归梯度下降py实现
  7. SQL删除数据库表中重复的数据
  8. 什么是BFC?BFC的功能及其使用?
  9. apache-Tomcat 8.5.39安装包 安装过程以及启动文件详解
  10. 技术分享 | Goby IP库初探