├── .vscode └── extensions.json ├── .github └── workflows │ └── workflow.yml ├── README.md ├── .gitignore ├── platformio.ini ├── esp32 └── esp32.ino ├── LICENSE └── src └── esp8266.ino /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | // See http://go.microsoft.com/fwlink/?LinkId=827846 3 | // for the documentation about the extensions.json format 4 | "recommendations": [ 5 | "platformio.platformio-ide" 6 | ], 7 | "unwantedRecommendations": [ 8 | "ms-vscode.cpptools-extension-pack" 9 | ] 10 | } 11 | -------------------------------------------------------------------------------- /.github/workflows/workflow.yml: -------------------------------------------------------------------------------- 1 | name: PlatformIO CI 2 | 3 | on: [push] 4 | 5 | jobs: 6 | build: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/checkout@v3 10 | - uses: actions/cache@v3 11 | with: 12 | path: | 13 | ~/.cache/pip 14 | ~/.platformio/.cache 15 | key: ${{ runner.os }}-pio 16 | - uses: actions/setup-python@v4 17 | with: 18 | python-version: '3.9' 19 | - name: Install PlatformIO Core 20 | run: pip install --upgrade platformio 21 | 22 | - name: Build PlatformIO Project 23 | run: pio run -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # smart-sensor 2 | 3 | ```shell 4 | # Build project 5 | $ pio run 6 | 7 | # Upload firmware 8 | $ pio run --target upload 9 | 10 | # Build specific environment 11 | $ pio run -e nodemcuv2 12 | 13 | # Upload firmware for the specific environment 14 | $ pio run -e nodemcuv2 --target upload 15 | 16 | # Clean build files 17 | $ pio run --target clean 18 | ``` 19 | 20 | esp8266 libraries: 21 | ``` 22 | #include // MQTT by Joel Gaehwiler https://github.com/256dpi/arduino-mqtt 23 | #include // https://github.com/PaulStoffregen/Time 24 | #include // arduinojson 25 | Adafruit BME280 Library 26 | ``` -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .pio 2 | .vscode/.browse.c_cpp.db* 3 | .vscode/c_cpp_properties.json 4 | .vscode/launch.json 5 | .vscode/ipch 6 | 7 | *.bin 8 | # Prerequisites 9 | *.d 10 | 11 | # Object files 12 | *.o 13 | *.ko 14 | *.obj 15 | *.elf 16 | 17 | # Linker output 18 | *.ilk 19 | *.map 20 | *.exp 21 | 22 | # Precompiled Headers 23 | *.gch 24 | *.pch 25 | 26 | # Libraries 27 | *.lib 28 | *.a 29 | *.la 30 | *.lo 31 | 32 | # Shared objects (inc. Windows DLLs) 33 | *.dll 34 | *.so 35 | *.so.* 36 | *.dylib 37 | 38 | # Executables 39 | *.exe 40 | *.out 41 | *.app 42 | *.i*86 43 | *.x86_64 44 | *.hex 45 | 46 | # Debug files 47 | *.dSYM/ 48 | *.su 49 | *.idb 50 | *.pdb 51 | 52 | # Kernel Module Compile Results 53 | *.mod* 54 | *.cmd 55 | .tmp_versions/ 56 | modules.order 57 | Module.symvers 58 | Mkfile.old 59 | dkms.conf 60 | -------------------------------------------------------------------------------- /platformio.ini: -------------------------------------------------------------------------------- 1 | ; PlatformIO Project Configuration File 2 | ; 3 | ; Build options: build flags, source filter 4 | ; Upload options: custom upload port, speed and extra flags 5 | ; Library options: dependencies, extra library storages 6 | ; Advanced options: extra scripting 7 | ; 8 | ; Please visit documentation for the other options and examples 9 | ; https://docs.platformio.org/page/projectconf.html 10 | 11 | [env:nodemcuv2] 12 | platform = espressif8266 13 | board = nodemcuv2 14 | framework = arduino 15 | upload_speed = 921600 16 | build_flags = 17 | -D wifissid='"${sysenv.WIFI_SSID}"' 18 | -D wifiPassword='"${sysenv.WIFI_PASSWORD}"' 19 | lib_deps = 20 | adafruit/Adafruit Unified Sensor@^1.1.7 21 | adafruit/Adafruit BME280 Library@^2.2.2 22 | paulstoffregen/Time@^1.6.1 23 | arduino-libraries/NTPClient@^3.2.1 24 | bblanchon/ArduinoJson@^6.20.1 25 | martin-laclaustra/CronAlarms@^0.1.0 26 | -------------------------------------------------------------------------------- /esp32/esp32.ino: -------------------------------------------------------------------------------- 1 | /* 2 | To upload through terminal you can use: curl -F "image=@firmware.bin" esp32-webupdate.local/update 3 | */ 4 | extern "C" int rom_phy_get_vdd33(); 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include "DHT.h" 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | 17 | #define DHTTYPE DHT11 18 | 19 | WiFiUDP ntpUDP; 20 | WiFiUDP wifiUDP; 21 | NTPClient timeClient(ntpUDP); 22 | 23 | const char* host = "esp32-webupdate"; 24 | const char* ssid = "}RooT{"; 25 | const char* password = ""; 26 | unsigned int localUdpPort = 6930; 27 | uint64_t chipid = ESP.getEfuseMac(); 28 | uint16_t chip = (uint16_t)(chipid >> 32); 29 | char deviceName[23]; 30 | 31 | const int DHTPin = 22; 32 | DHT dht(DHTPin, DHTTYPE); 33 | String celsiusTemp; 34 | String fahrenheitTemp; 35 | String humidityTemp; 36 | 37 | const String deviceType = "HiGrowEsp32"; 38 | const String firmwareVersion = "201903301731"; 39 | const String sensorErrorInfo = "Could not init sensor, check wiring!"; 40 | boolean sensorInitialized; 41 | 42 | WebServer server(80); 43 | 44 | const char* serverIndex = "
"; 45 | 46 | void handleRoot() { 47 | server.send(200, "text/plain", getSensorDataXML()); 48 | } 49 | 50 | void handleJSON() { 51 | server.send(200, "application/json", getSensorDataJSON()); 52 | } 53 | 54 | void handleCSV() { 55 | server.send(200, "text/csv", getSensorDataCSV()); 56 | } 57 | 58 | String moisure() { 59 | return String(map(analogRead(32), 3200, 1440, 0, 100)); 60 | } 61 | 62 | void dthMeashure() { 63 | float h = dht.readHumidity(); 64 | float t = dht.readTemperature(); 65 | float f = dht.readTemperature(true); 66 | float hic = dht.computeHeatIndex(t, h, false); 67 | if (isnan(h) || isnan(t) || isnan(f)) { 68 | Serial.println("Failed to read from DHT sensor!"); 69 | celsiusTemp = "Failed"; 70 | fahrenheitTemp = "Failed"; 71 | humidityTemp = "Failed"; 72 | } else { 73 | float hic = dht.computeHeatIndex(t, h, false); 74 | celsiusTemp = hic; 75 | float hif = dht.computeHeatIndex(f, h); 76 | fahrenheitTemp = hif; 77 | humidityTemp = h; 78 | } 79 | } 80 | 81 | String getSensorDataXML() { 82 | if (sensorInitialized) { 83 | dthMeashure(); 84 | return "\n\n" + String(timeClient.getEpochTime(), DEC) 85 | + "" + "\n" 86 | + celsiusTemp + "" + "\n" + 87 | moisure() + "" + 88 | "\n" + humidityTemp + "\n\n" + 89 | String(chip) + "\n" + deviceType + "\n" + 90 | String(min(max(2 * (WiFi.RSSI() + 100), 0), 100), DEC) + "\n" + 91 | String(rom_phy_get_vdd33() / 1024.00f, DEC) + "\n" + 92 | firmwareVersion + "\n\n"; 93 | } else { 94 | return sensorErrorInfo; 95 | } 96 | } 97 | 98 | String getSensorDataJSON() { 99 | if (sensorInitialized) { 100 | dthMeashure(); 101 | return "{\"measurements\": {\"unixtimestamp\": " + String(timeClient.getEpochTime(), DEC) + 102 | ",\"temperature\": " + 103 | celsiusTemp + 104 | ",\"moisture\": " + moisure() + 105 | + ",\"humidity\": " + 106 | humidityTemp + "},\"systemInfo\": { \"serialNumber\": \"" + 107 | String(chip) + "\",\"type\": \"" + deviceType + "\", \"rssi\": " + 108 | String(min(max(2 * (WiFi.RSSI() + 100), 0), 100), DEC) + ",\"vcc\": " + 109 | String(rom_phy_get_vdd33() / 1024.00f, DEC) + 110 | ",\"firmwareVersion\": \"" + 111 | firmwareVersion + "\"}}"; 112 | } else { 113 | return sensorErrorInfo; 114 | } 115 | } 116 | 117 | 118 | String getSensorDataCSV() { 119 | if (sensorInitialized) { 120 | dthMeashure(); 121 | return deviceType + ";" + String(timeClient.getEpochTime(), DEC) + ";" + 122 | celsiusTemp + ";" + 123 | moisure() + ";" + 124 | humidityTemp + ";" + 125 | String(min(max(2 * (WiFi.RSSI() + 100), 0), 100), DEC) + ";" + 126 | String(rom_phy_get_vdd33() / 1024.00f, DEC) + ";" + 127 | firmwareVersion + ";" + 128 | String(chip) + ";\n"; 129 | } else { 130 | return sensorErrorInfo; 131 | } 132 | } 133 | 134 | void handleNotFound() { 135 | String message = "File Not Found\n\n"; 136 | message += "URI: "; 137 | message += server.uri(); 138 | message += "\nMethod: "; 139 | message += (server.method() == HTTP_GET) ? "GET" : "POST"; 140 | message += "\nArguments: "; 141 | message += server.args(); 142 | message += "\n"; 143 | for (uint8_t i = 0; i < server.args(); i++) { 144 | message += " " + server.argName(i) + ": " + server.arg(i) + "\n"; 145 | } 146 | server.send(404, "text/plain", message); 147 | } 148 | 149 | void setup(void) { 150 | 151 | snprintf(deviceName, 23, "smart-sensor-esp32-%04X%08X", chip, (uint32_t)chipid); 152 | dht.begin(); 153 | Serial.begin(115200); 154 | Serial.println(); 155 | Serial.println("Booting Sketch..."); 156 | WiFi.mode(WIFI_STA); 157 | WiFi.setHostname(deviceName); 158 | WiFi.begin(ssid, password); 159 | if (WiFi.waitForConnectResult() == WL_CONNECTED) { 160 | MDNS.begin(deviceName); 161 | server.on("/", handleRoot); 162 | server.on("/sensor.csv", handleCSV); 163 | server.on("/sensor.json", handleJSON); 164 | server.on("/reboot", HTTP_GET, []() { 165 | server.sendHeader("Connection", "close"); 166 | server.sendHeader("Access - Control - Allow - Origin", "*"); 167 | server.send(200, "text/html", "reboot ok"); 168 | ESP.restart(); 169 | }); 170 | 171 | server.onNotFound(handleNotFound); 172 | server.on("/update", HTTP_GET, []() { 173 | server.sendHeader("Connection", "close"); 174 | server.send(200, "text/html", serverIndex); 175 | }); 176 | server.on("/update-firmware", HTTP_POST, []() { 177 | server.sendHeader("Connection", "close"); 178 | server.send(200, "text/plain", (Update.hasError()) ? "FAIL" : "OK"); 179 | ESP.restart(); 180 | }, []() { 181 | HTTPUpload& upload = server.upload(); 182 | if (upload.status == UPLOAD_FILE_START) { 183 | Serial.setDebugOutput(true); 184 | Serial.printf("Update: %s\n", upload.filename.c_str()); 185 | if (!Update.begin()) { //start with max available size 186 | Update.printError(Serial); 187 | } 188 | } else if (upload.status == UPLOAD_FILE_WRITE) { 189 | if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) { 190 | Update.printError(Serial); 191 | } 192 | } else if (upload.status == UPLOAD_FILE_END) { 193 | if (Update.end(true)) { //true to set the size to the current progress 194 | Serial.printf("Update Success: %u\nRebooting...\n", upload.totalSize); 195 | } else { 196 | Update.printError(Serial); 197 | } 198 | Serial.setDebugOutput(false); 199 | } 200 | }); 201 | waitNTPSync(); 202 | server.begin(); 203 | MDNS.addService("http", "tcp", 80); 204 | NBNS.begin(deviceName); 205 | wifiUDP.begin(localUdpPort); 206 | Serial.printf("Ready! Open http://%s.local in your browser\n", host); 207 | } else { 208 | Serial.println("WiFi Failed"); 209 | } 210 | sensorInitialized = true; 211 | } 212 | 213 | void loop(void) { 214 | timeClient.update(); 215 | server.handleClient(); 216 | handleUDPServer(); 217 | } 218 | 219 | void handleUDPServer() { 220 | if (wifiUDP.parsePacket()) { 221 | udpSend(getSensorDataCSV()); 222 | } 223 | } 224 | 225 | void udpSend(String payload) { 226 | wifiUDP.beginPacket(wifiUDP.remoteIP(), wifiUDP.remotePort()); 227 | //wifiUDP.write(payload.c_str()); 228 | wifiUDP.printf(payload.c_str()); 229 | wifiUDP.endPacket(); 230 | } 231 | 232 | bool waitNTPSync() { 233 | timeClient.end(); 234 | timeClient.setUpdateInterval(60 * 60 * 1000); 235 | timeClient.begin(); 236 | while (timeClient.getEpochTime() < 10000) { 237 | timeClient.update(); 238 | } 239 | return true; 240 | } 241 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /src/esp8266.ino: -------------------------------------------------------------------------------- 1 | /* 2 | Articles for next update 3 | http://www.esp8266.com/viewtopic.php?f=29&t=4209 4 | //Adafruit_BME280 sensor(CS, MOSI, MISO, SCK); 5 | //DHT dht(D3, DHT11); 6 | //#include / 7 | #include 8 | */ 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include 21 | 22 | //#include 23 | 24 | #include 25 | #include 26 | #include 27 | 28 | #define DEBUG 29 | 30 | #define CS D4 31 | #define CLK D5 32 | #define MISO D6 33 | #define MOSI D7 34 | #define SENSOR_ADDRESS 0x76 35 | 36 | // const char* ssid = "myssid"; 37 | // const char* wifiPassword = "mypass"; 38 | 39 | //const char* mqttUserName = "5ba8acec"; 40 | //const char* mqttPassword = ""; 41 | //const char* mqttURL = "broker.shiftr.io"; 42 | //const char* topic = "bme280.rec"; 43 | const char* serialNumber = "1"; 44 | const char* firmwareVersion = "202302191708"; 45 | String deviceName = ("smart-sensor-bme280-" + String(ESP.getChipId(), DEC)); 46 | String name = ("smart" + String(ESP.getChipId(), DEC)); 47 | 48 | unsigned int localUdpPort = 6930; 49 | const char* sensorErrorInfo = "Could not find a valid BME280 sensor, check wiring!"; 50 | boolean sensorInitialized; 51 | long lastMsg = 0; 52 | //int mqttConnectRetrysAllowed = 5; 53 | //int mqttConnectRetrys; 54 | 55 | WiFiUDP ntpUDP; 56 | WiFiUDP wifiUDP; 57 | NTPClient timeClient(ntpUDP); 58 | WiFiClientSecure espClient; 59 | HTTPClient https; 60 | //MQTTClient client; 61 | Adafruit_BME280 sensor; 62 | MDNSResponder mdns; 63 | ESP8266WebServer server(80); 64 | ESP8266HTTPUpdateServer httpUpdater; 65 | 66 | void handleRoot() { 67 | server.send(200, "text/plain", getSensorDataXML()); 68 | } 69 | 70 | void handleJSON() { 71 | server.send(200, "application/json", getSensorDataJSON()); 72 | } 73 | 74 | void handleCSV() { 75 | server.send(200, "text/csv", getSensorDataCSV()); 76 | } 77 | 78 | String getSensorDataXML() { 79 | if (sensorInitialized) { 80 | return "\n\n" + String(timeClient.getEpochTime(), DEC) + "" + "\n" + String(sensor.readTemperature(), 1) + "" + "\n" + String(sensor.readPressure() / 100, 1) + "" + "\n" + String(sensor.readAltitude(1013.25), 1) + "" + "\n" + String(sensor.readHumidity(), 1) + "\n\n\nBME280\n" + String(WiFi.RSSI(), DEC) + "\n" + String(ESP.getVcc() / 1024.00f, DEC) + "\n" + serialNumber + "\n" + firmwareVersion + "\n" + ESP.getChipId() + "\n" + ESP.getFlashChipId() + "\n" + WiFi.macAddress() + "\n"; 81 | } else { 82 | return sensorErrorInfo; 83 | } 84 | } 85 | 86 | String getSensorDataJSON() { 87 | if (sensorInitialized) { 88 | const size_t capacity = JSON_OBJECT_SIZE(2) + JSON_OBJECT_SIZE(5) + JSON_OBJECT_SIZE(8); 89 | DynamicJsonDocument doc(capacity); 90 | 91 | JsonObject measurements = doc.createNestedObject("measurements"); 92 | measurements["unixtimestamp"] = timeClient.getEpochTime(); 93 | measurements["temperature"] = sensor.readTemperature(); 94 | measurements["pressure"] = sensor.readPressure() / 100; 95 | measurements["altitude"] = sensor.readAltitude(1013.25); 96 | measurements["humidity"] = sensor.readHumidity(); 97 | 98 | JsonObject systemInfo = doc.createNestedObject("systemInfo"); 99 | systemInfo["type"] = "BME280"; 100 | systemInfo["rssi"] = WiFi.RSSI(); 101 | systemInfo["vcc"] = ESP.getVcc() / 1024.00f; 102 | systemInfo["serialNumber"] = serialNumber; 103 | systemInfo["firmwareVersion"] = firmwareVersion; 104 | systemInfo["chipId"] = ESP.getChipId(); 105 | systemInfo["flashChipId"] = ESP.getFlashChipId(); 106 | systemInfo["macAddress"] = WiFi.macAddress(); 107 | String output; 108 | serializeJson(doc, output); 109 | return output; 110 | } else { 111 | return sensorErrorInfo; 112 | } 113 | } 114 | 115 | 116 | String getSensorDataCSV() { 117 | if (sensorInitialized) { 118 | return "BME280;" + String(timeClient.getEpochTime(), DEC) + ";" + String(sensor.readTemperature(), 1) + ";" + String(sensor.readPressure() / 100, 1) + ";" + String(sensor.readAltitude(1013.25), 1) + ";" + String(sensor.readHumidity(), 1) + ";" + String(WiFi.RSSI(), DEC) + ";" + String(ESP.getVcc() / 1024.00f, DEC) + ";" + serialNumber + ";" + firmwareVersion + ";" + ESP.getChipId() + ";" + ESP.getFlashChipId() + ";" + WiFi.macAddress() + ";\n"; 119 | } else { 120 | return sensorErrorInfo; 121 | } 122 | } 123 | 124 | void handleNotFound() { 125 | String message = "File Not Found\n\n"; 126 | message += "URI: "; 127 | message += server.uri(); 128 | message += "\nMethod: "; 129 | message += (server.method() == HTTP_GET) ? "GET" : "POST"; 130 | message += "\nArguments: "; 131 | message += server.args(); 132 | message += "\n"; 133 | for (uint8_t i = 0; i < server.args(); i++) { 134 | message += " " + server.argName(i) + ": " + server.arg(i) + "\n"; 135 | } 136 | server.send(404, "text/plain", message); 137 | } 138 | 139 | void messageReceived(String &topic, String &payload) { 140 | #ifdef DEBUG 141 | Serial.println("incoming: " + topic + " - " + payload); 142 | #endif 143 | } 144 | 145 | void setup() { 146 | // ADC_MODE(ADC_VCC); 147 | #ifdef DEBUG 148 | Serial.begin(115200); 149 | Serial.setDebugOutput(true); 150 | Serial.println(); 151 | Serial.println("Booting"); 152 | Serial.print("WIFI scan start ... "); 153 | int n = WiFi.scanNetworks(); 154 | Serial.print(n); 155 | Serial.println(" network(s) found"); 156 | for (int i = 0; i < n; i++) { 157 | Serial.println(WiFi.SSID(i)); 158 | } 159 | Serial.println(); 160 | #endif 161 | // WiFi.persistent(false); 162 | // WiFi.disconnect(true); 163 | // WiFi.setAutoConnect(false); 164 | // WiFi.softAPdisconnect(true); 165 | WiFi.hostname(deviceName); 166 | WiFi.mode(WIFI_STA); 167 | // WiFi.setOutputPower(30); 168 | // WiFi.setPhyMode(WIFI_PHY_MODE_11G); 169 | while (WiFi.waitForConnectResult() != WL_CONNECTED) { 170 | #ifdef DEBUG 171 | Serial.println("Begin connect to WIFI " + String(wifissid)); 172 | #endif 173 | WiFi.begin(wifissid, wifiPassword); 174 | #ifdef DEBUG 175 | WiFi.printDiag(Serial); 176 | Serial.println("Retrying connection... ssid: '" + String(wifissid) + "' password: '" + wifiPassword + "'"); 177 | #endif 178 | delay(10000); 179 | } 180 | WiFi.setAutoConnect(true); 181 | WiFi.setAutoReconnect(true); 182 | #ifdef DEBUG 183 | Serial.println("Connected to WIFI " + String(wifissid)); 184 | //Serial.println("IP address: " + WiFi.localIP()); 185 | #endif 186 | if (mdns.begin(deviceName.c_str(), WiFi.localIP())) { 187 | #ifdef DEBUG 188 | Serial.println("MDNS responder started"); 189 | #endif 190 | } 191 | server.on("/", handleRoot); 192 | server.on("/sensor.csv", handleCSV); 193 | server.on("/sensor.json", handleJSON); 194 | server.on("/reboot", HTTP_GET, []() { 195 | server.sendHeader("Connection", "close"); 196 | server.sendHeader("Access - Control - Allow - Origin", "*"); 197 | server.send(200, "text/html", "reboot ok"); 198 | ESP.restart(); 199 | }); 200 | 201 | server.onNotFound(handleNotFound); 202 | ArduinoOTA.setHostname(deviceName.c_str()); 203 | httpUpdater.setup(&server); 204 | server.begin(); 205 | if (sensor.begin(SENSOR_ADDRESS)) { 206 | sensorInitialized = true; 207 | } else { 208 | #ifdef DEBUG 209 | Serial.println(sensorErrorInfo); 210 | #endif 211 | } 212 | waitNTPSync(); 213 | NBNS.begin(deviceName.c_str()); 214 | wifiUDP.begin(localUdpPort); 215 | espClient.setInsecure(); 216 | // client.begin(mqttURL, 8883, espClient); 217 | // client.onMessage(messageReceived); 218 | Cron.create("0 */3 * * * *", sendToBackend, false); 219 | Cron.create("0 0 */3 * * *", sendToTelegram, false); 220 | #ifdef DEBUG 221 | Serial.println("Smart sensor Ready"); 222 | #endif 223 | } 224 | 225 | void sendToBackend() { 226 | #ifdef DEBUG 227 | Serial.println("sendToBackend"); 228 | #endif 229 | String url = ""; 230 | const size_t capacity = JSON_OBJECT_SIZE(96);//JSON_OBJECT_SIZE(12); 231 | DynamicJsonDocument doc(capacity); 232 | doc["chipId"] = ESP.getChipId(); 233 | doc["flashChipId"] = ESP.getFlashChipId(); 234 | doc["macAddress"] = String(WiFi.macAddress()); 235 | doc["temperature"] = sensor.readTemperature(); 236 | doc["rssi"] = String(WiFi.RSSI(), DEC); 237 | doc["vcc"] = ESP.getVcc() / 1024.00f; 238 | doc["type"] = "BME280"; 239 | doc["serialNumber"] = serialNumber; 240 | doc["firmwareVersion"] = firmwareVersion; 241 | doc["pressure"] = sensor.readPressure() / 100; 242 | doc["altitude"] = sensor.readAltitude(1013.25); 243 | doc["humidity"] = sensor.readHumidity(); 244 | doc["unixtimestamp"] = timeClient.getEpochTime(); 245 | // deviceName 246 | String output; 247 | serializeJson(doc, output); 248 | https.begin(espClient, url); 249 | https.addHeader("Content-Type", "application/json"); 250 | int httpCode = https.POST(output); 251 | // String payload = https.getString(); 252 | // Serial.println(httpCode); //Print HTTP return code 253 | // Serial.println(payload); 254 | // https.writeToStream(&Serial); 255 | https.end(); 256 | } 257 | 258 | void sendToTelegram() { 259 | String url = "https://api.telegram.org/&text=Метеорологічні метрики:%0A" + 260 | String("назва: " + name + "%0A") + 261 | String("температура: " + String(sensor.readTemperature(), 1) + " °C%0A") + 262 | String("тиск: " + String(sensor.readPressure() / 100) + " hPa%0A") + 263 | String("вологість повітря: " + String(sensor.readHumidity()) + "%%0A") + 264 | String("висота над рівнем моря: " + String(sensor.readAltitude(1013.25))); 265 | https.begin(espClient, url); 266 | https.GET(); 267 | https.end(); 268 | } 269 | 270 | //void connect() { 271 | //#ifdef DEBUG 272 | // Serial.print("MQTT connecting..."); 273 | //#endif 274 | // int retrys; 275 | // while (!client.connect(deviceName.c_str(), mqttUserName, mqttPassword)) { 276 | // delay(1000); 277 | //#ifdef DEBUG 278 | // Serial.print("."); 279 | //#endif 280 | // if (retrys++ >= 3) { 281 | // delay(3000); 282 | // break; 283 | // } 284 | // } 285 | //#ifdef DEBUG 286 | // Serial.println("\nconnected!"); 287 | //#endif 288 | // 289 | // client.subscribe("bm280S", 1); 290 | //} 291 | 292 | void loop() { 293 | // if (mqttConnectRetrys++ <= mqttConnectRetrysAllowed && !client.connected()) { 294 | // connect(); 295 | // } 296 | timeClient.update(); 297 | // client.loop(); 298 | ArduinoOTA.handle(); 299 | server.handleClient(); 300 | // sendToQueue(); 301 | handleUDPServer(); 302 | Cron.delay(); 303 | delay(10); 304 | } 305 | 306 | void sendToQueue() { 307 | long now = millis(); 308 | if (now - lastMsg > 1 * (1000 * 60)) { 309 | lastMsg = now; 310 | const size_t capacity = JSON_OBJECT_SIZE(5); 311 | DynamicJsonDocument doc(capacity); 312 | 313 | doc["chipId"] = ESP.getChipId(); 314 | doc["temperature"] = sensor.readTemperature(); 315 | doc["pressure"] = sensor.readPressure() / 100; 316 | doc["altitude"] = sensor.readAltitude(1013.25); 317 | doc["humidity"] = sensor.readHumidity(); 318 | String output; 319 | serializeJson(doc, output); 320 | // if (client.publish(topic, output, 2, true)) { 321 | //#ifdef DEBUG 322 | // Serial.println("\ndelivered mqtt message!"); 323 | //#endif 324 | // } else { 325 | //#ifdef DEBUG 326 | // Serial.println("\nnot delivered mqtt message!"); 327 | //#endif 328 | // } 329 | } 330 | } 331 | 332 | void handleUDPServer() { 333 | if (wifiUDP.parsePacket()) { 334 | udpSend(getSensorDataCSV()); 335 | } 336 | } 337 | 338 | void udpSend(String payload) { 339 | wifiUDP.beginPacket(wifiUDP.remoteIP(), wifiUDP.remotePort()); 340 | wifiUDP.write(payload.c_str()); 341 | wifiUDP.endPacket(); 342 | } 343 | 344 | bool waitNTPSync() { 345 | timeClient.end(); 346 | timeClient.setUpdateInterval(60 * 60 * 1000); 347 | timeClient.begin(); 348 | while (timeClient.getEpochTime() < 10000) { 349 | timeClient.update(); 350 | } 351 | return true; 352 | } 353 | --------------------------------------------------------------------------------