最近做的微信小程序要调用手机自带的4.0蓝牙发送、接收数据

4.0蓝牙又叫BLE,整理了下,蓝牙连接要经过如下步骤:

  1. 初始化蓝牙
  2. 检查蓝牙是否初始化成功
  3. 开始搜索附近蓝牙设备
  4. 显示扫描得到的蓝牙
  5. 选择连接特定MAC地址的蓝牙设备
  6. 连接成功后,获取service ID
  7. 然后获取characteristic ID
  8. write/read data

*每个步骤对应的操作在js代码中有注释

我遇到的坑:一定要启用notify功能,否则只能发送,无法接收数据!!!

index.json为空,只上传了index.wxml,index.wxss,index.js三个文件,源码如下

index.wxml

<!--pages/mine/mine.wxml-->
<view class="container"><view class="section">       <!-- 第一行 --><view class="content"><text>蓝牙开关</text></view><view class="switch"><switch checked="{{isbluetoothready}}" bindchange="open_BLE" /></view></view><view class="section">        <!-- 第二行 --><button type="default" size="{{primarySize}}" loading="{{searchingstatus}}" plain="{{plain}}" disabled="{{disabled}}" bindtap="search_BLE"> {{searchingstatus?"搜索中":"搜索蓝牙"}} </button></view><block wx:for="{{list}}">     <!-- 第三行 --><view class="section" style="flex-direction:row" ><view><text>{{index}}:\n </text><text>设备名称:  {{item.name}}\n</text><text>MAC地址:   {{item.deviceId}}</text></view><view class="connection"><button id="{{item.deviceId}}" size="mini"bindtap="connectTO"> {{deviceconnected?"已连接":"连接"}} </button></view></view>
</block> <block wx:if="{{deviceconnected}}">    <!-- 第四行 --><view ><text>\n\n数据接收\n</text><text>{{receive_data}}\n</text><!-- <button size="mini" bindtap="receiveMessages">接收</button> --></view><view class="send"><form bindsubmit="formSubmit"><text>\n\n数据发送:</text><input name="senddata"/><button size="mini" formType="submit">发送</button><button size="mini" formType="reset">清空</button></form></view>
</block></view>

index.wxss

view {display: inline-block;
}.container {padding: 0;margin: 0;align-items: flex-start;
}.section {display: inline-block;width: 100%;margin-top: 50rpx;position: relative;
}.connection {margin-left: 90rpx;
}.list {margin-left: 20rpx;
}.content {margin-left: 100rpx;padding: auto;position: absolute;top: 5rpx;left: 10rpx;
}.switch {position: relative;float: right;margin-right: 100rpx;
}button {background: red\;
}.list-item {margin-top: 20rpx;margin-bottom: 20rpx; display: flex;flex-direction: column;box-sizing: border-box;border: 1px dashed #000;
}.list-item text {margin-top: 10rpx;
}.list-item button {margin-right: 10rpx;
}.deviceconnected{background-color:sandybrown
}.recieve{width: 100%
}.recieve_textarea{width: 100%;margin-top: 10dpx;
}input{display: block;border: 1px dashed;width: 200px;
}

index.js

