Advertisement
hneve

mqtt device

Feb 19th, 2018
223
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 6.24 KB | None | 0 0
  1. #define DEBUG 1             //Comment out if no need for serial debug
  2. //#define SWITCH 0          //comment out if no need for button/switch, define as pin number
  3. #define DS18B20 12          //comment out if no need for DS18B20 device, define as pin number
  4. //#define DHT22_PIN 12      //comment out if no need for DHT22 device, define as pin number
  5.  
  6.  
  7. // Define debug macros
  8. #ifdef DEBUG
  9.     #define DEBUG_PRINT(x)      Serial.print (x)
  10.     #define DEBUG_PRINTDEC(x)   Serial.print (x, DEC)
  11.     #define DEBUG_PRINTLN(x)    Serial.println (x)
  12.     #define DEBUG_PRINTHEX(x)   Serial.print (x, HEX)
  13. #else
  14.     #define DEBUG_PRINT(x)
  15.     #define DEBUG_PRINTDEC(x)
  16.     #define DEBUG_PRINTLN(x)
  17.     #define DEBUG_PRINTHEX(x)
  18. #endif
  19.  
  20.  
  21. #include <ESP8266WiFi.h>
  22. #include <PubSubClient.h>
  23. #include <DallasTemperature.h>
  24. #include <DHTesp.h>
  25.  
  26.  
  27.  
  28. //##################################  setup
  29. const char* ssid =          "SSID";
  30. const char* password =      "PWD";
  31. const char* mqtt_server =   "192.168.20.200";
  32. const char* tempTopic =     "/garasje/temperatur";          //## Topic to post temperature
  33. const char* humTopic =      "/mekkepult2/fuktighet";        //## Topic to post Humidity
  34. const char* btnTopic =      "/garasje/port_bryter";         //## Topic to post buttonstate
  35. const char* clientName =    "ESP_Garasje_xxx";              //## Client name. unike
  36.  
  37. WiFiClient espClient;
  38. PubSubClient client(espClient);
  39.  
  40. #ifdef DS18B20 
  41.     OneWire oneWire(DS18B20);                                           // onewire on pin 12
  42.     DallasTemperature ds18b20(&oneWire);
  43.     DeviceAddress insideThermometer;
  44. #endif
  45. #ifdef DHT22_PIN
  46.     DHTesp dht;
  47.     float humidity;
  48.     float temperature;
  49.     float last_humidity;
  50.     float last_temperature;
  51.     char Tmsg[10];
  52.     char Hmsg[10];
  53. #endif
  54.  
  55.  
  56. long lastMsg = 0;
  57. float lastValue = 0;
  58. char msg[50];
  59. int value = 0;
  60. bool button;
  61. bool old_button;
  62.  
  63. String MAC= WiFi.macAddress();
  64.  
  65.  
  66. void setup(){
  67.    
  68.     Serial.begin(115200);
  69.    
  70.     #ifdef SWITCH  
  71.     pinMode(SWITCH,INPUT);
  72.     #endif
  73.  
  74.     #ifdef DS18B20     
  75.     ds18b20.begin();
  76.     #endif
  77.  
  78.     #ifdef DHT22_PIN
  79.     dht.setup(12);
  80.     #endif
  81.    
  82.     //########################### WIFI begin
  83.     setup_wifi();
  84.     client.setServer(mqtt_server, 1883);
  85.     client.setCallback(callback);
  86.    
  87.  
  88.     #ifdef DS18B20
  89.     //########################### Sensor serial debug
  90.     DEBUG_PRINT("Locating devices...");
  91.     DEBUG_PRINT("Found ");
  92.     DEBUG_PRINTDEC(ds18b20.getDeviceCount());
  93.     DEBUG_PRINTLN(" devices.");
  94.     if (!ds18b20.getAddress(insideThermometer, 0)) DEBUG_PRINTLN("Unable to find address for Device 0");
  95.     DEBUG_PRINT("Device 0 Address: ");
  96.     printAddress(insideThermometer);
  97.     DEBUG_PRINTLN();
  98.  
  99.     ds18b20.setResolution(insideThermometer, 11);   // (Sensor_adress, bits)
  100.  
  101.     DEBUG_PRINT("Device 0 Resolution: ");
  102.     DEBUG_PRINTDEC(ds18b20.getResolution(insideThermometer));
  103.     #endif
  104. }   //## END OF setup()
  105.  
  106. void setup_wifi()
  107. {
  108.     delay(10);
  109.     DEBUG_PRINT("\nConnecting to ");
  110.     DEBUG_PRINTLN(ssid);
  111.  
  112.     WiFi.begin(ssid, password);
  113.  
  114.     while (WiFi.status() != WL_CONNECTED) {
  115.         delay(500);
  116.         DEBUG_PRINT(".");
  117.     }
  118.  
  119.     DEBUG_PRINTLN("\nWiFi connected");
  120.     DEBUG_PRINTLN("IP address: ");
  121.     DEBUG_PRINTLN(WiFi.localIP());
  122.     DEBUG_PRINT("MAC: ");
  123.     DEBUG_PRINTLN(MAC);
  124.  
  125. } //## END OF setup_wifi()
  126.  
  127. void callback(char* topic, byte* payload, unsigned int length) {
  128.     Serial.print("Message arrived [");
  129.     Serial.print(topic);
  130.     Serial.print("] >");
  131.    
  132.     for (int i = 0; i < length; i++) {
  133.         Serial.print((char)payload[i]);
  134.     }
  135.    
  136.     Serial.print("<\n");
  137.     MAC.toCharArray(msg,18);
  138.     client.publish(msg,"I'm alive!");
  139. }   //## END of callback()
  140.  
  141. void reconnect() {
  142.     while (!client.connected()) {                                   //while not connected
  143.         DEBUG_PRINTLN("\nAttempting MQTT connection...");
  144.         if (client.connect(clientName)) {                           //try to connect, and if connected:
  145.             DEBUG_PRINT(clientName);                                //debug clientname
  146.             DEBUG_PRINTLN(" connected");
  147.             snprintf(msg, 50,"Device %s connected", clientName);   
  148.             client.publish("Rapport", msg);                         //Send a mqtt message
  149.            
  150.            
  151.             MAC.toCharArray(msg,18);                           
  152.             client.subscribe( msg );                                // Subscribe to own MAC adress topic
  153.         }
  154.         else {                                                      //if NOT connected
  155.             DEBUG_PRINT("failed, rc=");                             //debug
  156.             DEBUG_PRINT(client.state());
  157.             DEBUG_PRINTLN(" try again in 5 seconds");
  158.             // Wait 5 seconds before retrying
  159.             delay(5000);                                            //wait 5sek and retry
  160.         }
  161.     }
  162. }
  163.  
  164. void loop() {
  165.     if (!client.connected()) {      //Check if connected, if not :
  166.         reconnect();
  167.     }
  168.    
  169.     client.loop();
  170.    
  171.     /* Switch doesent really need any time keeping */
  172.     #ifdef SWITCH  
  173.     button = !digitalRead(SWITCH);  //GPIO 0 is normal high, low when button pressed
  174.     if(button != old_button) { // Dont send same message more than once.
  175.         old_button = button;
  176.         if(button)  client.publish(btnTopic,"1");
  177.         else        client.publish(btnTopic,"0");
  178.     }
  179.     #endif
  180.  
  181.     // Timekeeping, check every 60s if change
  182.     long now = millis();
  183.     if (now - lastMsg > 60000) {
  184.         lastMsg = now;
  185.        
  186.         #ifdef DS18B20  //Block for DS18B20 sensor
  187.         ds18b20.requestTemperatures();
  188.         float tempC = ds18b20.getTempCByIndex(0);
  189.         /* Only send message if changed */
  190.         if (tempC != lastValue){
  191.             lastValue = tempC;
  192.             FtoChar2(tempC, msg,1); //Make text out of float and put in msg
  193.             DEBUG_PRINT("\nPublish message: ");
  194.             DEBUG_PRINT(msg);
  195.             client.publish(tempTopic, msg);
  196.         }
  197.         #endif 
  198.        
  199.        
  200.         #ifdef DHT22_PIN  // Block for DHT22 sensor
  201.         float humidity = dht.getHumidity();
  202.         float temperature = dht.getTemperature();
  203.         DEBUG_PRINT("\nT:");
  204.         DEBUG_PRINT(temperature);
  205.         DEBUG_PRINT("\tH:");
  206.         DEBUG_PRINT(humidity);
  207.        
  208.         if((temperature != last_temperature) || (humidity != last_humidity) ) {
  209.             last_humidity = humidity;
  210.             last_temperature = temperature;
  211.        
  212.             FtoChar2(temperature,Tmsg,1);
  213.             FtoChar2(humidity,Hmsg,1);
  214.             Serial.print(" Publishing messages: T:");
  215.             Serial.print(Tmsg);
  216.             client.publish(tempTopic, Tmsg);
  217.             Serial.print(" H:");
  218.             Serial.println(Hmsg);
  219.             client.publish(humTopic, Hmsg);
  220.         }
  221.         #endif
  222.     } // end of Timekeeping
  223. }// END of loop
  224.  
  225. #ifdef DS18B20 
  226. void printAddress(DeviceAddress deviceAddress){
  227.     for (uint8_t i = 0; i < 8; i++){
  228.         if (deviceAddress[i] < 16) Serial.print("0");
  229.         DEBUG_PRINTHEX(deviceAddress[i]);
  230.     }
  231. }
  232. #endif
  233.  
  234. char* FtoChar2(float fVal, char* cF, int nDigs) {
  235.     long dSep = pow(10, nDigs);
  236.     signed long slVal = fVal * dSep;
  237.     sprintf(cF, "%d.%d", int(slVal / dSep), abs(int(slVal % int(dSep))));
  238. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement