当前位置:   article > 正文

微信小程序自动连接蓝牙电子秤_手机如何利用微信小程序代码自动连接蓝牙设备控制继续电器

手机如何利用微信小程序代码自动连接蓝牙设备控制继续电器

 不同品牌的称,只需要打印下方函数返回值,根据自己需要做处理就可以了。

  1. wx.onBLECharacteristicValueChange(function (res) {
  2.           let receiverText = that.buf2string(res.value);
  3. }

 第一次连接需要手动配置,然后把所需参数(deviceId)保存到storage中,方便下次自动连接。

  1. App({
  2. globalData: {
  3. serviceId: '',
  4. characteristicId: '',
  5. deviceId: '', // 已连接蓝牙的设备ID
  6. BluetoothState: false, // 蓝牙适配器状态
  7. connectState: false, // 蓝牙连接状态,
  8. weight: 0, // 重量
  9. },
  10. onLaunch: function () {
  11. // 设置初始重量为0
  12. wx.setStorageSync('weight', 0)
  13. },
  14. onShow() {
  15. // 读取本地数据,实现蓝牙自动连接
  16. let deviceId = wx.getStorageSync('deviceId') || []
  17. if(deviceId){
  18. this.globalData.deviceId = deviceId
  19. this.initBlue()
  20. } else {
  21. wx.showToast({
  22. title: '蓝牙未连接',
  23. icon: 'error',
  24. duration: 3000,
  25. })
  26. }
  27. },
  28. // 初始化蓝牙
  29. initBlue(){
  30. var that = this;
  31. wx.openBluetoothAdapter({//调用微信小程序api 打开蓝牙适配器接口
  32. success: function (res) {
  33. console.log('app初始化蓝牙成功')
  34. that.getTheBlueDisConnectWithAccident();//监听蓝牙是否会异常断开
  35. that.globalData.BluetoothState = true
  36. that.monitorTheBlue(); // 监听手机蓝牙的开关
  37. that.startConnect(that.globalData.deviceId) // 连接蓝牙
  38. },
  39. fail: function (err) {//如果手机上的蓝牙没有打开,可以提醒用户
  40. if (err.errCode === 10001) { // 手机蓝牙未开启
  41. that.globalData.BluetoothState = false
  42. wx.showToast({
  43. title: '手机蓝牙未开启',
  44. icon: 'error',
  45. duration: 3000,
  46. })
  47. }
  48. }
  49. })
  50. },
  51. // 监听手机蓝牙的开关
  52. monitorTheBlue:function(){
  53. var that =this;
  54. wx.onBluetoothAdapterStateChange(function(res){
  55. if (res.available){
  56. that.globalData.BluetoothState = true
  57. if(!that.globalData.connectState){
  58. let deviceId = wx.getStorageSync('deviceId') || []
  59. if(deviceId){
  60. that.globalData.deviceId = deviceId
  61. that.initBlue()
  62. }
  63. }
  64. }else{
  65. wx.showToast({
  66. title: '蓝牙已关闭',
  67. icon: 'error',
  68. duration: 3000,
  69. })
  70. }
  71. })
  72. },
  73. // 监听蓝牙设备是否会异常断开
  74. getTheBlueDisConnectWithAccident:function(e){
  75. var that = this;
  76. wx.onBLEConnectionStateChange(function (res) {
  77. if (!res.connected){
  78. that.globalData.connectState = false
  79. wx.showToast({
  80. title: '蓝牙已断开连接',
  81. icon: 'error',
  82. duration: 3000,
  83. })
  84. that.monitorTheBlue()
  85. }
  86. })
  87. },
  88. // 停止搜索附近蓝牙
  89. stopSearchDevs: function () {
  90. wx.stopBluetoothDevicesDiscovery({
  91. success: function (res) { },
  92. })
  93. },
  94. // 开始连接
  95. startConnect(deviceId, isFirst = false){
  96. const that =this
  97. wx.createBLEConnection({
  98. deviceId: deviceId,
  99. timeout: 10000, // 10s连接超时
  100. success: function (res) {
  101. that.globalData.connectState = true
  102. wx.showToast({
  103. title: '蓝牙连接成功',
  104. icon: 'success',
  105. duration: 3000,
  106. success: res=>{
  107. that.getServiceId()
  108. if(isFirst){
  109. wx.navigateTo({
  110. url: `/pages/bluetooth/com/com`,
  111. })
  112. }
  113. }
  114. })
  115. },
  116. })
  117. },
  118. // 获取蓝牙设备服务ID
  119. getServiceId(){
  120. const that = this
  121. wx.getBLEDeviceServices({
  122. deviceId: wx.getStorageSync('deviceId'),
  123. success: function(res) {
  124. const services = res.services.filter((item, i) => {
  125. return !/^000018/.test(item.uuid)
  126. })
  127. that.globalData.serviceId = services[0].uuid
  128. that.getCharacteristicId()
  129. },
  130. fail: function(res) {
  131. wx.showToast({
  132. title: '设备服务获取失败',
  133. icon: 'none'
  134. })
  135. }
  136. })
  137. },
  138. // 获取特征ID
  139. getCharacteristicId(){
  140. const that = this
  141. wx.getBLEDeviceCharacteristics({
  142. deviceId: wx.getStorageSync('deviceId'),
  143. serviceId: that.globalData.serviceId,
  144. success: function(res) {
  145. for (var i = 0; i < res.characteristics.length; i++) {//2个值
  146. var model = res.characteristics[i]
  147. if (model.properties.notify == true) {
  148. that.startNotice(model.uuid)//7.0
  149. }
  150. }
  151. }
  152. })
  153. },
  154. // 接收值处理
  155. buf2string(buffer) {
  156. var arr = Array.prototype.map.call(new Uint8Array(buffer), x => x)
  157. return arr.map((char, i) => {
  158. return String.fromCharCode(char);
  159. }).join('');
  160. },
  161. // 开启通知,通知特征值变化
  162. startNotice(uuid) {
  163. var that = this;
  164. wx.notifyBLECharacteristicValueChange({
  165. state: true, // 启用 notify 功能
  166. deviceId: wx.getStorageSync('deviceId'),
  167. serviceId: that.globalData.serviceId,
  168. characteristicId: uuid, //第一步 开启监听 notityid
  169. success: function (res) {
  170. // 设备返回的方法
  171. wx.onBLECharacteristicValueChange(function (res) {
  172. let receiverText = that.buf2string(res.value);
  173. receiverText = receiverText.split('').reverse().join('').slice(1)
  174. receiverText = Number(receiverText)
  175. if(that.globalData.weigh == receiverText) {
  176. return;
  177. } else {
  178. // that.globalData.weight = receiverText
  179. wx.setStorageSync('weight', receiverText)
  180. }
  181. })
  182. },
  183. fail: function (res) {
  184. console.log(res);
  185. }
  186. })
  187. },
  188. // 断开连接
  189. endConnect(deviceId) {
  190. if (this.globalData.BluetoothState) {
  191. wx.closeBLEConnection({
  192. deviceId: deviceId,
  193. success: function (res) {},
  194. })
  195. }
  196. },
  197. onHide () {
  198. // Do something when hide.
  199. let deviceId = wx.getStorageSync('deviceId') || []
  200. this.endConnect(deviceId)
  201. this.globalData.connectState = false
  202. wx.closeBluetoothAdapter({
  203. success: res=>{
  204. this.globalData.BluetoothState = false
  205. }
  206. })
  207. },
  208. })

手动连接

  1. const app = getApp()
  2. Page({
  3. // 页面的初始数据
  4. data: {
  5. devs: []
  6. },
  7. // 自定义数据
  8. customData: {
  9. _devs: []
  10. },
  11. // 监听页面加载
  12. onLoad: function () {
  13. // 微信蓝牙模块初始化
  14. const self = this
  15. wx.openBluetoothAdapter({
  16. success: function (res) {
  17. app.globalData.BluetoothState = true
  18. self.startSearchDevs() // 搜索附近蓝牙
  19. },
  20. fail: function (err) {
  21. if (err.errCode === 10001) { // 手机蓝牙未开启
  22. app.globalData.BluetoothState = false
  23. wx.showLoading({
  24. title: '请开启手机蓝牙',
  25. })
  26. } else {
  27. // console.log(err.errMsg)
  28. }
  29. }
  30. })
  31. // 监听蓝牙适配器状态变化
  32. wx.onBluetoothAdapterStateChange(function(res) {
  33. if (res.available) {
  34. app.globalData.BluetoothState = true
  35. wx.openBluetoothAdapter({
  36. success: function(res) {
  37. app.globalData.BluetoothState = true
  38. wx.hideLoading()
  39. },
  40. })
  41. } else {
  42. app.globalData.BluetoothState = false
  43. app.globalData.connectState = false
  44. wx.showLoading({
  45. title: '请开启手机蓝牙',
  46. })
  47. }
  48. })
  49. // 监听BLE蓝牙连接状态变化
  50. wx.onBLEConnectionStateChange(function(res) {
  51. if (res.connected) {
  52. wx.hideLoading()
  53. wx.showToast({
  54. title: '连接成功',
  55. icon: 'success',
  56. success: function(res) {
  57. app.globalData.connectState = true
  58. }
  59. })
  60. } else {
  61. wx.hideLoading()
  62. wx.showToast({
  63. title: '已断开连接',
  64. icon: 'none',
  65. success: function(res) {
  66. app.globalData.connectState = false
  67. }
  68. })
  69. }
  70. })
  71. },
  72. // 监听页面卸载
  73. onUnload: function () {
  74. app.stopSearchDevs()
  75. },
  76. // 监听用户下拉动作
  77. onPullDownRefresh: function () {
  78. if (app.globalData.BluetoothState) {
  79. const self = this
  80. this.customData._devs = []
  81. wx.closeBluetoothAdapter({
  82. success: function (res) {
  83. wx.openBluetoothAdapter({
  84. success: function (res) {
  85. self.startSearchDevs()
  86. }
  87. })
  88. }
  89. })
  90. }
  91. setTimeout(() => {
  92. wx.stopPullDownRefresh()
  93. }, 2000)
  94. },
  95. // 开始搜索附近蓝牙
  96. startSearchDevs: function () {
  97. const self = this
  98. wx.startBluetoothDevicesDiscovery({ // 开启搜索
  99. allowDuplicatesKey: false,
  100. success: function (res) {
  101. wx.onBluetoothDeviceFound(function (devices) {
  102. var isExist = false
  103. if (devices.deviceId) {
  104. for (let item of self.customData._devs) {
  105. if (item.deviceId === devices.deviceId) {
  106. isExist = true
  107. break;
  108. }
  109. }
  110. !isExist && self.customData._devs.push(devices)
  111. self.setData({
  112. devs: self.customData._devs
  113. })
  114. }
  115. else if (devices.devices) {
  116. for (let item of self.customData._devs) {
  117. if (item.deviceId === devices.devices[0].deviceId) {
  118. isExist = true
  119. break;
  120. }
  121. }
  122. !isExist && self.customData._devs.push(devices.devices[0])
  123. self.setData({
  124. devs: self.customData._devs
  125. })
  126. }
  127. else if (devices[0]) {
  128. for (let item of self.customData._devs) {
  129. if (item.deviceId === devices[0].deviceId) {
  130. isExist = true
  131. break;
  132. }
  133. }
  134. !isExist && self.customData._devs.push(devices[0])
  135. self.setData({
  136. devs: self.customData._devs
  137. })
  138. }
  139. })
  140. }
  141. })
  142. },
  143. // 选择设备连接
  144. connect (event) {
  145. app.stopSearchDevs()
  146. if (app.globalData.BluetoothState) {
  147. const deviceId = event.currentTarget.dataset.dev.deviceId
  148. app.globalData.deviceId = deviceId
  149. wx.setStorageSync('deviceId', deviceId)
  150. wx.showLoading({
  151. title: '正在连接...',
  152. })
  153. app.startConnect(deviceId, true)
  154. }
  155. },
  156. })

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

闽ICP备14008679号