위챗 애플릿 미니 프로그램 개발 WeChat 애플릿이 Bluetooth를 구현하는 방법에 대한 공유 예

WeChat 애플릿이 Bluetooth를 구현하는 방법에 대한 공유 예

May 22, 2018 pm 04:30 PM
미니 프로그램 블루투스

이 글에서는 주로 위챗 애플릿의 블루투스 구현 예제 코드에 대한 관련 정보를 소개합니다. 필요한 친구는

위챗 애플릿의 블루투스 구현 예제 코드

1를 참조하세요. 어댑터 인터페이스 기본 라이브러리 버전 1.1.0부터 지원됩니다. iOS WeChat 클라이언트는 버전 6.5.6부터 지원되지만 Android 클라이언트는 아직 지원되지 않습니다.

Bluetooth에는 총 18개의 API 인터페이스가 추가되었습니다.



2.Api 분류

검색 카테고리Connection 카테고리

Communication 카테고리



3. API의 구체적인 용도

자세한 내용은 공식 홈페이지를 참고하세요:

https://mp.weixin.qq.com/debug/wxadoc/dev/api/bluetooth.html#wxgetconnectedbluethoothdevicesobject
로그인 후 복사

4.1. 블루투스 장치 검색

/**
 * 搜索设备界面
 */
Page({
 data: {
  logs: [],
  list:[],
 },
  onLoad: function () {
  console.log('onLoad')
var that = this;
// const SDKVersion = wx.getSystemInfoSync().SDKVersion || '1.0.0'
// const [MAJOR, MINOR, PATCH] = SDKVersion.split('.').map(Number)
// console.log(SDKVersion);
// console.log(MAJOR);
// console.log(MINOR);
// console.log(PATCH);

// const canIUse = apiName => {
//  if (apiName === 'showModal.cancel') {
//   return MAJOR >= 1 && MINOR >= 1
//  }
//  return true
// }

// wx.showModal({
//  success: function(res) {
//   if (canIUse('showModal.cancel')) {
//    console.log(res.cancel)
//   }
//  }
// })
   //获取适配器
   wx.openBluetoothAdapter({
   success: function(res){
    // success
    console.log("-----success----------");
     console.log(res);
     //开始搜索
    wx.startBluetoothDevicesDiscovery({
 services: [],
 success: function(res){
  // success
   console.log("-----startBluetoothDevicesDiscovery--success----------");
   console.log(res);
 },
 fail: function(res) {
  // fail
   console.log(res);
 },
 complete: function(res) {
  // complete
   console.log(res);
 }
})


   },
   fail: function(res) {
     console.log("-----fail----------");
    // fail
     console.log(res);
   },
   complete: function(res) {
    // complete
     console.log("-----complete----------");
     console.log(res);
   }
  })

   wx.getBluetoothDevices({
    success: function(res){
     // success
     //{devices: Array[11], errMsg: "getBluetoothDevices:ok"}
     console.log("getBluetoothDevices");
     console.log(res);
     that.setData({
     list:res.devices
     });
     console.log(that.data.list);
    },
    fail: function(res) {
     // fail
    },
    complete: function(res) {
     // complete
    }
   })

 },
 onShow:function(){


 },
  //点击事件处理
 bindViewTap: function(e) {
   console.log(e.currentTarget.dataset.title);
   console.log(e.currentTarget.dataset.name);
   console.log(e.currentTarget.dataset.advertisData);

  var title = e.currentTarget.dataset.title;
  var name = e.currentTarget.dataset.name;
   wx.redirectTo({
    url: '../conn/conn?deviceId='+title+'&name='+name,
    success: function(res){
     // success
    },
    fail: function(res) {
     // fail
    },
    complete: function(res) {
     // complete
    }
   })
 },
})
로그인 후 복사

4.2 연결하여 데이터

/**
 * 连接设备。获取数据
 */
Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    deviceId: '',
    name: '',
    serviceId: '',
    services: [],
    cd20: '',
    cd01: '',
    cd02: '',
    cd03: '',
    cd04: '',
    characteristics20: null,
    characteristics01: null,
    characteristics02: null,
    characteristics03: null,
    characteristics04: null,
    result,

  },
  onLoad: function (opt) {
    var that = this;
    console.log("onLoad");
    console.log('deviceId=' + opt.deviceId);
    console.log('name=' + opt.name);
    that.setData({ deviceId: opt.deviceId });
    /**
     * 监听设备的连接状态
     */
    wx.onBLEConnectionStateChanged(function (res) {
      console.log(`device ${res.deviceId} state has changed, connected: ${res.connected}`)
    })
    /**
     * 连接设备
     */
    wx.createBLEConnection({
      deviceId: that.data.deviceId,
      success: function (res) {
        // success
        console.log(res);
        /**
         * 连接成功,后开始获取设备的服务列表
         */
        wx.getBLEDeviceServices({
          // 这里的 deviceId 需要在上面的 getBluetoothDevices中获取
          deviceId: that.data.deviceId,
          success: function (res) {
            console.log('device services:', res.services)
            that.setData({ services: res.services });
            console.log('device services:', that.data.services[1].uuid);
            that.setData({ serviceId: that.data.services[1].uuid });
            console.log('--------------------------------------');
            console.log('device设备的id:', that.data.deviceId);
            console.log('device设备的服务id:', that.data.serviceId);
            /**
             * 延迟3秒,根据服务获取特征 
             */
            setTimeout(function () {
              wx.getBLEDeviceCharacteristics({
                // 这里的 deviceId 需要在上面的 getBluetoothDevices
                deviceId: that.data.deviceId,
                // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
                serviceId: that.data.serviceId,
                success: function (res) {
                  console.log('000000000000' + that.data.serviceId);
                  console.log('device getBLEDeviceCharacteristics:', res.characteristics)
                  for (var i = 0; i < 5; i++) {
                    if (res.characteristics[i].uuid.indexOf("cd20") != -1) {
                      that.setData({
                        cd20: res.characteristics[i].uuid,
                        characteristics20: res.characteristics[i]
                      });
                    }
                    if (res.characteristics[i].uuid.indexOf("cd01") != -1) {
                      that.setData({
                        cd01: res.characteristics[i].uuid,
                        characteristics01: res.characteristics[i]
                      });
                    }
                    if (res.characteristics[i].uuid.indexOf("cd02") != -1) {
                      that.setData({
                        cd02: res.characteristics[i].uuid,
                        characteristics02: res.characteristics[i]
                      });
                    } if (res.characteristics[i].uuid.indexOf("cd03") != -1) {
                      that.setData({
                        cd03: res.characteristics[i].uuid,
                        characteristics03: res.characteristics[i]
                      });
                    }
                    if (res.characteristics[i].uuid.indexOf("cd04") != -1) {
                      that.setData({
                        cd04: res.characteristics[i].uuid,
                        characteristics04: res.characteristics[i]
                      });
                    }
                  }
                  console.log(&#39;cd01= &#39; + that.data.cd01 + &#39;cd02= &#39; + that.data.cd02 + &#39;cd03= &#39; + that.data.cd03 + &#39;cd04= &#39; + that.data.cd04 + &#39;cd20= &#39; + that.data.cd20);
                  /**
                   * 回调获取 设备发过来的数据
                   */
                  wx.onBLECharacteristicValueChange(function (characteristic) {
                    console.log(&#39;characteristic value comed:&#39;, characteristic.value)
                    //{value: ArrayBuffer, deviceId: "D8:00:D2:4F:24:17", serviceId: "ba11f08c-5f14-0b0d-1080-007cbe238851-0x600000460240", characteristicId: "0000cd04-0000-1000-8000-00805f9b34fb-0x60800069fb80"}
                    /**
                     * 监听cd04cd04中的结果
                     */
                    if (characteristic.characteristicId.indexOf("cd01") != -1) {
                      const result = characteristic.value;
                      const hex = that.buf2hex(result);
                      console.log(hex);
                    }
                    if (characteristic.characteristicId.indexOf("cd04") != -1) {
                      const result = characteristic.value;
                      const hex = that.buf2hex(result);
                      console.log(hex);
                      that.setData({ result: hex });
                    }

                  })
                  /**
                   * 顺序开发设备特征notifiy
                   */
                  wx.notifyBLECharacteristicValueChanged({
                    deviceId: that.data.deviceId,
                    serviceId: that.data.serviceId,
                    characteristicId: that.data.cd01,
                    state: true,
                    success: function (res) {
                      // success
                      console.log(&#39;notifyBLECharacteristicValueChanged success&#39;, res);
                    },
                    fail: function (res) {
                      // fail
                    },
                    complete: function (res) {
                      // complete
                    }
                  })
                  wx.notifyBLECharacteristicValueChanged({
                    deviceId: that.data.deviceId,
                    serviceId: that.data.serviceId,
                    characteristicId: that.data.cd02,
                    state: true,
                    success: function (res) {
                      // success
                      console.log(&#39;notifyBLECharacteristicValueChanged success&#39;, res);
                    },
                    fail: function (res) {
                      // fail
                    },
                    complete: function (res) {
                      // complete
                    }
                  })
                  wx.notifyBLECharacteristicValueChanged({
                    deviceId: that.data.deviceId,
                    serviceId: that.data.serviceId,
                    characteristicId: that.data.cd03,
                    state: true,
                    success: function (res) {
                      // success
                      console.log(&#39;notifyBLECharacteristicValueChanged success&#39;, res);
                    },
                    fail: function (res) {
                      // fail
                    },
                    complete: function (res) {
                      // complete
                    }
                  })

                  wx.notifyBLECharacteristicValueChanged({
                    // 启用 notify 功能
                    // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
                    deviceId: that.data.deviceId,
                    serviceId: that.data.serviceId,
                    characteristicId: that.data.cd04,
                    state: true,
                    success: function (res) {
                      console.log(&#39;notifyBLECharacteristicValueChanged success&#39;, res)
                    }
                  })

                }, fail: function (res) {
                  console.log(res);
                }
              })
            }
              , 1500);
          }
        })
      },
      fail: function (res) {
        // fail
      },
      complete: function (res) {
        // complete
      }
    })
  },

  /**
   * 发送 数据到设备中
   */
  bindViewTap: function () {
    var that = this;
    var hex = &#39;AA5504B10000B5&#39;
    var typedArray = new Uint8Array(hex.match(/[\da-f]{2}/gi).map(function (h) {
      return parseInt(h, 16)
    }))
    console.log(typedArray)
    console.log([0xAA, 0x55, 0x04, 0xB1, 0x00, 0x00, 0xB5])
    var buffer1 = typedArray.buffer
    console.log(buffer1)
    wx.writeBLECharacteristicValue({
      deviceId: that.data.deviceId,
      serviceId: that.data.serviceId,
      characteristicId: that.data.cd20,
      value: buffer1,
      success: function (res) {
        // success
        console.log("success 指令发送成功");
        console.log(res);
      },
      fail: function (res) {
        // fail
        console.log(res);
      },
      complete: function (res) {
        // complete
      }
    })

  },
  /**
   * ArrayBuffer 转换为 Hex
   */
  buf2hex: function (buffer) { // buffer is an ArrayBuffer
    return Array.prototype.map.call(new Uint8Array(buffer), x => (&#39;00&#39; + x.toString(16)).slice(-2)).join(&#39;&#39;);
  }
})
로그인 후 복사

5. 효과 표시

확인 명령을 보냅니다. 결과 얻기

위 내용은 WeChat 애플릿이 Bluetooth를 구현하는 방법에 대한 공유 예의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
1 몇 달 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

win11에서 헤드폰과 스피커를 동시에 재생하는 문제 해결 win11에서 헤드폰과 스피커를 동시에 재생하는 문제 해결 Jan 06, 2024 am 08:50 AM

일반적으로 우리는 동시에 헤드폰이나 스피커 중 하나만 사용하면 됩니다. 그러나 일부 친구는 win11 시스템에서 헤드폰과 스피커가 동시에 들리는 문제가 발생했다고 보고했습니다. realtek 패널에서 끄면 괜찮을 것입니다. 아래를 살펴보겠습니다. win11에서 헤드폰과 스피커 소리가 함께 들리면 어떻게 해야 합니까? 1. 먼저 바탕 화면에서 "제어판"을 찾아 엽니다. 2. 제어판에 들어가서 "하드웨어 및 소리"를 찾아 엽니다. 스피커 아이콘이 있는 "Realtek High Definition"" 4. "스피커"를 선택하고 "후면 패널"을 클릭하여 스피커 설정으로 들어갑니다. 5. 열면 장치 유형이 표시됩니다. 헤드폰을 끄려면 "헤드폰"을 선택 취소하세요.

생체 내 전화에서 Bluetooth를 켜는 방법 생체 내 전화에서 Bluetooth를 켜는 방법 Mar 23, 2024 pm 04:26 PM

1. 아래와 같이 화면 하단을 위로 스와이프하여 제어 센터를 불러옵니다. 블루투스 스위치를 클릭하여 블루투스를 켭니다. 2. 페어링된 다른 Bluetooth 장치에 연결하거나 [Bluetooth 장치 검색]을 클릭하여 새 Bluetooth 장치에 연결할 수 있습니다. 다른 친구가 귀하의 휴대폰을 검색하여 Bluetooth 스위치에 연결하도록 하려면 [감지 기능]을 켜십시오. 방법 2. 1. 휴대폰 바탕 화면에 들어가서 설정을 찾아 엽니다. 2. [설정] 디렉토리를 아래로 내려 [추가 설정]을 찾은 후 클릭하여 들어갑니다. 3. [블루투스]를 클릭하여 열고 블루투스 스위치를 켜서 블루투스를 켭니다.

win11 시스템 장치 관리자에 Bluetooth 모듈이 없습니다. win11 시스템 장치 관리자에 Bluetooth 모듈이 없습니다. Mar 02, 2024 am 08:01 AM

win11 시스템의 장치 관리자에 Bluetooth 모듈이 없습니다. Windows 11 시스템을 사용하는 경우 장치 관리자에 Bluetooth 모듈이 없는 상황이 발생할 수 있습니다. Bluetooth 기술은 현대 사회에서 매우 보편화되었으며, 무선 장치를 연결하기 위해 Bluetooth를 사용해야 하는 경우가 많기 때문에 이는 일상적인 사용에 불편을 초래할 수 있습니다. 장치 관리자에서 Bluetooth 모듈을 찾을 수 없는 경우 걱정하지 마십시오. 가능한 해결 방법은 다음과 같습니다. 1. 하드웨어 연결을 확인하십시오. 먼저 컴퓨터나 노트북에 실제로 Bluetooth 모듈이 있는지 확인하십시오. 일부 장치에는 Bluetooth 기능이 내장되어 있지 않을 수 있으며, 이 경우 연결하려면 외부 Bluetooth 어댑터를 구입해야 합니다. 2. 드라이버 업데이트: 장치 관리자에 Bluetooth 모듈이 없는 이유는 드라이버 때문인 경우가 있습니다.

블루투스를 사용하지 않는 해리포터 저주 스왑 문제를 해결하는 방법 블루투스를 사용하지 않는 해리포터 저주 스왑 문제를 해결하는 방법 Mar 21, 2024 pm 04:30 PM

Harry Potter: Magic Awakening은 최근 주문 교환 기능을 추가했는데, 이를 위해서는 플레이어가 주문을 교환하기 위해 블루투스나 WiFi를 사용해야 합니다. 일부 플레이어는 블루투스 교환을 사용할 수 없다는 것을 알게 되는데 어떻게 블루투스를 사용하여 주문을 교환할 수 있습니까? 다음으로, 블루투스를 이용해 해리포터 주문을 교환할 수 없는 문제에 대한 해결책을 에디터가 알려드리겠습니다. 도움이 되셨으면 좋겠습니다. 블루투스를 사용하지 않는 해리포터 주문 교환 해결 방법 1. 먼저 플레이어는 도서관에서 주문 교환을 찾은 다음 블루투스나 WiFi를 사용하여 교환할 수 있습니다. 2. 블루투스 사용을 클릭하면 새 설치 패키지를 다운로드해야 한다는 메시지가 표시되지만 이전에 다운로드한 적이 있어 일부 플레이어가 혼란을 겪습니다. 3. 실제로 플레이어는 스토어에서 새 설치 패키지를 다운로드할 수 있으며, Android의 경우 Apple 스토어에서 업데이트할 수 있습니다.

Bluetooth 5.3에는 휴대폰 지원이 필요합니까? 자세한 내용은 참조하세요. Bluetooth 5.3에는 휴대폰 지원이 필요합니까? 자세한 내용은 참조하세요. Jan 14, 2024 pm 04:57 PM

휴대폰을 구입하면 휴대폰 매개변수에 Bluetooth 지원 옵션이 있는 것을 볼 수 있습니다. 때로는 구입한 Bluetooth 헤드셋이 휴대폰과 일치하지 않는 상황이 발생하므로 Bluetooth 5.3을 지원해야 합니다. 휴대폰은 사실 필요하지 않아요. Bluetooth 5.3에는 휴대폰 지원이 필요합니까? 답변: Bluetooth 5.3에는 휴대폰 지원이 필요합니다. 단, 블루투스를 지원하는 모든 휴대폰은 사용이 가능합니다. 1. 블루투스는 이전 버전과 호환되지만 해당 버전을 사용하려면 휴대폰 지원이 필요합니다. 2. 예를 들어 Bluetooth 5.3을 사용하는 무선 Bluetooth 헤드셋을 구입하는 경우. 3. 그러면 휴대폰이 Bluetooth 5.0만 지원하는 경우 연결 시 Bluetooth 5.0이 사용됩니다. 4. 따라서 이 휴대폰을 사용하여 헤드폰을 연결하여 음악을 들을 수는 있지만 속도는 Bluetooth만큼 좋지 않습니다.

Logitech 키보드를 페어링하는 방법 [USB 수신기, Bluetooth, iPad] Logitech 키보드를 페어링하는 방법 [USB 수신기, Bluetooth, iPad] Nov 18, 2023 pm 11:27 PM

PC에서 새 무선 키보드를 사용하려면 먼저 페어링해야 합니다. 이 가이드에서는 Logitech 키보드를 올바르게 페어링하는 방법을 보여 드리겠습니다. 프로세스는 매우 간단하고 몇 번의 클릭만으로 완료됩니다. 저희와 함께하시면 PC에서 수행하는 방법을 알려드리겠습니다. Logitech 키보드를 페어링 모드로 전환하려면 어떻게 해야 합니까? 테스트, 검토 및 점수를 매기는 방법은 무엇입니까? 지난 6개월 동안 우리는 콘텐츠 제작 방식에 대한 새로운 검토 시스템을 구축하기 위해 열심히 노력해 왔습니다. 이를 사용하여 우리는 우리가 제작한 가이드에 대한 실용적이고 실무적인 전문 지식을 제공하기 위해 기사의 대부분을 다시 작성했습니다. 자세한 내용은 Windows 보고서에서 테스트, 검토 및 평가하는 방법을 읽어보세요. 키보드를 엽니다. LED가 깜박이지 않는 경우

Win11 시스템에서 Bluetooth를 연결할 수 없는 문제에 대한 해결 방법 Win11 시스템에서 Bluetooth를 연결할 수 없는 문제에 대한 해결 방법 Jan 29, 2024 pm 02:36 PM

Win11 시스템에서 Bluetooth를 사용할 수 없으면 어떻게 해야 합니까? Win11 시스템이 출시되면서 많은 사용자가 컴퓨터를 업그레이드하고 싶어합니다. 그러나 일부 사용자는 업그레이드 후 일반적인 문제에 직면했습니다. Bluetooth가 작동하지 않습니다. 이는 블루투스 장치에 의존하는 사람들에게는 실망스러운 문제입니다. 다행히도 이 문제를 해결하는 데 도움이 되는 몇 가지 간단한 솔루션이 있습니다. 먼저 컴퓨터를 다시 시작해 보세요. 때로는 시스템을 다시 시작하기만 하면 Bluetooth가 작동하지 않는 등 일부 문제가 해결될 수도 있습니다. 다시 시작한 후 Bluetooth가 제대로 작동하는지 확인하십시오. 다시 시작해도 문제가 해결되지 않으면 Bluetooth 드라이버를 업데이트해 보십시오. 때로는 오래되었거나 손상된 드라이버로 인해

삼성, 여러 갤럭시 휴대폰과 태블릿에 Bluetooth Auracast 오디오 기능 제공 삼성, 여러 갤럭시 휴대폰과 태블릿에 Bluetooth Auracast 오디오 기능 제공 Feb 21, 2024 pm 01:50 PM

2월 21일 뉴스에 따르면, 삼성전자는 OneUI6.1 이상으로 업그레이드된 갤럭시 S23 시리즈, ZFold5, ZFlip5 휴대폰, 갤럭시 탭 S9 시리즈 태블릿에 블루투스 아우라캐스트 오디오 방송 기능을 탑재한다고 오늘 발표했습니다. 삼성전자는 지난해부터 갤럭시 버즈 2 프로 헤드셋에 블루투스 아우라캐스트 오디오 방송 기능 지원을 잇달아 추가했고, OneUI6.1을 탑재한 갤럭시 S24 시리즈 휴대폰에도 지원을 추가했다. OneUI6.1로 업그레이드할 수 있는 삼성 장치의 경우 "설정" > "블루투스" > "점 3개 메뉴" > "Auracast를 사용하여 사운드 방송"을 열 수 있습니다.

See all articles