Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Board : ESP8266 Boards --> LOLIN(WeMos) D1 R1
- #include "ESP8266WiFi.h"
- #include <PubSubClient.h>
- #include <OneWire.h>
- #include <DallasTemperature.h>
- #include <ArduinoJson.h>
- #include "secrets.h"
- //========================================================================
- // Defines
- //========================================================================
- #define FLASH_SLOW 700
- #define FLASH_FAST 50
- #define SECOND 1000
- #define MINUTE (60*SECOND)
- #define WIFI_RETRY_TIME (15*SECOND)
- #define MQTT_RETRY_TIME (5*SECOND)
- #define WIFI_MAX_RETRY (10*MINUTE/WIFI_RETRY_TIME)
- #define MQTT_MAX_RETRY (10*MINUTE/MQTT_RETRY_TIME)
- #define LONGDELAY 60 * 1000
- #define SHORTDELAY 1 * 1000
- #define PIN_GND_1 0
- #define PIN_DATA_1 4
- #define PIN_PWR_1 5
- #define PIN_GND_2 12
- #define PIN_DATA_2 14
- #define PIN_PWR_2 16
- #define ONE_WIRE_BUS_1 PIN_DATA_1
- #define ONE_WIRE_BUS_2 PIN_DATA_2
- //========================================================================
- // Variables
- //========================================================================
- // Wifi & MQTT
- const char* wifi_ssid = SECRET_WIFI_SSID;
- const char* wifi_pass = SECRET_WIFI_PASS;
- const char* mqtt_server = SECRET_MQTT_SERVER;
- const char* mqtt_user = SECRET_MQTT_USER;
- const char* mqtt_pass = SECRET_MQTT_PASS;
- char topic_stat[100];
- WiFiClient wifi_client;
- PubSubClient mqtt_client( wifi_client );
- bool wifi_begun(false);
- int resetcnt = 0;
- char macstr[40];
- char Device[40];
- OneWire oneWire1( ONE_WIRE_BUS_1 );
- OneWire oneWire2( ONE_WIRE_BUS_2 );
- DallasTemperature sensors1( &oneWire1 );
- DallasTemperature sensors2( &oneWire2 );
- //========================================================================
- // Functions
- //========================================================================
- //------------------------------------------------------------------------
- //
- //------------------------------------------------------------------------
- void FlashLed( int flashtime, int count=1 )
- {
- int space = flashtime;
- if( space < 300 ) space = 300;
- for( int i=0; i<count; i++ )
- {
- if( i )
- delay( space );
- digitalWrite( LED_BUILTIN, LOW );
- delay( flashtime );
- digitalWrite( LED_BUILTIN, HIGH );
- }
- }
- //------------------------------------------------------------------------
- //
- //------------------------------------------------------------------------
- void SendMqttTemps( char* topic, float temp1, float temp2 )
- {
- DynamicJsonDocument doc(1024);
- char buffer[256];
- char tmpstr[20];
- boolean result;
- doc["rssi"] = WiFi.RSSI();
- sprintf( tmpstr, "%.1f", temp1 );
- if( temp1 >= 0 && temp1 < 80 )
- doc["temp1"] = tmpstr;
- sprintf( tmpstr, "%.1f", temp2 );
- if( temp2 >= 0 && temp2 < 80 )
- doc["temp2"] = tmpstr;
- size_t n = serializeJson(doc, buffer);
- result = mqtt_client.publish( topic, buffer, n );
- if( result == false )
- Serial.println( "error!" );
- Serial.println( topic );
- Serial.println( buffer );
- }
- //------------------------------------------------------------------------
- //
- //------------------------------------------------------------------------
- void SendMqttDiscoveryMsg( char* description, char* unit_of_measurement, char* dev_class )
- {
- DynamicJsonDocument root(2048);
- char buffer[1024];
- char topic_config[100];
- char id_str[80];
- char name_str[80];
- char unid_str[80];
- char val_str[80];
- boolean result;
- sprintf( topic_config, "homeassistant/sensor/cvtemp-%s/%s/config", Device, description );
- //sprintf( topic_config, "cv_temp/%s/config", Device );
- sprintf( id_str, "cvtemp-%s", Device );
- sprintf( name_str, "mqtt_cvtemp_%s_%s", Device, description );
- sprintf( unid_str, "cvtemp-%s-%s", Device, description );
- sprintf( val_str, "{{ value_json.%s }}", description );
- root["name"] = name_str;
- root["stat_t"] = topic_stat;
- root["uniq_id"] = unid_str;
- root["dev_cla"] = dev_class;
- root["unit_of_meas"] = unit_of_measurement;
- root["val_tpl"] = val_str;
- #if 1
- JsonObject device = root.createNestedObject("dev");
- JsonArray ar = device.createNestedArray("identifiers");
- //device["identifiers"] = id_str;
- ar.add(id_str);
- device["manufacturer"] = "Me";
- device["model"] = "model";
- device["name"] = "CV_Temp_module";
- device["sw_version"] = "1.0";
- #endif
- /*
- size_t n = serializeJson(root, buffer);
- result = mqtt_client.publish( topic_config, buffer, n );
- if( result == false )
- Serial.println( "error!" );
- */
- result = mqtt_client.beginPublish(topic_config, measureJson(root), true);
- if( result == false )
- Serial.println( "error begin!" );
- // WriteBufferingPrint bufferedClient(mqtt_client, 32);
- // serializeJson(root, bufferedClient);
- // bufferedClient.flush();
- serializeJson(root, mqtt_client);
- result = mqtt_client.endPublish();
- if( result == false )
- Serial.println( "error end!" );
- serializeJsonPretty(root, buffer);
- Serial.println( topic_config );
- Serial.println( buffer );
- }
- //------------------------------------------------------------------------
- //scan SSIDs, and if my SSID is present return 1
- //------------------------------------------------------------------------
- char ScanSSIDs()
- {
- char score=0;
- int numSsid = WiFi.scanNetworks();
- if( numSsid == -1 )
- return(0); //error
- for( int thisNet=0; thisNet<numSsid; thisNet++ )
- if( strcmp( WiFi.SSID( thisNet ).c_str(), wifi_ssid ) == 0 )
- score = 1; //if one is = to my SSID
- return(score);
- }
- //------------------------------------------------------------------------
- //
- //------------------------------------------------------------------------
- void ConnectWifi()
- {
- wifi_begun = false;
- Serial.print( F( "Wifi connecting to " ) ); Serial.print( wifi_ssid ); Serial.print( F( " " ) );
- resetcnt = 0;
- WiFi.begin( wifi_ssid, wifi_pass);
- delay(250);
- for(;;)
- {
- // Try
- if( WiFi.status() == WL_CONNECTED )
- break;
- // Failed
- Serial.print( F( "." ) );
- FlashLed( FLASH_FAST, 2 );
- if( ++resetcnt > WIFI_MAX_RETRY ) // 10 minutes
- {
- Serial.println(); Serial.println( F( "Too many retries. Reset!" ) );
- ESP.restart();
- }
- delay( WIFI_RETRY_TIME );
- }
- // Succes
- wifi_begun = true;
- Serial.println(); Serial.print( F( "Connected. IP = " ) ); Serial.println( WiFi.localIP() ); Serial.println();
- FlashLed( FLASH_SLOW, 2 );
- delay( 2000 );
- }
- //------------------------------------------------------------------------
- //
- //------------------------------------------------------------------------
- void ConnectMqtt()
- {
- resetcnt = 0;
- for(;;)
- {
- // Try
- Serial.print( F( "MQTT connecting to " ) ); Serial.println( mqtt_server );
- mqtt_client.setKeepAlive( 120 );
- if( mqtt_client.connect( Device, mqtt_user, mqtt_pass ) )
- break;
- // Failed
- Serial.print( F( "Failed. Error code = " ) ); Serial.println( mqtt_client.state() );
- FlashLed( FLASH_FAST, 3 );
- if( ++resetcnt > MQTT_MAX_RETRY ) //
- {
- Serial.println( F( "Too many retries. Reset!" ) );
- ESP.restart();
- }
- delay( MQTT_RETRY_TIME );
- }
- // Succes
- Serial.println( F( "Connected" ) ); Serial.println();
- delay( 200 );
- SendMqttDiscoveryMsg( "temp1", "°C", "temperature" ) ;
- SendMqttDiscoveryMsg( "temp2", "°C", "temperature" ) ;
- SendMqttDiscoveryMsg( "rssi", "dBm", "signal_strength" ) ;
- FlashLed( FLASH_SLOW, 3 );
- delay( 2000 );
- }
- //------------------------------------------------------------------------
- //
- //------------------------------------------------------------------------
- void setup()
- {
- // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- // Pin IO
- pinMode( PIN_GND_1, OUTPUT );
- pinMode( PIN_DATA_1, INPUT_PULLUP );
- pinMode( PIN_PWR_1, OUTPUT );
- pinMode( PIN_GND_2, OUTPUT );
- pinMode( PIN_DATA_2, INPUT_PULLUP );
- pinMode( PIN_PWR_2, OUTPUT );
- digitalWrite( PIN_GND_1, LOW );
- digitalWrite( PIN_PWR_1, HIGH );
- digitalWrite( PIN_GND_2, LOW );
- digitalWrite( PIN_PWR_2, HIGH );
- // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- // initialize LED
- pinMode( LED_BUILTIN, OUTPUT );
- FlashLed( FLASH_SLOW, 1 );
- delay( 500 );
- // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- // Serial
- Serial.begin( 115200 );
- while( !Serial )
- {
- ; // wait for serial port to connect. Needed for native USB port only
- }
- // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- // WIFI
- WiFi.mode(WIFI_STA);
- // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- // MQTT
- mqtt_client.setServer( mqtt_server, 1883 );
- // mqtt_client.setBufferSize(512);
- sprintf( macstr, "%s", WiFi.macAddress().c_str() );
- Device[ 0] = macstr[0];
- Device[ 1] = macstr[1];
- Device[ 2] = macstr[3];
- Device[ 3] = macstr[4];
- Device[ 4] = macstr[6];
- Device[ 5] = macstr[7];
- Device[ 6] = macstr[9];
- Device[ 7] = macstr[10];
- Device[ 8] = macstr[12];
- Device[ 9] = macstr[13];
- Device[10] = macstr[15];
- Device[11] = macstr[16];
- //Device[12] = 0;
- Device[12] = 'X';
- Device[13] = 0;
- strcpy( topic_stat, "cv_temp/" );
- strcat( topic_stat, Device );
- strcat( topic_stat, "/stat" );
- Serial.flush();
- Serial.println();
- //Serial.print( "mac = "); Serial.println( macstr );
- Serial.print( "Device = "); Serial.println( Device );
- }
- //------------------------------------------------------------------------
- //
- //------------------------------------------------------------------------
- void loop()
- {
- int period = SHORTDELAY;
- float temp1, temp2;
- if( wifi_begun == false )
- {
- ConnectWifi();
- }
- else
- {
- int StatusWiFi = WiFi.status();
- if( StatusWiFi == WL_CONNECTION_LOST ||
- StatusWiFi == WL_DISCONNECTED ||
- StatusWiFi == WL_SCAN_COMPLETED ||
- WiFi.RSSI() == 0 )
- {
- Serial.println( F( "Disconected" ) );
- if( ScanSSIDs() )
- {
- wifi_begun = false;
- Serial.println( F( "Reconnect" ) );
- WiFi.disconnect();
- delay(1000);
- ConnectWifi(); //if my SSID is present, connect
- }
- }
- }
- if (!mqtt_client.connected())
- {
- ConnectMqtt();
- }
- mqtt_client.loop();
- sensors1.requestTemperatures(); // Send the command to get temperature readings
- temp1 = sensors1.getTempCByIndex(0);
- sensors2.requestTemperatures(); // Send the command to get temperature readings
- temp2 = sensors2.getTempCByIndex(0);
- SendMqttTemps( topic_stat, temp1, temp2 );
- FlashLed( FLASH_FAST, 1 );
- Serial.println(".");
- wifi_set_sleep_type(LIGHT_SLEEP_T);
- delay(30*1000);
- wifi_set_sleep_type(NONE_SLEEP_T);
- Serial.println("..");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement