当前位置:网站首页>Esp8266 connects to bafayun (TCP maker cloud) through Arduino IED
Esp8266 connects to bafayun (TCP maker cloud) through Arduino IED
2022-07-06 12:05:00 【A geek is as deep as the sea】
Mainly based on the official examples , Simplify it in part . Realize data upload , The function of cloud platform data distribution control
Issue control
VeryCapture_20220613204702
Program
/* Intelligent language control , Support tmall 、 Little love 、 Xiaodu 、google Assistent Control at the same time 2021-08-12 QQ Communication group :566565915 Official website https://bemfa.com */
#include <ESP8266WiFi.h>
#define server_ip "bemfa.com" // The default address of Bafa ECS can be
#define server_port "8344" // Server port ,tcp Maker cloud port 8344
//******************** What needs to be changed *******************//
#define wifi_name "xxx" //WIFI name , Case sensitive , Don't write wrong
#define wifi_password "12345678" //WIFI password
String UID = "xxxxxxxxxxxxxxxxxxxxxxxxx"; // User private key , Available on the console , Change it to your own UID
String TOPIC = "test"; // Subject name , You can create a new
const int LED_Pin = D4; // Single chip microcomputer LED Pin value ,D2 yes NodeMcu Pin naming method , other esp8266 The model will D2 Change to your own pin
//**************************************************//
// Maximum number of bytes
#define MAX_PACKETSIZE 512
// Set the heartbeat value 60s
#define KEEPALIVEATIME 60*1000
//tcp Client related initialization , The default can be
WiFiClient TCPclient;
String TcpClient_Buff = "";// Initialize string , Used to receive data from the server
unsigned long TcpClient_preTick = 0;
unsigned long preHeartTick = 0;// heartbeat
unsigned long preTCPStartTick = 0;// Connect
bool preTCPConnected = false;
// Initialization of related functions
// Connect WIFI
void doWiFiTick();
void startSTA();
//TCP Initialize connection
void doTCPClientTick();
void startTCPClient();
void sendtoTCPServer(String p);
//led Control function , See the following for specific functions
void turnOnLed();
void turnOffLed();
/* Send data to TCP The server */
void sendtoTCPServer(String p) {
if (!TCPclient.connected())
{
Serial.println("Client is not readly");
return;
}
TCPclient.print(p);
}
/* Initialize and establish a connection with the server */
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 = ""; // Initialize string
tcpTemp = "cmd=1&uid=" + UID + "&topic=" + TOPIC + "\r\n"; // Build subscription instructions
sendtoTCPServer(tcpTemp); // Send subscription instructions
tcpTemp = ""; // Empty
preTCPConnected = true;
preHeartTick = millis();
TCPclient.setNoDelay(true);
}
else {
Serial.print("Failed connected to server:");
Serial.println(server_ip);
TCPclient.stop();
preTCPConnected = false;
}
preTCPStartTick = millis();
}
/* Check the data , Send a heartbeat */
void doTCPClientTick() {
// Check for disconnection , Disconnected and reconnected
if (WiFi.status() != WL_CONNECTED) return;
if (!TCPclient.connected()) {
// Disconnect and reconnect
if (preTCPConnected == true) {
preTCPConnected = false;
preTCPStartTick = millis();
Serial.println();
Serial.println("TCP Client disconnected.");
TCPclient.stop();
}
else if (millis() - preTCPStartTick > 1 * 1000) // Reconnect the
startTCPClient();
}
else
{
if (TCPclient.available()) {
// Receive data
while (TCPclient.available() > 0)
{
char c = TCPclient.read();
TcpClient_Buff += c;
}
Serial.println(" The server starts --------- The accepted data is :");
Serial.println(String("")+" The accepted string size is :"+TcpClient_Buff.length());
String getMsg=TcpClient_Buff.substring(TcpClient_Buff.lastIndexOf("&msg")+5,TcpClient_Buff.length()-2);
Serial.println(String("")+" The string required for cutting is :"+getMsg);
TcpClient_preTick = millis();
Serial.println(" End of server --------- The accepted data is !!!");
if (getMsg == "on") {
// If it's news == open
turnOnLed();
} else if (getMsg == "off") {
// If it's news == close
turnOffLed();
}
preHeartTick = millis();
}
if (millis() - preHeartTick >= KEEPALIVEATIME) {
// Keep your heart beating
preHeartTick = millis();
Serial.println("--Keep alive:");
sendtoTCPServer("ping\r\n"); // Send a heartbeat , Instruction needs \r\n ending , See the introduction of access document for details
}
}
TcpClient_Buff = "";
}
/* initialization wifi Connect */
void startSTA() {
WiFi.disconnect();
WiFi.mode(WIFI_STA);
WiFi.begin(wifi_name, wifi_password);
}
/************************************************************************** WIFI ***************************************************************************/
/* WiFiTick Check whether initialization is required WiFi Check WiFi Is it connected , If the connection starts successfully TCP Client Control indicator */
void doWiFiTick() {
static bool startSTAFlag = false;
static bool taskStarted = false;
static uint32_t lastWiFiCheckTick = 0;
if (!startSTAFlag) {
startSTAFlag = true;
startSTA();
}
// Unconnected 1s Reconnection
if ( WiFi.status() != WL_CONNECTED ) {
if (millis() - lastWiFiCheckTick > 1000) {
lastWiFiCheckTick = millis();
}
}
// Connection established successfully
else {
if (taskStarted == false) {
taskStarted = true;
Serial.print("\r\nGet IP Address: ");
Serial.println(WiFi.localIP());
startTCPClient();
}
}
}
// Turn on the bulb.
void turnOnLed() {
Serial.println("Turn ON");
digitalWrite(LED_Pin, LOW);
}
// Turn off the light bulb
void turnOffLed() {
Serial.println("Turn OFF");
digitalWrite(LED_Pin, HIGH);
}
// initialization , amount to main function
void setup() {
Serial.begin(115200);
pinMode(LED_Pin, OUTPUT);
digitalWrite(LED_Pin, HIGH);
Serial.println("Beginning...");
}
// loop
void loop() {
// If you need to subscribe to multiple topics , The subscription instruction can be sent again
String tcpTemp1 = "cmd=2&uid=" + UID + "&topic=" + TOPIC + "&msg=#" + String(random(0, 100)) + "#" + String(random(1000, 10000)) + "#\r\n";; // Build subscription instructions
sendtoTCPServer(tcpTemp1); // Send subscription instructions
tcpTemp1 = ""; // Empty
doWiFiTick();
doTCPClientTick();
delay(1000);
}
边栏推荐
- ESP8266使用arduino连接阿里云物联网
- Matlab learning and actual combat notes
- Principle and implementation of MySQL master-slave replication
- Analysis of charging architecture of glory magic 3pro
- FTP file upload file implementation, regularly scan folders to upload files in the specified format to the server, C language to realize FTP file upload details and code case implementation
- Rough analysis of map file
- Oppo vooc fast charging circuit and protocol
- Unit test - unittest framework
- Detailed explanation of Union [C language]
- AMBA、AHB、APB、AXI的理解
猜你喜欢
MP3mini播放模块arduino<DFRobotDFPlayerMini.h>函数详解
I2C总线时序详解
Machine learning -- linear regression (sklearn)
机器学习--线性回归(sklearn)
Basic use of pytest
Kconfig Kbuild
A possible cause and solution of "stuck" main thread of RT thread
Principle and implementation of MySQL master-slave replication
电商数据分析--薪资预测(线性回归)
Implementation scheme of distributed transaction
随机推荐
Unit test - unittest framework
分布式事务的实现方案
arduino获取数组的长度
E-commerce data analysis -- User Behavior Analysis
ESP learning problem record
Distribute wxWidgets application
机器学习--线性回归(sklearn)
Linux yum安装MySQL
几个关于指针的声明【C语言】
ES6语法总结--下篇(进阶篇 ES6~ES11)
电商数据分析--用户行为分析
优先级反转与死锁
Variable parameter principle of C language function: VA_ start、va_ Arg and VA_ end
Pytorch four commonly used optimizer tests
JS array + array method reconstruction
树莓派 轻触开关 按键使用
选择法排序与冒泡法排序【C语言】
RuntimeError: cuDNN error: CUDNN_ STATUS_ NOT_ INITIALIZED
Some concepts often asked in database interview
[esp32 learning-2] esp32 address mapping