当前位置:网站首页>ESP8266通过arduino IED连接巴法云(TCP创客云)

ESP8266通过arduino IED连接巴法云(TCP创客云)

2022-07-06 09:16:00 一入极客深似海

主要是根据官方提供的示例,将其简化一部分。实现数据上传,云平台数据下发控制的功能
下发控制

VeryCapture_20220613204702

程序

/* 智能语言控制控制,支持天猫、小爱、小度、google Assistent同时控制 2021-08-12 QQ交流群:566565915 官网https://bemfa.com */
#include <ESP8266WiFi.h>


#define server_ip "bemfa.com" //巴法云服务器地址默认即可
#define server_port "8344" //服务器端口,tcp创客云端口8344

//********************需要修改的部分*******************//

#define wifi_name "xxx" //WIFI名称,区分大小写,不要写错
#define wifi_password "12345678" //WIFI密码
String UID = "xxxxxxxxxxxxxxxxxxxxxxxxx";  //用户私钥,可在控制台获取,修改为自己的UID
String TOPIC = "test";         //主题名字,可在控制台新建
const int LED_Pin = D4;              //单片机LED引脚值,D2是NodeMcu引脚命名方式,其他esp8266型号将D2改为自己的引脚

//**************************************************//
//最大字节数
#define MAX_PACKETSIZE 512
//设置心跳值60s
#define KEEPALIVEATIME 60*1000
//tcp客户端相关初始化,默认即可
WiFiClient TCPclient;
String TcpClient_Buff = "";//初始化字符串,用于接收服务器发来的数据
unsigned long TcpClient_preTick = 0;
unsigned long preHeartTick = 0;//心跳
unsigned long preTCPStartTick = 0;//连接
bool preTCPConnected = false;
//相关函数初始化
//连接WIFI
void doWiFiTick();
void startSTA();

//TCP初始化连接
void doTCPClientTick();
void startTCPClient();
void sendtoTCPServer(String p);

//led控制函数,具体函数内容见下方
void turnOnLed();
void turnOffLed();



/* 发送数据到TCP服务器 */
void sendtoTCPServer(String p) {
    
  if (!TCPclient.connected())
  {
    
    Serial.println("Client is not readly");
    return;
  }
  TCPclient.print(p);
}


/* 初始化和服务器建立连接 */
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 = ""; //清空



    preTCPConnected = true;
    preHeartTick = millis();
    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()) {
    //收数据
      while (TCPclient.available() > 0)
      {
    
        char c = TCPclient.read();
        TcpClient_Buff += c;
      }

      Serial.println("服务器开始---------接受数据为:");
      Serial.println(String("")+"接受字符串大小为:"+TcpClient_Buff.length());      
      String getMsg=TcpClient_Buff.substring(TcpClient_Buff.lastIndexOf("&msg")+5,TcpClient_Buff.length()-2);         
      Serial.println(String("")+"切割所需字符串为:"+getMsg);      
      TcpClient_preTick = millis();
        Serial.println("服务器结束---------接受数据为!!!");
        if (getMsg  == "on") {
         //如果是消息==打开
    turnOnLed();
  } else if (getMsg == "off") {
     //如果是消息==关闭
    turnOffLed();
  }
      preHeartTick = millis();
    }
    if (millis() - preHeartTick >= KEEPALIVEATIME) {
     //保持心跳
      preHeartTick = millis();
      Serial.println("--Keep alive:");
      sendtoTCPServer("ping\r\n"); //发送心跳,指令需\r\n结尾,详见接入文档介绍
    }
  }

  TcpClient_Buff = "";

}
/* 初始化wifi连接 */
void startSTA() {
    
  WiFi.disconnect();
  WiFi.mode(WIFI_STA);
  WiFi.begin(wifi_name, wifi_password);
}



/************************************************************************** WIFI ***************************************************************************/
/* 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();
    }
  }
}
//打开灯泡
void turnOnLed() {
    
  Serial.println("Turn ON");
  digitalWrite(LED_Pin, LOW);
}
//关闭灯泡
void turnOffLed() {
    
  Serial.println("Turn OFF");
  digitalWrite(LED_Pin, HIGH);
}


// 初始化,相当于main 函数
void setup() {
    
  Serial.begin(115200);
  pinMode(LED_Pin, OUTPUT);
  digitalWrite(LED_Pin, HIGH);
  Serial.println("Beginning...");
}

//循环
void loop() {
    
  //如果需要订阅多个主题,可再次发送订阅指令
  String  tcpTemp1 = "cmd=2&uid=" + UID + "&topic=" + TOPIC + "&msg=#" + String(random(0, 100)) + "#" + String(random(1000, 10000)) + "#\r\n";; //构建订阅指令
  sendtoTCPServer(tcpTemp1); //发送订阅指令
  tcpTemp1 = ""; //清空

  doWiFiTick();
  doTCPClientTick();
  delay(1000);
}
原网站

版权声明
本文为[一入极客深似海]所创,转载请带上原文链接,感谢
https://blog.csdn.net/sdagv/article/details/125268025