当前位置:网站首页>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 :
边栏推荐
- Warp matrix functions in CUDA
- Storage space modifier in CUDA
- Redis——缓存击穿、穿透、雪崩
- TensorRT的命令行程序
- CUDA中的线程层次
- NodeJs - Express 中间件修改 Header: TypeError [ERR_INVALID_CHAR]: Invalid character in header content
- CUDA中的动态全局内存分配和操作
- ModuleNotFoundError: No module named ‘jieba.analyse‘; ‘jieba‘ is not a package
- 看完有用的blog
- TensorRT中的循环
猜你喜欢
随机推荐
Find the highest value of the current element Z-index of the page
Redis---1. Data structure characteristics and operation
构建学习tensorflow
Virtualenv and pipenv installation
TensorRT的功能
Warp matrix functions in CUDA
CUDA中内置的Vector类型和变量
selenium的web自动化中常用的js-修改元素属性翻页
No process runs when querying GPU, but the video memory is occupied
分布式事务 :可靠消息最终一致性方案
Selenium+msedgedriver+edge browser installation driver pit
Redis——大Key问题
20210306转载如何使TextEdit有背景图片
Distributed transactions: the final consistency scheme of reliable messages
Redis - big key problem
Kotlin - verify whether the time format is yyyy MM DD hh:mm:ss
Redis---1.数据结构特点与操作
底层机制Mvcc
Win电脑截图黑屏解决办法
Is there a really free applet?

![Data science [9]: SVD (2)](/img/2c/f1a8c3ff34ff3f3cc6e26157a32bfd.png)







