WeChat 애플릿의 Bluetooth 링크

不言
풀어 주다: 2018-06-22 16:33:32
원래의
2279명이 탐색했습니다.

이 글은 위챗 애플릿의 블루투스 링크 관련 정보를 주로 소개합니다. 이 글을 통해 모두가 애플릿의 블루투스 개발 방법을 익힐 수 있기를 바랍니다.

위챗의 블루투스 링크를 참고하세요. WeChat 애플릿

WeChat 미니 프로그램 Bluetooth 연결 2.0 설명:

1 이 버전은 ANDROID 및 IOS 시스템에서 다양한 Bluetooth 연결 방법을 구별합니다.

2. 더 많은 상황에서 호환되는 링크는 다음과 같습니다.

(1) 장치 Bluetooth가 켜져 있지 않으면 Bluetooth가 켜지면 연결이 자동으로 시작됩니다.
(2) Bluetooth 초기화에 실패한 후 3000ms마다 Bluetooth 어댑터를 자동으로 다시 초기화합니다.
(3) Android 측에서 블루투스 어댑터를 열 때 스캔이 실패하고 3000ms마다 자동으로 다시 시작됩니다.
(4) IOS 측은 연결된 블루투스 장치를 비어 있는 것으로 획득하고 3000ms마다 자동으로 다시 획득합니다.
(5) Android Bluetooth 연결이 시작된 후 검색이 중단됩니다. 연결에 실패하면 다시 검색하세요.
(6) IOS 측에서 장치 연결을 시작한 후 연결된 장치 획득을 중지합니다. 연결에 실패하면 자동으로 획득을 다시 시작합니다.
(7) 성공적으로 연결되면 시스템 블루투스를 끄고 블루투스 어댑터를 재설정하세요.
(8) 연결이 성공한 후 시스템 블루투스를 껐다가 다시 켜면 연결이 자동으로 다시 시작됩니다.
(9) 성공적으로 연결되면 대상 Bluetooth 장치를 끄고 자동으로 스캔(획득)을 다시 시작합니다.
(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은 연결하려는 Bluetooth 장치의 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);
   }
  })
 }
로그인 후 복사

설명: 이 메서드는 현재 Bluetooth 상태를 가져오는 데 사용됩니다.

Bluetooth를 사용할 수 있는 것으로 감지되면 judegIfDiscovering 메서드가 호출됩니다.

judegIfDiscovering code:

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를 통해 획득되어 Android 기기인지 IOS 기기인지 확인합니다.

Android 장치인 경우 startBluetoothDevicesDiscovery()를 호출하여 검색을 시작하고, IOS 장치인 경우 getConnectedBluetoothDevices()를 호출하여 페어링된 Bluetooth 장치 가져오기를 시작합니다.

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 Android 기기에서만 주변 블루투스 기기 검색을 활성화합니다.

2. 성공적인 콜백에서 새 Bluetooth 장치를 검색하기 위해 BluetoothDeviceFound()에서 이벤트 모니터링을 활성화합니다.

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. 검색된 Bluetooth 장치는 이름 속성을 기준으로 여기에서 필터링됩니다.

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;
   }
  });
 }
로그인 후 복사

참고: Bluetooth 페어링 Bluetooth 장치 획득에 실패하면 또는 획득한 목록은 에어컨입니다. 시스템에서 페어링되었습니다.

2. 장치 목록을 얻으면 loopConnect() 메서드를 호출하여 Bluetooth 장치 호출을 재귀적으로 시작합니다.

loopConnect 코드:

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);
 }
로그인 후 복사

참고: 연결 생성 메서드가 실패한 후 looConnect는 배열의 첫 번째 값을 삭제한 다음 모든 장치가 연결될 때까지 이 메서드를 계속 호출합니다.

거의 놓칠 뻔했습니다. app.js의 onShow에서 init() 메서드를 호출하세요.

특별 지침:

1. 현재 버전에서는 Android 및 IOS에서 Bluetooth 연결에 다른 방법을 권장합니다. Android 장치는 애플릿의 Bluetooth 연결을 직접 사용하여 시스템 페어링을 취소합니다. IOS 장치는 시스템 페어링 및 미니 프로그램 열기 후 몇 초 안에 성공적으로 연결할 수 있습니다.

2. 이 버전의 연결은 여전히 ​​개선되어야 합니다. 연결은 자동으로 종료되지 않으며(필요한 경우 직접 추가할 수 있음) 성공할 때까지 무한히 검색하고 다시 연결합니다.

3. 연결 성공 후 작업은 데이터 쓰기와 알림 켜기를 동시에 수행해야 하는 경우 먼저 쓰고 알림을 켜는 것이 좋습니다. (이유는 알 수 없습니다. 그렇지 않으면 10008 오류가 발생합니다.)

위 내용은 이 글의 전체 내용입니다. 모든 분들의 학습에 도움이 되었으면 좋겠습니다. 더 많은 관련 내용은 PHP 중국어 홈페이지를 주목해주세요!

관련 권장 사항:

WeChat 미니 프로그램의 장바구니에 대한 간단한 예

WeChat 미니 프로그램이 Meituan 메뉴를 구현하는 방법

WeChat 미니 프로그램의 로그인 인증 단계 정보

위 내용은 WeChat 애플릿의 Bluetooth 링크의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!