Advertisement
hneel

Liligo_temp

Jan 26th, 2022
1,185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 11.10 KB | None | 0 0
  1.  
  2. // Board : ESP8266 Boards --> LOLIN(WeMos) D1 R1
  3.  
  4. #include "ESP8266WiFi.h"
  5. #include <PubSubClient.h>
  6. #include <OneWire.h>
  7. #include <DallasTemperature.h>
  8. #include <ArduinoJson.h>
  9. #include "secrets.h"
  10.  
  11.  
  12. //========================================================================
  13. // Defines
  14. //========================================================================
  15.  
  16. #define FLASH_SLOW                700
  17. #define FLASH_FAST                 50
  18.  
  19. #define SECOND                   1000
  20. #define MINUTE            (60*SECOND)
  21.  
  22. #define WIFI_RETRY_TIME   (15*SECOND)                
  23. #define MQTT_RETRY_TIME    (5*SECOND)                
  24.  
  25. #define WIFI_MAX_RETRY    (10*MINUTE/WIFI_RETRY_TIME)
  26. #define MQTT_MAX_RETRY    (10*MINUTE/MQTT_RETRY_TIME)
  27.  
  28.  
  29. #define LONGDELAY    60 * 1000
  30. #define SHORTDELAY    1 * 1000
  31.  
  32.  
  33. #define PIN_GND_1     0
  34. #define PIN_DATA_1    4
  35. #define PIN_PWR_1     5
  36.  
  37. #define PIN_GND_2    12
  38. #define PIN_DATA_2   14
  39. #define PIN_PWR_2    16
  40.  
  41. #define ONE_WIRE_BUS_1  PIN_DATA_1
  42. #define ONE_WIRE_BUS_2  PIN_DATA_2
  43.  
  44.  
  45. //========================================================================
  46. // Variables
  47. //========================================================================
  48.  
  49. // Wifi & MQTT
  50. const char* wifi_ssid     = SECRET_WIFI_SSID;
  51. const char* wifi_pass     = SECRET_WIFI_PASS;
  52. const char* mqtt_server   = SECRET_MQTT_SERVER;
  53. const char* mqtt_user     = SECRET_MQTT_USER;
  54. const char* mqtt_pass     = SECRET_MQTT_PASS;
  55. char  topic_stat[100];
  56.  
  57. WiFiClient  wifi_client;
  58. PubSubClient mqtt_client( wifi_client );
  59.  
  60. bool wifi_begun(false);
  61.  
  62. int resetcnt = 0;
  63.  
  64. char macstr[40];
  65. char Device[40];
  66.  
  67. OneWire oneWire1( ONE_WIRE_BUS_1 );
  68. OneWire oneWire2( ONE_WIRE_BUS_2 );
  69.  
  70. DallasTemperature sensors1( &oneWire1 );
  71. DallasTemperature sensors2( &oneWire2 );
  72.  
  73.  
  74.  
  75. //========================================================================
  76. // Functions
  77. //========================================================================
  78.  
  79. //------------------------------------------------------------------------
  80. //
  81. //------------------------------------------------------------------------
  82. void FlashLed( int flashtime, int count=1 )
  83. {
  84.   int space = flashtime;
  85.   if( space < 300 ) space = 300;
  86.  
  87.  
  88.   for( int i=0; i<count; i++ )
  89.   {
  90.     if( i )
  91.       delay( space );
  92.  
  93.     digitalWrite( LED_BUILTIN, LOW );  
  94.     delay( flashtime );
  95.     digitalWrite( LED_BUILTIN, HIGH );
  96.   }
  97. }
  98.  
  99.  
  100. //------------------------------------------------------------------------
  101. //
  102. //------------------------------------------------------------------------
  103. void SendMqttTemps( char* topic, float temp1, float temp2 )
  104. {
  105.   DynamicJsonDocument doc(1024);
  106.   char buffer[256];
  107.   char tmpstr[20];
  108.   boolean result;
  109.  
  110.   doc["rssi"] = WiFi.RSSI();
  111.  
  112.   sprintf( tmpstr, "%.1f", temp1 );
  113.   if( temp1 >= 0 && temp1 < 80 )
  114.    doc["temp1"]   = tmpstr;
  115.  
  116.   sprintf( tmpstr, "%.1f", temp2 );
  117.   if( temp2 >= 0 && temp2 < 80 )
  118.     doc["temp2"]   = tmpstr;
  119.  
  120.   size_t n = serializeJson(doc, buffer);
  121.  
  122.   result = mqtt_client.publish( topic, buffer, n );
  123.   if( result == false )
  124.     Serial.println( "error!" );
  125.  
  126.   Serial.println( topic );
  127.   Serial.println( buffer );
  128. }
  129.  
  130. //------------------------------------------------------------------------
  131. //
  132. //------------------------------------------------------------------------
  133. void SendMqttDiscoveryMsg( char* description, char* unit_of_measurement, char* dev_class )
  134. {
  135.   DynamicJsonDocument  root(2048);
  136.   char buffer[1024];
  137.   char topic_config[100];
  138.   char id_str[80];
  139.   char name_str[80];
  140.   char unid_str[80];
  141.   char val_str[80];
  142.   boolean result;
  143.  
  144.   sprintf( topic_config,  "homeassistant/sensor/cvtemp-%s/%s/config", Device, description );
  145. //sprintf( topic_config,  "cv_temp/%s/config", Device );
  146.   sprintf( id_str,        "cvtemp-%s", Device );
  147.   sprintf( name_str,      "mqtt_cvtemp_%s_%s", Device, description );
  148.   sprintf( unid_str,      "cvtemp-%s-%s", Device, description );
  149.   sprintf( val_str,       "{{ value_json.%s }}", description );
  150.  
  151.   root["name"]         = name_str;
  152.   root["stat_t"]       = topic_stat;
  153.   root["uniq_id"]      = unid_str;
  154.   root["dev_cla"]      = dev_class;
  155.   root["unit_of_meas"] = unit_of_measurement;
  156.   root["val_tpl"]      = val_str;
  157.  
  158. #if 1
  159.   JsonObject device  = root.createNestedObject("dev");
  160.  
  161.   JsonArray ar       =    device.createNestedArray("identifiers");
  162.  
  163. //device["identifiers"]   = id_str;
  164.   ar.add(id_str);
  165.   device["manufacturer"]  = "Me";
  166.   device["model"]         = "model";
  167.   device["name"]          = "CV_Temp_module";
  168.   device["sw_version"]    = "1.0";
  169. #endif
  170.  
  171. /*
  172.   size_t n = serializeJson(root, buffer);
  173.  
  174.  
  175.   result = mqtt_client.publish( topic_config, buffer, n );
  176.   if( result == false )
  177.     Serial.println( "error!" );
  178. */
  179.  
  180.   result = mqtt_client.beginPublish(topic_config, measureJson(root), true);
  181.   if( result == false )
  182.     Serial.println( "error begin!" );  
  183.    
  184. //  WriteBufferingPrint bufferedClient(mqtt_client, 32);
  185. //  serializeJson(root, bufferedClient);
  186. //  bufferedClient.flush();
  187.   serializeJson(root, mqtt_client);
  188.  
  189.   result = mqtt_client.endPublish();
  190.   if( result == false )
  191.     Serial.println( "error end!" );
  192.  
  193.  
  194.   serializeJsonPretty(root, buffer);
  195.  
  196.   Serial.println( topic_config );
  197.   Serial.println( buffer );
  198. }
  199.  
  200. //------------------------------------------------------------------------
  201. //scan SSIDs, and if my SSID is present return 1
  202. //------------------------------------------------------------------------
  203. char ScanSSIDs()
  204. {
  205.   char score=0;
  206.   int  numSsid = WiFi.scanNetworks();
  207.  
  208.   if( numSsid == -1 )
  209.     return(0); //error
  210.    
  211.   for( int thisNet=0; thisNet<numSsid; thisNet++ )
  212.     if( strcmp( WiFi.SSID( thisNet ).c_str(), wifi_ssid ) == 0 )
  213.       score = 1; //if one is = to my SSID
  214.      
  215.   return(score);
  216. }
  217.  
  218.  
  219. //------------------------------------------------------------------------
  220. //
  221. //------------------------------------------------------------------------
  222. void ConnectWifi()
  223. {
  224.   wifi_begun = false;
  225.  
  226.   Serial.print( F( "Wifi connecting to " ) );  Serial.print( wifi_ssid );  Serial.print( F( "  " ) );
  227.  
  228.   resetcnt = 0;
  229.  
  230.   WiFi.begin( wifi_ssid, wifi_pass);
  231.   delay(250);
  232.  
  233.   for(;;)
  234.   {
  235.     // Try
  236.     if( WiFi.status() == WL_CONNECTED )
  237.       break;
  238.  
  239.     // Failed
  240.     Serial.print( F( "." ) );
  241.     FlashLed( FLASH_FAST, 2 );
  242.  
  243.     if( ++resetcnt > WIFI_MAX_RETRY ) // 10 minutes
  244.     {
  245.       Serial.println();  Serial.println( F( "Too many retries. Reset!" ) );
  246.       ESP.restart();
  247.     }
  248.  
  249.     delay( WIFI_RETRY_TIME );
  250.   }
  251.  
  252.   // Succes
  253.   wifi_begun = true;
  254.  
  255.   Serial.println();  Serial.print( F( "Connected. IP = " ) );  Serial.println( WiFi.localIP() );  Serial.println();
  256.   FlashLed( FLASH_SLOW, 2 );
  257.   delay( 2000 );
  258. }
  259.  
  260.  
  261. //------------------------------------------------------------------------
  262. //
  263. //------------------------------------------------------------------------
  264. void ConnectMqtt()
  265. {
  266.   resetcnt = 0;
  267.   for(;;)
  268.   {
  269.     // Try
  270.     Serial.print( F( "MQTT connecting to " ) );  Serial.println( mqtt_server );
  271.  
  272.     mqtt_client.setKeepAlive( 120 );
  273.     if( mqtt_client.connect( Device, mqtt_user, mqtt_pass ) )
  274.       break;
  275.    
  276.     // Failed
  277.     Serial.print( F( "Failed. Error code = " ) );  Serial.println( mqtt_client.state() );
  278.     FlashLed( FLASH_FAST, 3 );
  279.  
  280.     if( ++resetcnt > MQTT_MAX_RETRY ) //
  281.     {
  282.       Serial.println( F( "Too many retries. Reset!" ) );
  283.       ESP.restart();
  284.     }
  285.  
  286.     delay( MQTT_RETRY_TIME );
  287.   }
  288.  
  289.   // Succes
  290.   Serial.println( F( "Connected" ) );  Serial.println();
  291.   delay( 200 );
  292.   SendMqttDiscoveryMsg( "temp1", "°C", "temperature" ) ;
  293.   SendMqttDiscoveryMsg( "temp2", "°C", "temperature" ) ;
  294.   SendMqttDiscoveryMsg( "rssi",  "dBm", "signal_strength" ) ;
  295.   FlashLed( FLASH_SLOW, 3 );
  296.   delay( 2000 );
  297. }
  298.  
  299.  
  300. //------------------------------------------------------------------------
  301. //
  302. //------------------------------------------------------------------------
  303. void setup()
  304. {
  305.   // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  306.   // Pin IO
  307.   pinMode( PIN_GND_1,  OUTPUT );
  308.   pinMode( PIN_DATA_1, INPUT_PULLUP );
  309.   pinMode( PIN_PWR_1,  OUTPUT );
  310.  
  311.   pinMode( PIN_GND_2,  OUTPUT );
  312.   pinMode( PIN_DATA_2, INPUT_PULLUP );
  313.   pinMode( PIN_PWR_2,  OUTPUT );
  314.  
  315.   digitalWrite( PIN_GND_1, LOW  );
  316.   digitalWrite( PIN_PWR_1, HIGH );
  317.  
  318.   digitalWrite( PIN_GND_2, LOW  );
  319.   digitalWrite( PIN_PWR_2, HIGH );
  320.  
  321.  
  322.   // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  323.   // initialize LED
  324.   pinMode( LED_BUILTIN, OUTPUT );    
  325.  
  326.   FlashLed( FLASH_SLOW, 1 );
  327.   delay( 500 );
  328.  
  329.  
  330.   // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  331.   // Serial
  332.   Serial.begin( 115200 );
  333.   while( !Serial )
  334.   {
  335.     ; // wait for serial port to connect. Needed for native USB port only
  336.   }
  337.  
  338.   // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  339.   // WIFI
  340.   WiFi.mode(WIFI_STA);
  341.  
  342.   // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  343.   // MQTT
  344.   mqtt_client.setServer( mqtt_server, 1883 );
  345.  
  346.  
  347.  // mqtt_client.setBufferSize(512);
  348.  
  349.   sprintf( macstr, "%s", WiFi.macAddress().c_str() );
  350.   Device[ 0] = macstr[0];
  351.   Device[ 1] = macstr[1];
  352.   Device[ 2] = macstr[3];
  353.   Device[ 3] = macstr[4];  
  354.   Device[ 4] = macstr[6];
  355.   Device[ 5] = macstr[7];  
  356.   Device[ 6] = macstr[9];
  357.   Device[ 7] = macstr[10];  
  358.   Device[ 8] = macstr[12];
  359.   Device[ 9] = macstr[13];  
  360.   Device[10] = macstr[15];
  361.   Device[11] = macstr[16];  
  362. //Device[12] = 0;
  363.   Device[12] = 'X';
  364.   Device[13] = 0;
  365.  
  366.   strcpy( topic_stat, "cv_temp/" );
  367.   strcat( topic_stat, Device );
  368.   strcat( topic_stat, "/stat" );
  369.  
  370.   Serial.flush();
  371.   Serial.println();
  372. //Serial.print( "mac    = "); Serial.println( macstr );
  373.   Serial.print( "Device = "); Serial.println( Device );
  374. }
  375.  
  376.  
  377. //------------------------------------------------------------------------
  378. //
  379. //------------------------------------------------------------------------
  380. void loop()
  381. {
  382.   int period = SHORTDELAY;
  383.   float temp1, temp2;
  384.  
  385.  
  386.   if( wifi_begun == false )
  387.   {
  388.     ConnectWifi();
  389.   }
  390.   else
  391.   {
  392.     int StatusWiFi = WiFi.status();
  393.     if( StatusWiFi == WL_CONNECTION_LOST ||
  394.         StatusWiFi == WL_DISCONNECTED ||
  395.         StatusWiFi == WL_SCAN_COMPLETED ||
  396.         WiFi.RSSI() == 0 )
  397.     {
  398.       Serial.println( F( "Disconected" ) );
  399.       if( ScanSSIDs() )
  400.       {
  401.         wifi_begun = false;
  402.         Serial.println( F( "Reconnect" ) );
  403.  
  404.         WiFi.disconnect();
  405.         delay(1000);
  406.         ConnectWifi(); //if my SSID is present, connect
  407.       }
  408.     }
  409.   }
  410.  
  411.   if (!mqtt_client.connected())
  412.   {
  413.     ConnectMqtt();
  414.   }
  415.  
  416.   mqtt_client.loop();  
  417.  
  418.   sensors1.requestTemperatures(); // Send the command to get temperature readings
  419.   temp1 = sensors1.getTempCByIndex(0);
  420.  
  421.   sensors2.requestTemperatures(); // Send the command to get temperature readings
  422.   temp2 = sensors2.getTempCByIndex(0);
  423.  
  424.   SendMqttTemps( topic_stat, temp1, temp2 );    
  425.   FlashLed( FLASH_FAST, 1 );
  426.   Serial.println(".");
  427.  
  428.   wifi_set_sleep_type(LIGHT_SLEEP_T);
  429.   delay(30*1000);
  430.   wifi_set_sleep_type(NONE_SLEEP_T);
  431.  
  432.   Serial.println("..");
  433. }
  434.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement