_____ 巴法云介绍
https://cloud.bemfa.com/docs/#/
特点: 支持发布/订阅模式
平台使用,参见文档
- 基本原理
1, 巴法云创建主题
2, 单片机程序里设置巴法云中的创建的主题
3, 巴法云里某主题下发送消息,单片机里因为订阅了主题,所以能收到消息
- 使用步骤
1, 登录注册
2, 获取私钥 UID
3, 创建主题
4, 推送消息
a, 在该主题处输入消息
b, 点击推送
- 平台接入协议
巴法云物联网平台基于TCP协议栈同时支持TCP心跳长连接和MQTT3.1.1协议。
* TCP创客云
发送任意数据 为心跳消息, 指令也算是心跳,但要以回车换行结尾。
心跳消息是告诉服务器设备还在线,建议60秒发送一次,超过65秒未发送心跳会掉线。
TCP服务器地址IP: bemfa.com, 端口号 8344
* TCP设备云
与 TCP 创客云协议相同,只是端口不同
端口号 8340
* MQTT 设备云
服务器地址:bemfa.com
普通端口:9501
加密端口:9503 ,支持TLS1.2
加密websocket协议端口:9504 , path:/wss
MQTT 支持Qos0 Qos1,支持retian保留消息,不支持qos2,使用qos2会被强制下线,次数过多可造成账号异常无法使用。
- HTTP API接入
单片机建议使用http默认端口80,https默认端口是443
_____ esp32c3 利用巴法云控制 led 程序
在巴法云网站上 TCP 创客云里新建主题,
建好了后可以直接推送消息
发送的消息是这样的格式: cmd=2&uid=b6feb740f6004cb09a4125d291dc5073&topic=weixin&msg=on
https://cloud.bemfa.com/docs/#/
esp32 客户端需要每 60s 发送心跳帧到服务器,否则连接会中断
from https://bemfa.blog.csdn.net/article/details/107019002?utm_relevant_index=2
#include "common.h"
#include "ota.h"
#include "network.h"
#include <WiFi.h>
#include <HTTPUpdate.h>
/**********************************/
extern void LED_init(void);
extern void LED_ON(void);
extern void LED_OFF(void);
extern void LED_task(void *parameter);
extern void KEY_init(void);
// ----------------------- 需要修改的地方
#define server_ip "bemfa.com" //巴法云服务器地址默认即可
#define server_port "8344" //服务器端口,tcp创客云端口8344
String UID = "b6feb740f6004cb09a4125d291dc5073"; //用户私钥,可在控制台获取,修改为自己的UID
String TOPIC = "weixin"; //主题名字,可在控制台新建
// -----------------------
//最大字节数
#define MAX_PACKET_SIZE 512
//设置心跳值60s
#define KEEP_ALIVEA_TIME 60 * 1000
//tcp客户端相关初始化,默认即可
WiFiClient TCPclient;
String TcpClient_Buff = ""; //初始化字符串,用于接收服务器发来的数据
unsigned int TcpClient_BuffIndex = 0;
unsigned long TcpClient_preTick = 0;
unsigned long preHeartTick = 0; //心跳
unsigned long preTCPStartTick = 0; //连接
bool preTCPConnected = false;
//相关函数初始化
//连接WIFI
void doWiFiTick();
//TCP初始化连接
void doTCPClientTick();
void startTCPClient();
void sendtoTCPServer(String p);
/*
*发送数据到TCP服务器
*/
void sendtoTCPServer(String p) {
if (!TCPclient.connected()) {
Serial.println("Client is not readly");
return;
}
TCPclient.print(p);
preHeartTick = millis(); //心跳计时开始,需要每隔60秒发送一次数据
}
/*
*初始化和服务器建立连接
*/
void startTCPClient() {
if (TCPclient.connect(server_ip, atoi(server_port))) {
Serial.print("\nConnected to server:");
Serial.printf("%s:%d\r\n", server_ip, atoi(server_port));
String tcpTemp = ""; //初始化字符串
tcpTemp = "cmd=1&uid=" + UID + "&topic=" + TOPIC + "\r\n"; //构建订阅指令
sendtoTCPServer(tcpTemp); //发送订阅指令
tcpTemp = ""; //清空
/*
//如果需要订阅多个主题,可发送 cmd=1&uid=xxxxxxxxxxxxxxxxxxxxxxx&topic=xxx1,xxx2,xxx3,xxx4\r\n
教程:https://bbs.bemfa.com/64
*/
preTCPConnected = true;
TCPclient.setNoDelay(true);
} else {
Serial.print("Failed connected to server:");
Serial.println(server_ip);
TCPclient.stop();
preTCPConnected = false;
}
preTCPStartTick = millis();
}
/*
*检查数据,发送心跳
*/
void doTCPClientTick() {
//检查是否断开,断开后重连
if (WiFi.status() != WL_CONNECTED)
return;
if (!TCPclient.connected()) { //断开重连
if (preTCPConnected == true) {
preTCPConnected = false;
preTCPStartTick = millis();
Serial.println();
Serial.println("TCP Client disconnected.");
TCPclient.stop();
} else if (millis() - preTCPStartTick > 1 * 1000) //重新连接
startTCPClient();
} else {
if (TCPclient.available()) { //收数据
char c = TCPclient.read();
TcpClient_Buff += c;
TcpClient_BuffIndex++;
TcpClient_preTick = millis();
if (TcpClient_BuffIndex >= MAX_PACKET_SIZE - 1) {
TcpClient_BuffIndex = MAX_PACKET_SIZE - 2;
TcpClient_preTick = TcpClient_preTick - 200;
}
}
if (millis() - preHeartTick >= KEEP_ALIVEA_TIME) { //保持心跳
preHeartTick = millis();
Serial.println("--Keep alive:");
sendtoTCPServer("ping\r\n"); //发送心跳,指令需\r\n结尾,详见接入文档介绍
}
}
if ((TcpClient_Buff.length() >= 1) && (millis() - TcpClient_preTick >= 200)) {
TCPclient.flush();
Serial.print("Rev string: ");
TcpClient_Buff.trim(); //去掉首位空格
Serial.println(TcpClient_Buff); //打印接收到的消息
String getTopic = "";
String getMsg = "";
if (TcpClient_Buff.length()
> 15) { //注意TcpClient_Buff只是个字符串,在上面开头做了初始化 String TcpClient_Buff = "";
//此时会收到推送的指令,指令大概为 cmd=2&uid=xxx&topic=light002&msg=off
int topicIndex = TcpClient_Buff.indexOf("&topic=")
+ 7; //c语言字符串查找,查找&topic=位置,并移动7位,不懂的可百度c语言字符串查找
int msgIndex = TcpClient_Buff.indexOf("&msg="); //c语言字符串查找,查找&msg=位置
getTopic = TcpClient_Buff.substring(topicIndex,
msgIndex); //c语言字符串截取,截取到topic,不懂的可百度c语言字符串截取
getMsg = TcpClient_Buff.substring(msgIndex + 5); //c语言字符串截取,截取到消息
Serial.print("topic:------");
Serial.println(getTopic); //打印截取到的主题值
Serial.print("msg:--------");
Serial.println(getMsg); //打印截取到的消息值
}
if (getMsg == "on") { //如果是消息==打开
LED_ON();
} else if (getMsg == "off") { //如果是消息==关闭
LED_OFF();
}
TcpClient_Buff = "";
TcpClient_BuffIndex = 0;
}
}
/*
WiFiTick
检查是否需要初始化WiFi
检查WiFi是否连接上,若连接成功启动TCP Client
控制指示灯
*/
void doWiFiTick() {
static bool startSTAFlag = false;
static bool taskStarted = false;
static uint32_t lastWiFiCheckTick = 0;
if (!startSTAFlag) {
startSTAFlag = true;
NET_connectToWifi(3000);
}
//未连接1s重连
if (WiFi.status() != WL_CONNECTED) {
if (millis() - lastWiFiCheckTick > 1000) {
lastWiFiCheckTick = millis();
}
}
//连接成功建立
else {
if (taskStarted == false) {
taskStarted = true;
Serial.print("\r\nGet IP Address: ");
Serial.println(WiFi.localIP());
startTCPClient();
}
}
}
// ----------------------- function definition -----------------------
void setup(void) {
LED_init();
Serial.begin(115200);
Serial.println();
Serial.println("enter setup:");
// start wifi if wifi info available
NET_connectToWifi(3000);
}
void loop(void) {
doWiFiTick();
doTCPClientTick();
}
_____ 微信小程序
按照上一节里的 blog 上传小程序
from https://bemfa.blog.csdn.net/article/details/107019002?utm_relevant_index=2
微信小程序提交审核那里选择体验版
小程序是和巴法云进行通信
esp32 是巴法云进行控制的
巴法云是服务器,其他两个都是客户端
微信小程序代码
里面的接口官方文档已经搜不到了,但用就行了
// pages/index/index
console.log('pages/index/index')
//获取应用实例
// initializing a reference to the global app instance for use in the page
const app = getApp();
// used to define a new page in the WeChat mini-programg
Page({
data: {
uid: "b6feb740f6004cb09a4125d291dc5073", //用户密钥,巴法云控制台获取
topic: "weixin", // 系统主题,控制台创建
device_status: "离线", //默认离线
powerstatus: "已关闭", //默认关闭
time: (new Date()).toString()
},
// “打开” 按钮触发函数
openclick: function () {
//当点击打开按钮,更新开关状态为打开
var that = this;
// 逻辑层和渲染层的数据传输
that.setData({
powerstatus: "已打开",
});
//控制接口
//请求设备状态,检查设备是否在线
//api 接口详细说明见巴法云接入文档 https://cloud.bemfa.com/docs/#/?id=_54-%e8%8e%b7%e5%8f%96%e8%ae%be%e5%a4%87%e5%9c%a8%e7%ba%bf
// 发送 post 请求
// 在樱花云上文档上搜到,巴法云上不一样,http://cherryer.com/docs/#/?id=_11-%e7%ae%80%e4%bb%8b
// 不重要,只用来测试
wx.request({
url: "https://api.bemfa.com/api/device/v1/data/1/", //api接口,详见接入文档
method: "POST",
data: {
//请求字段,详见巴法云接入文档,http接口
uid: that.data.uid,
topic: that.data.topic,
msg: "on", //发送消息为on的消息
},
header: {
"content-type": "application/x-www-form-urlencoded",
},
success(res) {
console.log(res.data);
// 显示提示框
wx.showToast({
title: "打开成功",
icon: "success",
duration: 1000,
});
},
});
},
//”关闭“按钮处理函数函数
closeclick: function () {
//当点击关闭按钮,更新开关状态为关闭
var that = this;
that.setData({
powerstatus: "已关闭",
});
//控制接口
wx.request({
url: "https://api.bemfa.com/api/device/v1/data/1/", //api接口,详见接入文档
method: "POST",
data: {
uid: that.data.uid,
topic: that.data.topic,
msg: "off",
},
header: {
"content-type": "application/x-www-form-urlencoded",
},
success(res) {
console.log(res.data);
wx.showToast({
title: "关闭成功",
icon: "success",
duration: 1000,
});
},
});
},
onLoad: function () {
var that = this;
//请求设备状态
//设备断开不会立即显示离线,由于网络情况的复杂性,离线1分钟左右才判断真离线
wx.request({
url: "https://api.bemfa.com/api/device/v1/status/", //状态api接口,详见巴法云接入文档
data: {
uid: that.data.uid,
topic: that.data.topic,
},
header: {
"content-type": "application/x-www-form-urlencoded",
},
success(res) {
console.log(res.data);
if (res.data.status === "online") {
that.setData({
device_status: "在线",
});
} else {
that.setData({
device_status: "离线",
});
}
console.log(that.data.device_status);
},
});
//请求询问设备开关/状态
wx.request({
url: "https://api.bemfa.com/api/device/v1/data/1/", //get接口,详见巴法云接入文档
data: {
uid: that.data.uid,
topic: that.data.topic,
},
header: {
"content-type": "application/x-www-form-urlencoded",
},
success(res) {
console.log(res.data);
if (res.data.msg === "on") {
that.setData({
powerstatus: "已打开",
});
}
console.log(that.data.powerstatus);
},
});
// 设置定时器,每五秒请求一下设备状态
setInterval(function () {
console.log("定时请求设备状态,默认五秒");
wx.request({
url: "https://api.bemfa.com/api/device/v1/status/", //get 设备状态接口,详见巴法云接入文档
data: {
uid: that.data.uid,
topic: that.data.topic,
},
header: {
"content-type": "application/x-www-form-urlencoded",
},
success(res) {
console.log(res.data);
if (res.data.status === "online") {
that.setData({
device_status: "在线",
});
} else {
that.setData({
device_status: "离线",
});
}
console.log(that.data.device_status);
},
});
//请求询问设备开关/状态
wx.request({
url: "https://api.bemfa.com/api/device/v1/data/1/", //get接口,详见巴法云接入文档
data: {
uid: that.data.uid,
topic: that.data.topic,
},
header: {
"content-type": "application/x-www-form-urlencoded",
},
success(res) {
console.log(res.data);
if (res.data.msg === "on") {
that.setData({
powerstatus: "已打开",
});
}
console.log(that.data.powerstatus);
},
});
}, 5000);
},
});