实现安卓和IOS系统给蓝牙模块发送指令。
//index.js
//获取应用实例
var app = getApp();
var devices_list = []
Page({
data: {
status: "",
sousuo: "",
connectedDeviceId: "", //已连接设备uuid
services: "", // 连接设备的服务
characteristics: "", // 连接设备的状态值
writeServicweId: "", // 可写服务uuid
writeCharacteristicsId: "",//可写特征值uuid
readServicweId: "", // 可读服务uuid
readCharacteristicsId: "",//可读特征值uuid
notifyServicweId: "", //通知服务UUid
notifyCharacteristicsId: "", //通知特征值UUID
inputValue: "",
characteristics1: "", // 连接设备的状态值
},
onLoad: function () {
if (wx.openBluetoothAdapter) {
wx.openBluetoothAdapter()
} else {
// 如果希望用户在最新版本的客户端上体验您的小程序,可以这样子提示
wx.showModal({
title: '提示',
content: '当前微信版本过低,无法使用该功能,请升级到最新微信版本后重试。'
})
}
//打开蓝牙适配
var that = this;
this.lanya4();
},
// 初始化蓝牙适配器
lanya1: function () {
var that = this;
wx.openBluetoothAdapter({
success: function (res) {
that.setData({
msg: "初始化蓝牙适配器成功!" + JSON.stringify(res),
})
//监听蓝牙适配器状态
wx.onBluetoothAdapterStateChange(function (res) {
if (!res.available) {
wx.showModal({
title: '提示',
content: '请打开蓝牙!'
})
}
if (!res.discovering) {
wx.showModal({
title: '提示',
content: '已停止设备搜索'
})
}
})
}
})
},
// 本机蓝牙适配器状态
lanya2: function () {
var that = this;
wx.getBluetoothAdapterState({
success: function (res) {
if (!res.available) {
wx.showModal({
title: '提示',
content: '请打开蓝牙!'
})
}
//监听蓝牙适配器状态
wx.onBluetoothAdapterStateChange(function (res) {
if (!res.available) {
wx.showModal({
title: '提示',
content: '请打开蓝牙!'
})
}
})
}
})
},
//搜索设备
lanya3: function () {
var that = this;
wx.startBluetoothDevicesDiscovery({
success: function (res) {
that.setData({
msg: "搜索设备" + JSON.stringify(res),
})
//监听蓝牙适配器状态
wx.onBluetoothAdapterStateChange(function (res) {
if (!res.available) {
wx.showModal({
title: '提示',
content: '请打开蓝牙!'
})
}
})
}
})
},
// 获取所有已发现的设备
ab2hex: function (buffer) {
var hexArr = Array.prototype.map.call(
new Uint8Array(buffer),
function (bit) {
return ('00' + bit.toString(16)).slice(-2)
}
)
return hexArr.join('');
}, buf2hex: function (buffer) {
return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('');
},
lanya4: function () {
var that = this;
that.lanya2();
that.lanya3();
wx.getBluetoothDevices({
success: function (res) {
//是否有已连接设备