当前位置:网站首页>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
android
andios
Are 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 :
边栏推荐
- Redis——Cluster数据分布算法&哈希槽
- 代码技巧——Controller参数注解@RequestParam
- sprintf_s的使用方法
- RestTemplate请求时设置请求头,请求参数,请求体。
- 20201025 visual studio2019 qt5.14 use of signal and slot functions
- CUDA中的存储空间修饰符
- Redis---1. Data structure characteristics and operation
- Sentinel rules persist to Nacos
- CUDA用户对象
- The intern left a big hole when he ran away and made two online problems, which made me miserable
猜你喜欢
默认google浏览器打不开链接(点击超链接没有反应)
QQ email cannot receive the email sent by Jenkins using email extension after construction (timestamp or auth...)
Win10桌面图标没有办法拖动(可以选中可以打开可以删除新建等操作但是不能拖动)
Sparse array (nonlinear structure)
TensorRT的数据格式定义详解
The intern left a big hole when he ran away and made two online problems, which made me miserable
Sentinel规则持久化到Nacos
qq邮箱接收不到jenkins构建后使用email extension 发送的邮件(timestamp 或 auth.......)
Win10:添加或者删除开机启动项,在开机启动项中添加在用户自定义的启动文件
Redis——热点key问题
随机推荐
ctf三计
ctf-web之练习赛
利用NVIDIA GPU将Minecraft场景渲染成真实场景
DeprecationWarning: .ix is deprecated. Please use.loc for label based indexing or.iloc for positi
Présence d'une panne de courant anormale; Problème de gestion de la fsck d'exécution résolu
Warp matrix functions in CUDA
Unexpected inconsistency caused by abnormal power failure; Run fsck manually problem resolved
CUDA中的异步数据拷贝
Redis——大Key問題
MySQL的10大经典错误
MySQL的10大經典錯誤
[literature reading and thought notes 13] unprocessing images for learned raw denoising
Redis - big key problem
一口气说出 6 种实现延时消息的方案
记录一次RDS故障排除--RDS容量徒增
Sentinel规则持久化到Nacos
pytest(1) 用例收集规则
CUDA中的Warp matrix functions
[self cultivation of programmers] - Reflection on job hunting Part II
2020-9-23 QT的定时器Qtimer类的使用。