Advertisement
Guest User

Untitled

a guest
Dec 16th, 2018
339
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 6.24 KB | None | 0 0
  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 D8     // what digital pin the DHT22 is conected to
  16. #define DHTTYPE DHT22   // There are multiple kinds of DHT sensors
  17.  
  18. DHT dht(DHTPIN, DHTTYPE);
  19.  
  20. // WiFi credentials.
  21. const char* WIFI_SSID = "Android";
  22. const char* WIFI_PASS = "";
  23.  
  24. // Losant credentials.
  25. const char* LOSANT_DEVICE_ID = "MyLosantId";
  26. const char* LOSANT_ACCESS_KEY = "MyAccesKey";
  27. const char* LOSANT_ACCESS_SECRET = "MyAccesSecret";
  28.  
  29.  
  30. WiFiClient wifiClient;
  31.  
  32. LosantDevice device(LOSANT_DEVICE_ID);
  33.  
  34. void 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.    
  132.     delay(500);
  133.      Serial.println(device.mqttClient.state()); // HERE
  134.     Serial.print(".");
  135.  
  136.  
  137.   }
  138.  
  139.  
  140.   Serial.println("Connected!");
  141.   Serial.println();
  142.   Serial.println("This device is now ready for use!");
  143. }
  144.  
  145. void setup() {
  146.   Serial.begin(9600);
  147.   Serial.setTimeout(2000);
  148.  
  149.   // Wait for serial to initialize.
  150.   while(!Serial) { }
  151.  
  152.   Serial.println("Device Started");
  153.   Serial.println("-------------------------------------");
  154.   Serial.println("Running DHT!");
  155.   Serial.println("-------------------------------------");
  156.  
  157.   connect();
  158. }
  159.  
  160. void report(double humidity, double tempC, double tempF, double heatIndexC, double heatIndexF) {
  161.   StaticJsonBuffer<500> jsonBuffer;
  162.   JsonObject& root = jsonBuffer.createObject();
  163.   root["humidity"] = humidity;
  164.   root["tempC"] = tempC;
  165.   root["tempF"] = tempF;
  166.   root["heatIndexC"] = heatIndexC;
  167.   root["heatIndexF"] = heatIndexF;
  168.   device.sendState(root);
  169.   Serial.println("Reported!");
  170. }
  171.  
  172. int timeSinceLastRead = 0;
  173. void loop() {
  174.    bool toReconnect = false;
  175.  
  176.   if (WiFi.status() != WL_CONNECTED) {
  177.     Serial.println("Disconnected from WiFi");
  178.     toReconnect = true;
  179.   }
  180.  
  181.   if (!device.connected()) {
  182.     Serial.println("Disconnected from MQTT");
  183.     Serial.println(device.mqttClient.state());
  184.     toReconnect = true;
  185.   }
  186.  
  187.   if (toReconnect) {
  188.     connect();
  189.   }
  190.  
  191.   device.loop();
  192.  
  193.   // Report every 2 seconds.
  194.   if(timeSinceLastRead > 2000) {
  195.     // Reading temperature or humidity takes about 250 milliseconds!
  196.     // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  197.     float h = dht.readHumidity();
  198.     // Read temperature as Celsius (the default)
  199.     float t = dht.readTemperature();
  200.     // Read temperature as Fahrenheit (isFahrenheit = true)
  201.     float f = dht.readTemperature(true);
  202.  
  203.     // Check if any reads failed and exit early (to try again).
  204.     if (isnan(h) || isnan(t) || isnan(f)) {
  205.       Serial.println("Failed to read from DHT sensor!");
  206.       timeSinceLastRead = 0;
  207.       return;
  208.     }
  209.  
  210.     // Compute heat index in Fahrenheit (the default)
  211.     float hif = dht.computeHeatIndex(f, h);
  212.     // Compute heat index in Celsius (isFahreheit = false)
  213.     float hic = dht.computeHeatIndex(t, h, false);
  214.  
  215.     Serial.print("Humidity: ");
  216.     Serial.print(h);
  217.     Serial.print(" %\t");
  218.     Serial.print("Temperature: ");
  219.     Serial.print(t);
  220.     Serial.print(" *C ");
  221.     Serial.print(f);
  222.     Serial.print(" *F\t");
  223.     Serial.print("Heat index: ");
  224.     Serial.print(hic);
  225.     Serial.print(" *C ");
  226.     Serial.print(hif);
  227.     Serial.println(" *F");
  228.     report(h, t, f, hic, hif);
  229.  
  230.     timeSinceLastRead = 0;
  231.   }
  232.   delay(100);
  233.   timeSinceLastRead += 100;
  234. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement