GVKun编程网logo

微信小程序之蓝牙链接实例教程(微信小程序蓝牙设备接入教程)

9

对于想了解微信小程序之蓝牙链接实例教程的读者,本文将提供新的信息,我们将详细介绍微信小程序蓝牙设备接入教程,并且为您提供关于[微信小程序之小白教程系列]微信小程序--入口、[微信小程序之小白教程系列]

对于想了解微信小程序之蓝牙链接实例教程的读者,本文将提供新的信息,我们将详细介绍微信小程序蓝牙设备接入教程,并且为您提供关于[微信小程序之小白教程系列] 微信小程序 -- 入口、[微信小程序之小白教程系列] 微信小程序 -- 样式(WXSS)、小程序之蓝牙的使用、微信小程序 蓝牙的实现实例代码的有价值信息。

本文目录一览:

微信小程序之蓝牙链接实例教程(微信小程序蓝牙设备接入教程)

微信小程序之蓝牙链接实例教程(微信小程序蓝牙设备接入教程)

本文主要和大家介绍微信小程序之蓝牙的链接的相关资料,希望通过本文大家能够掌握小程序蓝牙的开发方法,需要的朋友可以参考下,希望能帮助到大家。

微信小程序之蓝牙的链接

微信小程序蓝牙连接2.0说明:

1、本版本区分了ANDROID和IOS系统下蓝牙连接的不同方式。

2、兼容了更多情况下的链接包括:

(1)未开启设备蓝牙,当监听到开启了蓝牙后自动开始连接。
(2)初始化蓝牙失败后每3000ms自动重新初始化蓝牙适配器。
(3)安卓端开启蓝牙适配器扫描失败,每3000ms自动重新开启。
(4)IOS端获取已连接蓝牙设备为空,每3000ms自动重新获取。
(5)安卓端蓝牙开始链接后中断扫描,连接失败了,重新开始扫描。
(6)IOS端开始连接设备后,停止获取已连接设备,连接失败自动重新开启获取。
(7)连接成功后,关闭系统蓝牙,蓝牙适配器重置。
(8)连接成功后,关闭系统蓝牙,再次打开蓝牙,自动重新开始连接。
(9)连接成功后,关闭目标蓝牙设备,自动重新开始扫描(获取)。
(10)连接成功后,最小化小程序(连接未中断),打开小程序显示已连接。
(11)连接成功后,杀掉小程序进程,连接关闭,自动重新开始扫描(获取)。

3、想起来了再来更新....。

4、流程图,明天或后天或...谁有空帮我画一下也行。

我的连接是在App.js中做的。

在App.js中的onLaunch触发是调用 init()方法。

init代码:


init: function (n) {
  this.list = [];
  this.serviceId = "6E400001-B5A3-F393-E0A9-E50E24DCCA9E";
  this.serviceId_2 = "00001803-0000-1000-8000-00805F9B34FB";
  this.serviceId_3 = "00001814-0000-1000-8000-00805F9B34FB";
  this.serviceId_4 = "00001802-0000-1000-8000-00805F9B34FB";
  this.serviceId_5 = "00001804-0000-1000-8000-00805F9B34FB";
  this.serviceId_6 = "00001535-1212-EFDE-1523-785FEABCD123";
  this.characterId_write = "6E400042-B5A3-F393-E0A9-E50E24DCCA9E";
  this.characterId_read = "6E400012-B5A3-F393-E0A9-E50E24DCCA9E";
  this.connectDeviceIndex = 0;
  this.isGettingConnected = false;
  this.isDiscovering = false;
  this.isConnecting = false;
  this.connectedDevice = {};
  console.log('init state', this.connectedDevice.state);
  if (!this.connectedDevice.state || n == 200) {
   this.connectedDevice.state = false;
   this.connectedDevice.deviceId = '';
   this.adapterHasInit = false
  }
  this.startConnect();
 }
登录后复制

说明:

1、 serviceId_2~6 是我已知的想要连接的蓝牙设备的serviceId可以只写一个。
2、characterId_write 是我已知的想要连接的蓝牙设备写入数据的特征值。
3、characterId_read是我已知的想要连接的蓝牙设备读取数据的特征值。
(以上3个都是为了做比对,真实的操作按照获取到的sericeid, characterid为准)。
4、connectedDevice 是已连接了的设备信息对象。

init完成后开始调用连接 startConnect();

startConnect代码:


startConnect: function () {
  var that = this;
  if (that.connectedDevice.state) return;
  that.connectedDevice.deviceId = "";
  that.connectedDevice.state = false;
  // 如果适配器已经初始化不在调用初始化(重复初始化会报错)
  if (this.adapterHasInit == undefined || this.adapterHasInit) return;
  wx.showLoading({
   title: '初始化蓝牙',
   duration: 2000
  });
  // 开启蓝牙适配器状态监听
  this.listenAdapterStateChange();
  // 初始化蓝牙适配器状态(必须步骤,否则无法进行后续的任何操作)
  wx.openBluetoothAdapter({
   success: function (res) {
    console.log("初始化蓝牙适配器成功");
    that.getBluetoothAdapterState();
    that.adapterHasInit = true;
   },
   fail: function (err) {
    console.log(err);
    wx.showLoading({
     title: '请开蓝牙',
     icon: 'loading',
     duration: 2000
    })
   }
  });
 }
登录后复制

说明:这段有注释,就不多说了,比较简单。

在初始化蓝牙适配器状态成功后调用getBluetoothAdapterState()方法。

getBluetoothAdapterState代码:


getBluetoothAdapterState: function () {
  var that = this;
  wx.getBluetoothAdapterState({
   success: function (res) {
    console.log(res);
    var available = res.available;
    that.isDiscovering = res.discovering;
    if (!available) {
     wx.showLoading({
      title: '请开蓝牙',
      icon: 'loading',
      duration: 2000
     })
    } else {
     if (!that.connectedDevice['state']) {
      that.judegIfDiscovering(res.discovering);
     }
    }
   },
   fail: function (err) {
    console.log(err);
   }
  })
 }
登录后复制

说明:此方法是用来获取当前蓝牙状态。

当检测到蓝牙可用时调用judegIfDiscovering方法。

judegIfDiscovering代码


judegIfDiscovering: function (discovering) {
  var that = this;
  if (this.isConnectinng) return;
  wx.getConnectedBluetoothDevices({
   services: [that.serviceId],
   success: function (res) {
    console.log("获取处于连接状态的设备", res);
    var devices = res['devices'];
    if (devices[0]) {
     if (that.isAndroidPlatform) {
      wx.showToast({
       title: '蓝牙连接成功',
       icon: 'success',
       duration: 2000
      });
     } else {
      that.getConnectedBluetoothDevices(256);
     }
    } else {
     if (discovering) {
      wx.showLoading({
       title: '蓝牙搜索中'
      })
     } else {
      if (that.isAndroidPlatform) {
       that.startBluetoothDevicesDiscovery();
      } else {
       that.getConnectedBluetoothDevices(267);
      }
     }
    }
   },
   fail: function (err) {
    console.log('getConnectedBluetoothDevices err 264', err);
    if (that.isAndroidPlatform) {
     that.startBluetoothDevicesDiscovery();
    } else {
     that.getConnectedBluetoothDevices(277);
    }
   }
  });
 }
登录后复制

说明:

1、此方法是用来判断是否正在扫描。

2、isAndroidPlatform 是通过小程序的getSystemInfo获取到的判断是安卓设备还是IOS设备。

如果是安卓设备调用startBluetoothDevicesDiscovery()开启扫描,如果是IOS设备调用getConnectedBluetoothDevices() 开启获取已配对的蓝牙设备。

startBluetoothDevicesDiscovery代码:


