#include <WiFi.h>
#include <PubSubClient.h>
#include <Arduino.h>
#include <Ticker.h>
#include <DFRobot_DHT11.h>
#define clientId 'esp32' // id
#define userName 'device' // username
#define mqtt_password 'esp32wroom' // password
#define BUILTIN_LED 13
#define DHT_PIN 17
void connectWifi();
void connectMQTTServer();
void subscribeTopic();
void publishTopic(String topic, String msg);
void receiveCallback(char *topic, byte *payload, unsigned int length);
void tickerContent();
String getDHTData();
const char *ssid = 'Redmi_91AE';
const char *password = '****';
const char *mqttServer = '192.168.31.108';
// const char *mqttServer = '183.230.40.39'; // oneNet
// const char *mqttServer = 'mqtt.heclouds.com'; // oneNet
// const uint16_t port = 6002;
const uint16_t port = 1883;
int count = 0;
WiFiClient wifiClient;
PubSubClient mqttClient(wifiClient);
Ticker ticker;
DFRobot_DHT11 dht;
void setup()
{
Serial.begin(115200);
pinMode(13, OUTPUT);
WiFi.mode(WIFI_STA);
connectWifi();
mqttClient.setServer(mqttServer, port);
mqttClient.setCallback(receiveCallback);
connectMQTTServer();
ticker.attach(1, tickerContent);
}
void loop()
{
if (mqttClient.connected())
{ // 如果開發(fā)板成功連接服務(wù)器
mqttClient.loop(); // 保持客戶端心跳
}
else
{ // 如果開發(fā)板未能成功連接服務(wù)器
connectMQTTServer(); // 則嘗試連接服務(wù)器
}
if (count >=60 )
{
count = 0;
// publishTopic();
publishTopic('data/temperature_data', getDHTData());
// Serial.println(getDHTData());
}
}
// 連接mqtt服務(wù)器
void connectMQTTServer()
{
if (WiFi.isConnected())
{
if (mqttClient.connect(clientId, userName, mqtt_password))
{
Serial.println('MQTT Server Connected.');
Serial.println('Server Address: ');
Serial.println(mqttServer);
Serial.println('ClientId:');
Serial.println(clientId);
subscribeTopic();
}
else
{
Serial.print('MQTT Server Connect Failed. Client State:');
Serial.println(mqttClient.state());
delay(3000);
}
}
else
{
connectWifi();
}
}
// 連接wifi
void connectWifi()
{
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(1000);
Serial.print('.');
}
Serial.println('');
Serial.println('WiFi Connected!');
Serial.println('');
}
// 訂閱 topic
void subscribeTopic()
{
String topic = 'command/LED_Switch';
if (mqttClient.subscribe(topic.c_str()))
{
Serial.println('Subscrib Topic:');
Serial.println(topic);
}
else
{
Serial.print('Subscribe Fail...');
}
}
// 發(fā)布數(shù)據(jù)
void publishTopic(String topic, String msg)
{
if (mqttClient.publish(topic.c_str(), msg.c_str()))
{
Serial.println('Publish Topic:');
Serial.println(topic);
Serial.println('Publish message:');
Serial.println(msg);
}
else
{
Serial.println('Message Publish Failed.');
}
}
// 收到消息后的回調(diào)函數(shù)
void receiveCallback(char *topic, byte *payload, unsigned int length)
{
Serial.print('Message Received [');
Serial.print(topic);
Serial.print('] ');
for (int i = 0; i < length; i++)
{
Serial.print((char)payload[i]);
}
Serial.println('');
Serial.print('Message Length(Bytes) ');
Serial.println(length);
if (strcmp(topic, 'command/LED_Switch') == 0)
{
if ((char)payload[0] == '1')
{ // 如果收到的信息以“1”為開始
digitalWrite(BUILTIN_LED, HIGH); // 則點亮LED。
Serial.println('LED ON');
}
else
{
digitalWrite(BUILTIN_LED, LOW); // 否則熄滅LED。
Serial.println('LED OFF');
}
}
else
{
Serial.println('else');
// 默認(rèn)指令 topic
}
}
void tickerContent()
{
count++;
}
String getDHTData()
{
dht.read(DHT_PIN);
return ' { \'temperature\' : ' + String(dht.temperature) + ', \'humidity\': ' + String(dht.humidity) + '}';
}
本站僅提供存儲服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請
點擊舉報。