-
Notifications
You must be signed in to change notification settings - Fork 0
/
esp32-aws-weather-station.ino
102 lines (78 loc) · 2.53 KB
/
esp32-aws-weather-station.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include "secrets.h"
#include <WiFiClientSecure.h>
#include <DHT.h>
#include <MQTTClient.h>
#include <ArduinoJson.h>
#include "WiFi.h"
#define DHT_PIN 4 // pin connected to data pin of DHT11
#define DHT_TYPE DHT11 // Type of the DHT Sensor, DHT11/DHT22
// The MQTT topics that this device should publish/subscribe
#define AWS_IOT_PUBLISH_TOPIC "thing/esp32/pub"
#define AWS_IOT_SUBSCRIBE_TOPIC "thing/esp32/sub"
DHT dht(DHT_PIN, DHT_TYPE);
WiFiClientSecure net = WiFiClientSecure();
MQTTClient client = MQTTClient(256);
void connectAWS()
{
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.println("Connecting to Wi-Fi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
// Configure WiFiClientSecure to use the AWS IoT device credentials
net.setCACert(AWS_CERT_CA);
net.setCertificate(AWS_CERT_CRT);
net.setPrivateKey(AWS_CERT_PRIVATE);
// Connect to the MQTT broker on the AWS endpoint we defined earlier
client.begin(AWS_IOT_ENDPOINT, 8883, net);
// Create a message handler
client.onMessage(messageHandler);
Serial.println("Connecting to AWS IOT");
while (!client.connect(THINGNAME)) {
Serial.print(".");
delay(100);
}
if (!client.connected()) {
Serial.println("AWS IoT Timeout!");
return;
}
// Subscribe to a topic
client.subscribe(AWS_IOT_SUBSCRIBE_TOPIC);
Serial.println("AWS IoT Connected!");
}
void publishMessage()
{
StaticJsonDocument<200> doc;
dht.begin();
float temp = dht.readTemperature(); // return temperature in °C
float humidity = dht.readHumidity(); // return humidity in %
float heatIndex = dht.computeHeatIndex(temp, humidity, false); // Compute heat index in Celsius (isFahreheit = false)
// check whether reading was successful or not
if (temp == NAN || humidity == NAN) { // NAN means no available data
Serial.println("Reading failed.");
} else {
doc["time"] = String(millis());
doc["temp"] = String(temp) + " °C";
doc["humidity"] = String(humidity ) + " %";
doc["heat_index"] = String(heatIndex ) + " %";
char jsonBuffer[512];
serializeJson(doc, jsonBuffer); // print to client
Serial.print("Publishing:- ");
Serial.println(jsonBuffer);
client.publish(AWS_IOT_PUBLISH_TOPIC, jsonBuffer); // publish on MQTT topic
}
}
void messageHandler(String &topic, String &payload) {
Serial.println("incoming: " + topic + " - " + payload);
}
void setup() {
Serial.begin(9600);
connectAWS();
}
void loop() {
publishMessage();
client.loop();
delay(15000);
}