startBluetoothDevicesDiscovery: function () {
  var that = this;
  if (!this.isAndroidPlatform) return;
  if (!this.connectedDevice['state']) {
   wx.getBluetoothAdapterState({
    success: function (res) {
     console.log(res);
     var available = res.available;
     that.isDiscovering = res.discovering;
     if (!available) {
      wx.showLoading({
       title: '请开蓝牙',
       icon: 'loading',
       duration: 2000
      })
     } else {
      if (res.discovering) {
       wx.showLoading({
        title: '蓝牙搜索中'
       })
      } else {
       wx.startBluetoothDevicesDiscovery({
        services: [],
        allowDuplicatesKey: true,
        success: function (res) {
         that.onBluetoothDeviceFound();
         wx.showLoading({
          title: '蓝牙搜索中'
         })
        },
        fail: function (err) {
         if (err.isDiscovering) {
          wx.showLoading({
           title: '蓝牙搜索中'
          })
         } else {
          that.startDiscoveryTimer = setTimeout(function () {
           if (!that.connectedDevice.state) {
            that.startBluetoothDevicesDiscovery();
           }
          }, 5000)
         }
        }
       });
      }
     }
    },
    fail: function (err) {
     console.log(err);
    }
   })
  }
登录后复制

说明:

1、仅在安卓端设备上开启扫描附近蓝牙设备。

2、在开启成功的回调中开启发现新蓝牙设备的事件监听onBluetoothDeviceFound()。

onBluetoothDeviceFound代码:


[mw_shl_code=javascript,true]onBluetoothDeviceFound: function () {
  var that = this;
  wx.onBluetoothDeviceFound(function (res) {
   console.log('new device list has founded');
   if (res.devices[0]) {
    var name = res.devices[0]['name'];
    if (name.indexOf('FeiZhi') != -1) {
     var deviceId = res.devices[0]['deviceId'];
     console.log(deviceId);
     that.deviceId = deviceId;
     if (!that.isConnecting) {
      that.startConnectDevices();
     }
    }
   }
  })
 }
登录后复制

说明:

1、此处对已发现的蓝牙设备根据name属性进行了过滤。

2、当筛选出含有需要连接的设备的name属性的设备是获取到deviceId,开始连接调用startConnectDevices()方法。

startConnectDevices代码:


startConnectDevices: function (ltype, array) {
  var that = this;
  clearTimeout(this.getConnectedTimer);
  clearTimeout(this.startDiscoveryTimer);
  this.getConnectedTimer = null;
  this.startDiscoveryTimer = null;
  this.isConnectinng = true;
  wx.showLoading({
   title: '正在连接'
  });
  that.stopBluetoothDevicesDiscovery();
  wx.createBLEConnection({
   deviceId: that.deviceId,
   success: function (res) {
    console.log('连接成功', res);
    wx.showLoading({
     title: '正在连接'
    });
    that.connectedDevice.state = true;
    that.connectedDevice.deviceId = that.deviceId;
    if (res.errCode == 0) {
     setTimeout(function () {
      that.getService(that.deviceId);
     }, 5000)
    }
    wx.onBLEConnectionStateChange(function (res) {
     console.log('连接变化', res);
     that.connectedDevice.state = res.connected;
     that.connectedDevice.deviceId = res.deviceId;
     if (!res.connected) {
      that.init('200');
     }
    });
   },
   fail: function (err) {
    console.log('连接失败:', err);
    wx.hideLoading();
    if (ltype == 'loop') {
     array = array.splice(0, 1);
     console.log(array);
     that.loopConnect(array);
    } else {
     if (that.isAndroidPlatform) {
      that.startBluetoothDevicesDiscovery();
     } else {
      that.getConnectedBluetoothDevices(488);
     }
    }
   },
   complete: function () {
    that.isConnectinng = false;
   }
  });
 }
登录后复制

说明:

1、开启连接后终止扫描(获取已配对)方法。
2、根据deviceId创建低功耗蓝牙连接。如果连接成功,就继续做后续读写操作。
3、如果连接失败根据设备系统分别调用startBluetoothDevicesDiscovery() 或 getConnectedBluetoothDevices();

getConnectedBluetoothDevices代码:


getConnectedBluetoothDevices: function (n) {
  var that = this;
  that.isGettingConnected = true;
  wx.showLoading({
   title: '蓝牙搜索中'
  });
  wx.getConnectedBluetoothDevices({
   services: [that.serviceId],
   success: function (res) {
    console.log("获取处于连接状态的设备", res);
    var devices = res['devices'],
     flag = false,
     index = 0,
     conDevList = [];
    devices.forEach(function (value, index, array) {
     if (value['name'].indexOf('FeiZhi') != -1) {
      // 如果存在包含FeiZhi字段的设备
      flag = true;
      index += 1;
      conDevList.push(value['deviceId']);
      that.deviceId = value['deviceId'];
     }
    });
    if (flag) {
     that.connectDeviceIndex = 0;
     that.loopConnect(conDevList);
    } else {
     that.failToGetConnected();
    }
   },
   fail: function (err) {
    that.failToGetConnected();
   },
   complete: function () {
    that.isGettingConnected = false;
   }
  });
 }
登录后复制

说明:如果获取蓝牙已配对的蓝牙设备失败了,或获取到的列表为空调用failToGetConnected();

failToGetConnected代码:


failToGetConnected: function () {
  var that = this;
  if (!that.getConnectedTimer) {
   clearTimeout(that.getConnectedTimer);
   that.getConnectedTimer = null;
  }
  that.getConnectedTimer = setTimeout(function () {
   wx.getBluetoothAdapterState({
    success: function (res) {
     console.log(res);
     var available = res.available;
     if (!available) {
      wx.showLoading({
       title: '请开蓝牙',
       icon: 'loading',
       duration: 2000
      })
     } else {
      if (!that.connectedDevice['state']) {
       that.getConnectedBluetoothDevices();
      }
     }
    },
    fail: function (err) {
     console.log(err);
    }
   })
  }, 5000);
 }
登录后复制

说明:

1、该方法调用成功后返回的devices是一个数组包含多个已经系统配对的蓝牙设备。
2、如果devices列表获取到调用loopConnect()方法开始递归调用连接蓝牙设备。

loopConnect代码:


loopConnect: function (array) {
  var that = this;
  var listLen = array.length;
  if (array[0]) {
   that.deviceId = array[0];
   if (!that.isConnecting) {
    that.startConnectDevices('loop', array);
   }
  } else {
   console.log('已配对的设备小程序蓝牙连接失败');
   if (!that.isAndroidPlatform) {
    that.getConnectedBluetoothDevices(431);
   }
  }
 }
登录后复制

说明:looConnect在创建连接的方法连接失败后会操作删除数组的第一个值,然后继续调用该方法,直到其中所有的设备都连接过。

差点漏了:在app.js的onShow里调用init()方法。

特别说明:

1、安卓和IOS的蓝牙连接在当前版本中推荐采用不同方式。安卓设备直接使用小程序的蓝牙连接,取消系统配对。IOS设备先系统配对在打开小程序可以时效秒连接成功。

2、此版本的连接仍然有待完善,连接不会自动终止(需要的可以自己加),会无限扫描重连,直到成功。

3、链接成功后的操作如果写入数据和开启notify需要同时进行,建议先写入,后开启notify。(原因未知,否则必然出现10008错误)。

相关推荐:

微信小程序蓝牙设备代码与错误整理

微信小程序如何实现蓝牙的实例分享

微信小程序--Ble蓝牙

以上就是微信小程序之蓝牙链接实例教程的详细内容,更多请关注php中文网其它相关文章!

[微信小程序之小白教程系列] 微信小程序 -- 入口

[微信小程序之小白教程系列] 微信小程序 -- 入口

作为一名后端开发人员,我希望能从后端语言的某些模式来理解小程序,让我快速的入门。

今天我们依然模拟一个女项目经理和后端工程师的博弈,为你逐步展开小程序的面纱。

角色定位

  • 女一号 大樱桃:女项目经理,30岁,未婚。
  • 男一号 老沙:帅气的后端工程师,30岁,已婚。

alt

App

当听到大樱桃这样说自己的时候,老沙明白的确是自己的问题,小程序工具为我们生成了一个基础的框架,但是这个框架里的文件都是做什么用,每个文件如何去操作他并不知道,这的确是一个问题。

于是老沙决定用30分钟的时候先研究下其中的 app.js / app.json / app.wxss / project.config.json

app.js

从微信小程序官方文档我们知道:“小程序包含一个描述整体程序的 app 和多个描述各自页面的 page。”,而app的构建、维护以及配置就是由上面4个文件管理的。

@@nai8@@

当我们打开一个小程序的时候,伴随着生成一个小程序的实例,这个很像yii中入口对application的生成逻辑。

同时提供了一个叫做App()的函数用来接收小程序实例完成最后的注册,这个函数存在于app.js中,而所谓的注册,里面可以包含我们自己的逻辑,比如启动后你想做什么?遇到错误你想做什么,这些都可以在注册小程序的时候实现。

打开你的app.js,你发现有4+个函数,4个内置函数和你可以自己定义的N个函数。

alt

名词解释

  • onLanuch 当小程序初始化完成时,会触发 onLaunch(全局只触发一次)
  • onShow 当小程序启动,或从后台进入前台显示,会触发 onShow
  • onHide 当小程序从前台进入后台,会触发 onHide
  • onError 当小程序发生脚本错误,或者 api 调用失败时,会触发 onError 并带上错误信息

这里有一个疑问我想大家也会遇到,就是前后台的概念,简单的说就是当你在左上角关闭小程序后(或按home键退出微信),这个小程序并不会真正的销毁而是进入后台模式运行,当再次打开进入前台运行而非重新启动。

最明显的一个现象就是你在小程序某个特定页面关闭小程序,再次打开会直接进入这个特定页面而非启动页。

globalData
这个字段也很有用。用来存放一些全局的东西,比如统一的远程接口地址等,这里设置的值是有办法在其他page页面使用的。

比如某个小程序的globalData如下图

alt

N个函数

我们都知道除了内置的函数,我们也可以在app.js里写其他函数,那么问题来了?什么函数要写到app.js里那?

回答这个问题之前我们要先知道一个事情,那就是在小程序的其他页面可以通过getApp函数获取到app对象,进而可以调用app.js里的东西,也就是说你在app.js里定义的那些N个函数可以被其他页面获取并使用。

这样你明白了吧?比如登录函数、获取用户信息、弹出框等用于整个app的高频函数都可以写到app.js中。

研究到此,老沙欣慰的一笑,先来杯咖啡。

alt

onLaunch

接下来老沙决定研究一下onLaunch函数,首先要说的是onLaunch的参数options里都有什么?很简单,在onLaunch函数内写下了console.log(options)将它打印到控制台。

alt

在今后的日子里,如果你不清楚一个对象或参数什么的,记住使用console.log打印到控制台,很方便。

当然,onLaunch可以获取很多参数,比如path代表打开小程序的路径,当你分享小程序某个页面A到微信群,别人通过A打开了小程序,则path就是A页面的路径。

关于参数的详细介绍可以看下图

alt

path、query、scene是常规的参数,在特定情况下会出现其他参数,比如当你要捕获群分享后的数据时shareTicket参数会出现等等。

一般来说当一个小程序启动后就需要做的事情可以写到onLaunch函数,比如登录。

而onShow接收的参数和onLanuch是一致的。

注意点

官方给了一些注意点,基本就是所有了,列下方便大家学习。

  • App() 必须在 app.js 中注册,且不能注册多个。
  • 不要在定义于 App() 内的函数中调用 getApp() ,使用 this 就可以拿到 app 实例。
  • 不要在 onLaunch 的时候调用 getCurrentPages(),此时 page 还没有生成。
  • 通过 getApp() 获取实例之后,不要私自调用生命周期函数。

对于上面的getApp你可能还不了解,接下来研究下。

getApp

这是一个函数,主要目的是在其他页面获取app实例,比如接下来的代码

alt

获取后你就可以在页面函数体内直接调用app.js的函数和数据,比如app.xxx()或app.globalData这样。

这里要重复下上面的注意事项:不要在定义于 App() 内的函数中调用 getApp()

app.json

一顿研究后,老沙对app.js已经基本了解,接下来攻克app.json这个文件。微信官方是这样说的:“app.json文件用来对微信小程序进行全局配置,决定页面文件的路径、窗口表现、设置网络超时时间、设置多 tab 等。”

接下来用老百姓的话为大家解释下:

  • 将页面注册到小程序如何配置?找app.json
  • 如何设置导航栏颜色?找app.json
  • 如何制定窗口背景颜色?找app.json
  • 如何启动下拉功能?找app.json
  • 如何设置小程序底部tab切换页面?找app.json
  • 如何设置网络超时时间?找app.json

一句话,和小程序自身相关的配置,去app.json里找。

关于app.json里的详细配合可以参考官方地址 https://mp.weixin.qq.com/debu...

app.wxss

最好理解的就是它了,上篇大家已经知道wxss是样式文件,app.wxss则是小程序的全局样式,它可以应用到所有page页面。

wxss是微信小程序自己定义的样式语言,它支持内联、导入等等。同时具有css大部分的特性,所以你可以像写css一样写它们。

关于使用方法可以参考 https://mp.weixin.qq.com/debu...

project.config.json

这是一个项目配置文件,比如项目的名字,appid等等。

如果你还不懂,可以看下开发工具的详情,那里面的设置和project.config.json是一样的,一个配置文件,一个可视化的,目的是一样的。

alt

小结

30分钟过去了,老沙基本搞明白了入口的逻辑,赶紧给大樱桃看看去。

.......

10分钟过去了

.......

老沙低着脑袋回来了,为何?下回给你说。

[微信小程序之小白教程系列] 微信小程序 -- 样式(WXSS)

[微信小程序之小白教程系列] 微信小程序 -- 样式(WXSS)

官方文档地址 https://mp.weixin.qq.com/debu...

问题来了?既然如此,我们为何还要写这篇文章?

答案只有一个,让你更快的“易懂”,换换思路,接下来的文章会对官方文档做一个段落类的解释。

为了适应广大的前端开发者,WXSS 具有 CSS 大部分特性。同时为了更适合开发微信小程序,WXSS 对 CSS 进行了扩充以及修改。与 CSS 相比,WXSS 扩展的特性有:尺寸单位和样式导入。

补充:关于扩展的特性我们下面会说,既然文档说了WXSS具有CSS 大部分特性,那么有什么不同那?

1、没有body
是的,在小程序的每一个page里是没有body属性的,不过你可以通过在wxss中对page的设置来影响整个页面的样式,比如下面的代码

page {
    background:#F8F8F8
}

诸如此类,当然你也可以设置page的xxx.json中的backgroundColor属性来影响一个page页面下拉时出现的空白区域的颜色,一般来说当你页面有下拉刷新和上拉加载功能时,往往要设置backgroundColor属性。

2、没有父子关系(现在版本已经支持了,这条过。)
在使用css的时候,我们经常让样式的层级关系和html接点的层级关系保持一致,比如你的html代码中有下面代码

<div>
    <p>
        <strong ></strong>
    </p>
</div>

我们习惯于css的写法如下

.box .content strong {}

这样写的好处是strong的样式不会去影响其他地方的strong。但是在小程序中并不支持这种父子的层级关系。你只能一个一个的设置,看下面的小程序代码

<view>
    <text></text>
</view>

针对于上面的视图,对应的wxss应该如何写那?看下面代码

// 正确的
.box {}
.box-txt {}

// 错误的
.box .box-txt {}

这样说你明白了吧?!

3、尺寸的变化
在css中我们有很多衡量尺寸的单位,比如px、em等等,当然这些在小程序中也依然可以使用,但是小程序又为自己增加了一个单位,那就是rpx

小程序作为移动端的应用需要适配不同规格的设备并且兼容越来越大的手机(话说我依然喜欢iphone5的尺寸,单手可控而且床上看电影不会砸到头)。

所以rpx最重要的特性就是可以根据屏幕宽度进行自适应。它规定屏幕宽为750rpx。如在 iPhone6 上,屏幕宽度为375px,共有750个物理像素,则750rpx = 375px = 750物理像素,1rpx = 0.5px = 1物理像素。

算明白了么?官方给了一个表格,很浅显易懂,见下图。

alt

这个换算比较简单,不在讲解,如果你真不懂可以留言。

4、样式导入
小程序的wxss支持样式的导入,这个功能相当有用,尤其是我们使用一些其他库的时候可以直接导入第三方的wxss文件,何其乐哉。

用法也很简单,看看下面代码。

@import "common.wxss";
.middle-p {
  padding:15px;
}

5、内联样式
和css一样,wxss支持class和style两种样式,但是在用法上还是有区别的,一句话概括:“如果你的样式中存在动态内容,将其写到style中,其他的都放到class文件,

比如这段代码

<view/>

将过多的样式写到style中带来的问题就是小程序在渲染视图的时候还要伴随着解析对应的样式布局等,必然对性能有一些影响。

6、选择器
另外对于css中的选择器,wxss基本都支持了,比如类、ID、组件等,看看下面官方给的图

alt

而且类似于last-child等css的高级属性,在wxss你也可以愉快的使用。

7、全局样式与局部样式
原则上一个在小程序中一个wxss负责一个wxml视图文件,但是对于一个应用来说总会有一些公用的属性,因此小程序为应用自身提供了一个wxss,那就是app.wxss,当然你无需人工引入,它会自动的加载到每一个视图上,这点要记住。

一点总结

关于wxss到底对css支持了哪些,微信官方并没有给出相应的文档,更多细节我们要慢慢挖掘,毕竟腾讯不是百度,会把文档写的那么好。

小程序之蓝牙的使用

小程序之蓝牙的使用

初始化蓝牙

使用蓝牙之前,首先要先初始化蓝牙(openBluetoothAdapter),之后才能调用蓝牙的各种api。初始化状态分为两种: 初始化成功:这时可以去搜索蓝牙设备(startBluetoothDevicesDiscovery)。 初始化失败:这个时候需要提示用户打开蓝牙,同时监听蓝牙的状态(onBluetoothAdapterStateChange),当蓝牙打开时,去搜索设备。

  openBluetoothAdapter() {
    const that = this
    wx.openBluetoothAdapter({
      success: (res) => {
        console.log(''openBluetoothAdapter success'', res)
        // 初始化成功,去搜索设备
        this.startBluetoothDevicesDiscovery()
      },
      fail: (res) => {
        if (res.errCode === 10001) {
          // 蓝牙未打开,监听蓝牙状态
          wx.onBluetoothAdapterStateChange(function (res) {
            console.log(''onBluetoothAdapterStateChange'', res)
            if (res.available) {
              that.startBluetoothDevicesDiscovery()
            }
          })
        }
      }
    })
  }

搜索蓝牙设备

开始搜索附近的蓝牙设备(startBluetoothDevicesDiscovery),该操作比较耗费资源,建议在连接到蓝牙设备后,手动停止搜索。

  startBluetoothDevicesDiscovery() {
    if (this._discoveryStarted) {
      return
    }
    this._discoveryStarted = true
    // 开始搜索蓝牙设备,allowDuplicatesKey,会重复搜索同一设备
    wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: true,
      success: (res) => {
        console.log(''startBluetoothDevicesDiscovery success'', res)
        this.onBluetoothDeviceFound()
      },
    })
  }

获取蓝牙设备

获取蓝牙设备有两个api。

  • onBluetoothDeviceFound:获取新发现的设备,将startBluetoothDevicesDiscovery中的allowDuplicatesKey设置为true时,该方法重复上报同一蓝牙设备。
  • getBluetoothDevices:获取已经发现的蓝牙设备列表,该方法获取的蓝牙设备数量跟搜索时间有关系,一般在开始搜索蓝牙设备后,延时一段时间在调用该方法。
  onBluetoothDeviceFound() {
    // 获取新发现的蓝牙设备
    wx.onBluetoothDeviceFound((res) => {
      res.devices.forEach(device => {
        if (!device.name && !device.localName) {
          return
        }
        const foundDevices = this.data.devices
        const idx = inArray(foundDevices, ''deviceId'', device.deviceId)
        const data = {}
        if (idx === -1) {
          data[`devices[${foundDevices.length}]`] = device
        } else {
          data[`devices[${idx}]`] = device
        }
        this.setData(data)
      })
    })
  }

连接蓝牙设备

createBLEConnection:连接蓝牙设备,基本上到这,蓝牙设备就连接上了。为了避免一个设备多个连接实例,一般和closeBLEConnection成对调用。在连接成功后,一般需要调用stopBluetoothDevicesDiscovery,停止蓝牙的搜索。

  createBLEConnection(e) {
    const ds = e.currentTarget.dataset
    const deviceId = ds.deviceId
    const name = ds.name
    // 开始连接蓝牙设备
    wx.createBLEConnection({
      deviceId,
      success: (res) => {
        this.setData({
          connected: true,
          name,
          deviceId,
        })
        this.getBLEDeviceServices(deviceId)
      }
    })
    // 在连接蓝牙设备后,停止搜索蓝牙。
    this.stopBluetoothDevicesDiscovery()
  }

停止搜索蓝牙设备

stopBluetoothDevicesDiscovery: 在蓝牙设备连接成功后,需要停止搜索蓝牙设备。

  stopBluetoothDevicesDiscovery() {
    wx.stopBluetoothDevicesDiscovery()
  }

监听蓝牙设备的连接状态

onBLEConnectionStateChange:监听蓝牙设备的连接状态,包括蓝牙设备的丢失,断开,可以在该方法中进行处理这些连接后发生的异常情况。

wx.onBLEConnectionStateChange(function (res) {
  // 该方法回调中可以用于处理连接意外断开等异常情况
  console.log(`device ${res.deviceId} state has changed, connected: ${res.connected}`)
})

获取蓝牙设备服务

在连接上蓝牙设备后,我们想要的还是跟蓝牙进行通信,或读取蓝牙设备的数据,或写数据到蓝牙设备。首先需要获取蓝牙设备的服务信息。

  getBLEDeviceServices(deviceId) {
    // 获取蓝牙设备的服务信息。
    wx.getBLEDeviceServices({
      deviceId,
      success: (res) => {
        for (let i = 0; i < res.services.length; i++) {
          if (res.services[i].isPrimary) {
            // 获取蓝牙设备的特征值
            this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid)
            return
          }
        }
      }
    })
  }

获取蓝牙设备的特征值

getBLEDeviceCharacteristics:根据蓝牙的服务信息,获取可以跟蓝牙进行通信的特征值。一般使用notify或indicate为true、read或write为true的特征值。

启用蓝牙设备的通知功能

notifyBLECharacteristicValueChange: 启用蓝牙设备的通知功能,该方法需要蓝牙设备的特征值 notify 或 indicate 为 true。只有在在蓝牙设备启用该功能,才能监听到蓝牙设备的数据变化。

获取蓝牙设备的数据

onBLECharacteristicValueChange:监听蓝牙设备的数据变化,当蓝牙设备的数据变化时,可以获取相应变化后的数据。需要在启用蓝牙设备的通知功能后才能使用。

写数据到蓝牙设备

writeBLECharacteristicValue:写数据到蓝牙设备,需要特征值的write为true

  // 获取蓝牙设备的特征值
  getBLEDeviceCharacteristics(deviceId, serviceId) {
    wx.getBLEDeviceCharacteristics({
      deviceId,
      serviceId,
      success: (res) => {
        console.log(''getBLEDeviceCharacteristics success'', res.characteristics)
        for (let i = 0; i < res.characteristics.length; i++) {
          let item = res.characteristics[i]
          if (item.properties.read) {
            // 读取蓝牙设备的数据
            wx.readBLECharacteristicValue({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
            })
          }
          if (item.properties.write) {
            this.setData({
              canWrite: true
            })
            this._deviceId = deviceId
            this._serviceId = serviceId
            this._characteristicId = item.uuid
            // 写数据到蓝牙设备
            this.writeBLECharacteristicValue()
          }
          if (item.properties.notify || item.properties.indicate) {
            // 启用蓝牙设备的通知功能,之后才能监听到蓝牙数据的变化
            wx.notifyBLECharacteristicValueChange({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
              state: true,
            })
          }
        }
      },
      fail(res) {
        console.error(''getBLEDeviceCharacteristics'', res)
      }
    })
    // 监听蓝牙设备的数据变化
    wx.onBLECharacteristicValueChange((characteristic) => {
      const idx = inArray(this.data.chs, ''uuid'', characteristic.characteristicId)
      const data = {}
      if (idx === -1) {
        data[`chs[${this.data.chs.length}]`] = {
          uuid: characteristic.characteristicId,
          value: ab2hex(characteristic.value)
        }
      } else {
        data[`chs[${idx}]`] = {
          uuid: characteristic.characteristicId,
          value: ab2hex(characteristic.value)
        }
      }
      this.setData(data)
    })
  }
  // 写数据到蓝牙设备
  writeBLECharacteristicValue() {
    // 向蓝牙设备发送一个0x00的16进制数据
    let buffer = new ArrayBuffer(1)
    let dataView = new DataView(buffer)
    dataView.setUint8(0, Math.random() * 255 | 0)
    wx.writeBLECharacteristicValue({
      deviceId: this._deviceId,
      serviceId: this._serviceId,
      characteristicId: this._characteristicId,
      value: buffer,
    })
  }

