/*
功能:WIFI连接、巴法云平台控制、小程序控制、APP控制、小爱同学控制、舵机控制(可改成控制其它模块)、低功耗模式、定时进入低功耗模式并设置低功耗时间、获取当时时间(如需其它功能可参考巴法云技术文档)
参考链接:
https://cloud.bemfa.com/docs/#/
https://blog.csdn.net/bemfa/article/details/123634246?spm=1001.2014.3001.5501
https://blog.csdn.net/bemfa/article/details/122162435?spm=1001.2014.3001.5501
https://blog.csdn.net/bemfa/article/details/121489211?spm=1001.2014.3001.5501
https://blog.csdn.net/bemfa/article/details/121441910?spm=1001.2014.3001.5501
https://blog.csdn.net/bemfa/article/details/120057589?spm=1001.2014.3001.5501
https://blog.csdn.net/weixin_44614230/article/details/127131814?spm=1001.2014.3001.5502
*/
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266httpUpdate.h>
#include <Servo.h>
#define server_ip "bemfa.com" //巴法云服务器地址默认即可
#define server_port "8344" //服务器端口,tcp创客云端口8344
String get_url = "http://api.bemfa.com/api/time/now/?type=1";//详见接入文档,type=1是只获取时间,type=2是获取日期和时间
String upUrl = "http://bin.bemfa.com/b/xxxxxxxxxxxxxxxxxxxxxxxxxxxx";//固件链接
//********************需要修改的部分*******************//
#define wifi_name "xxxxx" //WIFI名称,区分大小写,不要写错
#define wifi_password "xxxxxxxx" //WIFI密码
String UID = "c43a1e6f281cfc0240dc591ddff74b6a"; //用户私钥,可在控制台获取,修改为自己的UID,建议在后缀上加上001到005,这样就可以使用小爱同学控制
String TOPIC = "xxxxxxxxx"; //主题名字,可在控制台新建
const int LED_Pin = 2; //单片机LED引脚值
#define servo_on 50 //设置舵机的PWM值——开灯(建议数值调大一点)
#define servo_middle 115 //设置舵机的PWM值——回中(防止舵机过载)
#define servo_off 155 //设置舵机的PWM值——关灯(建议数值调大一点)
//**************************************************//
uint16_t hour , minute , second;//返回时间参数
Servo myservo;//舵机声明
//最大字节数
#define MAX_PACKETSIZE 512
//设置心跳值60s
#define KEEPALIVEATIME 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();
void startSTA();
//TCP初始化连接
void sendtoTCPServer(String p);
void startTCPClient();
void doTCPClientTick();
//固件升级函数
void updateBin();
//获取北京时间
void getTime();
//led控制函数
void turnOnLed();
void turnOffLed();
//进入休眠模式
void sleepMode(uint16_t sleepHour , uint16_t sleepMinute);
//休眠闹钟
void sleep_alarmClock(uint16_t hourClock, uint16_t minuteClock, uint16_t sleep_Hour, uint16_t sleep_Minute);
// 初始化,相当于main 函数
void setup() {
// 设置睡眠模式(可选参数:WIFI_NONE_SLEEP、WIFI_LIGHT_SLEEP、WIFI_MODEM_SLEEP )
WiFi.setSleepMode(WIFI_MODEM_SLEEP);
Serial.begin(115200);
pinMode(LED_Pin,OUTPUT);
myservo.attach(2);
digitalWrite(LED_Pin,0);
Serial.println("Beginning...");
delay(1000);
}
//循环
void loop() {
// getTime();//获取北京时间
doWiFiTick();
doTCPClientTick();
// sleep_alarmClock(1,20,20,30);//1点20分进入休眠模式,休眠20小时30分钟
}
/*
*初始化wifi连接
*/
void startSTA(){
WiFi.disconnect();
WiFi.mode(WIFI_STA);
WiFi.begin(wifi_name, wifi_password);
}
/*
WiFiTick
检查是否需要初始化WiFi
检查WiFi是否连接上,若连接成功启动TCP Client
控制指示灯
*/
void doWiFiTick(){
static bool startSTAFlag = false;
static bool taskStarted = false;
static uint32_t lastWiFiCheckTick = 0;
if (!startSTAFlag) {
startSTAFlag = true;
startSTA();
}
//未连接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();
}
}
}
/*
*发送数据到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="";//清空
tcpTemp = "cmd=7&uid="+UID+"&type=2\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_PACKETSIZE - 1){
TcpClient_BuffIndex = MAX_PACKETSIZE-2;
TcpClient_preTick = TcpClient_preTick - 200;
}
}
if(millis() - preHeartTick >= KEEPALIVEATIME)
{//保持心跳
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" || getMsg == "1"){ //开灯
turnOnLed();
}
else if(getMsg == "off" || getMsg == "0"){ //关灯
turnOffLed();
}
else if(getMsg == "sleep" || getMsg == "s"){ //休眠(不休眠功耗约为74ma)
myservo.write(servo_middle);//指定舵机转动角度位置(0-180)
digitalWrite(LED_Pin,HIGH);
sleepMode(20,0); //进入休眠模式(20小时)
}
else if(getMsg == "updata" || getMsg == "u"){ //升级固件
updateBin();
}
TcpClient_Buff="";
TcpClient_BuffIndex = 0;
}
}
/***********************************************************
*@fuction :sleepMode
*@brief :进入休眠模式
*@param :sleepHour:设置休眠小时
*@param :sleepMinute:设置休眠分钟
***********************************************************/
void sleepMode(uint16_t sleepHour , uint16_t sleepMinute){
WiFi.forceSleepBegin(); // Wifi off 功耗约为17.7ma
for(uint16_t Minute=0;Minute<sleepHour*60+sleepMinute;Minute++)//分钟
{
delay(60000);//一分钟
}
WiFi.forceSleepWake(); // Wifi on
}
/**
* 固件升级函数
* 在需要升级的地方,加上这个函数即可
* 原理:通过http请求获取远程固件,实现升级
* 附:错误代码
如果报错,错误代码可参考
/// note we use HTTP client errors too so we start at 100
//TODO - in v3.0.0 make this an enum
constexpr int HTTP_UE_TOO_LESS_SPACE = (-100);
constexpr int HTTP_UE_SERVER_NOT_REPORT_SIZE = (-101);
constexpr int HTTP_UE_SERVER_FILE_NOT_FOUND = (-102);
constexpr int HTTP_UE_SERVER_FORBIDDEN = (-103);
constexpr int HTTP_UE_SERVER_WRONG_HTTP_CODE = (-104);
constexpr int HTTP_UE_SERVER_FAULTY_MD5 = (-105);
constexpr int HTTP_UE_BIN_VERIFY_HEADER_FAILED = (-106);
constexpr int HTTP_UE_BIN_FOR_WRONG_FLASH = (-107);
constexpr int HTTP_UE_SERVER_UNAUTHORIZED = (-108);
**/
//当升级开始时,打印日志
void update_started() {
Serial.println("CALLBACK: HTTP update process started");
}
//当升级结束时,打印日志
void update_finished() {
Serial.println("CALLBACK: HTTP update process finished");
}
//当升级中,打印日志
void update_progress(int cur, int total) {
Serial.printf("CALLBACK: HTTP update process at %d of %d bytes...\n", cur, total);
}
//当升级失败时,打印日志
void update_error(int err) {
Serial.printf("CALLBACK: HTTP update fatal error code %d\n", err);
}
void updateBin(){
Serial.println("start update");
WiFiClient UpdateClient;
ESPhttpUpdate.onStart(update_started);//当升级开始时
ESPhttpUpdate.onEnd(update_finished); //当升级结束时
ESPhttpUpdate.onProgress(update_progress); //当升级中
ESPhttpUpdate.onError(update_error); //当升级失败时
t_httpUpdate_return ret = ESPhttpUpdate.update(UpdateClient, upUrl);
switch(ret) {
case HTTP_UPDATE_FAILED: //当升级失败
Serial.println("[update] Update failed.");
break;
case HTTP_UPDATE_NO_UPDATES: //当无升级
Serial.println("[update] Update no Update.");
break;
case HTTP_UPDATE_OK: //当升级成功
Serial.println("[update] Update ok.");
break;
}
}
//获取北京时间
void getTime(){
//发送http get请求
HTTPClient http; //Declare an object of class HTTPClient
http.begin(get_url); //Specify request destination
int httpCode = http.GET(); //发送请求,并获取状态码
String response = http.getString(); //获取返回的数据
Serial.println(response); //打印获取的数据
http.end(); //Close connection
//字符串示例 12:56:40,进行字符串切割,依次获取小时分钟和秒数
hour = response.substring(0,2).toInt();
minute = response.substring(3,5).toInt();
second = response.substring(6,8).toInt();
// Serial.println(hour);
// Serial.println(minute);
// Serial.println(second);
}
/***********************************************************
*@fuction :sleep_alarmClock
*@brief :休眠闹钟
*@param :hourClock:设置闹钟时间-时
*@param :minuteClock:设置闹钟时间-分
*@param :sleep_Hour:设置休眠小时
*@param :sleep_Minute:设置休眠分钟
***********************************************************/
void sleep_alarmClock(uint16_t hourClock,uint16_t minuteClock, uint16_t sleep_Hour , uint16_t sleep_Minute){
if(hour == hourClock && minute == minuteClock){
sleepMode(sleep_Hour, sleep_Minute); //进入休眠模式
}
}
//打开灯泡
void turnOnLed(){
Serial.println("Turn ON");
myservo.write(servo_on);//指定舵机转动角度位置(0-180)
delay(700);
myservo.write(servo_middle);//指定舵机转动角度位置(0-180)
delay(700);
digitalWrite(LED_Pin,HIGH);
}
//关闭灯泡
void turnOffLed(){
Serial.println("Turn OFF");
myservo.write(servo_off);//指定舵机转动角度位置(0-180)
delay(700);
myservo.write(servo_middle);//指定舵机转动角度位置(0-180)
delay(700);
digitalWrite(LED_Pin,HIGH);
}
esp01s控制开关(巴法云控制)
最新推荐文章于 2024-10-16 13:24:26 发布