小程序硬件配网的两种方式

现在智能家居,物联网很多地方用到硬件配网,我记一下我用过的两种

1.一键配网:

这个现在小程序里面还没有,可以用JSSDK里面的的,然后用web-view组件引入就行

           /* $.ajax({//获取:access_token              

                 url:'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx1bd659ad9f7&secret=564c61888041393ca96ea3ac3f601d9d',
                type:"get",
                dataType:"json",
                crossDomain: true,
                async: true,
                success: function (result) {
                    console.log(JSON.stringify(result))
                },
                error: function (result) {
                    alert(JSON.stringify(result))
                }
            });
          $.ajax({//获取:signature
                url:'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=26_9S9g8BzLnKKomKLXDW-idJC0gtssZJclVyXfpvf-F04ePh7qB9xPxogVU0KhDXm0zUtuQ8md_ddIKuCi78hmY_tZl60PlVXfbvdiCEiCcRE9itGFlN54ATS6lPJwyabdInxjRsXWykQlkRKPAKIaAEAQAY&type=jsapi',
                type:"get",
                dataType:"jsonp",
                async: true,
                success: function (result) {
                    console.log(JSON.stringify(result))
                },
                error: function (result) {
                    alert(result);
                }
                 });*/
   
 
        
          wx.config({
                debug: false,
                beta: true,
                appId: '', // 必填,公众号的唯一标识
                timestamp: '1571309318', // 必填,生成签名的时间戳
                nonceStr: 'cXIZpY0OGduBJ8RR', // 必填,生成签名的随机串
                signature: '',// 必填,签名通过上边两个方法可以获取到,上边两方法是微信基于安全考虑后台实现的,最后给你返回signature
                jsApiList: [
                    'chooseImage',
                    'configWXDeviceWiFi'
                    
                ] // 必填,需要使用的JS接口列表
        });
         wx.ready(function(){
           wx.checkJsApi({
                jsApiList: ['configWXDeviceWiFi'],
                success: function(res) {
                    wx.invoke('configWXDeviceWiFi', {}, function(res){
                     console.log(JSON.stringify(res))
                 });

                },error:function(res){
                
                  
                }
            });
        });

这样很简单的就自动调起微信一键配网的页面,只需要输入wifi密码确认就行

2.蓝牙配网(我这里用到是ESP32的BluFi模块),官网:https://docs.espressif.com/projects/esp-idf/zh_CN/latest/api-guides/blufi.html

我这里只是写了个demol,代码没有整理 ,有很多bug,但是可以跑起来

js :

var app = getApp()
var temp = []
var string_temp = ""
var serviceId ="";
var characteristicId = "";
Page({
data: {
isbluetoothready: false,
defaultSize: 'default',
primarySize: 'default',
warnSize: 'default',
disabled: false,
plain: false,
loading: false,
searchingstatus: false,
onreceiving: false,
list: [],
receive_data: 'none',
bleSendSequence: 0,
connectedDeviceId:"",
deviceId:"",
wifiSSID:"",
wifipassword:""
},
onLoad: function () {
var that=this;
wx.startWifi({ //初始化wifi
success: function (res) {
wx.getConnectedWifi({
success: function (e) {
that.setData({
wifiSSID: e.wifi.SSID
})
console.log(JSON.stringify(e))
},
fail: function (e) {
console.log(JSON.stringify(e))
}
})

}

});
},
open_BLE: function () {
var that = this
that.setData({
isbluetoothready: !that.data.isbluetoothready,
})
if (that.data.isbluetoothready) {
//开启蓝牙模块并初始化
wx.openBluetoothAdapter({
success: function (res) {
},
fail: function (res) {
wx.showModal({
title: '提示',
content: '请检查手机蓝牙是否打开',
})
}
})
//开启蓝牙模块并初始化

//检查蓝牙模块是否初始化成功
wx.getBluetoothAdapterState({
success: function (res) {
console.log(JSON.stringify(res))
var available = res.available
if (!available) {
wx.showToast({
title: '蓝牙初始化失败',
icon: 'loading',
duration: 2000
})
}
else {
wx.showToast({
title: '蓝牙初始化成功',
icon: 'success',
duration: 2000
})
}
}
})
//检查蓝牙模块是否初始化成功
}
else {
wx.closeBLEConnection({
deviceId: that.data.connectedDeviceId,
complete: function (res) {
that.setData({
deviceconnected: false,
connectedDeviceId: ""
})
wx.showToast({
title: '蓝牙连接断开',
icon: 'success',
duration: 2000
})
}
})
setTimeout(function () {
that.setData({
list: []
})
//释放蓝牙适配器
wx.closeBluetoothAdapter({
success: function (res) {
that.setData({
isbluetoothready: false,
deviceconnected: false,
devices: [],
searchingstatus: false,
})
wx.showToast({
title: '蓝牙适配器释放',
icon: 'success',
duration: 2000
})
},
fail: function (res) {

}
})
//释放蓝牙适配器
}, 1000)
}
},

search_BLE: function () {
temp = []
var that = this
if (!that.data.searchingstatus) {
var that = this
that.setData({
searchingstatus: !that.data.searchingstatus
})
//开始搜索附近蓝牙设备
wx.startBluetoothDevicesDiscovery({
success: function (res) {
wx.showToast({
title: '开始搜索BLE',
icon: 'loading',
duration: 1000
})
setTimeout(function () {
//获取发现的蓝牙设备
wx.getBluetoothDevices({
success: function (res) {
console.log(JSON.stringify(res))
for (var i = 0; i < res.devices.length; i++) {
if (res.devices[i].name =='Seal_前置') {
var arr = [res.devices[i]]
that.setData({
list: arr
});
//停止搜索附近蓝牙设备
wx.stopBluetoothDevicesDiscovery({
success: function (res) {
that.setData({
searchingstatus: !that.data.searchingstatus
});

}
})
console.log(JSON.stringify(that.data.list))
}
}
 
}
})
 
}, 2000)
 
}
})
}
},
connectTO: function (e) {
var that = this
wx.showLoading({
title: '连接蓝牙设备中...',
})
console.log(e.currentTarget.id);
wx.createBLEConnection({
deviceId: e.currentTarget.id,
success: function (res) {
console.log(JSON.stringify(res))
wx.getBLEDeviceServices({
deviceId: e.currentTarget.id,
success: function (res) {
serviceId = res.services[0].uuid;
wx.getBLEDeviceCharacteristics({
deviceId: e.currentTarget.id,
serviceId: serviceId,
success: function (res) {
console.log(JSON.stringify(res))
for (var i = 0; i < res.characteristics.length; i++) {
if (res.characteristics[i].properties.write ) {
characteristicId = res.characteristics[i].uuid
}
}
// 启用 notify 功能
wx.notifyBLECharacteristicValueChanged({
state: true,
deviceId: e.currentTarget.id,
serviceId: serviceId,
characteristicId: characteristicId,
success: function (res) {
console.log(JSON.stringify(res))
}
})

},
fail: function (res) {
}
})
},
fail: (res) => {
}
})
wx.hideLoading()
wx.showToast({
title: '连接成功',
icon: 'success',
duration: 1000
})
that.setData({
deviceconnected: true,
connectedDeviceId: e.currentTarget.id
})
 
// 启用 notify 功能
// ArrayBuffer转为16进制数
function ab2hex(buffer) {
var hexArr = Array.prototype.map.call(
new Uint8Array(buffer),
function (bit) {
return ('00' + bit.toString(16)).slice(-2)
}
)
return hexArr.join('');
}
// 16进制数转ASCLL码
function hexCharCodeToStr(hexCharCodeStr) {
var trimedStr = hexCharCodeStr.trim();
var rawStr = trimedStr.substr(0, 2).toLowerCase() === "0x" ? trimedStr.substr(2) : trimedStr;
var len = rawStr.length;
var curCharCode;
var resultStr = [];
for (var i = 0; i < len; i = i + 2) {
curCharCode = parseInt(rawStr.substr(i, 2), 16);
resultStr.push(String.fromCharCode(curCharCode));
}
return resultStr.join("");
}
//监听回调,接收数据
wx.onBLECharacteristicValueChange(function (characteristic) {
var hex = ab2hex(characteristic.value)
that.setData({
receive_data: hexCharCodeToStr(hex)
})
})
},
fail: function (res) {
wx.hideLoading()
wx.showToast({
title: '连接设备失败',
icon: 'success',
duration: 1000
})
that.setData({
connected: false
})
}
})
 
wx.stopBluetoothDevicesDiscovery({
success: function (res) {

}
})
},

formSubmit: function (e) {
this.bleSendCMD3()
},
bleSendCMD3() {
var that = this;
var ab = new ArrayBuffer(6)
var u8array = new Uint8Array(ab);
var LSB_Type = (0x02 << 2) | 0x00;
u8array[0] = LSB_Type;
u8array[1] = 0x00
u8array[2] = this.data.bleSendSequence;
u8array[3] = 1;
u8array[4] = 1;
this.data.bleSendSequence++;
wx.writeBLECharacteristicValue({
deviceId: that.data.connectedDeviceId,
serviceId: serviceId,
characteristicId: characteristicId,
value: ab,
success: function (res) {
console.log(JSON.stringify(res))
that.bindtap_buttom1()
},
fail(res) {
console.log(JSON.stringify(res))
}
})
},
//ESP32的蓝牙配网命令接口
bleSendCMD(frameControl, payload) {//账号
var that = this;
var ab = new ArrayBuffer(payload.length + 6)
var u8array = new Uint8Array(ab);
var LSB_Type = (0x02 << 2) | 0x01;
u8array[0] = LSB_Type;
u8array[1] = frameControl;
u8array[2] = this.data.bleSendSequence;
u8array[3] = payload.length;
for (let i = 0; i < payload.length; i++) {
u8array[4 + i] = payload[i];
}
this.data.bleSendSequence++;
wx.writeBLECharacteristicValue({
deviceId: that.data.connectedDeviceId,
serviceId: serviceId,
characteristicId: characteristicId,
value: ab,
success: function (res) {
console.log(JSON.stringify(res))
that.bindtap_buttom2()
},
fail(res) {
console.log(JSON.stringify(res))
}
})
},
bleSendCMD1(frameControl, payload) {//密码
var that = this;
var ab = new ArrayBuffer(payload.length + 6)
var u8array = new Uint8Array(ab);
var LSB_Type = (0x03 << 2) | 0x01;
u8array[0] = LSB_Type;
u8array[1] = frameControl;
u8array[2] = this.data.bleSendSequence;
u8array[3] = payload.length;
for (let i = 0; i < payload.length; i++) {
u8array[4 + i] = payload[i];
}
this.data.bleSendSequence++;
wx.writeBLECharacteristicValue({
deviceId: that.data.connectedDeviceId,
serviceId: serviceId,
characteristicId: characteristicId,
value: ab,
success: function (res) {
console.log(JSON.stringify(res))
that.bleSendCMD2()
},
fail(res) {
console.log(JSON.stringify(res))
}
})
},
bleSendCMD2() {//连接
var that = this;
var ab = new ArrayBuffer(3)
var u8array = new Uint8Array(ab);
var LSB_Type = (0x03 << 2) | 0x00;
u8array[0] = LSB_Type;
u8array[1] = 0x00;
u8array[2] = this.data.bleSendSequence;
this.data.bleSendSequence++;
wx.writeBLECharacteristicValue({
deviceId: that.data.connectedDeviceId,
serviceId: serviceId,
characteristicId: characteristicId,
value: ab,
success: function (res) {
console.log(JSON.stringify(res))
wx.showToast({
title: '连接成功',
icon: 'success',
duration: 2000
})

},
 
})
},
bindtap_buttom2() {
let password = '12345678'
let u8buffer = new Uint8Array(password.length)
for (var i = 0; i < password.length; i++) {
console.log(password.charCodeAt(i))
u8buffer[i] = password.charCodeAt(i)
}
this.bleSendCMD1(0, u8buffer)
},
bindtap_buttom1() {
let SSID = this.data.wifiSSID
let u8buffer = new Uint8Array(SSID.length)
for (var i = 0; i < SSID.length; i++) {
u8buffer[i] = SSID.charCodeAt(i)
}
this.bleSendCMD(0,u8buffer)
}
 
})
wxml:
<!--pages/mine/mine.wxml-->
<view class="container">
 
<view class="section"> <!-- 第一行 -->
<view class="content">
<text>蓝牙开关</text>
</view>
<view class="switch">
<switch checked="{{isbluetoothready}}" bindchange="open_BLE" />
</view>
</view>
 
<view class="section"> <!-- 第二行 -->
<button type="default" size="{{primarySize}}" loading="{{searchingstatus}}" plain="{{plain}}" disabled="{{disabled}}" bindtap="search_BLE"> {{searchingstatus?"搜索中":"搜索蓝牙"}} </button>
</view>
 
<block wx:for="{{list}}"> <!-- 第三行 -->
<view class="section" style="flex-direction:row" >
<view>
<text>设备名称: {{item.name}}\n</text>
<text>MAC地址: {{item.deviceId}}</text>
</view>
<view class="connection">
<button id="{{item.deviceId}}" size="mini"
bindtap="connectTO"> {{deviceconnected?"已连接":"连接"}} </button>
</view>
</view>
</block>
 
<block wx:if="{{deviceconnected}}"> <!-- 第四行 -->
<view >
<text>{{receive_data}}\n</text>
<button size="mini" bindtap="receiveMessages">接收</button>
</view>
<view class="send">
<form bindsubmit="formSubmit">
<text>数据发送:</text>
<button size="mini" formType="submit">发送</button>
</form>
</view>
</block>
 
</view>
wxss:
view {
display: inline-block;
}
.container {
padding: 0;
margin: 0;
align-items: flex-start;
}
.section {
display: inline-block;
width: 100%;
margin-top: 50rpx;
position: relative;
}
.connection {
margin-left: 90rpx;
}
.list {
margin-left: 20rpx;
}
.content {
margin-left: 100rpx;
padding: auto;
position: absolute;
top: 5rpx;
left: 10rpx;
}
.switch {
position: relative;
float: right;
margin-right: 100rpx;
}
button {
background: red\;
}
.list-item {
margin-top: 20rpx;
margin-bottom: 20rpx;
display: flex;
flex-direction: column;
box-sizing: border-box;
border: 1px dashed #000;
}
.list-item text {
margin-top: 10rpx;
}
.list-item button {
margin-right: 10rpx;
}
.recieve{
width: 100%
}
.recieve_textarea{
width: 100%;
margin-top: 10dpx;
}
input{
display: block;
border: 1px dashed;
width: 200px;
}
 

 

posted @ 2019-11-14 09:24  *沧海一粟*  阅读(2758)  评论(1编辑  收藏  举报