断开蓝牙设备的连接

closeBLEConnection:断开与蓝牙设备的连接

  closeBLEConnection() {
    // 断开蓝牙设备的连接
    wx.closeBLEConnection({
      deviceId: this.data.deviceId
    })
    this.setData({
      connected: false,
      chs: [],
      canWrite: false,
    })
  }

关闭蓝牙模块

closeBluetoothAdapter: 当蓝牙使用完成后,关闭蓝牙模块,释放系统资源。

// 关闭蓝牙模块
wx.closeBluetoothAdapter({
  success(res) {
    console.log(res)
  }
})

微信小程序 蓝牙的实现实例代码

微信小程序 蓝牙的实现实例代码

微信小程序 蓝牙的实现实例代码

1.简述

蓝牙适配器接口是基础库版本 1.1.0 开始支持。 iOS 微信客户端 6.5.6 版本开始支持,Android 客户端暂不支持 蓝牙总共增加了18个api接口。

2.Api分类

搜索类 连接类 通信类

3.API的具体使用

详细见官网:

https://mp.weixin.qq.com/debug/wxadoc/dev/api/bluetooth.html#wxgetconnectedbluethoothdevicesobject

4. 案例实现

4.1 搜索蓝牙设备

// const canIUse = apiName => {
// if (apiName === 'showModal.cancel') {
// return MAJOR >= 1 && MInor >= 1
// }
// return true
// }

// wx.showModal({
// success: function(res) {
// if (canIUse('showModal.cancel')) {
// console.log(res.cancel)
// }
// }
// })
//获取适配器
wx.openBluetoothAdapter({
success: function(res){
// success
console.log("-----success----------");
console.log(res);
//开始搜索
wx.startBluetoothDevicesdiscovery({
services: [],success: function(res){
// success
console.log("-----startBluetoothDevicesdiscovery--success----------");
console.log(res);
},fail: function(res) {
// fail
console.log(res);
},complete: function(res) {
// complete
console.log(res);
}
})

},fail: function(res) {
console.log("-----fail----------");
// fail
console.log(res);
},complete: function(res) {
// complete
console.log("-----complete----------");
console.log(res);
}
})

wx.getBluetoothDevices({
success: function(res){
// success
//{devices: Array[11],errMsg: "getBluetoothDevices:ok"}
console.log("getBluetoothDevices");
console.log(res);
that.setData({
list:res.devices
});
console.log(that.data.list);
},fail: function(res) {
// fail
},complete: function(res) {
// complete
}
})

},onShow:function(){

},//点击事件处理
bindViewTap: function(e) {
console.log(e.currentTarget.dataset.title);
console.log(e.currentTarget.dataset.name);
console.log(e.currentTarget.dataset.advertisData);

var title = e.currentTarget.dataset.title;
var name = e.currentTarget.dataset.name;
wx.redirectTo({
url: '../conn/conn?deviceid='+title+'&name='+name,success: function(res){
// success
},complete: function(res) {
// complete
}
})
},})

4.2连接 获取数据

