首页 微信小程序 小程序开发 微信小程序之蓝牙链接实例教程

微信小程序之蓝牙链接实例教程

Feb 06, 2018 am 09:03 AM
实例 小程序 教程

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

微信小程序之蓝牙的链接

微信小程序蓝牙连接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中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

得物使用教程 得物使用教程 Mar 21, 2024 pm 01:40 PM

得物APP是当前十分火爆品牌购物的软件,但是多数的用户不知道得物APP中功能如何的使用,下方会整理最详细的使用教程攻略,接下来就是小编为用户带来的得物多功能使用教程汇总,感兴趣的用户快来一起看看吧!得物使用教程【2024-03-20】得物分期购怎么使用【2024-03-20】得物优惠券怎么获得【2024-03-20】得物人工客服怎么找【2024-03-20】得物取件码怎么查看【2024-03-20】得物求购在哪里看【2024-03-20】得物vip怎么开【2024-03-20】得物怎么申请退换货

夏天,一定要试试拍摄彩虹 夏天,一定要试试拍摄彩虹 Jul 21, 2024 pm 05:16 PM

夏天雨后,经常能见到一种美丽且神奇的特殊天气景象——彩虹。这也是摄影中可遇而不可求的难得景象,非常出片。彩虹出现有这样几个条件:一是空气中有充足的水滴,二是太阳以较低的角度进行照射。所以下午雨过天晴后的一段时间内,是最容易看到彩虹的时候。不过彩虹的形成受天气、光线等条件的影响较大,因此一般只会持续一小段时间,而最佳观赏、拍摄时间更为短暂。那么遇到彩虹,怎样才能合理将其记录下来并拍出质感呢?1.寻找彩虹除了上面提到的条件外,彩虹通常出现在阳光照射的方向,即如果太阳由西向东照射,彩虹更有可能出现在东

微信关收款声音的步骤教程 微信关收款声音的步骤教程 Mar 26, 2024 am 08:30 AM

1、首先打开微信。2、点击右上角【+】。3、点击二维码收款。4、点击右上角三个小点。5、点击关闭收款到账语音提醒。

DisplayX(显示器测试软件)使用教程 DisplayX(显示器测试软件)使用教程 Mar 04, 2024 pm 04:00 PM

在购买显示器的时候对其进行测试是必不可少的一环,能够避免买到有损坏的,今天小编教大家来使用软件对显示器进行测试。方法步骤1.首先要在本站搜索下载DisplayX这款软件,安装打开,会看到提供给用户很多种检测方法。2.用户点击常规完全测试,首先是测试显示器的亮度,用户调节显示器使得方框都能看得清。3.之后点击鼠标即可进入下一环节,如果显示器能够分清每个黑色白色区域那说明显示器还是不错的。4.再次单击鼠标左键,会看到显示器的灰度测试,颜色过渡越平滑表示显示器越好。5.另外在displayx软件中我们

photoshopcs5是什么软件?-photoshopcs5使用教程 photoshopcs5是什么软件?-photoshopcs5使用教程 Mar 19, 2024 am 09:04 AM

PhotoshopCS是PhotoshopCreativeSuite的缩写,由Adobe公司出品的软件,被广泛用于平面设计和图像处理,作为新手学习PS,今天就让小编为您解答一下photoshopcs5是什么软件以及photoshopcs5使用教程。一、photoshopcs5是什么软件AdobePhotoshopCS5Extended是电影、视频和多媒体领域的专业人士,使用3D和动画的图形和Web设计人员,以及工程和科学领域的专业人士的理想选择。呈现3D图像并将它合并到2D复合图像中。轻松编辑视

专家教你!华为手机截长图的正确方法 专家教你!华为手机截长图的正确方法 Mar 22, 2024 pm 12:21 PM

随着智能手机的不断发展,手机的功能也变得越来越强大,其中截长图功能成为了许多用户日常使用的重要功能之一。截长图可以帮助用户将一个较长的网页、对话记录或者图片一次性保存下来,方便查阅和分享。而在众多手机品牌中,华为手机也是备受用户推崇的一款品牌之一,其截长图功能也备受好评。本文将为大家介绍华为手机截长图的正确方法,以及一些专家技巧,帮助大家更好地利用华为手机的

PHP教程:如何将int类型转换为字符串 PHP教程:如何将int类型转换为字符串 Mar 27, 2024 pm 06:03 PM

PHP教程:如何将int类型转换为字符串在PHP中,将整型数据转换为字符串是一种常见的操作。本教程将介绍如何使用PHP内置的函数将int类型转换为字符串,同时提供具体的代码示例。使用强制类型转换:在PHP中,可以使用强制类型转换的方式将整型数据转换为字符串。这种方法非常简单,只需要在整型数据前加上(string)即可将其转换为字符串。下面是一个简单的示例代码

荣耀手机鸿蒙系统升级教程 荣耀手机鸿蒙系统升级教程 Mar 23, 2024 pm 12:45 PM

荣耀手机一直以来都备受消费者青睐,其出色的性能和稳定的系统让人爱不释手。而近日,荣耀手机发布了全新的鸿蒙系统,引起了众多用户的关注和期待。鸿蒙系统被称为“一统天下”的系统,具有更加流畅的操作体验和更高的安全性,让用户体验到全新的智能手机世界。不少用户纷纷表示想要升级自己的荣耀手机系统为鸿蒙系统,那么,接下来我们就一起来看看荣耀手机鸿蒙系统的升级教程。首先,我

See all articles