Advertisement
Guest User

Untitled

a guest
Feb 25th, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.98 KB | None | 0 0
  1. // Need to create a payload function for publish a json string
  2.  
  3. #include <ESP8266WiFi.h>
  4. #include <Ethernet.h>
  5. #include "PubSubClient.h"
  6. #include "time.h"
  7. #include "Adafruit_Sensor.h"
  8. #include "DHT.h"
  9. #include "U8glib.h" //https://github.com/olikraus/u8glib/wiki
  10.  
  11. // Erzwinge Deep Sleep
  12. //#define FORCE_DEEPSLEEP
  13. // DHT Sensor auswahl
  14. #define DHTTYPE DHT22
  15.  
  16. // define Batterie Staus
  17. // unsigned int batt;
  18. // double battV;
  19.  
  20. // WiFi credentials.
  21. const char* WIFI_SSID = "xxxxx";
  22. const char* WIFI_PASS = "xxx";
  23. // MQTT credentials.
  24. const char* MQTT_USER = "xxx";
  25. const char* MQTT_PASS = "xxx";
  26. const char* MQTT_CLIENT = "ESP8266-IOT-DH22";
  27. const char* MQTT_BROKER = "x";
  28. const char* MQTT_Topic = "ESP01/DHT22";
  29.  
  30. char buf [4];
  31.  
  32. int timezone = 0; //4 = Sommerzeit
  33. int dst = 0;
  34.  
  35. String clientName;
  36. // On a ESP32-01
  37. int DHTPIN = 2; // DHT22 PIN
  38.  
  39. U8GLIB_SSD1306_128X64 u8g(U8G_I2C_OPT_NO_ACK);
  40. WiFiClient net;
  41. PubSubClient client(net);
  42. DHT dht(DHTPIN, DHTTYPE);
  43.  
  44. void callback(char* topic, byte* payload, unsigned int length)
  45. {
  46. // handle message arrived
  47. }
  48. //PubSubClient client(MQTT_BROKER, 1883, callback, net);
  49. void reconnect();
  50. void connectwifi();
  51. void draw(float temperatur, float feuchtigkeit);
  52.  
  53.  
  54.  
  55. // setup () only run once
  56. void setup()
  57. {
  58. // put your setup code here, to run once:
  59. Serial.begin(115200);
  60. Serial.setTimeout(2000);
  61.  
  62. // Wait for serial to initialize.
  63. while (!Serial) { }
  64. Serial.println("Device Started");
  65. Serial.println("-------------------------------------");
  66. Serial.println("DHT22 sketch!");
  67. Serial.println("-------------------------------------");
  68. //connect wifif fuction to connect to a wifi network
  69. connectwifi();
  70. delay(1500);
  71. // INitiat MQQT Server
  72. client.setServer(MQTT_BROKER, 1883);
  73. // client is now configured for use
  74. delay(1500);
  75. //Get current time for MQTT transmission for ntp server
  76. configTime(3600, 0, "pool.ntp.org", "time.nist.gov");
  77. Serial.println("\nWaiting for time");
  78. while (!time(nullptr)) {
  79. Serial.print(".");
  80. delay(1000);
  81. }
  82. time_t now = time(nullptr);
  83. Serial.println(ctime(&now));
  84. Serial.println("-------------------------------------");
  85. // Init DHT22
  86. dht.begin();
  87.  
  88. }
  89.  
  90. void loop()
  91. {
  92.  
  93. float h = dht.readHumidity();
  94. float t = dht.readTemperature();
  95.  
  96. // Whether or not the PubSubClient client is connected. Note that a client is considered connected if the connection has been closed but there is still unread data.
  97. if (!client.connected()) {
  98. // reconnect
  99. reconnect();
  100. }
  101. //loop() to allow the client to process incoming messages and maintain its connection to the server.
  102. if (!client.loop()) {
  103. Serial.print("Client disconnected...");
  104. // Connect with MQTT credentials
  105. if (client.connect(MQTT_CLIENT, MQTT_USER, MQTT_PASS)) {
  106. Serial.println("MQTT reconnected.");
  107. } else {
  108. Serial.println("MQTT connection failed.");
  109. }
  110.  
  111. }
  112. if (client.loop())
  113. {
  114. Serial.println("Read Sensor data");
  115.  
  116. // Check if any reads failed and exit early (to try again).
  117.  
  118. //read sonsor data from SensorPin
  119. Serial.print("Temperatur:");
  120. Serial.println(String(t));
  121. Serial.print("Feuchtigkeit:");
  122. Serial.println(String(h));
  123. Serial.println("-------------------------------------");
  124. Serial.println("Publish MQTT");
  125. Serial.print("MQTT Client: ");
  126. Serial.println(MQTT_CLIENT);
  127. Serial.print("MQTT Broker: ");
  128. Serial.println(MQTT_BROKER);
  129. Serial.print("Topic: ");
  130. Serial.println(MQTT_Topic);
  131. Serial.println("-------------------------------------");
  132. Serial.print("Date: ");
  133. time_t now = time(nullptr);
  134. Serial.println(ctime(&now));
  135. Serial.println("-------------------------------------");
  136. // Create the JSON String called payload to be send via MQQT
  137. String payload = "{\"Date\":";
  138. payload += "\"";
  139. payload += now;
  140. payload += "\"";
  141. payload += ",\"Node\":";
  142. payload += "\"";
  143. payload += MQTT_CLIENT;
  144. payload += "\"";
  145. payload += ",\"IP\":";
  146. payload += "\"";
  147. payload += WiFi.localIP().toString();
  148. payload += "\"";
  149. payload += ",\"Temperatur\":";
  150. payload += "\"";
  151. payload += String(t);
  152. payload += "\"";
  153. payload += ",\"Humidity\":";
  154. payload += "\"";
  155. payload += String(h);
  156. payload += "\"";
  157. payload += "}";
  158. Serial.println("Payload: ");
  159. Serial.println(payload)
  160. / Serial.println("-------------------------------------");
  161. // Publish data on screen
  162. u8g.firstPage();
  163. do {
  164. draw(t,h);
  165. } while ( u8g.nextPage() );
  166. delay(1);
  167.  
  168. // clinet.publish will publish the JSON string
  169. if (client.publish(MQTT_Topic, (char*) payload.c_str())) {
  170. Serial.println("Publish ok");
  171. delay(10*60*1000);
  172. }
  173. else {
  174. Serial.println("Publish failed");
  175. abort();
  176. }
  177. }
  178. }
  179.  
  180. //publish a payload (json) string
  181. boolean publishmqtt(String payload)
  182. {
  183. if (!client.connected())
  184. {
  185. if (client.connect((char*) MQTT_CLIENT))
  186. {
  187. Serial.println("Connected to MQTT broker again");
  188. Serial.print("Topic is: ");
  189. Serial.println(MQTT_Topic);
  190. }
  191. else
  192. {
  193. Serial.println("MQTT connect failed");
  194. Serial.println("Will reset and try again...");
  195. abort();
  196. }
  197. }
  198.  
  199. if (client.connected())
  200. {
  201. Serial.print("Sending payload: ");
  202. Serial.println(payload);
  203. if (client.publish(MQTT_Topic, (char*) payload.c_str()))
  204. {
  205. Serial.println("Publish ok");
  206. }
  207. }
  208. else
  209. {
  210. Serial.println("Publish failed");
  211. }
  212. }
  213. // need a funtion for int to Char* and other
  214. String macToStr(const uint8_t* mac)
  215. {
  216. String result;
  217. for (int i = 0; i < 6; ++i)
  218. {
  219. result += String(mac[i], 16);
  220. if (i < 5)
  221. result += ':';
  222. }
  223. return result;
  224. }
  225.  
  226. void reconnect() {
  227. // Solange wiederholen bis Verbindung wiederhergestellt ist
  228. while (!net.connected()) {
  229. Serial.print("Versuch des MQTT Verbindungsaufbaus...");
  230.  
  231. //Verbindungsversuch:
  232. if (client.connect(MQTT_CLIENT, MQTT_USER, MQTT_PASS)) {
  233. Serial.println("Erfolgreich verbunden!");
  234. // Nun versendet der Arduino eine Nachricht in outTopic ...
  235. // client.publish("outTopic","Arduino nach Hause telefonieren");
  236.  
  237. // und meldet sich bei inTopic für eingehende Nachrichten an:
  238. // client.subscribe("inTopic");
  239. } else { // Im Fehlerfall => Fehlermeldung und neuer Versuch
  240. Serial.print("Fehler, rc=");
  241. Serial.println(client.state());
  242. Serial.println("-------------------------------------");
  243. Serial.println("Nächster Versuch in 5 Sekunden");
  244. // 5 Sekunden Pause vor dem nächsten Versuch
  245. delay(5000);
  246. }
  247. }
  248. }
  249.  
  250. void connectwifi()
  251. {
  252. // Connect to Wifi.
  253. Serial.println();
  254. Serial.println();
  255. Serial.println("Connecting to");
  256. Serial.println(WIFI_SSID);
  257. Serial.println("-------------------------------------");
  258. // WiFi.begin(WIFI_SSID, WIFI_PASS);
  259.  
  260. // WiFi fix: https://github.com/esp8266/Arduino/issues/2186
  261. WiFi.persistent(false);
  262. WiFi.mode(WIFI_OFF);
  263. WiFi.mode(WIFI_STA);
  264. WiFi.begin(WIFI_SSID, WIFI_PASS);
  265.  
  266. unsigned long wifiConnectStart = millis();
  267.  
  268. while (WiFi.status() != WL_CONNECTED)
  269. {
  270. // Check to see if
  271. if (WiFi.status() == WL_CONNECT_FAILED) {
  272. Serial.println("Failed to connect to WiFi. Please verify credentials: ");
  273. Serial.println("-------------------------------------");
  274. delay(10000);
  275. }
  276.  
  277. delay(500);
  278. Serial.print(".");
  279. // Only try for 5 seconds.
  280. if (millis() - wifiConnectStart > 30000)
  281. {
  282. Serial.println("Failed to connect to WiFi");
  283. Serial.println("-------------------------------------");
  284. return;
  285. }
  286. }
  287. Serial.println("");
  288. Serial.println("WiFi connected");
  289. Serial.println("-------------------------------------");
  290. Serial.println("IP address: ");
  291. Serial.println(WiFi.localIP());
  292. Serial.println("-------------------------------------");
  293.  
  294. clientName += "esp8266-";
  295. uint8_t mac[6];
  296. WiFi.macAddress(mac);
  297. clientName += macToStr(mac);
  298. clientName += "-";
  299. clientName += String(micros() & 0xff, 16);
  300.  
  301. Serial.print("Connecting as ");
  302. Serial.println(clientName);
  303. Serial.println("-------------------------------------");
  304. }
  305.  
  306. double mapDouble(double x, double in_min, double in_max, double out_min, double out_max)
  307. {
  308. double temp = (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
  309. temp = (int) (4*temp + .5);
  310. return (double) temp/4;
  311. }
  312.  
  313. //draw t & h on the OLED display
  314. void draw(float temperatur, float feuchtigkeit) {
  315.  
  316. u8g.setFont(u8g_font_fub25); //https://github.com/olikraus/u8glib/wiki/fontsize
  317. u8g.setPrintPos(10, 32);
  318. u8g.print(temperatur, 1);
  319. u8g.setFont(u8g_font_fub25);
  320. u8g.setPrintPos(10, 64);
  321. u8g.print(feuchtigkeit, 1);
  322. u8g.setFont(u8g_font_fub25);
  323. u8g.drawStr(95, 32, "C");
  324. u8g.setFont(u8g_font_ncenB12);
  325. u8g.drawStr(85, 10, "o");
  326. u8g.setFont(u8g_font_fub25);
  327. u8g.drawStr(85, 64, "%");
  328.  
  329. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement