当前位置:网站首页>Fe - wechat applet - Bluetooth ble development research and use
Fe - wechat applet - Bluetooth ble development research and use
2022-07-02 06:38:00 【Xiao Ming Yuan】
background
Recent research weex When , I feel more than a little pain , From documentation to sample code , Then to the code warehouse , What a mess . Look back Wechat applet documentation It's perfect , The existing products of the company deal with hardware , Therefore, we have made great efforts in the development of Bluetooth . Beginning of the year , When I see the applet , Its Bluetooth does not support android , A lot of features are missing . I don't know when , Wechat has updated Bluetooth (ble) Development content , Today, I have the honor to try this in wechat applet , Tried and tested .

Let's talk about feelings first , advantage : Only according to api Document writing js that will do , Can be in The WeChat android and ios End of the applet used , strong . shortcoming : It belongs to the wechat applet ecological environment .
design sketch
Basic test content : Connect our company ble product , And can transmit data normally , Last , And test it in android and ios In the wechat applet of , Whether it can operate normally .
- scanning ble equipment
- Connect ble equipment
- receive ble Device data
androidandiosAre they all normal
(ios design sketch ) 
( In the figure ’ Bluetooth is not turned on ’ The words change when Bluetooth is turned off and on )
1、ble- initialization
Initialization will determine whether it supports ble Whether you can get bleAdapter;
bleInit:function(){
console.log(' Initialize Bluetooth ')
let self = this
wx.openBluetoothAdapter({
success: function(res) {
self.setData({
bleAdapterStatus: " Successful initialization "
})
},
fail:function(msg){
self.setData({
bleAdapterStatus: " initialization failed "
})
wx.showModal({
showCancel:false,
title: ' Tips ',
content: ' Device Bluetooth is not turned on , Please turn on the Bluetooth function ',
success:function(res){
if (res.confirm) {
//console.log(' The user clicks ok ')
// Exit applet
}
}
});
}
});
}2、ble- Scan Bluetooth
Basic steps :ble initialization => Scanning equipment => Get device information
onScanClick:function(event){
console.log(' The scan starts ')
let self = this
wx.openBluetoothAdapter({
success: function(res) {
// Scan Bluetooth
self.bleDisCovery()
self.setData({
bleAdapterStatus:" Successful initialization "
})
},
fail:function(error){
self.setData({
bleAdapterStatus: " initialization failed "
})
wx.showModal({
showCancel: false,
title: ' Tips ',
content: ' Device Bluetooth is not turned on , Please turn on the Bluetooth function ',
success: function (res) {
if (res.confirm) {
//console.log(' The user clicks ok ')
}
}
});
},
complete:function(){
//console.log('complete')
}
});
},,
/** * Parse data information */
bleFound:function(){
console.log(" Discover device information ")
let self =this
wx.onBluetoothDeviceFound(function (res) {
let devices = res.devices
console.log(devices)
let length = self.data.bleChips.length
let devicesLength = devices.length
if (devicesLength > length){
self.data.bleChips = devices
self.setData({
bleChips: devices
});
}
console.log(self.data.bleChips)
});
},
/** * Scanning equipment */
bleDisCovery:function(){
console.log(" Scan Bluetooth ")
let self = this
wx.startBluetoothDevicesDiscovery({
interval:1000,
success: function(res){
self.bleFound();
}
});
},3、ble- Connecting device
The scanned data list displays , Pay attention to the connection button , Click event to send parameters , adopt data- Custom parameter name ;
Such as my data-item : The parameter name is item ;
<view wx:if="{
{!bleConnSuccess}}" class='scan_result' wx:for="{
{
bleChips}}"> <text class="result_text">{
{
index}}-{
{
item.name}}-{
{
item.deviceId}}</text> <button bindtap='onConnBle' data-item='{
{
item}}'> Connect </button> </view>secondly , receive data :
onConnBle:function(e){
// Stop scanning
wx.stopBluetoothDevicesDiscovery({
success: function(res) {
},
});
// Receive the parameters of click event
let device = e.currentTarget.dataset.item
console.log(`conn ble >> ${device}`)
this.setData({
bleChipInfo: device
})
let deviceId = device.deviceId
let self = this
// Connecting device
console.log(" In connection device ...")
wx.createBLEConnection({
deviceId: deviceId,
success: function(res) {
wx.showToast({
title: ' Successful connection ',
});
// Successful connection , open notify
setTimeout(function(){
self.bleServices(deviceId)
},1500)
},
fail:function(errMsg){
wx.showToast({
title: ` The connection fails :${errMsg}`,
})
}
});
}4、ble- obtain services
bleServices: function (deviceId){
let self = this
wx.getBLEDeviceServices({
deviceId: deviceId,
success: function (res) {
wx.showToast({
title: 'service success',
})
// In the equipment services
let services = res.services
for(let index in services){
let service= services[index]
console.log(service)
}
console.log('device services:', res.services)
}
})
},5、ble-service obtain characteristics
bleServiceChart: function (deviceId,serviceId){
let self = this;
wx.getBLEDeviceCharacteristics({
// there deviceId It needs to be up there getBluetoothDevices or onBluetoothDeviceFound Interface
deviceId: deviceId,
// there serviceId It needs to be up there getBLEDeviceServices Interface
serviceId: serviceId,
success: function (res) {
console.log('device getBLEDeviceCharacteristics:', res.characteristics)
let characteristics = res.characteristics
for (let index in characteristics){
let characteristic = characteristics[index]
//
}
console.log(characteristic)
}
self.openNotify(deviceId)
}
})
},6、ble- notify data
Turn on notify data , To use onBLECharacteristicValueChange Receive data ;
openNotify: function (deviceId) {
this.setData({
bleConnSuccess: true
});
let self = this
wx.notifyBLECharacteristicValueChange({
deviceId: deviceId,
serviceId: ' Yours service id',
characteristicId: ' Yours characteristic Id',
state: true,
success: function (res) {
console.log('notify success')
self.onNotifyChange()
wx.showToast({
title: 'notify success',
});
},
fail: function (err) {
console.log(err)
wx.showToast({
title: 'notify fail',
});
}
});
}7、ble - receive data
onNotifyChange:function(){
// receive data
let self = this
wx.onBLECharacteristicValueChange(function (res) {
console.log(res.characteristicId)
let byteDatas = Array.from(new Int8Array(res.value))
console.log(byteDatas)
const data = byteDatas.join(',')
self.setData({
bleNotifyData:data
});
console.log(data)
});
},Last
Write and read operations , I won't explain too much here , The official documents have made it clear ;
matters needing attention
stay ios and android When testing ,android The platform does not need to get service and characteristic, You can start notify ; And in the ios The platform must manually get what you want to operate service and characteristic, Otherwise notify You don't succeed ;
Github :
边栏推荐
- AtCoder Beginner Contest 253 F - Operations on a Matrix // 树状数组
- Dynamic global memory allocation and operation in CUDA
- Error "list" object is not callable in Web automatic switching window
- 【每日一题】—华为机试01
- Redis——热点key问题
- JS modification element attribute flipping commonly used in selenium's Web Automation
- Sparse array (nonlinear structure)
- Cglib agent - Code enhancement test
- CUDA中的Warp matrix functions
- Linked list (linear structure)
猜你喜欢

