// 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.id
bluetooth.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 = array
resolve(array)
}
})
})
} // 获取蓝牙适配器的状态
_getBluetoothState() {
const that = this
wx.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.在需要使用的页面中调用

promise封装小程序的蓝牙类的更多相关文章

  1. promise封装小程序的请求类(request,清爽易懂)

    话不多说直接上代码,清爽易懂: import { config } from '../config.js' const tips = { 1:'抱歉出现了一个错误', 2:'网络错误', 1005:' ...

  2. 超简单 Promise封装小程序ajax 超好用 以及封装登录

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

  3. 小程序-promise封装小程序的请求方法

    // 在utils-->base.js中,封装一个Base类,有一个axios方法 class Base{ constructor(){ } axios(method,url,data){ co ...

  4. 微信小程序开发-蓝牙功能开发

    0. 前言 这两天刚好了解了一下微信小程序的蓝牙功能.主要用于配网功能.发现微信的小程序蓝牙API已经封装的很好了.编程起来很方便.什么蓝牙知识都不懂的情况下,不到两天就晚上数据的收发了,剩下的就是数 ...

  5. 微信小程序调用蓝牙功能控制车位锁

    第一次学用微信小程序,项目需要,被逼着研究了一下,功能是调用微信小程序的蓝牙功能,连接上智能车位锁,控制升降,大概步骤及调用的小程序接口API如下: 1.打开蓝牙模块 wx.openBluetooth ...

  6. 微信小程序之蓝牙开发(详细读数据、写数据、附源码)

    本文将详细介绍微信小程序的蓝牙开发流程(附源码)准备:微信只支持低功耗蓝牙也就是蓝牙4.0,普通的蓝牙模块是用不了的,一定要注意. 蓝牙可以连TTL接到电脑上,再用XCOM调试 一开始定义的变量 va ...

  7. 微信小程序退款 处理类

    <?php /** * 微信小程序退款 处理类参考https://www.cnblogs.com/afei-qwerty/p/7922982.html * */ class WeixinRefu ...

  8. 基于promise对小程序http请求方法封装

    原因是我不想每次请求都复制粘贴那么长的请求地址,所以我把前边那一坨请求地址作为基础地址,只传后台给的路由就ok,而且,并不是每次请求都要显示正在加载,这对小程序体验很差,所以,我加了个形参,用来判断是 ...

  9. 微信小程序初探【类微信UI聊天简单实现】

    微信小程序最近很火,火到什么程度,只要你一打开微信,就是它的身影,几乎你用的各个APP都可以在微信中找到它的复制版,另外官方自带的跳一跳更是将它推到了空前至高的位置.对比公众号,就我的感觉来说,有以下 ...

随机推荐

  1. FFMPEG实现H264的解码(从源代码角度)

    农历2014年底了,将前段时间工作中研究的FFMPEG解码H264流程在此做一下整理,也算作年终技术总结了! H264解码原理: H264的原理参考另一篇博文 http://blog.csdn.net ...

  2. POJ2774Long Long Message (后缀数组&后缀自动机)

    问题: The little cat is majoring in physics in the capital of Byterland. A piece of sad news comes to ...

  3. CSS禁止鼠标事件---pointer-events:none

    pointer-events:none顾名思意,就是鼠标事件拜拜的意思.元素应用了该CSS属性,链接啊,点击啊什么的都变成了“浮云牌酱油”.

  4. C++STL库中vector容器常用应用

    #include<iostream> #include<vector> #include<algorithm> using namespace std; int m ...

  5. JVM类加载(2)—连接

    2.连接 连接就是将已经加载到内存中的类的二进制数据合并到Java虚拟机的运行时环境中去,加载阶段尚未完成,连接阶段可能已经开始.连接阶段包含验证.准备.解析过程. 2.1.验证 验证.class文件 ...

  6. Ajax前端调后台方法

    后台对当前页面类进行注册 Ajax.Utility.RegisterTypeForAjax(typeof(Login));//Login 当前类名 在方法上面加 [Ajax.AjaxMethod(Aj ...

  7. event.keyCode 事件属性

    转自:http://www.runoob.com/jsref/event-key-keycode.html <!DOCTYPE html> <html> <head> ...

  8. 又来一波!Android精品源码分享

    今天又汇总了几个不错的源码给大家!希望能帮到需要的小伙伴~话不多少,直接上源码! 1.Android精品源码:拖动条控件实现源码 此次分享的源码是一个不错的Android控件,建议大家可以细致的看下. ...

  9. Tiny4412学习杂记

    1.Android 挂载NFS 使用 busybox mount 来替代mount命令 2.修改Uboot中fastboot最大buff  使用U-boot烧写Android5.0的时候出现 remo ...

  10. CF1042E Vasya and Magic Matrix

    感觉不会期望. 首先把所有格子按照权值从小到大排一下序,这样一共有$n * m$个元素,每个元素有三个属性$x, y, val$. 下文中的下标均为排序后的下标. 这样子我们就可以推出公式: $f_i ...