· 6 years ago · Jan 26, 2020, 09:41 PM
1/**
2 * Example for sending temperature and humidity
3 * to the cloud using the DHT22 and ESP8266
4 *
5 * Copyright (c) 2016 Losant IoT. All rights reserved.
6 * https://www.losant.com
7 */
8
9
10#include "DHT.h"
11#include <ESP8266WiFi.h>
12#include <ESP8266HTTPClient.h>
13#include <Losant.h>
14
15#define DHTPIN 4 // what digital pin the DHT22 is conected to
16#define DHTTYPE DHT22 // There are multiple kinds of DHT sensors
17
18DHT dht(DHTPIN, DHTTYPE);
19
20// WiFi credentials.
21const char* WIFI_SSID = "Bozboi";
22const char* WIFI_PASS = "fiuieee18";
23
24// Losant credentials.
25const char* LOSANT_DEVICE_ID = "5e19ec6e299a850006146958";
26const char* LOSANT_ACCESS_KEY = "3a04702d-062a-49e0-b73a-49e3c3fc94d7";
27const char* LOSANT_ACCESS_SECRET = "b97e085146ae33c0706296a533cb63a9c00c36ef2f266f35346e266f2abc7b61";
28
29
30WiFiClientSecure wifiClient;
31
32LosantDevice device(LOSANT_DEVICE_ID);
33
34void connect() {
35
36 // Connect to Wifi.
37 Serial.println();
38 Serial.println();
39 Serial.print("Connecting to ");
40 Serial.println(WIFI_SSID);
41
42 // WiFi fix: https://github.com/esp8266/Arduino/issues/2186
43 WiFi.persistent(false);
44 WiFi.mode(WIFI_OFF);
45 WiFi.mode(WIFI_STA);
46 WiFi.begin(WIFI_SSID, WIFI_PASS);
47
48 unsigned long wifiConnectStart = millis();
49
50 while (WiFi.status() != WL_CONNECTED) {
51 // Check to see if
52 if (WiFi.status() == WL_CONNECT_FAILED) {
53 Serial.println("Failed to connect to WIFI. Please verify credentials: ");
54 Serial.println();
55 Serial.print("SSID: ");
56 Serial.println(WIFI_SSID);
57 Serial.print("Password: ");
58 Serial.println(WIFI_PASS);
59 Serial.println();
60 }
61
62 delay(500);
63 Serial.println("...");
64 // Only try for 5 seconds.
65 if(millis() - wifiConnectStart > 5000) {
66 Serial.println("Failed to connect to WiFi");
67 Serial.println("Please attempt to send updated configuration parameters.");
68 return;
69 }
70 }
71
72 Serial.println();
73 Serial.println("WiFi connected");
74 Serial.println("IP address: ");
75 Serial.println(WiFi.localIP());
76 Serial.println();
77
78 Serial.print("Authenticating Device...");
79 HTTPClient http;
80 http.begin("http://api.losant.com/auth/device");
81 http.addHeader("Content-Type", "application/json");
82 http.addHeader("Accept", "application/json");
83
84 /* Create JSON payload to sent to Losant
85 *
86 * {
87 * "deviceId": "575ecf887ae143cd83dc4aa2",
88 * "key": "this_would_be_the_key",
89 * "secret": "this_would_be_the_secret"
90 * }
91 *
92 */
93
94 StaticJsonBuffer<200> jsonBuffer;
95 JsonObject& root = jsonBuffer.createObject();
96 root["deviceId"] = LOSANT_DEVICE_ID;
97 root["key"] = LOSANT_ACCESS_KEY;
98 root["secret"] = LOSANT_ACCESS_SECRET;
99 String buffer;
100 root.printTo(buffer);
101
102 int httpCode = http.POST(buffer);
103
104 if(httpCode > 0) {
105 if(httpCode == HTTP_CODE_OK) {
106 Serial.println("This device is authorized!");
107 } else {
108 Serial.println("Failed to authorize device to Losant.");
109 if(httpCode == 400) {
110 Serial.println("Validation error: The device ID, access key, or access secret is not in the proper format.");
111 } else if(httpCode == 401) {
112 Serial.println("Invalid credentials to Losant: Please double-check the device ID, access key, and access secret.");
113 } else {
114 Serial.println("Unknown response from API");
115 }
116 }
117 } else {
118 Serial.println("Failed to connect to Losant API.");
119
120 }
121
122 http.end();
123
124 // Connect to Losant.
125 Serial.println();
126 Serial.print("Connecting to Losant...");
127
128 device.connectSecure(wifiClient, LOSANT_ACCESS_KEY, LOSANT_ACCESS_SECRET);
129
130 while(!device.connected()) {
131 delay(500);
132 Serial.print(".");
133 }
134
135 Serial.println("Connected!");
136 Serial.println();
137 Serial.println("This device is now ready for use!");
138}
139
140void setup() {
141 Serial.begin(9600);
142 Serial.setTimeout(2000);
143
144 // Wait for serial to initialize.
145 while(!Serial) { }
146
147 Serial.println("Device Started");
148 Serial.println("-------------------------------------");
149 Serial.println("Running DHT!");
150 Serial.println("-------------------------------------");
151
152 connect();
153}
154
155void report(double humidity, double tempC, double tempF, double heatIndexC, double heatIndexF) {
156 StaticJsonBuffer<500> jsonBuffer;
157 JsonObject& root = jsonBuffer.createObject();
158 root["humidity"] = humidity;
159 root["tempC"] = tempC;
160 root["tempF"] = tempF;
161 root["heatIndexC"] = heatIndexC;
162 root["heatIndexF"] = heatIndexF;
163 device.sendState(root);
164 Serial.println("Reported!");
165}
166
167int timeSinceLastRead = 0;
168void loop() {
169 bool toReconnect = false;
170
171 if (WiFi.status() != WL_CONNECTED) {
172 Serial.println("Disconnected from WiFi");
173 toReconnect = true;
174 }
175
176 if (!device.connected()) {
177 Serial.println("Disconnected from MQTT");
178 Serial.println(device.mqttClient.state());
179 toReconnect = true;
180 }
181
182 if (toReconnect) {
183 connect();
184 }
185
186 device.loop();
187
188 // Report every 2 seconds.
189 if(timeSinceLastRead > 2000) {
190 // Reading temperature or humidity takes about 250 milliseconds!
191 // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
192 float h = dht.readHumidity();
193 // Read temperature as Celsius (the default)
194 float t = dht.readTemperature();
195 // Read temperature as Fahrenheit (isFahrenheit = true)
196 float f = dht.readTemperature(true);
197
198 // Check if any reads failed and exit early (to try again).
199 if (isnan(h) || isnan(t) || isnan(f)) {
200 Serial.println("Failed to read from DHT sensor!");
201 timeSinceLastRead = 0;
202 return;
203 }
204
205 // Compute heat index in Fahrenheit (the default)
206 float hif = dht.computeHeatIndex(f, h);
207 // Compute heat index in Celsius (isFahreheit = false)
208 float hic = dht.computeHeatIndex(t, h, false);
209
210 Serial.print("Humidity: ");
211 Serial.print(h);
212 Serial.print(" %\t");
213 Serial.print("Temperature: ");
214 Serial.print(t);
215 Serial.print(" *C ");
216 Serial.print(f);
217 Serial.print(" *F\t");
218 Serial.print("Heat index: ");
219 Serial.print(hic);
220 Serial.print(" *C ");
221 Serial.print(hif);
222 Serial.println(" *F");
223 report(h, t, f, hic, hif);
224
225 timeSinceLastRead = 0;
226 }
227 delay(100);
228 timeSinceLastRead += 100;
229}