├── IMG_3333.JPG ├── README.md ├── Firebeetle_PIRSensor.ino ├── LICENSE └── Firebeetle_Gasmeter.ino /IMG_3333.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Torxgewinde/Firebeetle-2-ESP32-E/HEAD/IMG_3333.JPG -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Firebeetle-2-ESP32-E motion sensor 2 | This project is about using the Firebeetle ESP32-E (SKU:DFR0654-F) as battery powered motion sensor 3 | 4 | 5 | 6 | Description 7 | =========== 8 | This WiFi motion sensor consists of: 9 | - LiPo-Battery (2000mAh LiPo battery with 3.7V nominal voltage and protection circuits, ~7€) 10 | - PIR sensor to detect motion (Panasonic Series WL EKMB1303111K, Datasheet, 6µA current consumption, sometimes for ~9€) 11 | - ESP32 development board with LiPo charging circuit (Firebeetle-2-ESP32-E because it can really deepsleep with low deepsleep current, ~11€) 12 | 13 | Mainly the ESP32 saves power by entering DeepSleep state. In this state it draws about 23 µA if the "LowPower-Pad" to the RGB-color-LED is cut. Two events cause the ESP32 to wake up: 14 | - either a timer, or if 15 | - the PIR sensor changes state. 16 | 17 | The PIR state is transmitted via WiFi/MQTT and can be used in homeautomation software for further actions. 18 | 19 | Powersaving 20 | =========== 21 | Cache WiFi channel and BSSID/MAC 22 | -------------------------------- 23 | To bring the latency and energy-consumption down, Wifi channel and BSSID are cached in the RTC-RAM-section of the ESP. These cached values are still available even if the ESP32 wakes up from deep sleep. With good signal, the ESP32 is active for 450 to 1200 ms if the cached values still work. If the cached values do not work, the ESP32 performs a scan of all channels, authenticates and associates to the strongest Accesspoint found. This consumes a lot more time and thus energy, because the ESP32 needs to check all channels and see if it catches beacons of matching Accesspoints. It depends a lot on the accesspoints if the connections is quick and energy conserving or slow. 24 | 25 | PIR sensor 26 | ---------- 27 | The PIR sensor EKMB1303111K is a 3.3V type sensor with low power consumption and a reasonable price (Panasonic PaPIR). 28 | 29 | Battery protection 30 | ================== 31 | Battery itself 32 | -------------- 33 | LiPo-batteries need protection against overvoltage, short circuit and undervoltage/deep-discharge. Without these safety measures, they do not last long and can swell or even burn. The LiPo should have the proper connectors (PH2.0) with the correct polarity and sourced from a trustworthy supplier. The LiPo-battery as used has a DW01 protection IC. It shuts-down below 2.4V and above 4.25V. 34 | 35 | Deep-discharge protection 36 | ------------------------- 37 | Besides those safety measures build into the LiPo-battery, the sketch measures the battery voltage. To obtain accurate voltages, the sketch uses factory calibration values. Espressif either sets two-point, one-point or no calibration value to the EFUSE-area. 38 | If the voltage is below 3.2V, the sketch stops its regular work and enters deep-sleep for ten minute intervals. If put on a charger the device automatically enters the regular operation mode again within those ~10 minutes. If the battery drops to 3.1 to 3.0 V the sleep interval is longer with 60 minutes. If the voltage drops below 3.0V the device enters a hibernate-mode and a manual push of the reset-button is required. The voltage drops quite steeply below 3.3V and not many Ampere-hours are wasted with these levels. 39 | 40 | Tests 41 | ===== 42 | To measure the battery lifetime a device is placed in a busy room. Some figures: 43 | ``` 44 | 2021-11-24_08:44:35 Firebeetle2 off 45 | 2021-11-24_08:44:35 Firebeetle2 BatteryVoltage: 4.206 46 | 2021-11-24_08:44:35 Firebeetle2 BatteryRuntime: 52811.404255 47 | 2021-11-24_08:44:35 Firebeetle2 Restarts: 52 48 | 2021-11-24_08:44:35 Firebeetle2 ActiveTime: 42923 49 | ... 50 | 2022-05-23_18:16:49 Firebeetle2 on 51 | 2022-05-23_18:16:49 Firebeetle2 BatteryVoltage: 3.932 52 | 2022-05-23_18:16:49 Firebeetle2 BatteryRuntime: 15756413.517392 53 | 2022-05-23_18:16:49 Firebeetle2 Restarts: 28330 54 | 2022-05-23_18:16:49 Firebeetle2 ActiveTime: 14144317 55 | ``` 56 | 57 | 58 | As a plot it looks like this: 59 | ![Green line is number of activations, green dots are on/off states, red is battery voltage in %](https://user-images.githubusercontent.com/12876583/169874366-319b0b02-a340-44a7-9361-b057a8a5cffc.png) 60 | 61 | 62 | -------------------------------------------------------------------------------- /Firebeetle_PIRSensor.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | # # 3 | # Using the Firebeetle 2 ESP32-E as battery powered PIR sensor # 4 | # Project: https://github.com/Torxgewinde/Firebeetle-2-ESP32-E # 5 | # # 6 | # Firebeetle documentation at: # 7 | # https://wiki.dfrobot.com/FireBeetle_Board_ESP32_E_SKU_DFR0654 # # 8 | # # 9 | # Copyright (C) 2021 Tom Stöveken # 10 | # # 11 | # This program is free software; you can redistribute it and/or modify # 12 | # it under the terms of the GNU General Public License as published by # 13 | # the Free Software Foundation; version 2 of the License. # 14 | # # 15 | # This program is distributed in the hope that it will be useful, # 16 | # but WITHOUT ANY WARRANTY; without even the implied warranty of # 17 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # 18 | # GNU General Public License for more details. # 19 | # # 20 | # You should have received a copy of the GNU General Public License # 21 | # along with this program; if not, write to the Free Software # 22 | # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # 23 | # # 24 | ********************************************************************************/ 25 | 26 | #include 27 | #include 28 | 29 | #include "esp_adc_cal.h" 30 | 31 | #define ESSID "YOUR WIFI SSID" 32 | #define PSK "YOUR WIFI PASSWD" 33 | 34 | #define LOW_BATTERY_VOLTAGE 3.20 35 | #define VERY_LOW_BATTERY_VOLTAGE 3.10 36 | #define CRITICALLY_LOW_BATTERY_VOLTAGE 3.00 37 | 38 | String MQTTServerName = "YOUR MQTT SERVER"; 39 | uint16_t MQTTPort = 1883; 40 | String MQTTUsername = "MQTT USERNAME"; 41 | String MQTTPassword = "MQTT PASSWORD"; 42 | String MQTTDeviceName = "Firebeetle"; 43 | String MQTTRootTopic = "test/firebeetle"; 44 | 45 | enum _state { 46 | S_STARTUP = 0, 47 | S_IDLE, 48 | S_MOTION, 49 | S_IGNORE_PIR_AFTER_MOTION, 50 | S_IGNORE_PIR_AFTER_REST, 51 | }; 52 | 53 | RTC_NOINIT_ATTR struct { 54 | uint8_t bssid[6]; 55 | uint8_t channel; 56 | 57 | float BatteryVoltage; //battery voltage in V 58 | uint64_t NumberOfRestarts; //number of restarts 59 | uint64_t ActiveTime; //time being active in ms 60 | 61 | enum _state state; //keep track of current state 62 | } cache; 63 | 64 | //PIR motion sensor is connected to GPIO4 (Pin: D12) 65 | #define PIR_GPIO 4 66 | #define PIR_DEEPSLEEP_PIN GPIO_NUM_4 67 | 68 | //Panasonic-PIRs circuit stability time can be up to 30s according to datasheet, however 5s seems Ok 69 | #define STABILITY_TIME 5*1000000ULL 70 | 71 | //time to completly ignore sensor after motion 72 | #define SHORT_TIME 5*60*1000000ULL 73 | 74 | //stay in MOTION state for at least this time, time starts again on motion (=presence sensor) 75 | #define DWELL_TIME 15*60*1000000ULL 76 | 77 | //periodically wakeup and report battery status even without motion 78 | #define LONG_TIME 12*60*60*1000000ULL 79 | 80 | /****************************************************************************** 81 | Description.: bring the WiFi up 82 | Input Value.: When "tryCachedValuesFirst" is true the function tries to use 83 | cached values before attempting a scan + association 84 | Return Value: true if WiFi is up, false if it timed out 85 | ******************************************************************************/ 86 | bool WiFiUP(bool tryCachedValuesFirst) { 87 | WiFi.persistent(false); 88 | WiFi.mode(WIFI_STA); 89 | 90 | if(tryCachedValuesFirst && cache.channel > 0) { 91 | Serial.printf("Cached values as follows:\r\n"); 92 | Serial.printf(" Channel....: %d\r\n", cache.channel); 93 | Serial.printf(" BSSID......: %x:%x:%x:%x:%x:%x\r\n", cache.bssid[0], \ 94 | cache.bssid[1], \ 95 | cache.bssid[2], \ 96 | cache.bssid[3], \ 97 | cache.bssid[4], \ 98 | cache.bssid[5]); 99 | 100 | WiFi.begin(ESSID, PSK, cache.channel, cache.bssid); 101 | 102 | for (unsigned long i=millis(); millis()-i < 10000;) { 103 | delay(10); 104 | 105 | if (WiFi.status() == WL_CONNECTED) { 106 | Serial.printf("WiFi connected with cached values (%lu)\r\n", millis()-i); 107 | return true; 108 | } 109 | } 110 | } 111 | 112 | cache.channel = 0; 113 | for (uint32_t i = 0; i < sizeof(cache.bssid); i++) 114 | cache.bssid[i] = 0; 115 | 116 | // try it with the slower process 117 | WiFi.begin(ESSID, PSK); 118 | 119 | for (unsigned long i=millis(); millis()-i < 60000;) { 120 | delay(10); 121 | 122 | if (WiFi.status() == WL_CONNECTED) { 123 | Serial.printf("WiFi connected (%lu)\r\n", millis()-i); 124 | 125 | uint8_t *bssid = WiFi.BSSID(); 126 | for (uint32_t i = 0; i < sizeof(cache.bssid); i++) 127 | cache.bssid[i] = bssid[i]; 128 | cache.channel = WiFi.channel(); 129 | 130 | return true; 131 | } 132 | } 133 | 134 | Serial.printf("WiFi NOT connected\r\n"); 135 | return false; 136 | } 137 | 138 | /****************************************************************************** 139 | Description.: reads the battery voltage through the voltage divider at GPIO34 140 | if the ESP32-E has calibration eFused those will be used. 141 | In comparison with a regular voltmeter the values of ESP32 and 142 | multimeter differ only about 0.05V 143 | Input Value.: - 144 | Return Value: battery voltage in volts 145 | ******************************************************************************/ 146 | float readBattery() { 147 | uint32_t value = 0; 148 | int rounds = 11; 149 | esp_adc_cal_characteristics_t adc_chars; 150 | 151 | //battery voltage divided by 2 can be measured at GPIO34, which equals ADC1_CHANNEL6 152 | adc1_config_width(ADC_WIDTH_BIT_12); 153 | adc1_config_channel_atten(ADC1_CHANNEL_6, ADC_ATTEN_DB_11); 154 | switch(esp_adc_cal_characterize(ADC_UNIT_1, ADC_ATTEN_DB_11, ADC_WIDTH_BIT_12, 1100, &adc_chars)) { 155 | case ESP_ADC_CAL_VAL_EFUSE_TP: 156 | Serial.println("Characterized using Two Point Value"); 157 | break; 158 | case ESP_ADC_CAL_VAL_EFUSE_VREF: 159 | Serial.printf("Characterized using eFuse Vref (%d mV)\r\n", adc_chars.vref); 160 | break; 161 | default: 162 | Serial.printf("Characterized using Default Vref (%d mV)\r\n", 1100); 163 | } 164 | 165 | //to avoid noise, sample the pin several times and average the result 166 | for(int i=1; i<=rounds; i++) { 167 | value += adc1_get_raw(ADC1_CHANNEL_6); 168 | } 169 | value /= (uint32_t)rounds; 170 | 171 | //due to the voltage divider (1M+1M) values must be multiplied by 2 172 | //and convert mV to V 173 | return esp_adc_cal_raw_to_voltage(value, &adc_chars)*2.0/1000.0; 174 | } 175 | 176 | /****************************************************************************** 177 | Description.: signal motion, e.g. send MQTT message 178 | Input Value.: PIR_state to transmit, true for motion, false for no motion 179 | Return Value: true if OK, false if errors occured 180 | ******************************************************************************/ 181 | bool SignalMotion(bool PIR_State) { 182 | char buf[256] = {0}; 183 | 184 | Serial.printf("Signalling motion: %d\r\n", PIR_State); 185 | 186 | //read RTC 187 | struct timeval tv; 188 | gettimeofday(&tv, NULL); 189 | 190 | //establish connection to MQTT server 191 | WiFiClient net; 192 | MQTTClient MQTTClient; 193 | MQTTClient.setTimeout(5000); 194 | MQTTClient.begin(MQTTServerName.c_str(), MQTTPort, net); 195 | 196 | if( MQTTClient.connect(MQTTDeviceName.c_str(), MQTTUsername.c_str(), MQTTPassword.c_str())) { 197 | MQTTClient.publish(MQTTRootTopic+"/PIR", (PIR_State)?"On":"Off", false, 2); 198 | MQTTClient.publish(MQTTRootTopic+"/BatteryVoltage", String(cache.BatteryVoltage, 3), false, 2); 199 | snprintf(buf, sizeof(buf)-1, "%ld.%06ld", tv.tv_sec, tv.tv_usec); 200 | MQTTClient.publish(MQTTRootTopic+"/BatteryRuntime", buf, false, 2); 201 | snprintf(buf, sizeof(buf)-1, "%llu", cache.NumberOfRestarts); 202 | MQTTClient.publish(MQTTRootTopic+"/Restarts", buf, false, 2); 203 | snprintf(buf, sizeof(buf)-1, "%llu", cache.ActiveTime); 204 | MQTTClient.publish(MQTTRootTopic+"/ActiveTime", buf, false, 2); 205 | return true; 206 | } 207 | 208 | return false; 209 | } 210 | 211 | /****************************************************************************** 212 | Description.: since this is a battery sensor, everything happens in setup 213 | and when the tonguing' is done the device enters deep-sleep 214 | Input Value.: - 215 | Return Value: - 216 | ******************************************************************************/ 217 | void setup() { 218 | //visual feedback when we are active, turn on onboard LED 219 | pinMode(2, OUTPUT); 220 | digitalWrite(2, HIGH); 221 | 222 | cache.NumberOfRestarts++; 223 | 224 | Serial.begin(115200); 225 | Serial.print("===================================================\r\n"); 226 | Serial.printf("FireBeetle active\r\n" \ 227 | " Compiled at: " __DATE__ " - " __TIME__ "\r\n" \ 228 | " ESP-IDF: %s\r\n", esp_get_idf_version()); 229 | 230 | //read battery voltage 231 | cache.BatteryVoltage = readBattery(); 232 | Serial.printf("Voltage: %4.3f V\r\n", cache.BatteryVoltage); 233 | 234 | //a reset is required to wakeup again from below CRITICALLY_LOW_BATTERY_VOLTAGE 235 | //this is to prevent damaging the empty battery by saving as much power as possible 236 | if (cache.BatteryVoltage < CRITICALLY_LOW_BATTERY_VOLTAGE) { 237 | Serial.println("Battery critically low, hibernating..."); 238 | 239 | //switch off everything that might consume power 240 | esp_sleep_pd_config(ESP_PD_DOMAIN_RTC_SLOW_MEM, ESP_PD_OPTION_OFF); 241 | esp_sleep_pd_config(ESP_PD_DOMAIN_RTC_FAST_MEM, ESP_PD_OPTION_OFF); 242 | esp_sleep_pd_config(ESP_PD_DOMAIN_RTC_PERIPH, ESP_PD_OPTION_OFF); 243 | esp_sleep_pd_config(ESP_PD_DOMAIN_XTAL, ESP_PD_OPTION_OFF); 244 | esp_sleep_pd_config(ESP_PD_DOMAIN_VDDSDIO, ESP_PD_OPTION_OFF); 245 | //esp_sleep_pd_config(ESP_PD_DOMAIN_CPU, ESP_PD_OPTION_OFF); 246 | 247 | //disable all wakeup sources 248 | esp_sleep_disable_wakeup_source(ESP_SLEEP_WAKEUP_ALL); 249 | 250 | cache.ActiveTime += millis(); 251 | digitalWrite(2, LOW); 252 | esp_deep_sleep_start(); 253 | 254 | Serial.println("This should never get printed"); 255 | return; 256 | } 257 | 258 | //if battery is below LOW_BATTERY_VOLTAGE but still above CRITICALLY_LOW_BATTERY_VOLTAGE, 259 | //stop doing the regular work 260 | //when put on charge the device will wakeup after a while and recognize voltage is OK 261 | //this way the battery can run low, put still wakeup without physical interaction 262 | if (cache.BatteryVoltage < LOW_BATTERY_VOLTAGE) { 263 | Serial.println("Battery low, deep sleeping..."); 264 | 265 | //sleep ~60 minutes if battery is CRITICALLY_LOW_BATTERY_VOLTAGE to VERY_LOW_BATTERY_VOLTAGE 266 | //sleep ~10 minutes if battery is VERY_LOW_BATTERY_VOLTAGE to LOW_BATTERY_VOLTAGE 267 | uint64_t sleeptime = (cache.BatteryVoltage >= VERY_LOW_BATTERY_VOLTAGE) ? \ 268 | 10*60*1000000ULL : 60*60*1000000ULL; 269 | 270 | esp_sleep_enable_timer_wakeup(sleeptime); 271 | cache.ActiveTime += millis(); 272 | digitalWrite(2, LOW); 273 | esp_deep_sleep_start(); 274 | 275 | Serial.println("This should never get printed"); 276 | return; 277 | } 278 | 279 | //check if a reset/power-on occured 280 | if (esp_reset_reason() == ESP_RST_POWERON) { 281 | Serial.printf("ESP was just switched ON\r\n"); 282 | cache.state = S_STARTUP; 283 | cache.ActiveTime = 0; 284 | cache.NumberOfRestarts = 0; 285 | 286 | //set RTC to 0 287 | struct timeval tv; 288 | tv.tv_sec = 0; 289 | tv.tv_usec = 0; 290 | settimeofday(&tv, NULL); 291 | 292 | //default is to have WiFi off 293 | if (WiFi.getMode() != WIFI_OFF) { 294 | Serial.printf("WiFi wasn't off!\r\n"); 295 | WiFi.persistent(true); 296 | WiFi.mode(WIFI_OFF); 297 | } 298 | 299 | //try to connect 300 | WiFiUP(false); 301 | WiFi.disconnect(true, true); 302 | 303 | //transition to state S_STARTUP and wait till sensor output settles 304 | cache.state = S_STARTUP; 305 | esp_sleep_enable_timer_wakeup(STABILITY_TIME); 306 | } 307 | 308 | // check if ESP returns from deepsleep 309 | if (esp_reset_reason() == ESP_RST_DEEPSLEEP) { 310 | switch(esp_sleep_get_wakeup_cause()) { 311 | case ESP_SLEEP_WAKEUP_TIMER: 312 | Serial.printf("ESP woke up due to timer\r\n"); 313 | 314 | switch(cache.state) { 315 | case S_IGNORE_PIR_AFTER_MOTION: 316 | Serial.printf("transition to state MOTION\r\n"); 317 | cache.state = S_MOTION; 318 | esp_sleep_enable_ext0_wakeup(PIR_DEEPSLEEP_PIN, 1); 319 | esp_sleep_enable_timer_wakeup(DWELL_TIME); 320 | break; 321 | 322 | case S_IGNORE_PIR_AFTER_REST: 323 | case S_STARTUP: 324 | Serial.printf("transition to state IDLE\r\n"); 325 | cache.state = S_IDLE; 326 | esp_sleep_enable_ext0_wakeup(PIR_DEEPSLEEP_PIN, 1); 327 | esp_sleep_enable_timer_wakeup(LONG_TIME); 328 | break; 329 | 330 | case S_MOTION: 331 | case S_IDLE: 332 | Serial.printf("transition to state IGNORE_PIR_AFTER_REST\r\n"); 333 | cache.state = S_IGNORE_PIR_AFTER_REST; 334 | WiFiUP(true); 335 | SignalMotion(false); 336 | WiFi.disconnect(true, true); 337 | esp_sleep_enable_timer_wakeup(STABILITY_TIME); 338 | break; 339 | 340 | default: 341 | Serial.printf("this state should not occur\r\n"); 342 | } 343 | break; 344 | 345 | case ESP_SLEEP_WAKEUP_EXT0: 346 | Serial.printf("ESP woke up by EXT0\r\n"); 347 | 348 | switch(cache.state) { 349 | case S_MOTION: 350 | Serial.printf("transition to S_IGNORE_PIR_AFTER_MOTION\r\n"); 351 | cache.state = S_IGNORE_PIR_AFTER_MOTION; 352 | esp_sleep_enable_timer_wakeup(SHORT_TIME); 353 | break; 354 | 355 | case S_IDLE: 356 | Serial.printf("signalling motion and transition to S_IGNORE_PIR_AFTER_MOTION\r\n"); 357 | WiFiUP(true); 358 | SignalMotion(true); 359 | WiFi.disconnect(true, true); 360 | 361 | cache.state = S_IGNORE_PIR_AFTER_MOTION; 362 | esp_sleep_enable_timer_wakeup(SHORT_TIME); 363 | break; 364 | 365 | default: 366 | case S_IGNORE_PIR_AFTER_MOTION: 367 | case S_IGNORE_PIR_AFTER_REST: 368 | case S_STARTUP: 369 | Serial.printf("this state should not occur\r\n"); 370 | } 371 | break; 372 | 373 | default: 374 | Serial.printf("ESP woke due to an unknown reason\r\n"); 375 | } 376 | } 377 | 378 | Serial.printf("=== entering deepsleep after %d ms ===\r\n", millis()); 379 | cache.ActiveTime += millis(); 380 | digitalWrite(2, LOW); 381 | esp_deep_sleep_start(); 382 | 383 | Serial.println("This should never get printed"); 384 | } 385 | 386 | void loop() { 387 | Serial.println("This should never get printed"); 388 | } 389 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /Firebeetle_Gasmeter.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | # # 3 | # Using the Firebeetle 2 ESP32-E as battery powered gasmeter-reader # 4 | # Project: https://github.com/Torxgewinde/Firebeetle-2-ESP32-E # 5 | # # 6 | # Firebeetle documentation at: # 7 | # https://wiki.dfrobot.com/FireBeetle_Board_ESP32_E_SKU_DFR0654 # # 8 | # # 9 | # Copyright (C) 2023 Tom Stöveken # 10 | # # 11 | # This program is free software; you can redistribute it and/or modify # 12 | # it under the terms of the GNU General Public License as published by # 13 | # the Free Software Foundation; version 2 of the License. # 14 | # # 15 | # This program is distributed in the hope that it will be useful, # 16 | # but WITHOUT ANY WARRANTY; without even the implied warranty of # 17 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # 18 | # GNU General Public License for more details. # 19 | # # 20 | # You should have received a copy of the GNU General Public License # 21 | # along with this program; if not, write to the Free Software # 22 | # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # 23 | # # 24 | ********************************************************************************/ 25 | 26 | #include 27 | #include 28 | #include 29 | 30 | #include "esp_adc_cal.h" 31 | #include "driver/rtc_io.h" 32 | 33 | #define ESSID "My Wifi SSID" 34 | #define PSK "My Wifi Password" 35 | 36 | #define LOW_BATTERY_VOLTAGE 3.20 37 | #define VERY_LOW_BATTERY_VOLTAGE 3.10 38 | #define CRITICALLY_LOW_BATTERY_VOLTAGE 3.00 39 | 40 | //char *MQTTServer = "server.lan"; 41 | IPAddress MQTTServer = IPAddress(192,168,1,1); 42 | uint16_t MQTTPort = 1883; 43 | String MQTTUsername = "username"; 44 | String MQTTPassword = "password"; 45 | String MQTTDeviceName = "Gaszaehler"; 46 | String MQTTRootTopic = "Keller/Gaszaehler"; 47 | 48 | enum _state { 49 | S_STARTUP = 0, 50 | S_DEBOUNCE_LOW, 51 | S_DEBOUNCE_HIGH, 52 | S_LOW, 53 | S_HIGH 54 | }; 55 | 56 | enum _message { 57 | M_COUNTER = 0, 58 | M_STATUS 59 | }; 60 | 61 | RTC_NOINIT_ATTR struct { 62 | uint8_t bssid[6]; 63 | uint8_t channel; 64 | 65 | float BatteryVoltage; //battery voltage in V 66 | uint64_t NumberOfRestarts; //number of restarts 67 | uint64_t ActiveTime; //time being active in ms 68 | 69 | enum _state state; //keep track of current state 70 | 71 | uint64_t counter; //gasmeter-counter 72 | uint64_t debounceTime; //debounce time in ms 73 | } cache; 74 | 75 | //REED contact is connected to GPIO4 (Pin: D12) 76 | #define REED_GPIO 4 77 | #define REED_DEEPSLEEP_PIN GPIO_NUM_4 78 | 79 | //#define DEBOUNCE_TIME 1*1000000ULL // 1000 msec 80 | #define DEBOUNCE_TIME 200*1000ULL //200 msec 81 | 82 | //periodically wakeup and report battery status 83 | #define LONG_TIME 2*60*60*1000000ULL 84 | 85 | //time to spend on establishing Wifi connection in ms 86 | #define MAX_WIFI_CONNECTION_TIME 6000UL 87 | //time to spend on establishing MQTT connection in ms 88 | #define MAX_MQTT_CONNECTION_TIME 2000 89 | 90 | /****************************************************************************** 91 | Description.: bring the WiFi up 92 | Input Value.: When "tryCachedValuesFirst" is true the function tries to use 93 | cached values before attempting a scan + association 94 | "max_connection_time" in ms is the time to spend on establishing 95 | the WiFi connection 96 | Return Value: true if WiFi is up, false if it timed out 97 | ******************************************************************************/ 98 | bool WiFiUP(bool tryCachedValuesFirst, unsigned long max_connection_time) { 99 | unsigned long start = millis(); 100 | 101 | WiFi.persistent(false); 102 | WiFi.mode(WIFI_STA); 103 | 104 | if(tryCachedValuesFirst && cache.channel > 0) { 105 | Serial.printf("Cached values as follows:\r\n"); 106 | Serial.printf(" Channel....: %d\r\n", cache.channel); 107 | Serial.printf(" BSSID......: %x:%x:%x:%x:%x:%x\r\n", cache.bssid[0], \ 108 | cache.bssid[1], \ 109 | cache.bssid[2], \ 110 | cache.bssid[3], \ 111 | cache.bssid[4], \ 112 | cache.bssid[5]); 113 | 114 | WiFi.begin(ESSID, PSK, cache.channel, cache.bssid); 115 | 116 | for (unsigned long i=start; millis()-i < max_connection_time;) { 117 | delay(10); 118 | 119 | if (WiFi.status() == WL_CONNECTED) { 120 | Serial.printf("WiFi connected with cached values (%lu)\r\n", millis()-i); 121 | return true; 122 | } 123 | } 124 | } 125 | 126 | cache.channel = 0; 127 | for (uint32_t i = 0; i < sizeof(cache.bssid); i++) 128 | cache.bssid[i] = 0; 129 | 130 | // try it with the slower process 131 | WiFi.begin(ESSID, PSK); 132 | 133 | for (unsigned long i=start; millis()-i < max_connection_time;) { 134 | delay(10); 135 | 136 | if (WiFi.status() == WL_CONNECTED) { 137 | Serial.printf("WiFi connected (%lu)\r\n", millis()-i); 138 | 139 | uint8_t *bssid = WiFi.BSSID(); 140 | for (uint32_t i = 0; i < sizeof(cache.bssid); i++) 141 | cache.bssid[i] = bssid[i]; 142 | cache.channel = WiFi.channel(); 143 | 144 | return true; 145 | } 146 | } 147 | 148 | Serial.printf("WiFi NOT connected\r\n"); 149 | return false; 150 | } 151 | 152 | /****************************************************************************** 153 | Description.: reads the battery voltage through the voltage divider at GPIO34 154 | if the ESP32-E has calibration eFused those will be used. 155 | In comparison with a regular voltmeter the values of ESP32 and 156 | multimeter differ only about 0.05V 157 | Input Value.: - 158 | Return Value: battery voltage in volts 159 | ******************************************************************************/ 160 | float readBattery() { 161 | uint32_t value = 0; 162 | int rounds = 11; 163 | esp_adc_cal_characteristics_t adc_chars; 164 | 165 | //battery voltage divided by 2 can be measured at GPIO34, which equals ADC1_CHANNEL6 166 | adc1_config_width(ADC_WIDTH_BIT_12); 167 | adc1_config_channel_atten(ADC1_CHANNEL_6, ADC_ATTEN_DB_11); 168 | switch(esp_adc_cal_characterize(ADC_UNIT_1, ADC_ATTEN_DB_11, ADC_WIDTH_BIT_12, 1100, &adc_chars)) { 169 | case ESP_ADC_CAL_VAL_EFUSE_TP: 170 | Serial.println("Characterized using Two Point Value"); 171 | break; 172 | case ESP_ADC_CAL_VAL_EFUSE_VREF: 173 | Serial.printf("Characterized using eFuse Vref (%d mV)\r\n", adc_chars.vref); 174 | break; 175 | default: 176 | Serial.printf("Characterized using Default Vref (%d mV)\r\n", 1100); 177 | } 178 | 179 | //to avoid noise, sample the pin several times and average the result 180 | for(int i=1; i<=rounds; i++) { 181 | value += adc1_get_raw(ADC1_CHANNEL_6); 182 | } 183 | value /= (uint32_t)rounds; 184 | 185 | //due to the voltage divider (1M+1M) values must be multiplied by 2 186 | //and convert mV to V 187 | return esp_adc_cal_raw_to_voltage(value, &adc_chars)*2.0/1000.0; 188 | } 189 | 190 | /****************************************************************************** 191 | Description.: send MQTT message 192 | Input Value.: msg selects the message to send 193 | Return Value: true if OK, false if errors occured 194 | ******************************************************************************/ 195 | bool SendMessage(enum _message msg, int timeout) { 196 | char buf[256] = {0}; 197 | 198 | //read RTC 199 | struct timeval tv; 200 | gettimeofday(&tv, NULL); 201 | 202 | //establish connection to MQTT server 203 | WiFiClient net; 204 | MQTTClient MQTTClient(256); 205 | MQTTClient.begin(MQTTServer, MQTTPort, net); 206 | MQTTClient.setOptions(30, true, timeout); 207 | 208 | if( MQTTClient.connect(MQTTDeviceName.c_str(), MQTTUsername.c_str(), MQTTPassword.c_str())) { 209 | switch(msg) { 210 | case M_COUNTER: 211 | Serial.printf("Sending counter: %d\r\n", cache.counter); 212 | 213 | MQTTClient.publish(MQTTRootTopic+"/counter", String(cache.counter), true, 2); 214 | snprintf(buf, sizeof(buf)-1, "%.2f", cache.counter/100.0); 215 | MQTTClient.publish(MQTTRootTopic+"/qubicmeter", buf, false, 2); 216 | break; 217 | case M_STATUS: 218 | Serial.printf("Sending status\r\n"); 219 | 220 | MQTTClient.publish(MQTTRootTopic+"/counter", String(cache.counter), true, 2); 221 | snprintf(buf, sizeof(buf)-1, "%.2f", cache.counter/100.0); 222 | MQTTClient.publish(MQTTRootTopic+"/qubicmeter", buf, false, 2); 223 | MQTTClient.publish(MQTTRootTopic+"/BatteryVoltage", String(cache.BatteryVoltage, 3), false, 2); 224 | snprintf(buf, sizeof(buf)-1, "%ld.%06ld", tv.tv_sec, tv.tv_usec); 225 | MQTTClient.publish(MQTTRootTopic+"/BatteryRuntime", buf, false, 2); 226 | snprintf(buf, sizeof(buf)-1, "%llu", cache.NumberOfRestarts); 227 | MQTTClient.publish(MQTTRootTopic+"/Restarts", buf, false, 2); 228 | snprintf(buf, sizeof(buf)-1, "%llu", cache.ActiveTime); 229 | MQTTClient.publish(MQTTRootTopic+"/ActiveTime", buf, false, 2); 230 | snprintf(buf, sizeof(buf)-1, "%ld", WiFi.RSSI()); 231 | MQTTClient.publish(MQTTRootTopic+"/RSSI", buf, false, 2); 232 | break; 233 | default: 234 | Serial.printf("unkown message, not sending anything\r\n"); 235 | } 236 | 237 | MQTTClient.disconnect(); 238 | return true; 239 | } 240 | 241 | return false; 242 | } 243 | 244 | /****************************************************************************** 245 | Description.: get the config from MQTT, if it is retained we use it as start 246 | Input Value.: timeout in ms 247 | Return Value: true if MQTT connection was OK, false if errors occured 248 | also true even if no config was retrieved as this might be intended 249 | ******************************************************************************/ 250 | bool GetConfig(unsigned long timeout) { 251 | char buf[256] = {0}; 252 | bool gotCounter = false; 253 | bool gotDebounceTime = false; 254 | 255 | //establish connection to MQTT server 256 | WiFiClient net; 257 | MQTTClient MQTTClient(256); 258 | MQTTClient.begin(MQTTServer, MQTTPort, net); 259 | MQTTClient.setOptions(30, true, 5000); 260 | 261 | //callback as lambda-function, capture gotCounter by reference to signal when done 262 | MQTTClient.onMessage((MQTTClientCallbackSimpleFunction)([&](String &topic, String &payload) -> void { 263 | Serial.println("Received MQTT message: " + topic + " - " + payload); 264 | 265 | if ( topic == MQTTRootTopic+"/config/counter") { 266 | cache.counter = strtoull(payload.c_str(), NULL, 10); 267 | gotCounter = true; 268 | } 269 | 270 | if ( topic == MQTTRootTopic+"/config/debounceTime") { 271 | cache.debounceTime = strtoull(payload.c_str(), NULL, 10); 272 | gotDebounceTime = true; 273 | } 274 | 275 | return; 276 | })); 277 | 278 | if( MQTTClient.connect(MQTTDeviceName.c_str(), MQTTUsername.c_str(), MQTTPassword.c_str()) ) { 279 | MQTTClient.subscribe(MQTTRootTopic+"/config/counter"); 280 | MQTTClient.subscribe(MQTTRootTopic+"/config/debounceTime"); 281 | 282 | for (unsigned long i=millis(); millis()-i < timeout;) { 283 | MQTTClient.loop(); 284 | if(gotCounter && gotDebounceTime) { 285 | Serial.println("received counter and DebounceTime, will use it"); 286 | break; 287 | } 288 | delay(10); 289 | } 290 | 291 | MQTTClient.disconnect(); 292 | return true; 293 | } 294 | 295 | return false; 296 | } 297 | 298 | /****************************************************************************** 299 | Description.: since this is a battery sensor, everything happens in setup 300 | and when the tonguing' is done the device enters deep-sleep 301 | Input Value.: - 302 | Return Value: - 303 | ******************************************************************************/ 304 | void setup() { 305 | //visual feedback when we are active, turn on onboard LED 306 | pinMode(2, OUTPUT); 307 | digitalWrite(2, HIGH); 308 | 309 | cache.NumberOfRestarts++; 310 | 311 | Serial.begin(115200); 312 | Serial.print("===================================================\r\n"); 313 | Serial.printf("FireBeetle active\r\n" \ 314 | " Compiled at: " __DATE__ " - " __TIME__ "\r\n" \ 315 | " ESP-IDF: %s\r\n", esp_get_idf_version()); 316 | 317 | //read battery voltage 318 | cache.BatteryVoltage = readBattery(); 319 | Serial.printf("Voltage: %4.3f V\r\n", cache.BatteryVoltage); 320 | 321 | //a reset is required to wakeup again from below CRITICALLY_LOW_BATTERY_VOLTAGE 322 | //this is to prevent damaging the empty battery by saving as much power as possible 323 | if (cache.BatteryVoltage < CRITICALLY_LOW_BATTERY_VOLTAGE) { 324 | Serial.println("Battery critically low, hibernating..."); 325 | 326 | //switch off everything that might consume power 327 | esp_sleep_pd_config(ESP_PD_DOMAIN_RTC_SLOW_MEM, ESP_PD_OPTION_OFF); 328 | esp_sleep_pd_config(ESP_PD_DOMAIN_RTC_FAST_MEM, ESP_PD_OPTION_OFF); 329 | esp_sleep_pd_config(ESP_PD_DOMAIN_RTC_PERIPH, ESP_PD_OPTION_OFF); 330 | esp_sleep_pd_config(ESP_PD_DOMAIN_XTAL, ESP_PD_OPTION_OFF); 331 | esp_sleep_pd_config(ESP_PD_DOMAIN_VDDSDIO, ESP_PD_OPTION_OFF); 332 | //esp_sleep_pd_config(ESP_PD_DOMAIN_CPU, ESP_PD_OPTION_OFF); 333 | 334 | //disable all wakeup sources 335 | esp_sleep_disable_wakeup_source(ESP_SLEEP_WAKEUP_ALL); 336 | 337 | cache.ActiveTime += millis(); 338 | digitalWrite(2, LOW); 339 | esp_deep_sleep_start(); 340 | 341 | Serial.println("This should never get printed"); 342 | return; 343 | } 344 | 345 | //if battery is below LOW_BATTERY_VOLTAGE but still above CRITICALLY_LOW_BATTERY_VOLTAGE, 346 | //stop doing the regular work 347 | //when put on charge the device will wakeup after a while and recognize voltage is OK 348 | //this way the battery can run low, put still wakeup without physical interaction 349 | if (cache.BatteryVoltage < LOW_BATTERY_VOLTAGE) { 350 | Serial.println("Battery low, deep sleeping..."); 351 | 352 | //sleep ~60 minutes if battery is CRITICALLY_LOW_BATTERY_VOLTAGE to VERY_LOW_BATTERY_VOLTAGE 353 | //sleep ~10 minutes if battery is VERY_LOW_BATTERY_VOLTAGE to LOW_BATTERY_VOLTAGE 354 | uint64_t sleeptime = (cache.BatteryVoltage >= VERY_LOW_BATTERY_VOLTAGE) ? \ 355 | 10*60*1000000ULL : 60*60*1000000ULL; 356 | 357 | esp_sleep_enable_timer_wakeup(sleeptime); 358 | cache.ActiveTime += millis(); 359 | digitalWrite(2, LOW); 360 | esp_deep_sleep_start(); 361 | 362 | Serial.println("This should never get printed"); 363 | return; 364 | } 365 | 366 | //configure GPIO of reed-switch 367 | pinMode(REED_GPIO, INPUT_PULLUP); 368 | rtc_gpio_pullup_en(REED_DEEPSLEEP_PIN); 369 | rtc_gpio_pulldown_dis(REED_DEEPSLEEP_PIN); 370 | 371 | //read level of reed-switch 372 | int level = digitalRead(REED_GPIO); 373 | Serial.printf("Reed-switch: %s\r\n", (level)?"NOMAGNET (=HIGH)":"MAGNET (=LOW)"); 374 | 375 | //check if a reset/power-on occured 376 | if (esp_reset_reason() == ESP_RST_POWERON || esp_reset_reason() == ESP_RST_SW) { 377 | Serial.printf("ESP was just switched ON or software reset\r\n"); 378 | 379 | cache.state = S_STARTUP; 380 | cache.ActiveTime = 0; 381 | cache.NumberOfRestarts = 0; 382 | cache.counter = 0; 383 | cache.debounceTime = DEBOUNCE_TIME; 384 | 385 | //set RTC to 0 386 | struct timeval tv; 387 | tv.tv_sec = 0; 388 | tv.tv_usec = 0; 389 | settimeofday(&tv, NULL); 390 | 391 | //default is to have WiFi off 392 | if (WiFi.getMode() != WIFI_OFF) { 393 | Serial.printf("WiFi wasn't off!\r\n"); 394 | WiFi.persistent(true); 395 | WiFi.mode(WIFI_OFF); 396 | } 397 | 398 | //try to connect to WiFi for first time, use a very long timeout here 399 | if ( !WiFiUP(false, 60000) ) { 400 | //We only like to proceed if WiFi is working at least once, so just restart and try again... 401 | Serial.printf("WiFi does not connect, will try again right now...\r\n"); 402 | ESP.restart(); 403 | } 404 | //retrieve the previous gasmeter-counter, will return quickly if it is retained 405 | GetConfig(10*1000); 406 | WiFi.disconnect(true, true); 407 | 408 | //transition to new state 409 | if(level == HIGH) { 410 | cache.state = S_DEBOUNCE_HIGH; 411 | Serial.printf("RESET: S_STARTUP -> S_DEBOUNCE_HIGH\r\n"); 412 | esp_sleep_enable_timer_wakeup(cache.debounceTime); 413 | esp_sleep_enable_ext0_wakeup(REED_DEEPSLEEP_PIN, LOW); 414 | } else { 415 | cache.state = S_DEBOUNCE_LOW; 416 | Serial.printf("RESET: S_STARTUP -> S_DEBOUNCE_LOW\r\n"); 417 | esp_sleep_enable_timer_wakeup(cache.debounceTime); 418 | esp_sleep_enable_ext0_wakeup(REED_DEEPSLEEP_PIN, HIGH); 419 | } 420 | } 421 | 422 | // check if ESP returns from deepsleep 423 | if (esp_reset_reason() == ESP_RST_DEEPSLEEP) { 424 | switch(esp_sleep_get_wakeup_cause()) { 425 | case ESP_SLEEP_WAKEUP_TIMER: 426 | Serial.printf("ESP woke up due to timer\r\n"); 427 | 428 | //This state should not occur, no debounce state 429 | if(level == HIGH && cache.state == S_LOW) { 430 | cache.state = S_DEBOUNCE_HIGH; 431 | Serial.printf("TIMER: S_LOW -> S_DEBOUNCE_HIGH\r\n"); 432 | esp_sleep_enable_timer_wakeup(cache.debounceTime); 433 | esp_sleep_enable_ext0_wakeup(REED_DEEPSLEEP_PIN, LOW); 434 | break; 435 | } 436 | 437 | //can occur if LONG_TIME passed and level remains low 438 | if(level == LOW && cache.state == S_LOW) { 439 | cache.state = S_LOW; 440 | Serial.printf("TIMER: S_LOW -> S_LOW\r\n"); 441 | esp_sleep_enable_timer_wakeup(LONG_TIME); 442 | esp_sleep_enable_ext0_wakeup(REED_DEEPSLEEP_PIN, HIGH); 443 | 444 | if (WiFiUP(true, MAX_WIFI_CONNECTION_TIME)) { 445 | SendMessage(M_STATUS, MAX_MQTT_CONNECTION_TIME); 446 | WiFi.disconnect(true, true); 447 | } 448 | break; 449 | } 450 | 451 | //can occur if LONG_TIME passed and level remains high 452 | if(level == HIGH && cache.state == S_HIGH) { 453 | cache.state = S_HIGH; 454 | Serial.printf("TIMER: S_HIGH -> S_HIGH\r\n"); 455 | esp_sleep_enable_timer_wakeup(LONG_TIME); 456 | esp_sleep_enable_ext0_wakeup(REED_DEEPSLEEP_PIN, LOW); 457 | 458 | if (WiFiUP(true, MAX_WIFI_CONNECTION_TIME)) { 459 | SendMessage(M_STATUS, MAX_MQTT_CONNECTION_TIME); 460 | WiFi.disconnect(true, true); 461 | } 462 | break; 463 | } 464 | 465 | //this state should not occur, no debounce state 466 | if(level == LOW && cache.state == S_HIGH) { 467 | cache.state = S_DEBOUNCE_LOW; 468 | Serial.printf("TIMER: S_HIGH -> S_DEBOUNCE_LOW\r\n"); 469 | esp_sleep_enable_timer_wakeup(cache.debounceTime); 470 | esp_sleep_enable_ext0_wakeup(REED_DEEPSLEEP_PIN, HIGH); 471 | break; 472 | } 473 | 474 | //level was HIGH for the whole DEBOUNCE_TIME and still is 475 | if(level == HIGH && cache.state == S_DEBOUNCE_HIGH) { 476 | cache.state = S_HIGH; 477 | Serial.printf("TIMER: S_DEBOUNCE_HIGH -> S_HIGH\r\n"); 478 | esp_sleep_enable_timer_wakeup(LONG_TIME); 479 | esp_sleep_enable_ext0_wakeup(REED_DEEPSLEEP_PIN, LOW); 480 | break; 481 | } 482 | 483 | //timer is up, but level changed without triggering EXT0, strange but deal with it 484 | if(level == LOW && cache.state == S_DEBOUNCE_HIGH) { 485 | cache.state = S_DEBOUNCE_LOW; 486 | Serial.printf("TIMER: S_DEBOUNCE_HIGH -> S_DEBOUNCE_LOW\r\n"); 487 | esp_sleep_enable_timer_wakeup(cache.debounceTime); 488 | esp_sleep_enable_ext0_wakeup(REED_DEEPSLEEP_PIN, HIGH); 489 | break; 490 | } 491 | 492 | //timer is up, but level changed without triggering EXT0, strange but deal with it 493 | if(level == HIGH && cache.state == S_DEBOUNCE_LOW) { 494 | cache.state = S_DEBOUNCE_HIGH; 495 | Serial.printf("TIMER: S_DEBOUNCE_LOW -> S_DEBOUNCE_HIGH\r\n"); 496 | esp_sleep_enable_timer_wakeup(cache.debounceTime); 497 | esp_sleep_enable_ext0_wakeup(REED_DEEPSLEEP_PIN, LOW); 498 | break; 499 | } 500 | 501 | //level was LOW for the whole debounce time and still is 502 | if(level == LOW && cache.state == S_DEBOUNCE_LOW) { 503 | cache.state = S_LOW; 504 | Serial.printf("TIMER: S_DEBOUNCE_LOW -> S_LOW\r\n"); 505 | esp_sleep_enable_timer_wakeup(LONG_TIME); 506 | esp_sleep_enable_ext0_wakeup(REED_DEEPSLEEP_PIN, HIGH); 507 | 508 | cache.counter++; 509 | 510 | if(cache.counter % 20 == 0) { 511 | if (WiFiUP(true, MAX_WIFI_CONNECTION_TIME)) { 512 | SendMessage(M_STATUS, MAX_MQTT_CONNECTION_TIME); 513 | WiFi.disconnect(true, true); 514 | } 515 | } else if (cache.counter % 1 == 0) { 516 | if (WiFiUP(true, MAX_WIFI_CONNECTION_TIME)) { 517 | SendMessage(M_COUNTER, MAX_MQTT_CONNECTION_TIME); 518 | WiFi.disconnect(true, true); 519 | } 520 | } 521 | break; 522 | } 523 | break; 524 | 525 | case ESP_SLEEP_WAKEUP_EXT0: 526 | Serial.printf("ESP woke up by EXT0\r\n"); 527 | 528 | //level just changed from LOW to HIGH, start debounce time 529 | if(level == HIGH && cache.state == S_LOW) { 530 | cache.state = S_DEBOUNCE_HIGH; 531 | Serial.printf("EXT0: S_LOW -> S_DEBOUNCE_HIGH\r\n"); 532 | esp_sleep_enable_timer_wakeup(cache.debounceTime); 533 | esp_sleep_enable_ext0_wakeup(REED_DEEPSLEEP_PIN, LOW); 534 | break; 535 | } 536 | 537 | //Level was LOW, still is, no reason to change state 538 | if(level == LOW && cache.state == S_LOW) { 539 | cache.state = S_LOW; 540 | Serial.printf("EXT0: S_LOW -> S_LOW\r\n"); 541 | esp_sleep_enable_timer_wakeup(LONG_TIME); 542 | esp_sleep_enable_ext0_wakeup(REED_DEEPSLEEP_PIN, HIGH); 543 | break; 544 | } 545 | 546 | //level was HIGH, still is, no reason to change state 547 | if(level == HIGH && cache.state == S_HIGH) { 548 | cache.state = S_HIGH; 549 | Serial.printf("EXT0: S_HIGH -> S_HIGH\r\n"); 550 | esp_sleep_enable_timer_wakeup(LONG_TIME); 551 | esp_sleep_enable_ext0_wakeup(REED_DEEPSLEEP_PIN, LOW); 552 | break; 553 | } 554 | 555 | //level was HIGH, just changed to LOW, start to debounce, trigger EXT0 if bouncing to HIGH 556 | if(level == LOW && cache.state == S_HIGH) { 557 | cache.state = S_DEBOUNCE_LOW; 558 | Serial.printf("EXT0: S_HIGH -> S_DEBOUNCE_LOW\r\n"); 559 | esp_sleep_enable_timer_wakeup(cache.debounceTime); 560 | esp_sleep_enable_ext0_wakeup(REED_DEEPSLEEP_PIN, HIGH); 561 | break; 562 | } 563 | 564 | //level was HIGH, still is, however something triggered EXT0, restart DEBOUNCE_TIME 565 | if(level == HIGH && cache.state == S_DEBOUNCE_HIGH) { 566 | cache.state = S_DEBOUNCE_HIGH; 567 | Serial.printf("EXT0: S_DEBOUNCE_HIGH -> S_DEBOUNCE_HIGH, but restart DEBOUNCE_TIME\r\n"); 568 | esp_sleep_enable_timer_wakeup(cache.debounceTime); 569 | esp_sleep_enable_ext0_wakeup(REED_DEEPSLEEP_PIN, LOW); 570 | break; 571 | } 572 | 573 | //level was HIGH, just changed to LOW, might be just bouncing 574 | if(level == LOW && cache.state == S_DEBOUNCE_HIGH) { 575 | cache.state = S_DEBOUNCE_LOW; 576 | Serial.printf("EXT0: S_DEBOUNCE_HIGH -> S_DEBOUNCE_LOW\r\n"); 577 | esp_sleep_enable_timer_wakeup(cache.debounceTime); 578 | esp_sleep_enable_ext0_wakeup(REED_DEEPSLEEP_PIN, HIGH); 579 | break; 580 | } 581 | 582 | //level was LOW, now it is HIGH, might just be bouncing 583 | if(level == HIGH && cache.state == S_DEBOUNCE_LOW) { 584 | cache.state = S_DEBOUNCE_HIGH; 585 | Serial.printf("EXT0: S_DEBOUNCE_LOW -> S_DEBOUNCE_HIGH\r\n"); 586 | esp_sleep_enable_timer_wakeup(cache.debounceTime); 587 | esp_sleep_enable_ext0_wakeup(REED_DEEPSLEEP_PIN, LOW); 588 | break; 589 | } 590 | 591 | //level was LOW, still is, however something triggered EXT0, restart DEBOUNCE_TIME 592 | if(level == LOW && cache.state == S_DEBOUNCE_LOW) { 593 | cache.state = S_DEBOUNCE_LOW; 594 | Serial.printf("EXT0: S_DEBOUNCE_LOW -> S_DEBOUNCE_LOW, but restart DEBOUNCE_TIME\r\n"); 595 | esp_sleep_enable_timer_wakeup(cache.debounceTime); 596 | esp_sleep_enable_ext0_wakeup(REED_DEEPSLEEP_PIN, HIGH); 597 | break; 598 | } 599 | break; 600 | 601 | default: 602 | Serial.printf("ESP woke up due to an unknown reason\r\n"); 603 | } 604 | } 605 | 606 | Serial.printf("counter: %llu, debounceTime: %llu\r\n", cache.counter, cache.debounceTime); 607 | Serial.printf("=== entering deepsleep after %d ms ===\r\n", millis()); 608 | cache.ActiveTime += millis(); 609 | digitalWrite(2, LOW); 610 | esp_deep_sleep_start(); 611 | 612 | Serial.println("This should never get printed"); 613 | } 614 | 615 | void loop() { 616 | Serial.println("This should never get printed"); 617 | } 618 | --------------------------------------------------------------------------------