var app = getApp()
var temp = []
var string_temp=""
var serviceId = "0000ffe0-0000-1000-8000-00805f9b34fb"
var characteristicId = "0000ffe1-0000-1000-8000-00805f9b34fb"Page({data: {isbluetoothready: false,defaultSize: 'default',primarySize: 'default',warnSize: 'default',disabled: false,plain: false,loading: false,searchingstatus: false,receivedata: '666',onreceiving: false,id_text: string_temp,list: [],receive_data:'none  '},onLoad: function () {},open_BLE: function () {var that = thisthat.setData({isbluetoothready: !that.data.isbluetoothready,})if (that.data.isbluetoothready) {//开启蓝牙模块并初始化wx.openBluetoothAdapter({success: function (res) {},fail: function (res) {wx.showModal({title: '提示',content: '请检查手机蓝牙是否打开',})}})//开启蓝牙模块并初始化//检查蓝牙模块是否初始化成功wx.getBluetoothAdapterState({success: function (res) {var available = res.availableif (!available) {wx.showToast({title: '蓝牙初始化失败',icon: 'loading',duration: 2000})}else {wx.showToast({title: '蓝牙初始化成功',icon: 'success',duration: 2000})}}})//检查蓝牙模块是否初始化成功}else{wx.closeBLEConnection({deviceId: that.data.connectedDeviceId,complete: function (res) {that.setData({deviceconnected: false,connectedDeviceId: ""})wx.showToast({title: '蓝牙连接断开',icon: 'success',duration: 2000})}})setTimeout(function () {that.setData({list: []})//释放蓝牙适配器wx.closeBluetoothAdapter({success: function (res) {that.setData({isbluetoothready: false,deviceconnected: false,devices: [],searchingstatus: false,receivedata: ''})wx.showToast({title: '蓝牙适配器释放',icon: 'success',duration: 2000})},fail: function (res) {}})//释放蓝牙适配器}, 1000)}},search_BLE: function () {temp = []var that = thisif (!that.data.searchingstatus) {var that = this//开始搜索附近蓝牙设备wx.startBluetoothDevicesDiscovery({success: function (res) {wx.showToast({title: '开始搜索BLE',icon: 'loading',duration: 2000})that.setData({searchingstatus: !that.data.searchingstatus})}})//开始搜索附近蓝牙设备} else {//停止搜索附近蓝牙设备wx.stopBluetoothDevicesDiscovery({success: function (res) {wx.showToast({title: '停止搜索BLE',icon: 'success',duration: 2000})that.setData({searchingstatus: !that.data.searchingstatus})}})//停止搜索附近蓝牙设备setTimeout(function () {//获取发现的蓝牙设备wx.getBluetoothDevices({success: function (res) {for(var i=0;i<100;i++){if (res.devices[i]) {string_temp = string_temp + '\n' + res.devices[i].deviceId}}that.setData({id_text: string_temp,list: res.devices})}})//获取发现的蓝牙设备}, 1000)}},connectTO: function (e) {var that = thiswx.showLoading({title: '连接蓝牙设备中...',})wx.createBLEConnection({deviceId: e.currentTarget.id,success: function (res) {wx.hideLoading()wx.showToast({title: '连接成功',icon: 'success',duration: 1000})that.setData({deviceconnected: true,connectedDeviceId: e.currentTarget.id})// 启用 notify 功能wx.notifyBLECharacteristicValueChanged({state: true, deviceId: that.data.connectedDeviceId,serviceId: serviceId,characteristicId: characteristicId,success: function (res) {}})// 启用 notify 功能// ArrayBuffer转为16进制数function ab2hex(buffer) {var hexArr = Array.prototype.map.call(new Uint8Array(buffer),function (bit) {return ('00' + bit.toString(16)).slice(-2)})return hexArr.join('');}// 16进制数转ASCLL码function hexCharCodeToStr(hexCharCodeStr) {var trimedStr = hexCharCodeStr.trim();var rawStr = trimedStr.substr(0, 2).toLowerCase() === "0x" ? trimedStr.substr(2) : trimedStr;var len = rawStr.length;var curCharCode;var resultStr = [];for (var i = 0; i < len; i = i + 2) {curCharCode = parseInt(rawStr.substr(i, 2), 16);resultStr.push(String.fromCharCode(curCharCode));}return resultStr.join("");}//监听回调,接收数据wx.onBLECharacteristicValueChange(function (characteristic) {var hex = ab2hex(characteristic.value)that.setData({receive_data: hexCharCodeToStr(hex)})})},fail: function (res) {wx.hideLoading()wx.showToast({title: '连接设备失败',icon: 'success',duration: 1000})that.setData({connected: false})}})wx.stopBluetoothDevicesDiscovery({success: function (res) {}})},formSubmit: function (e) {var senddata = e.detail.value.senddata;var that = thislet buffer = new ArrayBuffer(senddata.length)let dataView = new DataView(buffer)for (var i = 0; i < senddata.length; i++) {dataView.setUint8(i, senddata.charAt(i).charCodeAt())}wx.writeBLECharacteristicValue({deviceId: that.data.connectedDeviceId,serviceId: serviceId,characteristicId: characteristicId,value: buffer,success: function (res) {wx.showToast({title: '发送成功',icon: 'success',duration: 2000})}})},receiveMessages: function () {var that = this;wx.readBLECharacteristicValue({deviceId: that.data.connectedDeviceId,serviceId: serviceId,characteristicId: characteristicId,success: function (res) {}})},})

微信小程序调用Android手机蓝牙BLE传输数据相关推荐

  1. 微信小程序调用安卓手机系统指纹实现登录功能

    index.js 中添加以下代码: Page({data: {hasLogin: false},onLoad: function () {const _this = thiswx.checkIsSup ...

  2. 微信小程序调用地图和跟据经纬度打开手机地图导航

    微信小程序调用地图和跟据经纬度打开手机地图导航 第一步:输入地址位置 wxml<button bindtap="onChooseLocation">打开地图</b ...

  3. 微信小程序调用小票打印机实现打印订单

    随着微信小程序的出现,微信已经完全占据了我们的生活,智能化互联网时代的到来,带给我们的便利我想不用说大家都是深有体会,随着小程序的火爆,随之带动着用户对打印的需求,那么,微信小程序是如何对接打印机的呢 ...

  4. 微信小程序调用相册和相机

    首先来写好wxml部分:给一个图片列表(img_list)和上传图片的按钮(addimg) <view class="container"><view class ...

  5. 老板提了个需求:微信小程序调用支付宝支付!然后群里炸锅了

    大前天,我们头戴菊花手拿红包的小编同学在社群里发出了灵魂提问: (声明一下:小编同学只是在我这里兼职运营社群,人家正经工作还是产品狗.所以这个老板不是我) 这个问题简单说,就是在微信小程序里调用支付宝 ...

  6. 微信小程序调用php,微信小程序调用PHP后台接口 解析纯html文本

    微信小程序调用php后台接口,解析纯html文本,效果图片预览 1.微信js动态传参: wx.request({ url: 'https://m.****.com/index.php/home/xia ...

  7. 微信小程序:升级版手机检测微信工具小程序源码

    这是一款升级版检测工具 自动检测手机真伪,序列号等等 另外还可以给手机检测各项功能是否正常 由于能检测的项目太多,所以大家到时候自行研究吧 小编就不多做介绍 另外支持多做流量主模式,比如激励视频,ba ...

  8. 微信小程序调用支付接口支付(tp5、小程序)

    微信小程序调用支付接口支付 今天记录一下学习的小程序调用微信支付接口 一.先理清一下调起微信支付的整个流程. 1.就是先调用微信的支付统一下单api获取到prepay_id 2.然后后端再将这个pre ...

  9. 微信小程序调用指纹验证

    微信小程序调用指纹验证共有三个相关的接口 1.wx.checkIsSupportSoterAuthentication() 获取本机支持的 SOTER 生物认证方式 wx.checkIsSupport ...

  10. uniapp微信小程序怎样获取宽高?获取系统信息?微信小程序 获取用户手机屏幕高度与宽度信息等

    第一种方案(推荐) "vw" = "view width" "vh" = "view height" 使用 CSS3 引 ...

最新文章

  1. 用js 判断datagrid 中的 checkbox 是否被选中
  2. shiro配置参考(一)
  3. 浅谈 DML、DDL、DCL的区别
  4. 多重if,嵌套if和switch case如何区别使用
  5. Linux下的零拷贝
  6. 校招需要看的书 巩固的知识
  7. MD5算法原理与常用实现
  8. 未定义函数或变量_变量提升:JavaScript是顺序执行,为什么变量在定义之前执行不会报错而是报Underfined...
  9. Win10磁盘分区工具-无损分区助手
  10. ffmpeg教程 php推流,详解NODEJS基于FFMPEG视频推流测试
  11. 小赛毛游C记——初识C语言(3)
  12. python模拟鼠标拖动滑块_py+selenium拼图式拖动滑块的验证
  13. MySQL 临时目录
  14. Windows操作系统基础
  15. 读书笔记: 经济学原理
  16. http status状态码,readyState状态码
  17. 戴尔 服务器重装后蓝屏,dell笔记本不能重装系统,一直进入蓝屏界面?
  18. Zynq-7000系列之linux开发学习笔记:编译Linux内核和制作设备树(六)
  19. Day1 Java读取二进制文件
  20. StarUML画类图步骤

热门文章

  1. Windows安装jupyter教程
  2. css实现3D动画效果——正方体变六边形
  3. winform的RichTextBox设置网格线,类似word的稿纸效果
  4. 笔试必备,行测图形推理
  5. Diskpart 删除OEM分区方法,set id=07 override 无效处理方法
  6. 飞秋下载 官方唯一的下载地址
  7. javaswing,JAVA中国象棋网上对弈
  8. [[城市]普及]支付网关,什么是支付网关,第三方支付模式
  9. 嵌入式软件开发需要学习的知识点
  10. 个人重装系统前备份___1000款最杰出的软件清单: