GitLab's annual major release is around the corner. Along with a lot of new and exciting features, there will be a few breaking changes. Learn more here.

VeryDeepSleep_MQTTsubscribe.ino 7.08 KB
Newer Older
diy_bloke's avatar
diy_bloke committed
1 2 3
/*************************************************
      Template for static IP,MQTT &DeepSleep
        Read out a DHT11
4 5
        By DIY_bloke
        https://arduinodiy.wordpress.com/2020/01/26/very-deep-sleep-part-4-subscribing-to-mqtt-messages/
diy_bloke's avatar
diy_bloke committed
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
 *************************************************/
long SLEEPTIME = 900e6; //15min
const char* WLAN_SSID = "NetGear500"; //insert your own ssid & password
const char* WLAN_PASSWD = "buttercup";
#include <ESP8266WiFi.h>
#include "PubSubClient.h"

// We make a structure to store connection information
// The ESP8266 RTC memory is arranged into blocks of 4 bytes. The access methods read and write 4 bytes at a time,
// so the RTC data structure should be padded to a 4-byte multiple.
struct {
  uint32_t crc32;   // 4 bytes
  uint8_t channel;  // 1 byte,   5 in total
  uint8_t ap_mac[6];// 6 bytes, 11 in total
  uint8_t padding;  // 1 byte,  12 in total
} rtcData;
byte ledPin=2;

IPAddress ip(192, 168, 1, 22); // pick your own IP outside the DHCP range of your router
IPAddress gateway(192, 168, 1, 1); //watch out, these are comma's not dots
IPAddress subnet(255, 255, 255, 0);
IPAddress dns(192, 168, 1, 1);
//---------voor pubsub
WiFiClient espClient;
PubSubClient client(espClient);
//---------Other------
String naam = (__FILE__);     // filenaam
unsigned int batt;
ADC_MODE(ADC_VCC); // vcc uitlezen.
//--------DHT11------
float  humid_hok;
float temp_hok;
#include <DHT.h>
#define DHTTYPE  DHT11
#define DHTPIN 12 // D6
DHT dht(DHTPIN, DHTTYPE, 11); //


