首頁 微信小程式 小程式開發 微信小程式中藍牙的鏈接

微信小程式中藍牙的鏈接

Jun 22, 2018 pm 04:33 PM
小程式 微信小程式 藍牙

這篇文章主要介紹了微信小程式之藍牙的連結的相關資料,希望透過本文大家能夠掌握小程式藍牙的開發方法,需要的朋友可以參考下

微信小程式之藍牙的連結

微信小程式藍牙連接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錯誤)。

以上就是本文的全部內容,希望對大家的學習有所幫助,更多相關內容請關注PHP中文網!

相關推薦:

微信小程式中購物車的簡單實例

微信小程式如何實作美團選單

關於微信小程式登入鑑權的步驟

以上是微信小程式中藍牙的鏈接的詳細內容。更多資訊請關注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

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

<🎜>:泡泡膠模擬器無窮大 - 如何獲取和使用皇家鑰匙
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
北端:融合系統,解釋
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora:巫婆樹的耳語 - 如何解鎖抓鉤
3 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Java教學
1667
14
CakePHP 教程
1426
52
Laravel 教程
1328
25
PHP教程
1273
29
C# 教程
1255
24
解決win11同時播放耳機與音響的問題 解決win11同時播放耳機與音響的問題 Jan 06, 2024 am 08:50 AM

一般來說,我們只需要同時使用耳機或音響的其中一個設備,但是有些朋友反映在win11系統中,遇到了耳機和音響一起響的問題,其實我們可以在realtek面板中將它關閉,就可以了,下面一起來看一下吧。 win11耳機和音響一起響怎麼辦1、先在桌面上找到並打開“控制面板”2、進入控制面板,在其中找到並打開“硬體和聲音”3、然後再找到一個喇叭圖標的“Realtek高清晰音訊管理器”4、選擇“揚聲器”再點擊“後面板”進入揚聲器設定。 5.打開之後我們可以看到設備類型,如果要關閉耳機就取消勾選“耳機”,如果要

閒魚微信小程式正式上線 閒魚微信小程式正式上線 Feb 10, 2024 pm 10:39 PM

閒魚官方微信小程式悄悄上線,在小程式中可以發布閒置與買家/賣家私訊交流、查看個人資料及訂單、搜尋物品等,有用好奇閒魚微信小程式叫什麼,現在快來看一下。閒魚微信小程式叫什麼答案:閒魚,閒置交易二手買賣估價回收。 1、在小程式中可以發布閒置、與買家/賣家私訊交流、查看個人資料及訂單、搜尋指定物品等功能;2、在小程式的頁面中有首頁、附近、發閒置、訊息、我的5項功能;3、想要使用的話必要要開通微信支付才可以購買;

vivo手機中開啟藍牙的方法 vivo手機中開啟藍牙的方法 Mar 23, 2024 pm 04:26 PM

1.在螢幕底端向上滑,調出控制中心,如下圖,點擊藍牙開關即可開啟藍牙。 2.我們就可以連接其他配對過的藍牙設備或點擊【搜尋藍牙設備】來和新的藍牙設備進行連接,想要其他小夥伴搜到自己的手機來連接藍牙時記得要打開【可檢測性】開關哦。方法二、1、進入手機桌面,找到並開啟設定。 2.在【設定】目錄下拉找到【更多設定】,點選進入,3、點選開啟【藍牙】,將藍牙開關開啟即可開啟藍牙啦。

win11系統裝置管理員沒有藍牙模組 win11系統裝置管理員沒有藍牙模組 Mar 02, 2024 am 08:01 AM

win11系統裝置管理員沒有藍牙模組在使用Windows11系統時,有時候會遇到裝置管理員中沒有藍牙模組的情況。這可能會對我們的日常使用造成不便,因為藍牙技術在現代社會中已經變得非常普遍,我們經常需要使用它來連接無線設備。如果你在裝置管理員中找不到藍牙模組,別擔心,以下將為你介紹一些可能的解決方法:1.檢查硬體連接:首先要確保你的電腦或筆記型電腦上確實有藍牙模組。有些裝置可能不會自備藍牙功能,這時你需要購買外部的藍牙轉接器來連接。 2.更新驅動程式:有時候裝置管理員中沒有藍牙模組是因為驅動程

哈利波特魔咒互換用不了藍牙解決方法 哈利波特魔咒互換用不了藍牙解決方法 Mar 21, 2024 pm 04:30 PM

哈利波特魔法覺醒中最近新增了一個魔咒互換功能,需要玩家使用藍牙或WiFi來互換魔咒,有些玩家發現自己使用不了藍牙互換,那麼怎麼才能使用藍牙互換魔咒呢?接下來小編就為大家帶來了哈利波特魔咒互換用不了藍牙解決方法,希望能夠幫助大家。哈利波特魔咒互換用不了藍牙解決方法1、首先玩家需要在圖書館中找到魔咒互換,就可以使用藍牙或WiFi進行互換了。 2.點選使用藍牙,提示需要下載新的安裝包,但之前已經下載過了,有些玩家就開始犯糊塗了。 3.其實新的安裝包玩家去商店即可下載,ios就去蘋果商店更新,安卓

藍牙5.3要求手機支援嗎?詳細資訊請看 藍牙5.3要求手機支援嗎?詳細資訊請看 Jan 14, 2024 pm 04:57 PM

我們在買手機的時候,會看到手機參數裡有一個支援藍牙選項,有時候就會遇到購買的藍牙耳機和手機不匹配的情況,那麼藍牙5.3需要手機支援嗎,其實是不需要的。藍牙5.3需要手機支援嗎:答:藍牙5.3需要手機支援。不過只要支援藍牙的手機就可以使用。 1.藍牙是向下相容的,不過要使用對應版本就需要手機支援。 2.舉例來說,如果我們購買了一款使用藍牙5.3的無線藍牙耳機。 3.那麼,如果我們的手機只支援藍牙5.0,那麼在連線時使用的就是藍牙5.0。4、因此,我們依舊是可以使用這款手機連接耳機來聽歌的,但是速度不如藍

實現微信小程式中的圖片濾鏡效果 實現微信小程式中的圖片濾鏡效果 Nov 21, 2023 pm 06:22 PM

實現微信小程式中的圖片濾鏡效果隨著社群媒體應用程式的流行,人們越來越喜歡在照片中應用濾鏡效果,以增強照片的藝術效果和吸引力。在微信小程式中也可以實現圖片濾鏡效果,為使用者提供更多有趣和創意的照片編輯功能。本文將介紹如何在微信小程式中實現圖片濾鏡效果,並提供具體的程式碼範例。首先,我們需要在微信小程式中使用canvas元件來載入和編輯圖片。 canvas元件可以在頁面

三星為多款 Galaxy 手機、平板帶來藍牙 Auracast 廣播音訊功能 三星為多款 Galaxy 手機、平板帶來藍牙 Auracast 廣播音訊功能 Feb 21, 2024 pm 01:50 PM

2月21日消息,三星公司今天發佈公告,宣佈為已升級OneUI6.1及更高版本的GalaxyS23系列、ZFold5、ZFlip5手機,以及GalaxyTabS9系列平板,帶來藍牙Auracast音訊廣播功能。三星於去年開始,已陸續在GalaxyBuds2Pro耳機、三星智慧電視上添加對藍牙Auracast音訊廣播功能的支持,運行OneUI6.1的GalaxyS24系列手機已添加支援。符合適配升級至OneUI6.1的三星設備,可開啟「設定」>「藍牙」>「三點選單」>「使用Auracast廣播聲音

See all articles