rush:js;"> /** * 连接设备。获取数据 */ Page({ data: { motto: 'Hello World',userInfo: {},deviceid: '',name: '',serviceId: '',services: [],cd20: '',cd01: '',cd02: '',cd03: '',cd04: '',characteristics20: null,characteristics01: null,characteristics02: null,characteristics03: null,characteristics04: null,result,onLoad: function (opt) { var that = this; console.log("onLoad"); console.log('deviceid=' + opt.deviceid); console.log('name=' + opt.name); that.setData({ deviceid: opt.deviceid }); /** * 监听设备的连接状态 */ wx.onBLEConnectionStateChanged(function (res) { console.log(`device ${res.deviceid} state has changed,connected: ${res.connected}`) }) /** * 连接设备 */ wx.createBLEConnection({ deviceid: that.data.deviceid,success: function (res) { // success console.log(res); /** * 连接成功,后开始获取设备的服务列表 */ wx.getBLEDeviceServices({ // 这里的 deviceid 需要在上面的 getBluetoothDevices中获取 deviceid: that.data.deviceid,success: function (res) { console.log('device services:',res.services) that.setData({ services: res.services }); console.log('device services:',that.data.services[1].uuid); that.setData({ serviceId: that.data.services[1].uuid }); console.log('--------------------------------------'); console.log('device设备的id:',that.data.deviceid); console.log('device设备的服务id:',that.data.serviceId); /** * 延迟3秒,根据服务获取特征 */ setTimeout(function () { wx.getBLEDevicecharacteristics({ // 这里的 deviceid 需要在上面的 getBluetoothDevices deviceid: that.data.deviceid,// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取 serviceId: that.data.serviceId,success: function (res) { console.log('000000000000' + that.data.serviceId); console.log('device getBLEDevicecharacteristics:',res.characteristics) for (var i = 0; i < 5; i++) { if (res.characteristics[i].uuid.indexOf("cd20") != -1) { that.setData({ cd20: res.characteristics[i].uuid,characteristics20: res.characteristics[i] }); } if (res.characteristics[i].uuid.indexOf("cd01") != -1) { that.setData({ cd01: res.characteristics[i].uuid,characteristics01: res.characteristics[i] }); } if (res.characteristics[i].uuid.indexOf("cd02") != -1) { that.setData({ cd02: res.characteristics[i].uuid,characteristics02: res.characteristics[i] }); } if (res.characteristics[i].uuid.indexOf("cd03") != -1) { that.setData({ cd03: res.characteristics[i].uuid,characteristics03: res.characteristics[i] }); } if (res.characteristics[i].uuid.indexOf("cd04") != -1) { that.setData({ cd04: res.characteristics[i].uuid,characteristics04: res.characteristics[i] }); } } console.log('cd01= ' + that.data.cd01 + 'cd02= ' + that.data.cd02 + 'cd03= ' + that.data.cd03 + 'cd04= ' + that.data.cd04 + 'cd20= ' + that.data.cd20); /** * 回调获取 设备发过来的数据 */ wx.onBLECharacteristicValueChange(function (characteristic) { console.log('characteristic value comed:',characteristic.value) //{value: ArrayBuffer,deviceId: "D8:00:D2:4F:24:17",serviceId: "ba11f08c-5f14-0b0d-1080-007cbe238851-0x600000460240",characteristicId: "0000cd04-0000-1000-8000-00805f9b34fb-0x60800069fb80"} /** * 监听cd04cd04中的结果 */ if (characteristic.characteristicId.indexOf("cd01") != -1) { const result = characteristic.value; const hex = that.buf2hex(result); console.log(hex); } if (characteristic.characteristicId.indexOf("cd04") != -1) { const result = characteristic.value; const hex = that.buf2hex(result); console.log(hex); that.setData({ result: hex }); }
              })
              /**
               * 顺序开发设备特征notifiy
               */
              wx.notifyBLECharacteristicValueChanged({
                deviceId: that.data.deviceId,serviceId: that.data.serviceId,characteristicId: that.data.cd01,state: true,success: function (res) {
                  // success
                  console.log('notifyBLECharacteristicValueChanged success',res);
                },fail: function (res) {
                  // fail
                },complete: function (res) {
                  // complete
                }
              })
              wx.notifyBLECharacteristicValueChanged({
                deviceId: that.data.deviceId,characteristicId: that.data.cd02,characteristicId: that.data.cd03,complete: function (res) {
                  // complete
                }
              })

              wx.notifyBLECharacteristicValueChanged({
                // 启用 notify 功能
                // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
                deviceId: that.data.deviceId,characteristicId: that.data.cd04,success: function (res) {
                  console.log('notifyBLECharacteristicValueChanged success',res)
                }
              })

            },fail: function (res) {
              console.log(res);
            }
          })
        },1500);
      }
    })
  },fail: function (res) {
    // fail
  },complete: function (res) {
    // complete
  }
})

},/**

  • 发送 数据到设备中
    */
    bindViewTap: function () {
    var that = this;
    var hex = 'AA5504B10000B5'
    var typedArray = new Uint8Array(hex.match(/[\da-f]{2}/gi).map(function (h) {
    return parseInt(h,16)
    }))
    console.log(typedArray)
    console.log([0xAA,0x55,0x04,0xB1,0x00,0xB5])
    var buffer1 = typedArray.buffer
    console.log(buffer1)
    wx.writeBLECharacteristicValue({
    deviceId: that.data.deviceId,characteristicId: that.data.cd20,value: buffer1,success: function (res) {
    // success
    console.log("success 指令发送成功");
    console.log(res);
    },fail: function (res) {
    // fail
    console.log(res);
    },complete: function (res) {
    // complete
    }
    })

},/**

  • ArrayBuffer 转换为 Hex
    */
    buf2hex: function (buffer) { // buffer is an ArrayBuffer
    return Array.prototype.map.call(new Uint8Array(buffer),x => ('00' + x.toString(16)).slice(-2)).join('');
    }
    })

5.效果展示

发送校验指令。获取结果

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

关于微信小程序之蓝牙链接实例教程微信小程序蓝牙设备接入教程的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于[微信小程序之小白教程系列] 微信小程序 -- 入口、[微信小程序之小白教程系列] 微信小程序 -- 样式(WXSS)、小程序之蓝牙的使用、微信小程序 蓝牙的实现实例代码等相关内容,可以在本站寻找。

本文标签:

上一篇实例详解微信小程序如何使用Socket(微信小程序 socket)

下一篇微信怎么让二维码换个样式 微信更换二维码样式操作分享(如何更换微信二维码样式)