void setup() {
  Serial.begin(115200);
  // we disable WiFi, coming from DeepSleep, as we do not need it right away
  WiFi.mode( WIFI_OFF );
  WiFi.forceSleepBegin();
  delay( 1 );
  Serial.println("wifi uit");

  // Try to read WiFi settings from RTC memory
  bool rtcValid = false;
  if ( ESP.rtcUserMemoryRead( 0, (uint32_t*)&rtcData, sizeof( rtcData ) ) ) {
    // Calculate the CRC of what we just read from RTC memory, but skip the first 4 bytes as that's the checksum itself.
    uint32_t crc = calculateCRC32( ((uint8_t*)&rtcData) + 4, sizeof( rtcData ) - 4 );
    if ( crc == rtcData.crc32 ) {
      rtcValid = true;
    }
  }
  //now do stuff
  Serial.println("do stuff");
  //strip naam
  //strip path van filenaam
  byte p1 = naam.lastIndexOf('\\');
  byte p2 = naam.lastIndexOf('.');
  naam = naam.substring(p1 + 1, p2);
  batt = ESP.getVcc();
  Serial.print("Sketch name ");
  Serial.println(naam);
  Serial.print("Battery Voltage ");
  Serial.println(batt/1023.0F);
  pinMode(ledPin, OUTPUT); // initialize digital ledPin as an output.
  delay(10);
  digitalWrite(ledPin, HIGH); 
  //---------
//-mac
Serial.println(WiFi.macAddress());

  //----------
  

  // Start connection WiFi
  //Switch Radio back On
  WiFi.forceSleepWake();
  delay( 1 );

  // Disable the WiFi persistence.  The ESP8266 will not load and save WiFi settings unnecessarily in the flash memory.
  WiFi.persistent( false );
 Serial.println("Start WiFi");
  // Bring up the WiFi connection
  WiFi.mode( WIFI_STA );
  WiFi.config( ip, dns, gateway, subnet );
  //-----------Now we replace the normally used "WiFi.begin();" with a precedure using connection data stored by us
  if ( rtcValid ) {
    // The RTC data was good, make a quick connection
    WiFi.begin( WLAN_SSID, WLAN_PASSWD, rtcData.channel, rtcData.ap_mac, true );
  }
  else {
    // The RTC data was not valid, so make a regular connection
    WiFi.begin( WLAN_SSID, WLAN_PASSWD );
  }
 

  //------now wait for connection
  int retries = 0;
  int wifiStatus = WiFi.status();
  while ( wifiStatus != WL_CONNECTED ) {
    retries++;
    if ( retries == 100 ) {
      // Quick connect is not working, reset WiFi and try regular connection
      WiFi.disconnect();
      delay( 10 );
      WiFi.forceSleepBegin();
      delay( 10 );
      WiFi.forceSleepWake();
      delay( 10 );
      WiFi.begin( WLAN_SSID, WLAN_PASSWD );
    }
    if ( retries == 600 ) {
      // Giving up after 30 seconds and going back to sleep
      WiFi.disconnect( true );
      delay( 1 );
      WiFi.mode( WIFI_OFF );
      ESP.deepSleep( SLEEPTIME, WAKE_RF_DISABLED );
      return; // Not expecting this to be called, the previous call will never return.
    }
    delay( 50 );
    wifiStatus = WiFi.status();
  }
  //---------

  Serial.println(" WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

  //-----
  // Write current connection info back to RTC
  rtcData.channel = WiFi.channel();
  memcpy( rtcData.ap_mac, WiFi.BSSID(), 6 ); // Copy 6 bytes of BSSID (AP's MAC address)
  rtcData.crc32 = calculateCRC32( ((uint8_t*)&rtcData) + 4, sizeof( rtcData ) - 4 );
  ESP.rtcUserMemoryWrite( 0, (uint32_t*)&rtcData, sizeof( rtcData ) );


  //---------As we are connected to WiFi, begin MQTT connection
  client.setServer("192.168.1.103", 1883); //your MQTT server's IP.Mind you, these are separated by dots again
  client.setCallback(callback);
//-------Here is where you send data


Serial.println("Start Sending data");
  sendMQTTmessage();
  //------------------
  if (!client.connected()) {
    reconnect();
  }
  for(int i=0;i<10; i++)
 {
   client.loop();  //Ensure we've sent & received everything
  // Serial.print(i);
   delay(100);
  }
  /* Close WiFi connection */
  
  //client.stop();

  //----and go to back to sleep
  Serial.println("Go back to sleep");
  WiFi.disconnect( true );
  delay( 1 );

  // WAKE_RF_DISABLED to keep the WiFi radio disabled when we wake up
  ESP.deepSleep( SLEEPTIME, WAKE_RF_DISABLED );
}


void loop(){
}

void sendMQTTmessage()
{
  if (!client.connected()) {
    reconnect();
  }
  client.publish("home/sleep/tele/naam", naam.c_str(), false);
  client.publish("home/sleep/tele/batt", String(batt / 1023.0F).c_str(), false);
  client.publish("home/sleep/tele/temp",String(dht.readTemperature()).c_str(),false);
  client.publish("home/sleep/tele/humid",String(dht.readHumidity()).c_str(),false);
  
  /* Close MQTT client cleanly */
  client.disconnect();
}

void reconnect() {
  while (!client.connected())
  {
    String ClientId = "ESP8266";
    ClientId += String(random(0xffff), HEX);
    if (client.connect(ClientId.c_str()))
      //if your MQTT server is protected with a password, use the next line instead of the revious
      //if (client.connect(ClientId.c_str()),mqtt_user,mqtt_password))
    {
      Serial.print("Connected");
      client.publish("home/sleep/stat/connection", "OK");
    client.subscribe("home/sleep/cmd/led");
    } else {
      Serial.print("failed, rc= ");
      Serial.print(client.state());
      delay(1000);
    }

  }
}


// the CRC routine
uint32_t calculateCRC32( const uint8_t *data, size_t length ) {
  uint32_t crc = 0xffffffff;
  while ( length-- ) {
    uint8_t c = *data++;
    for ( uint32_t i = 0x80; i > 0; i >>= 1 ) {
      bool bit = crc & 0x80000000;
      if ( c & i ) {
        bit = !bit;
      }

      crc <<= 1;
      if ( bit ) {
        crc ^= 0x04c11db7;
      }
    }
  }

  return crc;
}

void callback(char* topic, byte* payload, unsigned int length) {
 
  Serial.print("Message arrived in topic: ");
  Serial.println(topic);
 
  Serial.print("Message:");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }

  digitalWrite(ledPin,LOW);
 
}