Latex 编译报错 I found no \bibstyle & \bibdata & \citation command

【张三学C语言之】—深入理解数据存储

查询GPU时无进程运行,但是显存却被占用了

Detailed definition of tensorrt data format

Sentinel规则持久化到Nacos

Sentinel Alibaba open source traffic protection component
![[literature reading and thought notes 13] unprocessing images for learned raw denoising](/img/a5/ed26a90b3edd75a37b2e5164f6b7d2.png)
[literature reading and thought notes 13] unprocessing images for learned raw denoising

20201002 vs 2019 qt5.14 developed program packaging

pytest(2) mark功能

The intern left a big hole when he ran away and made two online problems, which made me miserable
随机推荐
eslint配置代码自动格式化
Three suggestions for all students who have graduated and will graduate
AWD学习
10 erreurs classiques de MySQL
日志 - 7 - 记录一次丢失文件(A4纸)的重大失误
Is there a really free applet?
重载全局和成员new/delete
selenium+msedgedriver+edge浏览器安装驱动的坑
Virtualenv and pipenv installation
Sublime Text 配置php编译环境
Error "list" object is not callable in Web automatic switching window
浏览器滚动加载更多实现
ctf-web之练习赛
奇葩pip install
FE - 微信小程序 - 蓝牙 BLE 开发调研与使用
TensorRT的功能
sprintf_ How to use s
CUDA and Direct3D consistency
Fe - weex uses a simple encapsulated data loading plug-in as the global loading method
Uploading attachments using Win32 in Web Automation