当前位置:   article > 正文

11.微信蓝牙操作_wx.getbluetoothdevices

wx.getbluetoothdevices
  1. 一.操作蓝牙适配器的共有 4 个,分别是
  2. wx.openBluetoothAdapter 初始化蓝牙适配器
  3. wx.closeBluetoothAdapter 关闭蓝牙模块
  4. wx.getBluetoothAdapterState 获取本机蓝牙适配器状态
  5. wx.onBluetoothAdapterStateChange 监听蓝牙适配器状态变化事件
  6. 二.连接前使用的共有 4 个,分别是
  7. wx.startBluetoothDevicesDiscovery 开始搜寻附近的蓝牙外围设备
  8. wx.stopBluetoothDevicesDiscovery 停止搜寻附近的蓝牙外围设备
  9. wx.getBluetoothDevices 获取所有已发现的蓝牙设备
  10. wx.onBluetoothDeviceFound 监听寻找到新设备的事件
  11. 三.连接和断开时使用的共有 2 个,分别是
  12. wx.createBLEConnection 连接低功耗蓝牙设备
  13. wx.closeBLEConnection 断开与低功耗蓝牙设备的连接
  14. 四.连接成功后使用的共有 8 个,分别是
  15. wx.getConnectedBluetoothDevices 根据 uuid 获取处于已连接状态的设备
  16. wx.getBLEDeviceServices 获取蓝牙设备所有 service(服务)
  17. wx.getBLEDeviceCharacteristics 获取蓝牙设备所有 characteristic(特征值)
  18. wx.readBLECharacteristicValue 读取低功耗蓝牙设备的特征值的二进制数据值
  19. wx.writeBLECharacteristicValue 向低功耗蓝牙设备特征值中写入二进制数据
  20. wx.notifyBLECharacteristicValueChange 启用低功耗蓝牙设备特征值变化时的 notify 功能
  21. wx.onBLECharacteristicValueChange 监听低功耗蓝牙设备的特征值变化
  22. wx.onBLEConnectionStateChange 监听低功耗蓝牙连接的错误事件
  23. wx.onBluetoothDeviceFound(监听寻找到新设备的事件 ——表示只要找到一个新的蓝牙设备就会调用一次该方法)
  24. wx.getBluetoothDevices(获取在蓝牙模块生效期间所有已发现的蓝牙设备。包括已经和本机处于连接状态的设备)
  25. 看两个方法的介绍我们知道他们的区别,但是不了解他们的区别会造成什么样的问题?
  26. 第一次我使用的是wx.onBluetoothDeviceFound方法进行联调,发现一切正常,由于调试的时候就只有一台设备,
  27. 发现第二次重新扫码这个蓝牙设备的时候,找不到这个设备了,因为对这个方法来说,这不是一个新的设备,
  28. 以前连接上过;或者当你因为某些原因蓝牙传送数据指令的时候出错了需要重新连接,再次连接的时候也找不到当前设备,
  29. 还是同样的原因,因为当前设备对这个方法来说不是一个新设备
  30. 所以后来我就用了wx.getBluetoothDevices方法
  1. // pages/bluetoothconfig/bluetoothconfig.js
  2. const util = require('../../utils/util.js')
  3. var delayTimer; //用来控制是否持续服务发现
  4. var isFound = false;
  5. Page({
  6. /**
  7. * 页面的初始数据
  8. */
  9. data: {
  10. ssid: '',
  11. pass: '',
  12. logs: [],
  13. deviceArray: [],
  14. currDeviceID: '请选择...'
  15. },
  16. onLoad: function(options) {
  17. var that = this;
  18. wx.startWifi({
  19. success(res) {
  20. console.log(res.errMsg)
  21. wx.getConnectedWifi({
  22. success: function(res) {
  23. console.log(res);
  24. that.setData({
  25. ssid: res.wifi.SSID
  26. })
  27. },
  28. fail: function(res) {
  29. if(res.errCode == 12006){
  30. wx.showModal({
  31. title: '请打开GPS定位',
  32. content: 'Android手机不打开GPS定位,无法搜索到蓝牙设备.',
  33. showCancel: false
  34. })
  35. }
  36. console.log(res);
  37. }
  38. })
  39. }
  40. })
  41. },
  42. bindPickerChange: function(ret){
  43. var array = this.data.deviceArray;
  44. console.log(array[ret.detail.value]);
  45. this.setData({
  46. currDeviceID: array[ret.detail.value]
  47. })
  48. },
  49. searchBleEvent: function(ret){
  50. var ssid = this.data.ssid;
  51. var pass = this.data.pass;
  52. console.log(ssid, pass);
  53. if (util.isEmpty(ssid) || util.isEmpty(pass)) {
  54. util.toastError('请输入WiFi名称及密码');
  55. return;
  56. }
  57. this.initBLE();
  58. },
  59. bleConfigEvent: function (ret) {
  60. var deviceID = this.data.currDeviceID;
  61. console.log("选中:" + deviceID);
  62. if (util.isEmpty(deviceID) || deviceID == "请选择..."){
  63. util.toastError("请先搜索设备");
  64. return ;
  65. }
  66. var device = deviceID.split('[');
  67. if(device.length <= 1){
  68. util.toastError("请先搜索设备");
  69. return ;
  70. }
  71. var id = device[device.length - 1].replace("]", "");
  72. console.log(id);
  73. util.toastError("连接" + id);
  74. this.createBLE(id);
  75. },
  76. initBLE: function() {
  77. this.printLog("启动蓝牙适配器, 蓝牙初始化")
  78. var that = this;
  79. wx.openBluetoothAdapter({
  80. success: function(res) {
  81. console.log(res);
  82. that.findBLE();
  83. },
  84. fail: function(res) {
  85. util.toastError('请先打开蓝牙');
  86. }
  87. })
  88. },
  89. findBLE: function() {
  90. this.printLog("打开蓝牙成功.")
  91. var that = this
  92. wx.startBluetoothDevicesDiscovery({
  93. allowDuplicatesKey: false,
  94. interval: 0,
  95. success: function(res) {
  96. wx.showLoading({
  97. title: '正在搜索设备',
  98. })
  99. console.log(res);
  100. delayTimer = setInterval(function(){
  101. that.discoveryBLE() //3.0 //这里的discovery需要多次调用
  102. }, 1000);
  103. setTimeout(function () {
  104. if (isFound) {
  105. return;
  106. } else {
  107. wx.hideLoading();
  108. console.log("搜索设备超时");
  109. wx.stopBluetoothDevicesDiscovery({
  110. success: function (res) {
  111. console.log('连接蓝牙成功之后关闭蓝牙搜索');
  112. }
  113. })
  114. clearInterval(delayTimer)
  115. wx.showModal({
  116. title: '搜索设备超时',
  117. content: '请检查蓝牙设备是否正常工作,Android手机请打开GPS定位.',
  118. showCancel: false
  119. })
  120. util.toastError("搜索设备超时,请打开GPS定位,再搜索")
  121. return
  122. }
  123. }, 15000);
  124. },
  125. fail: function(res) {
  126. that.printLog("蓝牙设备服务发现失败: " + res.errMsg);
  127. }
  128. })
  129. },
  130. discoveryBLE: function() {
  131. var that = this
  132. wx.getBluetoothDevices({
  133. success: function(res) {
  134. var list = res.devices;
  135. console.log(list);
  136. if(list.length <= 0){
  137. return ;
  138. }
  139. var devices = [];
  140. for (var i = 0; i < list.length; i++) {
  141. //that.data.inputValue:表示的是需要连接的蓝牙设备ID,
  142. //简单点来说就是我想要连接这个蓝牙设备,
  143. //所以我去遍历我搜索到的蓝牙设备中是否有这个ID
  144. var name = list[i].name || list[i].localName;
  145. if(util.isEmpty(name)){
  146. continue;
  147. }
  148. if(name.indexOf('JL') >= 0 && list[i].RSSI != 0){
  149. console.log(list[i]);
  150. devices.push(list[i]);
  151. }
  152. }
  153. console.log('总共有' + devices.length + "个设备需要设置")
  154. if (devices.length <= 0) {
  155. return;
  156. }
  157. that.connectBLE(devices);
  158. },
  159. fail: function() {
  160. util.toastError('搜索蓝牙设备失败');
  161. }
  162. })
  163. },
  164. connectBLE: function(devices){
  165. this.printLog('总共有' + devices.length + "个设备需要设置")
  166. var that = this;
  167. wx.hideLoading();
  168. isFound = true;
  169. clearInterval(delayTimer);
  170. wx.stopBluetoothDevicesDiscovery({
  171. success: function (res) {
  172. that.printLog('连接蓝牙成功之后关闭蓝牙搜索');
  173. }
  174. })
  175. //两个的时候需要选择
  176. var list = [];
  177. for (var i = 0; i < devices.length; i++) {
  178. var name = devices[i].name || devices[i].localName;
  179. list.push(name + "[" + devices[i].deviceId + "]")
  180. }
  181. this.setData({
  182. deviceArray: list
  183. })
  184. //默认选择
  185. this.setData({
  186. currDeviceID: list[0]
  187. })
  188. },
  189. createBLE: function(deviceId){
  190. this.printLog("连接: [" + deviceId+"]");
  191. var that = this;
  192. this.closeBLE(deviceId, function(res){
  193. console.log("预先关闭,再打开");
  194. setTimeout(function(){
  195. wx.createBLEConnection({
  196. deviceId: deviceId,
  197. success: function (res) {
  198. that.printLog("设备连接成功");
  199. that.getBLEServiceId(deviceId);
  200. },
  201. fail: function (res) {
  202. that.printLog("设备连接失败" + res.errMsg);
  203. }
  204. })
  205. }, 2000)
  206. });
  207. },
  208. //获取服务UUID
  209. getBLEServiceId: function(deviceId){
  210. this.printLog("获取设备[" + deviceId + "]服务列表")
  211. var that = this;
  212. wx.getBLEDeviceServices({
  213. deviceId: deviceId,
  214. success: function(res) {
  215. console.log(res);
  216. var services = res.services;
  217. if (services.length <= 0){
  218. that.printLog("未找到主服务列表")
  219. return;
  220. }
  221. that.printLog('找到设备服务列表个数: ' + services.length);
  222. if (services.length == 1){
  223. var service = services[0];
  224. that.printLog("服务UUID:["+service.uuid+"] Primary:" + service.isPrimary);
  225. that.getBLECharactedId(deviceId, service.uuid);
  226. }else{ //多个主服务
  227. //TODO
  228. }
  229. },
  230. fail: function(res){
  231. that.printLog("获取设备服务列表失败" + res.errMsg);
  232. }
  233. })
  234. },
  235. getBLECharactedId: function(deviceId, serviceId){
  236. this.printLog("获取设备特征值")
  237. var that = this;
  238. wx.getBLEDeviceCharacteristics({
  239. deviceId: deviceId,
  240. serviceId: serviceId,
  241. success: function(res) {
  242. console.log(res);
  243. //这里会获取到两个特征值,一个用来写,一个用来读
  244. var chars = res.characteristics;
  245. if(chars.length <= 0){
  246. that.printLog("未找到设备特征值")
  247. return ;
  248. }
  249. that.printLog("找到设备特征值个数:" + chars.length);
  250. if(chars.length == 2){
  251. for(var i=0; i<chars.length; i++){
  252. var char = chars[i];
  253. that.printLog("特征值[" + char.uuid + "]")
  254. var prop = char.properties;
  255. if(prop.notify == true){
  256. that.printLog("该特征值属性: Notify");
  257. that.recvBLECharacterNotice(deviceId, serviceId, char.uuid);
  258. }else if(prop.write == true){
  259. that.printLog("该特征值属性: Write");
  260. that.sendBLECharacterNotice(deviceId, serviceId, char.uuid);
  261. }else{
  262. that.printLog("该特征值属性: 其他");
  263. }
  264. }
  265. }else{
  266. //TODO
  267. }
  268. },
  269. fail: function(res){
  270. that.printLog("获取设备特征值失败")
  271. }
  272. })
  273. },
  274. recvBLECharacterNotice: function(deviceId, serviceId, charId){
  275. //接收设置是否成功
  276. this.printLog("注册Notice 回调函数");
  277. var that = this;
  278. wx.notifyBLECharacteristicValueChange({
  279. deviceId: deviceId,
  280. serviceId: serviceId,
  281. characteristicId: charId,
  282. state: true, //启用Notify功能
  283. success: function(res) {
  284. wx.onBLECharacteristicValueChange(function(res){
  285. console.log(res);
  286. that.printLog("收到Notify数据: " + that.ab2hex(res.value));
  287. //关闭蓝牙
  288. wx.showModal({
  289. title: '配网成功',
  290. content: that.ab2hex(res.value),
  291. showCancel: false
  292. })
  293. });
  294. },
  295. fail: function(res){
  296. console.log(res);
  297. that.printLog("特征值Notice 接收数据失败: " + res.errMsg);
  298. }
  299. })
  300. },
  301. sendBLECharacterNotice: function (deviceId, serviceId, charId){
  302. //发送ssid/pass
  303. this.printLog("延时1秒后,发送SSID/PASS");
  304. var that = this;
  305. var cell = {
  306. "ssid": this.data.ssid,
  307. "pass": this.data.pass
  308. }
  309. var buffer = this.string2buffer(JSON.stringify(cell));
  310. setTimeout(function(){
  311. wx.writeBLECharacteristicValue({
  312. deviceId: deviceId,
  313. serviceId: serviceId,
  314. characteristicId: charId,
  315. value: buffer,
  316. success: function(res) {
  317. that.printLog("发送SSID/PASS 成功");
  318. },
  319. fail: function(res){
  320. console.log(res);
  321. that.printLog("发送失败." + res.errMsg);
  322. },
  323. complete: function(){
  324. }
  325. })
  326. }, 1000);
  327. },
  328. closeBLE: function(deviceId, callback){
  329. var that = this;
  330. wx.closeBLEConnection({
  331. deviceId: deviceId,
  332. success: function(res) {
  333. that.printLog("断开设备[" + deviceId + "]成功.");
  334. console.log(res)
  335. },
  336. fail: function(res){
  337. that.printLog("断开设备成功.");
  338. },
  339. complete: callback
  340. })
  341. },
  342. printLog: function(msg){
  343. var logs = this.data.logs;
  344. logs.push(msg);
  345. this.setData({ logs: logs })
  346. },
  347. /**
  348. * 将字符串转换成ArrayBufer
  349. */
  350. string2buffer(str) {
  351. if (!str) return;
  352. var val = "";
  353. for (var i = 0; i < str.length; i++) {
  354. val += str.charCodeAt(i).toString(16);
  355. }
  356. console.log(val);
  357. str = val;
  358. val = "";
  359. let length = str.length;
  360. let index = 0;
  361. let array = []
  362. while (index < length) {
  363. array.push(str.substring(index, index + 2));
  364. index = index + 2;
  365. }
  366. val = array.join(",");
  367. //16进制转化为ArrayBuffer
  368. return new Uint8Array(val.match(/[\da-f]{2}/gi).map(function (h) {
  369. return parseInt(h, 16)
  370. })).buffer
  371. },
  372. /**
  373. * 将ArrayBuffer转换成字符串
  374. */
  375. ab2hex(buffer) {
  376. var hexArr = Array.prototype.map.call(
  377. new Uint8Array(buffer),
  378. function (bit) {
  379. return ('00' + bit.toString(16)).slice(-2)
  380. }
  381. )
  382. return hexArr.join('');
  383. },
  384. inputSSID: function(res) {
  385. var ssid = res.detail.value;
  386. this.setData({
  387. ssid: ssid
  388. })
  389. },
  390. inputPASS: function(res) {
  391. var pass = res.detail.value;
  392. this.setData({
  393. pass: pass
  394. })
  395. }
  396. })

  1. //补充util.js
  2. const formatTime = date => {
  3. const year = date.getFullYear()
  4. const month = date.getMonth() + 1
  5. const day = date.getDate()
  6. const hour = date.getHours()
  7. const minute = date.getMinutes()
  8. const second = date.getSeconds()
  9. return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
  10. }
  11. const formatNumber = n => {
  12. n = n.toString()
  13. return n[1] ? n : '0' + n
  14. }
  15. const isEmpty = function(str){
  16. if(str == null || str == undefined || str == ""){
  17. return true;
  18. }
  19. return false;
  20. }
  21. const randomWord = function(range){
  22. var str = "",
  23. arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
  24. // 随机产生
  25. for (var i = 0; i < range; i++) {
  26. var pos = Math.round(Math.random() * (arr.length - 1));
  27. str += arr[pos];
  28. }
  29. return str;
  30. }
  31. const toastServerError = function(){
  32. wx.showToast({
  33. title: '服务器异常,请稍后重试!',
  34. icon: 'none',
  35. duration: 1200,
  36. mask: true
  37. })
  38. }
  39. const toastError = function(info){
  40. wx.showToast({
  41. title: info,
  42. icon: 'none',
  43. duration: 1200,
  44. mask: true
  45. })
  46. }
  47. module.exports = {
  48. formatTime: formatTime,
  49. isEmpty: isEmpty,
  50. toastServerError: toastServerError,
  51. toastError: toastError,
  52. randomWord: randomWord
  53. }

  1. /* 统一发送数据,带分包 */
  2. sendBLEData: function (deviceId, serviceId, charId, array){
  3. var that = this;
  4. if(array.length <= 0){
  5. that.printLog("发送SSID/PASS 完成");
  6. return;
  7. }
  8. var list = array.splice(0, 20);
  9. var buffer = new Uint8Array(list).buffer;
  10. wx.writeBLECharacteristicValue({
  11. deviceId: deviceId,
  12. serviceId: serviceId,
  13. characteristicId: charId,
  14. value: buffer,
  15. success: function (res) {
  16. that.printLog("发送SSID/PASS 分包发送");
  17. that.sendBLEData(deviceId, serviceId, charId, array);
  18. },
  19. fail: function (res) {
  20. console.log(res);
  21. that.printLog("发送失败." + res.errMsg);
  22. },
  23. complete: function () {
  24. }
  25. })
  26. },

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/煮酒与君饮/article/detail/757991
推荐阅读
相关标签
  

闽ICP备14008679号