最初に作ったスマートカーテンはモーターのブラシやギアの摩耗が原因なのかトルク低下に加え駆動電流も徐々に増加しパラメタの再調整が必要な状況になってきた。
TOSO クリエティドラム ツインワンチェーン
ESP8266(WROOM02)でスマート・カーテン
ESP8266(WROOM02)でスマート・カーテン (その2)
ブラシ・モーターではやはり耐久性に難がありそうなので新たにブラシレス・モーターを探していたところ同程度のトルクがあり半分以下の駆動電流で動作するブラシレス・モーターをAliexpressで見つけた。ちなみに見た目が同じでもモータースペックの違う製品があるようなので注意しよう。
ブラシレスモーター,37mm,JGB37-BLDC3525 12V 107RPM
ヘリカルギヤのおかげなのか静かとはいえないものの動作音はなんとか耐えられそうなレベル。しかもモーター・ドライバーが必要なくロジック・レベル(5V)のみで制御できたりして使いやすいモーターだ。
早速、カーテンレールに取り付けられるように3Dプリンターでモーターケースを作ったりコネクタを取り付けたりして、
分離した制御部とモーター部を写真のようにセットアップしてみたがなんとなくこなれた感がしていいかも。
基板はいつものようにミスってしまい4度目の発注でようやく完成。写真はシルクやフットプリントがミスってる基板。(-_-;)
【回路図】
以前の回路で不安定さがあった電源と外部SW回路を改良。今回は回路を簡単にするためにモーターをPWM制御していないがPWM制御するためには5V電源回路を追加したうえでモーター側のバス・バッファ出力(1Y/2Y)をプルアップするかプッシュプル出力に変更する必要がある。
この 作品 は クリエイティブ・コモンズ 表示 – 継承 4.0 国際 ライセンスの下に提供されています。
【修正履歴】
2023-09-19
WiFi処理とモーター制御が重なるとカーテンを壊してしまう可能性があったためモーター制御を優先するように改良。
【ファームウェア】
以前のESP8266用のプログラムをESP32-C3に移植。いくつかの非互換性のための修正とモーター制御とADC処理を書き換えた程度で動作はしたもののSoftwareSerialが動作しなかったりモーター制御とWiFi接続処理が重なるとWiFi処理タスクのオーバーヘッドのためにモーターの時間制御がうまくできなくなるなどの問題が発生し追加作業を強いられてしまった。ESP32シリーズのほうがスペック上は優れているのだが実際に使ってみるとESP8266より劣っているように感じてしまうのはなぜなんだろう...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
[WiFi] ssid1= pswd1= [NTP] ntp1=ntp.nict.jp ntp2=time.nist.gov ntp3=time.windows.com timezoneoffset=32400 daylightoffset=0 [MQTT] server=*.local [BuiltinLED] gpio= [NODE] name=Smart Curtain [VCC] caribrate= |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
[curtain] id= [motor] position=1 current_limit=500 time_limit=50 rewind_time=0.6 closingup_time=3 falling_time=7 liftup_time=4.5 [time] inner_opening= inner_closing= outer_opening= outer_closing= daytime_start= daytime_end= [location] longitude=130.903102 latitude=30.404084 [sun] inner_opening=0 inner_closing=1 outer_opening=0 outer_closing=1 daytime_start=1 daytime_end=1 [light] inner_threshold=5000 outer_threshold=5000 inner_baudrate=38400 outer_baudrate=115200 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 |
/* esp32c3_toso.h - Smart Curtain Firmware for TOSO Twin One Chain Copyright (c) 2023 Sasapea's Lab. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* ------------------------------------ Arduino 2.0.4 ------------------------------------ M5Stack STAMP-C3 2.0.6 ------------------------------------ CPU Frequency: "160MHz (WiFi)" Core Debug Level: "None" Erase All Flash Before Sketch Upload: "Disable" Flash Frequency: "80MHz" Flash Mode: "QIO" Flash Size: "4MB (32Mb)" Partition Scheme: "Default 4MB with spiffs (1.2MB APP/1.5MB SPIFFS)" Upload Speed: "921600" */ //#define CURTAIN_DEBUG //#define LEDSENSOR_DEBUG #include <stdint.h> #include <stdbool.h> #include "espwnet.h" #include "ledsensor.h" #include "timedata.h" #include "curtain_toso.h" #define PIN_ADC 0 // adc analog input pin #define PIN_REV 1 // reverse operation switch input pin #define PIN_FWD 2 // forward operation switch input pin #define PIN_ODS 3 // light sensor pin (inner) #define PIN_CCW 4 // motor control output2 pin #define PIN_FG 5 // motor control output2 pin #define PIN_PWM 6 // motor control output1 pin // // MQTT spec // // N: Curtain ID (1,2,3,...) // // [topic] [payload] // /home/curtain/control/inner/N "UP" or "DOWN" or "STOP" // /home/curtain/control/outer/N "UP" or "DOWN" or "STOP" // /home/curtain/state/inner/N 100(closed) - 0(opend) % // /home/curtain/state/outer/N 100(closed) - 0(opend) % // /home/curtain/query/inner/N (query state) // /home/curtain/query/outer/N (query state) // static const String MQTT_CONTROL = "/home/curtain/control/"; static const String MQTT_STATE = "/home/curtain/state/"; static const String MQTT_QUERY = "/home/curtain/query/"; static const String MQTT_INNER = "inner/"; static const String MQTT_OUTER = "outer/"; static LEDSensor<HardwareSerial, Serial1, 0, PIN_ODS> inner_light; #if ARDUINO_USB_CDC_ON_BOOT static LEDSensor<HardwareSerial, Serial0, 1> outer_light; #else static LEDSensor<HardwareSerial, Serial, 1> outer_light; #endif static Curtain_TOSO<PIN_PWM, PIN_CCW, PIN_FWD, PIN_REV, PIN_ADC> curtain(&inner_light, &outer_light); static int curtain_status[2][2] = {{-1, -1}, {-1, -1}}; static bool connected; static void addBPSOption(String& html, int bps, int baudrate) { html += F("<option value='"); html += bps; html += F("'"); if (bps == baudrate) html += F(" selected"); html += F(">"); html += bps; html += F("</option>"); } void printTime(String& html, int time) { if (time >= 0) { int h = time / 60; int m = time % 60; if (h < 10) html += '0'; html += h; html += ':'; if (m < 10) html += '0'; html += m; } } static void onCurtainPage(void) { String html; ESPConf& conf = curtain.properties(); ESPWeb.client().setNoDelay(true); // // Save Properties and Restart // if (ESPWeb.arg("apply").equals("apply")) { conf.clear(); conf.setProperty("curtain" , "id" , ESPWeb.arg(F("curtain_id" )).c_str()); conf.setProperty("motor" , "position" , ESPWeb.arg(F("motor_position" )).c_str()); conf.setProperty("motor" , "current_limit" , ESPWeb.arg(F("current_limit" )).c_str()); conf.setProperty("motor" , "time_limit" , ESPWeb.arg(F("time_limit" )).c_str()); conf.setProperty("motor" , "rewind_time" , ESPWeb.arg(F("rewind_time" )).c_str()); conf.setProperty("motor" , "closingup_time" , ESPWeb.arg(F("closingup_time" )).c_str()); conf.setProperty("motor" , "falling_time" , ESPWeb.arg(F("falling_time" )).c_str()); conf.setProperty("motor" , "liftup_time" , ESPWeb.arg(F("liftup_time" )).c_str()); conf.setProperty("time" , "inner_opening" , ESPWeb.arg(F("time_inner_opening")).c_str()); conf.setProperty("time" , "inner_closing" , ESPWeb.arg(F("time_inner_closing")).c_str()); conf.setProperty("time" , "outer_opening" , ESPWeb.arg(F("time_outer_opening")).c_str()); conf.setProperty("time" , "outer_closing" , ESPWeb.arg(F("time_outer_closing")).c_str()); conf.setProperty("time" , "daytime_start" , ESPWeb.arg(F("time_daytime_start")).c_str()); conf.setProperty("time" , "daytime_end" , ESPWeb.arg(F("time_daytime_end" )).c_str()); conf.setProperty("location", "longitude" , ESPWeb.arg(F("location_longitude")).c_str()); conf.setProperty("location", "latitude" , ESPWeb.arg(F("location_latitude" )).c_str()); conf.setProperty("sun" , "inner_opening" , ESPWeb.arg(F("sun_inner_opening" )).c_str()); conf.setProperty("sun" , "inner_closing" , ESPWeb.arg(F("sun_inner_closing" )).c_str()); conf.setProperty("sun" , "outer_opening" , ESPWeb.arg(F("sun_outer_opening" )).c_str()); conf.setProperty("sun" , "outer_closing" , ESPWeb.arg(F("sun_outer_closing" )).c_str()); conf.setProperty("sun" , "daytime_start" , ESPWeb.arg(F("sun_daytime_start" )).c_str()); conf.setProperty("sun" , "daytime_end" , ESPWeb.arg(F("sun_daytime_end" )).c_str()); conf.setProperty("light" , "inner_threshold", ESPWeb.arg(F("inner_threshold" )).c_str()); conf.setProperty("light" , "outer_threshold", ESPWeb.arg(F("outer_threshold" )).c_str()); conf.setProperty("light" , "inner_baudrate" , ESPWeb.arg(F("inner_baudrate" )).c_str()); conf.setProperty("light" , "outer_baudrate" , ESPWeb.arg(F("outer_baudrate" )).c_str()); conf.save(CURTAIN_CONFIGURE_FILE); ESPWNet.onRestartPage("/curtain"); } // // Edit Properties // html = F("<html lang='en'>"); html += F("<head><meta http-equiv='content-type' content='text/html; charset=utf-8'>"); html += F("<meta http-equiv='content-style-type' content='text/css'><style type='text/css'><!--"); html += F("table{border-collapse: collapse}th{background-color: #cccccc; border: solid thin #FFFFFF; padding: 2pt; width: 10em; text-align: left;}"); html += F("td{background-color: #eeeeee; border: solid thin #FFFFFF; padding: 2pt;}--></style><title>Curtain</title></head>"); html += F("<body><form action='/curtain' method='post'><h3>Curtain</h3><table><tbody>"); html += F("<tr><th>ID</th><td><input required type='number' style='text-align:right' name='curtain_id' min='0' max='9999' value='"); html += conf.getProperty("curtain", "id"); html += F("'></tr><tr><th>Rewind Time</th><td><input required type='number' style='text-align:right' name='rewind_time' step='0.1' min='0' max='99.9' value='"); html += conf.getProperty("motor", "rewind_time"); html += F("'> sec</td></tr><tr><th>Closingup Time</th><td><input required type='number' style='text-align:right' name='closingup_time' step='0.1' min='0' max='99.9' value='"); html += conf.getProperty("motor", "closingup_time"); html += F("'> sec</td></tr><tr><th>Falling Time</th><td><input required type='number' style='text-align:right' name='falling_time' step='0.1' min='0' max='99.9' value='"); html += conf.getProperty("motor", "falling_time"); html += F("'> sec</td></tr><tr><th>Liftup Time</th><td><input required type='number' style='text-align:right' name='liftup_time' step='0.1' min='0' max='99.9' value='"); html += conf.getProperty("motor", "liftup_time"); html += F("'> sec</td</tr></tbody></table><h3>Installation Location</h3><table><tbody>"); html += F("<tr><th>longitude</th><td><input type='number' style='text-align:right' name='location_longitude' step='0.000001' min='-179.999999' max='179.999999' value='"); html += conf.getProperty("location", "longitude"); html += F("'> dec</td></tr><tr><th>latitude</th><td><input type='number' style='text-align:right' name='location_latitude' step='0.000001' min='-179.999999' max='179.999999' value='"); html += conf.getProperty("location", "latitude"); html += F("'> dec</td></tr></tbody></table><h3>Opening and Closing"); int sunrise = curtain.sunrise(); int sunset = curtain.sunset(); if ((sunrise >= 0) && (sunset >= 0)) { html += F(" (SunRise "); printTime(html, sunrise); html += F(", SunSet "); printTime(html, sunset); html += F(")"); } html += F("</h3><table><tbody>"); html += F("<tr><th></th><th>Opening Time</th><th>Closing Time</th></tr>"); html += F("<tr><th>Inner Curtain</th><td><input type='time' name='time_inner_opening' value='"); html += conf.getProperty("time", "inner_opening"); html += F("'> <input type='checkbox' name='sun_inner_opening' value='1'"); if (conf.getPropertyInt("sun", "inner_opening")) html += F(" checked"); html += F(">SunRise</td><td><input type='time' name='time_inner_closing' value='"); html += conf.getProperty("time", "inner_closing"); html += F("'> <input type='checkbox' name='sun_inner_closing' value='1'"); if (conf.getPropertyInt("sun", "inner_closing")) html += F(" checked"); html += F(">SunSet</td></tr><tr><th>Outer Curtain</th><td><input type='time' name='time_outer_opening' value='"); html += conf.getProperty("time", "outer_opening"); html += F("'> <input type='checkbox' name='sun_outer_opening' value='1'"); if (conf.getPropertyInt("sun", "outer_opening")) html += F(" checked"); html += F(">SunRise</td><td><input type='time' name='time_outer_closing' value='"); html += conf.getProperty("time", "outer_closing"); html += F("'> <input type='checkbox' name='sun_outer_closing' value='1'"); if (conf.getPropertyInt("sun", "outer_closing")) html += F(" checked"); html += F(">SunSet</td></tr><tr><th>Daytime</th><td><input type='time' name='time_daytime_start' value='"); html += conf.getProperty("time", "daytime_start"); html += F("'> <input type='checkbox' name='sun_daytime_start' value='1'"); if (conf.getPropertyInt("sun", "daytime_start")) html += F(" checked"); html += F(">SunRise</td><td><input type='time' name='time_daytime_end' value='"); html += conf.getProperty("time", "daytime_end"); html += F("'> <input type='checkbox' name='sun_daytime_end' value='1'"); if (conf.getPropertyInt("sun", "daytime_end")) html += F(" checked"); html += F(">SunSet</td></tr></tbody></table><h3>Light Sensor"); sunrise = curtain.light_sunrise(); sunset = curtain.light_sunset(); if (sunrise && sunset) { html += F(" (SunRise "); html += sunrise; html += F(", SunSet "); html += sunset; html += F(")"); } else if (sunrise) { html += F(" (SunRise "); html += sunrise; html += F(")"); } else if (sunset) { html += F(" (SunSet "); html += sunset; html += F(")"); } html += F("</h3><table><tbody><tr><th></th><th>Baudrate</th><th>Threshold (0-65536)</th><tr>"); html += F("<tr><th>Inner Sensor</th><td><select required name='inner_baudrate'>"); int baudrate = conf.getPropertyInt("light", "inner_baudrate"); addBPSOption(html, 115200, baudrate); addBPSOption(html, 57600, baudrate); addBPSOption(html, 38400, baudrate); addBPSOption(html, 19200, baudrate); addBPSOption(html, 14400, baudrate); addBPSOption(html, 9600, baudrate); html += F("</select> bps</td><td><input required type='number' style='text-align:right' name='inner_threshold' min='0' max='65536' value='"); html += conf.getProperty("light", "inner_threshold"); html += F("'> ("); html += curtain.light(true); html += F(")</td></tr><tr><th>Outer Sensor</th><td><select required name='outer_baudrate'>"); baudrate = conf.getPropertyInt("light", "outer_baudrate"); addBPSOption(html, 115200, baudrate); addBPSOption(html, 57600, baudrate); addBPSOption(html, 38400, baudrate); addBPSOption(html, 19200, baudrate); addBPSOption(html, 14400, baudrate); addBPSOption(html, 9600, baudrate); html += F("</select> bps</td><td><input required type='number' style='text-align:right' name='outer_threshold' min='0' max='65536' value='"); html += conf.getProperty("light", "outer_threshold"); html += F("'> ("); html += curtain.light(false); html += F(")</td></tr></tbody></table><h3>Motor</h3><table><tbody>"); html += F("<tr><th>Current Limit</th><td><input required type='number' style='text-align:right' name='current_limit' min='0' max='999' value='"); html += conf.getProperty("motor", "current_limit"); html += F("'> mA</td></tr>"); html += F("<tr><th>Time Limit</th><td><input required type='number' style='text-align:right' name='time_limit' min='0' max='999' value='"); html += conf.getProperty("motor", "time_limit"); html += F("'> sec ("); html += (max(curtain.progress(true), curtain.progress(false)) / 1000); html += F(")</td></tr>"); html += F("<tr><th>Installation Position</th><td>"); int position = conf.getPropertyInt("motor", "position"); html += F("<input type='radio' name='motor_position' value='0'"); if (position == 0) html += F("checked"); html += F(">left "); html += F("<input type='radio' name='motor_position' value='1'"); if (position != 0) html += F("checked"); html += F(">right</td></tr></tbody></table><p><input type='submit' name='apply' value='apply'></p></form></body></html>"); ESPWeb.send(ESPWNET_HTTP_STATUS_OK, F(ESPWNET_HTML_CONTENT_TYPE), html); } static int mqtt_curtain_id(const String& str, bool& inner) { int id = -1; if (str.startsWith(MQTT_INNER)) { id = str.substring(MQTT_INNER.length()).toInt(); inner = true; } else if (str.startsWith(MQTT_OUTER)) { id = str.substring(MQTT_OUTER.length()).toInt(); inner = false; } return id; } static void mqtt_state(bool inner) { String val; val += curtain_status[inner][0]; ESPWNet.publish((MQTT_STATE + (inner ? MQTT_INNER : MQTT_OUTER) + curtain.id()).c_str(), (uint8_t *)val.c_str(), val.length()); } static void mqtt_callback(char *topic, uint8_t *payload, size_t len) { String str = topic; bool inner; int id; // // curtain control // if (str.startsWith(MQTT_CONTROL)) { id = mqtt_curtain_id(str.substring(MQTT_CONTROL.length()), inner); if ((id == 0) || (id == curtain.id())) { str.clear(); str.concat((char *)payload, len); if (str.equalsIgnoreCase("UP" ) || str.equals("0" )) { curtain.opening(inner); ESPLog.printf("MQTT: Curtain Opening (%s)", inner ? "Inner" : "Outer"); ESPLog.add(LOG_INFO); } if (str.equalsIgnoreCase("DOWN") || str.equals("100")) { curtain.closing(inner); ESPLog.printf("MQTT: Curtain Closing (%s)", inner ? "Inner" : "Outer"); ESPLog.add(LOG_INFO); } if (str.equalsIgnoreCase("STOP") || str.equals("OFF")) { curtain.stop(); ESPLog.printf("MQTT: Curtain Stop"); ESPLog.add(LOG_INFO); } } } // // curtain query // else if (str.startsWith(MQTT_QUERY)) { id = mqtt_curtain_id(str.substring(MQTT_QUERY.length()), inner); if ((id == 0) || (id == curtain.id())) mqtt_state(inner); } } static void mqtt_notify(void) { static uint32_t t; if (millis() - t >= 1000) { t = millis(); for (size_t i = 0; i < sizeof(curtain_status) / sizeof(curtain_status[0]); ++i) { int status = curtain_status[i][0]; if (curtain_status[i][1] != status) { curtain_status[i][1] = status; mqtt_state(i); } } } } static void curtain_callback(bool inner, uint32_t percent) { curtain_status[inner][0] = 100 - percent; } static void restart_callback(void) { curtain.stop(true); } bool handle(void) { if (ESPWNet.handle()) { if (!connected) { connected = true; ESPLog.printf("WiFi: Connected (%ld ms)", millis()); ESPLog.add(LOG_INFO); } mqtt_notify(); } return connected; } void setup() { int timezone, daylight; // init serial Serial.begin(115200); // init espwnet ESPWeb.on("/curtain", [](){onCurtainPage();}); ESPWNet.addHtmlRootLink("/curtain", "Curtain"); ESPWNet.setRestartCallback(restart_callback); ESPWNet.setMQTTCallback(mqtt_callback); ESPWNet.subscribe((MQTT_CONTROL + '#').c_str()); ESPWNet.subscribe((MQTT_STATE + '#').c_str()); ESPWNet.begin(); ESPWNet.getTimeZone(&timezone, &daylight); // init curtain curtain.callback(curtain_callback); curtain.begin(timezone, daylight); // connect for (uint32_t t = millis(); (millis() - t < 30000) && !handle(); ) continue; } void loop() { if (!curtain.handle()) { if (handle()) { if (!connected) { connected = true; ESPLog.printf("WiFi: Connected (%ld ms)", millis()); ESPLog.add(LOG_INFO); } mqtt_notify(); } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 |
/* curtain_toso.h - Smart Curtain Library for TOSO Twin One Chain Copyright (c) 2023 Sasapea's Lab. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef __CURTAIN_TOSO_H #define __CURTAIN_TOSO_H #include <stdint.h> #include <stdbool.h> #include <stdlib.h> #include <time.h> #include "espconf.h" #include "suncalc.h" #include "timedata.h" #include "ledsensor.h" #include "Arduino.h" typedef void (*CURTAIN_STATE_CALLBACK)(bool inner, uint32_t percent); #define CURTAIN_CONFIGURE_FILE "/curtain.conf" #define CURTAIN_CLOSE_MODE 10 #define CURTAIN_INNER_LIGHT_BAUDRATE 38400 // 9600 - 115200 bps #define CURTAIN_INNER_LIGHT_THRESHOLD 5000 // 0 - 65536 #define CURTAIN_OUTER_LIGHT_BAUDRATE 115200 // 9600 - 115200 bps #define CURTAIN_OUTER_LIGHT_THRESHOLD 5000 // 0 - 65536 #define CURTAIN_MOTOR_POSITION 1 // 0=left, 1=right #define CURTAIN_MOTOR_CURRENT_LIMIT 500 // mA #define CURTAIN_MOTOR_CURRENT_NOLOAD 10 // mA #define CURTAIN_MOTOR_TIME_LIMIT 64 // sec #define CURTAIN_MOTOR_RUSH_CURRENT_TIME 300 // ms #define CURTAIN_REWIND_TIME "0.8" // sec #define CURTAIN_CLOSINGUP_TIME "4" // sec #define CURTAIN_FALLING_TIME "6" // sec #define CURTAIN_LIFTUP_TIME "6" // sec #define CURTAIN_LED_BLINK_INTERVAL 3000 // ms #define CURTAIN_LED_BLINK_ON_TIME 100 // ms #define CURTAIN_ODS_HYSTERESIS 10 // % #define CURTAIN_BTN_INTERVAL 20 // ms #define CURTAIN_BTN_LONG_TIME_PRESS 3000 // ms #define CURTAIN_BTN_OPEN_PERCENT 50 // % #define CURTAIN_ADC_INTERVAL 10 // ms #define CURTAIN_ADC_RESISTOR 0.20 // Ω #define CURTAIN_PWM_FREQUENCY 1000 // Hz #define CURTAIN_PWM_RISE_TIME CURTAIN_MOTOR_RUSH_CURRENT_TIME #define CURTAIN_PWM_START_DUTY 100 // % #define CURTAIN_PWM_CHANNEL 0 // PWM CHANNEL #define CURTAIN_PWM_BITS 8 // PWM RESOLUTION BITS enum { CURTAIN_MOTOR_STOP = 0, CURTAIN_MOTOR_FWD = 1, CURTAIN_MOTOR_REV = 2, CURTAIN_MOTOR_BRAKE = 3, }; template<uint8_t PWMPIN, uint8_t CCWPIN, uint8_t FWDPIN, uint8_t REVPIN, uint8_t ADCPIN> class Curtain_TOSO { private: typedef struct { uint32_t progress; TimeData opening; TimeData closing; } curtain_t; ESPConf _sys_config; int _crt_id; LEDSensorBase *_pds_inner; LEDSensorBase *_pds_outer; int _pds_inner_threshold; int _pds_outer_threshold; uint16_t _pds_sunrise; uint16_t _pds_sunset; uint32_t _pds_blink; int _pds_control; uint32_t _adc_start; uint32_t _adc_delay; uint32_t _adc_value; uint32_t _dcm_position; uint32_t _dcm_curr_limit; uint32_t _dcm_time_limit; uint32_t _dcm_rewind; uint32_t _dcm_closingup; uint32_t _dcm_falling; uint32_t _dcm_liftup; uint32_t _dcm_start; uint32_t _dcm_start2; uint32_t _dcm_status; uint32_t _dcm_control[4]; uint32_t _dcm_percent[4]; uint32_t _btn_start; uint32_t _btn_pushed; uint32_t _btn_status; curtain_t _crt_control[2]; curtain_t *_crt_current; uint32_t _crt_command; uint32_t _crt_percent; bool _crt_ready; TimeData _day_start; TimeData _day_end; bool _day_time; int _sch_minute; float _loc_longitude; float _loc_latitude; bool _loc_valid; SunCalc _sun_calc; int _sun_timezone; int _sun_daylight; int _sun_yday; int _sun_sunrise; int _sun_sunset; bool _sun_inner_opening; bool _sun_inner_closing; bool _sun_outer_opening; bool _sun_outer_closing; bool _sun_daytime_start; bool _sun_daytime_end; CURTAIN_STATE_CALLBACK _crt_callback; uint32_t mode(bool inner) { return (inner ? CURTAIN_MOTOR_REV : CURTAIN_MOTOR_FWD); } uint32_t reverse(uint32_t mode) { return mode ^ CURTAIN_MOTOR_BRAKE; } curtain_t& curtain(uint32_t mode) { return _crt_control[mode - 1]; } uint32_t motor_current(void) { if (millis() - _adc_start >= _adc_delay) { _adc_start = millis(); _adc_delay = CURTAIN_ADC_INTERVAL; _adc_value = (analogReadMilliVolts(ADCPIN) * 100) / (int)(CURTAIN_ADC_RESISTOR * 100); #ifdef CURTAIN_DEBUG _adc_delay = 100; Serial.printf("%d mA\r\n", _adc_value); #endif } return _adc_value; } void motor_output(void) { #if CURTAIN_PWM_START_DUTY < 100 uint32_t duty; #endif switch (_dcm_status) { case CURTAIN_MOTOR_FWD: case CURTAIN_MOTOR_REV: digitalWrite(CCWPIN, _dcm_status & (_dcm_position ? CURTAIN_MOTOR_FWD : CURTAIN_MOTOR_REV)); #if CURTAIN_PWM_START_DUTY < 100 duty = millis() - _dcm_start; if (duty >= CURTAIN_PWM_RISE_TIME) duty = 100; else duty = duty * (100 - CURTAIN_PWM_START_DUTY) / CURTAIN_PWM_RISE_TIME + CURTAIN_PWM_START_DUTY; ledcWrite(CURTAIN_PWM_CHANNEL, (1 << CURTAIN_PWM_BITS) * duty / 100); #else digitalWrite(PWMPIN, HIGH); #endif break; } } void control(uint32_t mode, bool stop = true) { if ((mode &= CURTAIN_MOTOR_BRAKE) != _dcm_status) { _dcm_status = mode; _dcm_start = millis(); switch (mode) { case CURTAIN_MOTOR_FWD: case CURTAIN_MOTOR_REV: // delay adc until motor stabilizes _adc_start = _dcm_start; _adc_delay = CURTAIN_MOTOR_RUSH_CURRENT_TIME; _adc_value = CURTAIN_MOTOR_CURRENT_NOLOAD; break; default: #if CURTAIN_PWM_START_DUTY < 100 ledcWrite(0, 0); #else digitalWrite(PWMPIN, LOW); #endif digitalWrite(CCWPIN, HIGH); if (stop) motor_command_clear(); break; } } } int after_time(int a, int b) { return a < b ? b : a; } int before_time(int a, int b) { return a > b ? a : b; } void time_handle(void) { time_t now = time(NULL); struct tm lt = *localtime(&now); int year = lt.tm_year + 1900; if ((year >= 2021) && (_sch_minute != lt.tm_min)) { _sch_minute = lt.tm_min; if ((_sun_yday != lt.tm_yday) && _loc_valid) { _sun_yday = lt.tm_yday; _sun_calc.calculate(_loc_longitude, _loc_latitude, lt.tm_yday, year, _sun_timezone, _sun_daylight); _sun_sunrise = _sun_calc.hour(SUNCALC_SUNRISE) * 60 + _sun_calc.minute(SUNCALC_SUNRISE); _sun_sunset = _sun_calc.hour(SUNCALC_SUNSET ) * 60 + _sun_calc.minute(SUNCALC_SUNSET ); } int hhmm = lt.tm_hour * 60 + lt.tm_min; // log light level if (_pds_outer) { if (hhmm == _sun_sunrise) _pds_sunrise = _pds_outer->handle(); if (hhmm == _sun_sunset) _pds_sunset = _pds_outer->handle(); } // int start = _day_start.getTime(); int end = _day_end.getTime(); if (_sun_daytime_start) start = after_time(start, _sun_sunrise); if (_sun_daytime_end) end = before_time(end, _sun_sunset); if (start < 0) start = 0; if (end < 0) end = 24 * 60; _day_time = (start <= hhmm) && (hhmm < end); for (size_t i = 0; i < sizeof(_crt_control) / sizeof(_crt_control[0]); ++i) { curtain_t& curtain = _crt_control[i]; int open = curtain.opening.getTime(); int close = curtain.closing.getTime(); if (i ? _sun_inner_opening : _sun_outer_opening) open = after_time(open, _sun_sunrise); if (i ? _sun_inner_closing : _sun_outer_closing) close = before_time(close, _sun_sunset); if (open == hhmm) { opening(i); ESPLog.printf("Time: Curtain Opening (%s)", i ? "Inner" : "Outer"); ESPLog.add(LOG_INFO); } else if ((close == hhmm) || (_dcm_liftup && ((start == hhmm) || (end == hhmm)))) { closing(i); ESPLog.printf("Time: Curtain Closing (%s)", i ? "Inner" : "Outer"); ESPLog.add(LOG_INFO); } } } } void light_handle(void) { // // led blink control // if (_pds_inner && CURTAIN_LED_BLINK_INTERVAL) { uint32_t t = millis() - _pds_blink; if (t >= CURTAIN_LED_BLINK_INTERVAL) { _pds_blink = millis(); _pds_inner->led(true); } else if (t >= CURTAIN_LED_BLINK_ON_TIME) { _pds_inner->led(false); } } // // curtain control by ambient light // if (_pds_inner && _pds_outer) { uint16_t inner_val = _pds_inner->handle(); uint16_t outer_val = _pds_outer->handle(); if (inner_val && outer_val) { int inner_hysterisis = _pds_inner_threshold * CURTAIN_ODS_HYSTERESIS / 100; int outer_hysterisis = _pds_outer_threshold * CURTAIN_ODS_HYSTERESIS / 100; // be quiet at night! if (!_crt_ready || !_day_time) _pds_control = 0; // [TODO] west day ? else if ((inner_val < outer_val) && (outer_val < 2000)) ; // dark inner and bright outer else if ((inner_val >= _pds_inner_threshold + inner_hysterisis) && (outer_val < _pds_outer_threshold)) { if (_pds_control != 1) { _pds_control = 1; opening(); ESPLog.printf("Light[%d, %d]: Curtain Opening (Inner)", inner_val, outer_val); ESPLog.add(LOG_INFO); } } // bright inner and dark outer else if ((inner_val < _pds_inner_threshold) && (outer_val >= _pds_outer_threshold + outer_hysterisis)) { if (_pds_control != 2) { _pds_control = 2; closing(); ESPLog.printf("Light[%d, %d]: Curtain Closing (Inner)", inner_val, outer_val); ESPLog.add(LOG_INFO); } } } } } void button_handle(void) { uint32_t now = millis(); if (now - _btn_start >= CURTAIN_BTN_INTERVAL) { _btn_start = now; uint32_t m = CURTAIN_MOTOR_STOP; if (digitalRead(FWDPIN) == 0) m |= CURTAIN_MOTOR_FWD; if (digitalRead(REVPIN) == 0) m |= CURTAIN_MOTOR_REV; if (!_crt_ready) /* ignore. */; else if (_btn_status == CURTAIN_MOTOR_BRAKE) { if (m == CURTAIN_MOTOR_STOP) { control(m); if (now - _btn_pushed >= CURTAIN_BTN_LONG_TIME_PRESS) { motor_command(CURTAIN_CLOSE_MODE + CURTAIN_MOTOR_FWD); motor_command(CURTAIN_CLOSE_MODE + CURTAIN_MOTOR_REV); } _btn_status = CURTAIN_MOTOR_STOP; } } else if (m == CURTAIN_MOTOR_BRAKE) { control(m); if (_btn_status != m) _btn_pushed = now; _btn_status = m; } else if (m != CURTAIN_MOTOR_STOP) { if (_btn_status != m) _btn_pushed = now; _btn_status = m; } else if (_btn_status != CURTAIN_MOTOR_STOP) { bool inner = (_btn_status == mode(true)); if (now - _btn_pushed < CURTAIN_BTN_LONG_TIME_PRESS) { opening(inner, CURTAIN_BTN_OPEN_PERCENT); ESPLog.printf("Button: Curtain Opening (%s)", inner ? "Inner" : "Outer"); ESPLog.add(LOG_INFO); } else { closing(inner); ESPLog.printf("Button: Curtain Closing (%s)", inner ? "Inner" : "Outer"); ESPLog.add(LOG_INFO); } _btn_status = CURTAIN_MOTOR_STOP; } } } void fireStateChangeEvent(uint32_t cmd) { if (_crt_callback) _crt_callback(cmd == mode(true), _crt_current->progress * 100 / _dcm_time_limit); } void motor_command(uint32_t cmd, uint32_t percent = 0) { if (_crt_command == cmd) { if (cmd < CURTAIN_CLOSE_MODE) { if ((percent += _crt_percent) > 100) percent = 100; } _crt_percent = percent; return; } for (size_t i = 0; i < sizeof(_dcm_control) / sizeof(_dcm_control[0]); ++i) { if (_dcm_control[i] == cmd) { if (cmd < CURTAIN_CLOSE_MODE) { if ((percent += _dcm_percent[i]) > 100) percent = 100; } _dcm_percent[i] = percent; break; } else if (_dcm_control[i] == CURTAIN_MOTOR_STOP) { if (cmd < CURTAIN_CLOSE_MODE) { if ((percent += ((curtain(cmd).progress * 100 / _dcm_time_limit) / CURTAIN_BTN_OPEN_PERCENT) * CURTAIN_BTN_OPEN_PERCENT) > 100) percent = 100; } _dcm_percent[i] = percent; _dcm_control[i] = cmd; break; } } } void motor_command_clear(void) { for (size_t i = 0; i < sizeof(_dcm_control) / sizeof(_dcm_control[0]); ++i) { _dcm_control[i] = CURTAIN_MOTOR_STOP; _dcm_percent[i] = 0; } } void motor_command_shift(void) { size_t i; for (i = 0; i < sizeof(_dcm_control) / sizeof(_dcm_control[0]) - 1; ++i) { _dcm_control[i] = _dcm_control[i + 1]; _dcm_percent[i] = _dcm_percent[i + 1]; } _dcm_control[i] = CURTAIN_MOTOR_STOP; _dcm_percent[i] = 0; } bool motor_stopping(uint32_t ms) { uint32_t current = motor_current(); switch (_dcm_status) { case CURTAIN_MOTOR_FWD: case CURTAIN_MOTOR_REV: if ((current < CURTAIN_MOTOR_CURRENT_NOLOAD) || (current >= _dcm_curr_limit)) return true; break; } return millis() - _dcm_start >= ms; } bool motor_handle(void) { uint32_t t; switch (_dcm_control[0]) { // // stop // default: control(CURTAIN_MOTOR_STOP); _crt_command = CURTAIN_MOTOR_STOP; _crt_percent = 0; _crt_ready = true; break; // // opening the curtain // case CURTAIN_MOTOR_FWD: case CURTAIN_MOTOR_REV: _crt_command = _dcm_control[0]; _crt_percent = _dcm_percent[0]; _crt_current = &curtain(_crt_command); if (_crt_current->progress * 10 >= _dcm_time_limit * 9) motor_command_shift(); else { control(reverse(_crt_command)); _dcm_control[0] = CURTAIN_MOTOR_REV + 1; } break; case CURTAIN_MOTOR_REV + 1: if (motor_stopping(_dcm_rewind >> 1)) { control(CURTAIN_MOTOR_STOP, false); ++_dcm_control[0]; } break; case CURTAIN_MOTOR_REV + 2: if (motor_stopping(CURTAIN_MOTOR_RUSH_CURRENT_TIME)) { control(_crt_command); ++_dcm_control[0]; _dcm_start2 = _dcm_start; } break; case CURTAIN_MOTOR_REV + 3: t = millis() - _dcm_start2; if (t) { _dcm_start2 += t; _crt_current->progress += t; fireStateChangeEvent(_crt_command); } if (motor_stopping(_dcm_time_limit) || (_crt_current->progress * 100 / _dcm_time_limit >= _crt_percent)) { control(CURTAIN_MOTOR_STOP, false); // _crt_current->progress = _dcm_time_limit * 100 / _crt_percent; ++_dcm_control[0]; } break; case CURTAIN_MOTOR_REV + 4: if (motor_stopping(CURTAIN_MOTOR_RUSH_CURRENT_TIME)) { control(reverse(_crt_command)); ++_dcm_control[0]; } break; case CURTAIN_MOTOR_REV + 5: if (motor_stopping(_dcm_rewind)) { control(CURTAIN_MOTOR_STOP, false); ++_dcm_control[0]; } break; case CURTAIN_MOTOR_REV + 6: if (motor_stopping(CURTAIN_MOTOR_RUSH_CURRENT_TIME)) motor_command_shift(); break; // // closing the curtain // case CURTAIN_CLOSE_MODE + CURTAIN_MOTOR_FWD: case CURTAIN_CLOSE_MODE + CURTAIN_MOTOR_REV: _crt_command = _dcm_control[0]; _crt_percent = _dcm_percent[0]; _crt_current = &curtain(_crt_command - CURTAIN_CLOSE_MODE); #if 0 if (_crt_current->progress == 0) motor_command_shift(); else #endif { control(reverse(_crt_command - CURTAIN_CLOSE_MODE)); _dcm_control[0] = CURTAIN_CLOSE_MODE + CURTAIN_MOTOR_REV + 1; } break; case CURTAIN_CLOSE_MODE + CURTAIN_MOTOR_REV + 1: if (motor_stopping(_dcm_rewind >> 1)) { control(CURTAIN_MOTOR_STOP, false); ++_dcm_control[0]; } break; case CURTAIN_CLOSE_MODE + CURTAIN_MOTOR_REV + 2: if (motor_stopping(CURTAIN_MOTOR_RUSH_CURRENT_TIME)) { control(_crt_command - CURTAIN_CLOSE_MODE); ++_dcm_control[0]; } break; case CURTAIN_CLOSE_MODE + CURTAIN_MOTOR_REV + 3: if (motor_stopping(_dcm_closingup)) { control(CURTAIN_MOTOR_STOP, false); ++_dcm_control[0]; } break; case CURTAIN_CLOSE_MODE + CURTAIN_MOTOR_REV + 4: if (motor_stopping(CURTAIN_MOTOR_RUSH_CURRENT_TIME)) { control(reverse(_crt_command - CURTAIN_CLOSE_MODE)); ++_dcm_control[0]; } break; case CURTAIN_CLOSE_MODE + CURTAIN_MOTOR_REV + 5: if (motor_stopping(_dcm_rewind)) { control(CURTAIN_MOTOR_STOP, false); ++_dcm_control[0]; } break; case CURTAIN_CLOSE_MODE + CURTAIN_MOTOR_REV + 6: if (motor_stopping(_dcm_falling + CURTAIN_MOTOR_RUSH_CURRENT_TIME)) { control(_crt_command - CURTAIN_CLOSE_MODE); ++_dcm_control[0]; } break; case CURTAIN_CLOSE_MODE + CURTAIN_MOTOR_REV + 7: if (motor_stopping(_dcm_rewind + (_dcm_rewind >> 1))) { control(CURTAIN_MOTOR_STOP, false); ++_dcm_control[0]; } break; case CURTAIN_CLOSE_MODE + CURTAIN_MOTOR_REV + 8: if (motor_stopping(CURTAIN_MOTOR_RUSH_CURRENT_TIME)) { control(reverse(_crt_command - CURTAIN_CLOSE_MODE)); ++_dcm_control[0]; } break; case CURTAIN_CLOSE_MODE + CURTAIN_MOTOR_REV + 9: if (motor_stopping(_dcm_rewind + (_dcm_rewind >> 1))) { control(CURTAIN_MOTOR_STOP, false); ++_dcm_control[0]; } break; case CURTAIN_CLOSE_MODE + CURTAIN_MOTOR_REV + 10: if (motor_stopping(_dcm_falling + CURTAIN_MOTOR_RUSH_CURRENT_TIME)) { _crt_current->progress = 0; fireStateChangeEvent(_crt_command - CURTAIN_CLOSE_MODE); if (_day_time && _dcm_liftup) { control(_crt_command - CURTAIN_CLOSE_MODE); ++_dcm_control[0]; _dcm_start2 = _dcm_start; } else motor_command_shift(); } break; case CURTAIN_CLOSE_MODE + CURTAIN_MOTOR_REV + 11: t = millis() - _dcm_start2; if (t) { _dcm_start2 += t; _crt_current->progress += t; fireStateChangeEvent(_crt_command - CURTAIN_CLOSE_MODE); } if (motor_stopping(_dcm_liftup)) { control(CURTAIN_MOTOR_STOP, false); ++_dcm_control[0]; } break; case CURTAIN_CLOSE_MODE + CURTAIN_MOTOR_REV + 12: if (motor_stopping(CURTAIN_MOTOR_RUSH_CURRENT_TIME)) { control(reverse(_crt_command - CURTAIN_CLOSE_MODE)); ++_dcm_control[0]; } break; case CURTAIN_CLOSE_MODE + CURTAIN_MOTOR_REV + 13: if (motor_stopping(_dcm_rewind)) { control(CURTAIN_MOTOR_STOP, false); ++_dcm_control[0]; } break; case CURTAIN_CLOSE_MODE + CURTAIN_MOTOR_REV + 14: if (motor_stopping(CURTAIN_MOTOR_RUSH_CURRENT_TIME)) motor_command_shift(); break; } motor_output(); return _crt_command != CURTAIN_MOTOR_STOP; } public: Curtain_TOSO(LEDSensorBase *inner = nullptr, LEDSensorBase *outer = nullptr) : _crt_id(0) , _pds_inner(inner) , _pds_outer(outer) , _pds_inner_threshold(0) , _pds_outer_threshold(0) , _pds_sunrise(0) , _pds_sunset(0) , _pds_blink(0) , _pds_control(0) , _adc_start(0) , _adc_delay(0) , _adc_value(0) , _dcm_position(0) , _dcm_curr_limit(0) , _dcm_time_limit(0) , _dcm_rewind(0) , _dcm_closingup(0) , _dcm_falling(0) , _dcm_liftup(0) , _dcm_start(0) , _dcm_start2(0) , _dcm_status(CURTAIN_MOTOR_STOP) , _btn_start(0) , _btn_status(0) , _crt_current(nullptr) , _crt_command(0) , _crt_ready(false) , _day_time(false) , _sch_minute(-1) , _loc_longitude(0) , _loc_latitude(0) , _loc_valid(false) , _sun_timezone(0) , _sun_daylight(0) , _sun_yday(-1) , _sun_sunrise(-1) , _sun_sunset(-1) , _sun_inner_opening(false) , _sun_inner_closing(false) , _sun_outer_opening(false) , _sun_outer_closing(false) , _sun_daytime_start(false) , _sun_daytime_end(false) , _crt_callback(nullptr) { motor_command_clear(); for (size_t i = 0; i < sizeof(_crt_control) / sizeof(_crt_control[0]); ++i) _crt_control[i].progress = 1; } virtual ~Curtain_TOSO(void) { } ESPConf& properties(void) { return _sys_config; } int id(void) { return _crt_id; } int sunrise(void) { return _sun_sunrise; } int sunset(void) { return _sun_sunset; } uint16_t light(bool inner) { LEDSensorBase *obj = inner ? _pds_inner : _pds_outer; return obj ? obj->handle() : 0; } uint16_t light_sunrise(void) { return _pds_sunrise; } uint16_t light_sunset(void) { return _pds_sunset; } void callback(CURTAIN_STATE_CALLBACK cb) { _crt_callback = cb; } void begin(int timezone = 0, int daylight = 0) { uint32_t inner_baudrate, outer_baudrate; // Button SW pinMode(FWDPIN, INPUT_PULLUP); pinMode(REVPIN, INPUT_PULLUP); // MOTOR pinMode(CCWPIN, OUTPUT); digitalWrite(CCWPIN, HIGH); pinMode(PWMPIN, OUTPUT); #if CURTAIN_PWM_START_DUTY < 100 // PWM ledcSetup(CURTAIN_PWM_CHANNEL, CURTAIN_PWM_FREQUENCY, CURTAIN_PWM_BITS); ledcAttachPin(PWMPIN, CURTAIN_PWM_CHANNEL); ledcWrite(CURTAIN_PWM_CHANNEL, 0); #else digitalWrite(PWMPIN, LOW); #endif // ADC pinMode(ADCPIN, ANALOG); analogSetAttenuation(ADC_0db); // _sun_timezone = timezone; _sun_daylight = daylight; // init properties _sys_config.setPropertyInt("curtain" , "id", 0); _sys_config.setPropertyInt("light" , "inner_threshold", CURTAIN_INNER_LIGHT_THRESHOLD); _sys_config.setPropertyInt("light" , "outer_threshold", CURTAIN_OUTER_LIGHT_THRESHOLD); _sys_config.setPropertyInt("light" , "inner_baudrate" , CURTAIN_INNER_LIGHT_BAUDRATE ); _sys_config.setPropertyInt("light" , "outer_baudrate" , CURTAIN_OUTER_LIGHT_BAUDRATE ); _sys_config.setPropertyInt("motor" , "position" , CURTAIN_MOTOR_POSITION ); _sys_config.setPropertyInt("motor" , "current_limit" , CURTAIN_MOTOR_CURRENT_LIMIT ); _sys_config.setPropertyInt("motor" , "time_limit" , CURTAIN_MOTOR_TIME_LIMIT ); _sys_config.setProperty ("motor" , "rewind_time" , CURTAIN_REWIND_TIME ); _sys_config.setProperty ("motor" , "closingup_time" , CURTAIN_CLOSINGUP_TIME ); _sys_config.setProperty ("motor" , "falling_time" , CURTAIN_FALLING_TIME ); _sys_config.setProperty ("motor" , "liftup_time" , CURTAIN_LIFTUP_TIME ); _sys_config.setPropertyInt("sun" , "inner_opening" , 0); _sys_config.setPropertyInt("sun" , "inner_closing" , 1); _sys_config.setPropertyInt("sun" , "outer_opening" , 0); _sys_config.setPropertyInt("sun" , "outer_closing" , 0); _sys_config.setPropertyInt("sun" , "daytime_start" , 1); _sys_config.setPropertyInt("sun" , "daytime_end" , 1); _sys_config.setProperty ("location", "longitude" , ""); _sys_config.setProperty ("location", "latitude" , ""); _sys_config.setProperty ("time" , "inner_opening" , ""); _sys_config.setProperty ("time" , "inner_closing" , ""); _sys_config.setProperty ("time" , "outer_opening" , ""); _sys_config.setProperty ("time" , "outer_closing" , ""); _sys_config.setProperty ("time" , "daytime_start" , ""); _sys_config.setProperty ("time" , "daytime_end" , ""); // load properties _sys_config.load(CURTAIN_CONFIGURE_FILE); // get properties _crt_id = _sys_config.getPropertyInt("curtain", "id", 0); _pds_inner_threshold = _sys_config.getPropertyInt("light" , "inner_threshold", CURTAIN_INNER_LIGHT_THRESHOLD); _pds_outer_threshold = _sys_config.getPropertyInt("light" , "outer_threshold", CURTAIN_OUTER_LIGHT_THRESHOLD); inner_baudrate = _sys_config.getPropertyInt("light" , "inner_baudrate" , CURTAIN_INNER_LIGHT_BAUDRATE ); outer_baudrate = _sys_config.getPropertyInt("light" , "outer_baudrate" , CURTAIN_OUTER_LIGHT_BAUDRATE ); _dcm_position = _sys_config.getPropertyInt("motor" , "position" , CURTAIN_MOTOR_POSITION ); _dcm_curr_limit = _sys_config.getPropertyInt("motor" , "current_limit" , CURTAIN_MOTOR_CURRENT_LIMIT ); _dcm_time_limit = _sys_config.getPropertyInt("motor" , "time_limit" , CURTAIN_MOTOR_TIME_LIMIT ) * 1000; _dcm_rewind = atof(_sys_config.getProperty("motor", "rewind_time" , CURTAIN_REWIND_TIME )) * 1000; _dcm_closingup = atof(_sys_config.getProperty("motor", "closingup_time" , CURTAIN_CLOSINGUP_TIME )) * 1000; _dcm_falling = atof(_sys_config.getProperty("motor", "falling_time" , CURTAIN_FALLING_TIME )) * 1000; _dcm_liftup = atof(_sys_config.getProperty("motor", "liftup_time" , CURTAIN_LIFTUP_TIME )) * 1000; _sun_inner_opening = _sys_config.getPropertyInt("sun" , "inner_opening" , 0) != 0; _sun_inner_closing = _sys_config.getPropertyInt("sun" , "inner_closing" , 1) != 0; _sun_outer_opening = _sys_config.getPropertyInt("sun" , "outer_opening" , 0) != 0; _sun_outer_closing = _sys_config.getPropertyInt("sun" , "outer_closing" , 0) != 0; _sun_daytime_start = _sys_config.getPropertyInt("sun" , "daytime_start" , 1) != 0; _sun_daytime_end = _sys_config.getPropertyInt("sun" , "daytime_end" , 1) != 0; String longitude = _sys_config.getProperty("location" , "longitude"); String latitude = _sys_config.getProperty("location" , "latitude" ); _loc_valid = longitude.length() && latitude.length(); _loc_longitude = atof(longitude.c_str()); _loc_latitude = atof(latitude.c_str()); curtain_t& inner = curtain(mode(true )); curtain_t& outer = curtain(mode(false)); inner.opening.setTime(_sys_config.getProperty("time", "inner_opening")); inner.closing.setTime(_sys_config.getProperty("time", "inner_closing")); outer.opening.setTime(_sys_config.getProperty("time", "outer_opening")); outer.closing.setTime(_sys_config.getProperty("time", "outer_closing")); _day_start .setTime(_sys_config.getProperty("time", "daytime_start")); _day_end .setTime(_sys_config.getProperty("time", "daytime_end" )); if (_pds_inner) _pds_inner->begin(inner_baudrate); if (_pds_outer) _pds_outer->begin(outer_baudrate); motor_command_clear(); motor_command(CURTAIN_CLOSE_MODE + CURTAIN_MOTOR_FWD); motor_command(CURTAIN_CLOSE_MODE + CURTAIN_MOTOR_REV); _crt_ready = false; } void stop(bool force = false) { if (_crt_ready || force) control(CURTAIN_MOTOR_STOP); } void opening(bool inner = true, uint32_t percent = 100) { if (_crt_ready) motor_command(mode(inner), percent); } void closing(bool inner = true) { if (_crt_ready) motor_command(mode(inner) + CURTAIN_CLOSE_MODE); } uint32_t progress(bool inner = true) { return _crt_control[inner].progress; } bool handle(void) { time_handle(); light_handle(); button_handle(); return motor_handle(); } }; #endif |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 |
/* ledsensor.h - Optical Detect Sensor Library for ATtiny10 LED Sensor Copyright (c) 2023 Sasapea's Lab. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef __LEDSENSOR_H #define __LEDSENSOR_H #include <stdlib.h> #include <stdint.h> #define LEDSENSOR_LPF 5 // % #define LEDSENSOR_BLINK_INTERVAL 3000 // ms #define LEDSENSOR_BLINK_ON_TIME 100 // ms class LEDSensorBase { private: uint32_t _start; uint16_t _result; uint8_t _filter; uint8_t _count; char _buffer[8]; uint8_t _id; int8_t _rxpin; uint8_t _ledctl; protected: void filter(uint8_t lpf = LEDSENSOR_LPF) { _filter = lpf; } public: LEDSensorBase(uint8_t id = 0, int8_t rxpin = -1) : _start(0) , _result(0) , _filter(LEDSENSOR_LPF) , _count(0) , _id(id) , _rxpin(rxpin) , _ledctl(0) { if (_rxpin >= 0) digitalWrite(_rxpin, LOW); } virtual ~LEDSensorBase(void) { } uint8_t id(void) { return _id; } virtual void begin(uint32_t baudrate, uint8_t lpf = LEDSENSOR_LPF) = 0; virtual int read(void) = 0; uint16_t handle(void) { for (int c; (c = read()) >= 0; ) { if ((_ledctl == 2) || (c == 0)) _count = 0; else if (c == '\n') { char *endptr; _buffer[_count] = 0; _count = 0; uint32_t val = strtoul(_buffer, &endptr, 16); if ((endptr == _buffer + 4) && (*endptr == '\r')) { // low pass filter _result += (int32_t)(val - _result) * _filter / 100; #ifdef LEDSENSOR_DEBUG Serial.printf("light[%d] = %d\r\n", _id, _result); } else { Serial.printf("light[%d] = error.\r\n", _id); #endif } } else if (_count < sizeof(_buffer)) _buffer[_count++] = c; } if ((_rxpin >= 0) && (_ledctl == 1) && (_count == 0)) { _ledctl = 2; pinMode(_rxpin, OUTPUT); } return _result; } virtual void led(bool on) { if (_rxpin >= 0) { if (on) { if (_ledctl == 0) _ledctl = 1; } else if (_ledctl) { if (_ledctl == 2) pinMode(_rxpin, INPUT); _ledctl = 0; } } } }; template<typename UART_T, UART_T& UART, uint8_t ID, int8_t RXPIN = -1> class LEDSensor : public LEDSensorBase { public: LEDSensor(void) : LEDSensorBase(ID, RXPIN) { } virtual ~LEDSensor(void) { } void begin(unsigned long baud, uint8_t lpf = LEDSENSOR_LPF) override { UART.begin(baud, SERIAL_8N1, RXPIN); filter(lpf); } int read(void) override { return UART.read(); } }; #endif |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 |
/* suncalc.h - SunRise and SunSet Time Calculation Library Caution: This is Approximate formula. There will be a few minutes of error. Copyright (c) 2023 Sasapea's Lab. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef __SUNCALC_H #define __SUNCALC_H #include <math.h> #define SUNCALC_PI 3.14159265358979323846 // πの値 #define SUNCALC_DEG(a) ((a) * 180 / SUNCALC_PI) // ラジアンを度に変換するマクロ #define SUNCALC_RAD(a) ((a) * SUNCALC_PI / 180) // 度をラジアンに変換するマクロ typedef enum { SUNCALC_SUNRISE = 0, SUNCALC_SUNSET = 1, } SUNCALC_TYPE; class SunCalc { private: int _year; int _yday; int _hour[2]; int _min[2]; int _sec[2]; protected: /* orignal url: http://radiopench.blog96.fc2.com/blog-entry-735.html Arduinoで日の出・日の入り時刻を計算 近似式を使って日の出・日の入り時刻を求める。 by ラジオペンチ, 2017/5/10, http://radiopench.blog96.fc2.com/ 参考サイト http://k-ichikawa.blog.enjoy.jp/etc/HP/js/sunRise/srs.html http://www.iot-kyoto.com/satoh/2016/01/22/post-99/ */ static float SunRise(float x, float y, int n, int m) // 日の出時刻を求める関数 { float d, e, t; y = SUNCALC_RAD(y); // 緯度をラジアンに変換 d = dCalc(n, m); // 太陽赤緯を求める e = eCalc(n, m); // 均時差を求める // 太陽の時角幅を求める (視半径、大気差などを補正 (-0.899度)) t = SUNCALC_DEG(acos((sin(SUNCALC_RAD(-0.899)) - sin(d) * sin(y)) / (cos(d) * cos(y)))); return (-t + 180 - x) / (360 / 24) - e; // 日の出時刻を返す } static float SunSet(float x, float y, int n, int m) // 日の入り時刻を求める関数 { float d, e, t; y = SUNCALC_RAD(y); // 緯度をラジアンに変換 d = dCalc(n, m); // 太陽赤緯を求める e = eCalc(n, m); // 均時差を求める // 太陽の時角幅を求める (視半径、大気差などを補正 (-0.899度)) t = SUNCALC_DEG(acos((sin(SUNCALC_RAD(-0.899)) - sin(d) * sin(y)) / (cos(d) * cos(y)))); return (t + 180 - x) / (360 / 24) - e; // 日の入り時刻を返す } static float dCalc(int n, int m) // 近似式で太陽赤緯を求める { float d, w; w = (n + 0.5) * 2 * SUNCALC_PI / m; // 日付をラジアンに変換 d = + 0.33281 - 22.984 * cos(w) - 0.34990 * cos(2 * w) - 0.13980 * cos(3 * w) + 3.7872 * sin(w) + 0.03250 * sin(2 * w) + 0.07187 * sin(3 * w); return SUNCALC_RAD(d); // 赤緯を返す(単位はラジアン) } static float eCalc(int n, int m) // 近似式で均時差を求める { float e, w; w = (n + 0.5) * 2 * SUNCALC_PI / m; // 日付をラジアンに換算 e = + 0.0072 * cos(w) - 0.0528 * cos(2 * w) - 0.0012 * cos(3 * w) - 0.1229 * sin(w) - 0.1565 * sin(2 * w) - 0.0041 * sin(3 * w); return e; // 均一時差を返す(単位は時) } /****************************************************************************************/ public: SunCalc(void) : _year(-1) , _yday(-1) { _hour[0] = _min[0] = _sec[0] = -1; _hour[1] = _min[1] = _sec[1] = -1; } virtual ~SunCalc(void) { } void calculate(float longitude, float latitude, int yday, int year, int timezone = 0, int daylight = 0) { if ((_yday != yday) || (_year != year)) { _yday = yday; _year = year; year = (!(year % 4) && (year % 100)) || !(year % 400) ? 366 : 365; int32_t t = SunRise(longitude, latitude, yday, year) * 3600 + timezone + daylight; if (t < 0) t += 86400; _hour[SUNCALC_SUNRISE] = t / 3600 % 24; _min [SUNCALC_SUNRISE] = t / 60 % 60; _sec [SUNCALC_SUNRISE] = t % 60; t = SunSet(longitude, latitude, yday, year) * 3600 + timezone + daylight; if (t < 0) t += 86400; _hour[SUNCALC_SUNSET ] = t / 3600 % 24; _min [SUNCALC_SUNSET ] = t / 60 % 60; _sec [SUNCALC_SUNSET ] = t % 60; } } int hour(SUNCALC_TYPE type) { return _hour[type]; } int minute(SUNCALC_TYPE type) { return _min[type]; } int second(SUNCALC_TYPE type) { return _sec[type]; } }; #endif |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 |
/* timedata.h - Time Data Library Copyright (c) 2023 Sasapea's Lab. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef __TIMEDATA_H #define __TIMEDATA_H #include <stdlib.h> #include <string> class TimeData { private: int _time; public: TimeData(int time = -1) : _time(time) { } virtual ~TimeData(void) { } bool isValid(void) { return _time >= 0; } void setTime(const char *time) { if (time) { std::string str = time; if ((str.length() == 5) && (str[2] == ':')) setTime(atoi(str.substr(0, 2).c_str()), atoi(str.substr(3).c_str())); else setTime(-1); } } void setTime(int hour, int min) { setTime((hour >= 0) && (min >= 0) ? hour * 60 + min : -1); } void setTime(int time) { _time = time; } int getTime(void) { return _time; } std::string& toString(std::string& str) { str.clear(); if (_time >= 0) { int h = _time / 60; int m = _time % 60; if (h < 10) str += '0'; str += h; str += ':'; if (m < 10) str += '0'; str += m; } return str; } }; #endif |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 |
/* espwnet.h - WiFi Network Library for ESP8266/ESP32 Copyright (c) 2023 Sasapea's Lab. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef _ESPWNET_H #define _ESPWNET_H #include <vector> #include <stdint.h> #include <stdbool.h> #include <time.h> #include "Arduino.h" #include "PubSubClient.h" #if defined(ESP32) #include "WebServer.h" #elif defined(ESP8266) #include "ESP8266WebServer.h" #define WebServer ESP8266WebServer #else #error "not supported enviroment." #endif #include "espconf.h" #include "logging.h" #define ESPWNET_HTTP_PORT 80 #define ESPWNET_HTTP_STATUS_OK 200 #define ESPWNET_HTML_CONTENT_TYPE "text/html; charset=utf-8" #define ESPWNET_TEXT_CONTENT_TYPE "text/plain; charset=utf-8" typedef void (*ESPWNET_MQTT_CALLBACK)(char*, uint8_t*, unsigned int); typedef void (*ESPWNET_RESTART_CALLBACK)(void); class ESPWNetClass { private: static const char *_NODE; static const char *_WIFI; static const char *_NTP; static const char *_MQTT; static const char *_LED; static const char *_VCC; ESPConf _config; time_t _sys_startup; uint32_t _sys_running; uint32_t _sys_millis; std::vector<String> _ntp_servers; int _ntp_timezone; int _ntp_daylightOffset; WiFiClient _wifi_client; PubSubClient _mqtt_client; String _mqtt_service; String _mqtt_hostname; IPAddress _mqtt_ipaddress; uint16_t _mqtt_port; std::vector<String> _mqtt_subscribes; unsigned long _mqtt_disconnected; uint8_t _builtin_led; int16_t _vcc_calibrate; String _node_name; String _host_name; std::vector<String> _root_links; int _setup_status; int _wifi_ssid_valid; ESPWNET_RESTART_CALLBACK _restart_cb; // void NTP_setup(); void OTA_setup(); void MQTT_setup(); bool MQTT_connect(); void MQTT_disconnect(); bool MQTT_handle(); bool setMQTTServer0(const char* host); void removeSubscribe(const char* topic); void WEB_setup(); void WEB_flush(); void onNotFoundPage(); void onRootPage(); void onSystemPage(); void onPropertiesPage(); void onLogPage(); String threeDigitFormat(String digit); String getContentType(String path); void fireRestartEvent(void); public: ESPWNetClass(); virtual ~ESPWNetClass(); uint32_t getChipId(); uint16_t getVcc(); void setVccCaribrate(int16_t val); String getHostName(); String getNodeName(); void setNodeName(const char* name); void addWiFiAP(const char* ssid, const char* pswd); void addNTPServer(const char* name); void setTimeZone(int timezone, int daylightOffset_sec); void getTimeZone(int *timezone,int *daylightOffset); void setMQTTServer(const char* host); void setMQTTCallback(ESPWNET_MQTT_CALLBACK cb); void setRestartCallback(ESPWNET_RESTART_CALLBACK cb); bool publish(const char* topic, const uint8_t* payload = nullptr, size_t length = 0, uint8_t qos = 1, bool retain = false); bool subscribe(const char* topic, uint8_t qos = 1); bool unsubscribe(const char* topic); void setBuiltinLED(uint8_t pin); void addHtmlRootLink(String uri, String name); void onRestartPage(const char* url = "/system"); void restart(void); void onFS(); void begin(bool wifi_ap = false); bool handle(); }; extern ESPWNetClass ESPWNet; extern WebServer ESPWeb; #endif |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 |
/* espwnet.h - WiFi Network Library for ESP8266/ESP32 Copyright (c) 2023 Sasapea's Lab. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef _ESPWNET_H #define _ESPWNET_H #include <vector> #include <stdint.h> #include <stdbool.h> #include <time.h> #include "Arduino.h" #include "PubSubClient.h" #if defined(ESP32) #include "WebServer.h" #elif defined(ESP8266) #include "ESP8266WebServer.h" #define WebServer ESP8266WebServer #else #error "not supported enviroment." #endif #include "espconf.h" #include "logging.h" #define ESPWNET_HTTP_PORT 80 #define ESPWNET_HTTP_STATUS_OK 200 #define ESPWNET_HTML_CONTENT_TYPE "text/html; charset=utf-8" #define ESPWNET_TEXT_CONTENT_TYPE "text/plain; charset=utf-8" typedef void (*ESPWNET_MQTT_CALLBACK)(char*, uint8_t*, unsigned int); typedef void (*ESPWNET_RESTART_CALLBACK)(void); class ESPWNetClass { private: static const char *_NODE; static const char *_WIFI; static const char *_NTP; static const char *_MQTT; static const char *_LED; static const char *_VCC; ESPConf _config; time_t _sys_startup; uint32_t _sys_running; uint32_t _sys_millis; std::vector<String> _ntp_servers; int _ntp_timezone; int _ntp_daylightOffset; WiFiClient _wifi_client; PubSubClient _mqtt_client; String _mqtt_service; String _mqtt_hostname; IPAddress _mqtt_ipaddress; uint16_t _mqtt_port; std::vector<String> _mqtt_subscribes; unsigned long _mqtt_disconnected; uint8_t _builtin_led; int16_t _vcc_calibrate; String _node_name; String _host_name; std::vector<String> _root_links; int _setup_status; int _wifi_ssid_valid; ESPWNET_RESTART_CALLBACK _restart_cb; // void NTP_setup(); void OTA_setup(); void MQTT_setup(); bool MQTT_connect(); void MQTT_disconnect(); bool MQTT_handle(); bool setMQTTServer0(const char* host); void removeSubscribe(const char* topic); void WEB_setup(); void WEB_flush(); void onNotFoundPage(); void onRootPage(); void onSystemPage(); void onPropertiesPage(); void onLogPage(); String threeDigitFormat(String digit); String getContentType(String path); void fireRestartEvent(void); public: ESPWNetClass(); virtual ~ESPWNetClass(); uint32_t getChipId(); uint16_t getVcc(); void setVccCaribrate(int16_t val); String getHostName(); String getNodeName(); void setNodeName(const char* name); void addWiFiAP(const char* ssid, const char* pswd); void addNTPServer(const char* name); void setTimeZone(int timezone, int daylightOffset_sec); void getTimeZone(int *timezone,int *daylightOffset); void setMQTTServer(const char* host); void setMQTTCallback(ESPWNET_MQTT_CALLBACK cb); void setRestartCallback(ESPWNET_RESTART_CALLBACK cb); bool publish(const char* topic, const uint8_t* payload = nullptr, size_t length = 0, uint8_t qos = 1, bool retain = false); bool subscribe(const char* topic, uint8_t qos = 1); bool unsubscribe(const char* topic); void setBuiltinLED(uint8_t pin); void addHtmlRootLink(String uri, String name); void onRestartPage(const char* url = "/system"); void restart(void); void onFS(); void begin(bool wifi_ap = false); bool handle(); }; extern ESPWNetClass ESPWNet; extern WebServer ESPWeb; #endif |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 |
/* espwnet.cpp - WiFi Network Library for ESP8266/ESP32 Copyright (c) 2023 Sasapea's Lab. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <vector> #include <set> #include <string.h> #include <time.h> #include "ArduinoOTA.h" #include "ESP.h" #if defined(ESP32) #include "ESPmDNS.h" #include "SPIFFS.h" #define CHIP_NAME "esp32" #define FS_NAME "SPIFFS" #elif defined(ESP8266) #include "ESP8266mDNS.h" #include "LittleFS.h" #define CHIP_NAME "esp8266" #define FS_NAME "LittleFS" #define SPIFFS LittleFS #endif #include "espwmap.h" #include "espwnet.h" #define ESPWNET_DEBUG 0 #define ESPWNET_DELIMITER '\t' #define ESPWNET_HTTP_STATUS_NOT_FOUND 404 #define ESPWNET_HTTP_STATUS_INTERNAL_SERVER_ERROR 500 #define ESPWNET_MQTT_KEEPALIVE 10 // default keep-alive time of Mosquitto #define ESPWNET_CONFIG_FILE "/espwnet.conf" ESPWNetClass ESPWNet; WebServer ESPWeb(ESPWNET_HTTP_PORT); const char* ESPWNetClass::_NODE = "NODE"; const char* ESPWNetClass::_WIFI = "WiFi"; const char* ESPWNetClass::_NTP = "NTP"; const char* ESPWNetClass::_MQTT = "MQTT"; const char* ESPWNetClass::_LED = "BuiltinLED"; const char* ESPWNetClass::_VCC = "VCC"; ESPWNetClass::ESPWNetClass() : _sys_startup(0) , _sys_running(0) , _sys_millis(0) , _ntp_timezone(0) , _ntp_daylightOffset(0) , _mqtt_port(1883) // MQTT default port , _mqtt_disconnected(0) , _builtin_led(0xFF) , _vcc_calibrate(0) , _setup_status(0) , _wifi_ssid_valid(0) , _restart_cb(nullptr) { _mqtt_client.setClient(_wifi_client); _mqtt_client.setKeepAlive(ESPWNET_MQTT_KEEPALIVE); _mqtt_client.setSocketTimeout(ESPWNET_MQTT_KEEPALIVE); _mqtt_ipaddress = INADDR_NONE; } ESPWNetClass::~ESPWNetClass() { } uint32_t ESPWNetClass::getChipId() { #if defined(ESP32) uint32_t id = ESP.getEfuseMac() >> 24; return ((id & 0x00FF0000) >> 16) | ((id & 0x0000FF00) << 0) | ((id & 0x000000FF) << 16); #elif defined(ESP8266) return ESP.getChipId(); #endif } uint16_t ESPWNetClass::getVcc() { #if defined(ESP32) return 0xFFFF; #elif defined(ESP8266) uint16_t vcc = ESP.getVcc(); return vcc == 0xFFFF ? vcc : vcc + _vcc_calibrate; #endif } void ESPWNetClass::setVccCaribrate(int16_t val) { _config.setPropertyInt(_VCC, "caribrate", val); } String ESPWNetClass::getHostName() { if (_host_name.length() == 0) { char name[32]; #if defined(ESP32) String model = ESP.getChipModel(); model.replace("-", ""); model.toLowerCase(); snprintf(name, sizeof(name), "%s-%06x", model.c_str(), getChipId()); #elif defined(ESP8266) snprintf(name, sizeof(name), CHIP_NAME "-%06x", getChipId()); #endif _host_name = name; } return _host_name; } String ESPWNetClass::getNodeName() { return _node_name.length() ? _node_name + " (" + getHostName() + ")" : getHostName(); } void ESPWNetClass::setNodeName(const char* name) { _config.setProperty(_NODE, "name", name); } void ESPWNetClass::addWiFiAP(const char* ssid, const char* pswd) { for (int i = 1;; ++i) { char SSIDn[16], PSWDn[16]; snprintf(SSIDn, sizeof(SSIDn),"ssid%d", i); snprintf(PSWDn, sizeof(PSWDn),"pswd%d", i); if (*_config.getProperty(_WIFI, SSIDn) && *_config.getProperty(_WIFI, PSWDn)) continue; _config.setProperty(_WIFI, SSIDn, ssid); _config.setProperty(_WIFI, PSWDn, pswd); break; } } void ESPWNetClass::addNTPServer(const char* name) { for (int i = 1;; ++i) { char NTPn[16]; snprintf(NTPn, sizeof(NTPn),"ntp%d", i); if (*_config.getProperty(_NTP, NTPn)) continue; _config.setProperty(_NTP, NTPn, name); break; } } void ESPWNetClass::setTimeZone(int timezone,int daylightOffset) { _config.setPropertyInt(_NTP, "timezoneoffset", timezone); _config.setPropertyInt(_NTP, "daylightoffset", daylightOffset); } void ESPWNetClass::getTimeZone(int *timezone,int *daylightOffset) { if (timezone) *timezone = _ntp_timezone; if (daylightOffset) *daylightOffset = _ntp_daylightOffset; } void ESPWNetClass::NTP_setup() { if (_ntp_servers.size()) { configTime(_ntp_timezone, _ntp_daylightOffset, _ntp_servers.size() > 0 ? _ntp_servers[0].c_str() : NULL, _ntp_servers.size() > 1 ? _ntp_servers[1].c_str() : NULL, _ntp_servers.size() > 2 ? _ntp_servers[2].c_str() : NULL ); } } void ESPWNetClass::OTA_setup() { ArduinoOTA.setHostname(getHostName().c_str()); ArduinoOTA.onStart ( []() { ESPWNet.fireRestartEvent(); } ); ArduinoOTA.onProgress ( [](unsigned int progress, unsigned int total) { if (progress == 0) Serial.println(); Serial.printf("OTA Progress: %u\r", progress / (total / 100)); } ); ArduinoOTA.onError ( [](ota_error_t error) { Serial.printf("\r\nOTA Error = %d\r\n", error); } ); ArduinoOTA.begin(); } void ESPWNetClass::setMQTTServer(const char* host) { _config.setProperty(_MQTT, "server", host); } bool ESPWNetClass::setMQTTServer0(const char* host) { String addr = host; String port; int right; addr.trim(); _mqtt_port = 1883; _mqtt_ipaddress = INADDR_NONE; _mqtt_hostname = ""; _mqtt_service = ""; if (addr.startsWith(F("["))) { right = addr.indexOf(F("]"), 1); if (right < 0) return false; port = addr.substring(right + 1); addr = addr.substring(1, right); } else { right = addr.lastIndexOf(':'); if (right >= 0) { port = addr.substring(right); addr = addr.substring(0, right); } } addr.trim(); if (!addr.length()) return false; port.trim(); if (port.length()) { if (port[0] != ':') return false; port = port.substring(1); port.trim(); if (port.length()) { for (int i = 0; i < (int)port.length(); ++i) { if (!isDigit(port[i])) return false; } _mqtt_port = port.toInt(); } } IPAddress ip; if (ip.fromString(addr)) { _mqtt_ipaddress = ip; _mqtt_hostname = addr; } else { _mqtt_service = addr; } return true; } void ESPWNetClass::setMQTTCallback(ESPWNET_MQTT_CALLBACK cb) { _mqtt_client.setCallback(cb); } void ESPWNetClass::setRestartCallback(ESPWNET_RESTART_CALLBACK cb) { _restart_cb = cb; } bool ESPWNetClass::publish(const char* topic, const uint8_t* payload, size_t length, uint8_t qos, bool retain) { qos = qos; if (payload && (length == 0)) length = strlen((char*)payload); return _mqtt_client.publish(topic, payload, length, retain); } void ESPWNetClass::removeSubscribe(const char* topic) { for (int i = 0; i < (int)_mqtt_subscribes.size(); ++i) { String name = _mqtt_subscribes[i]; int pos = name.indexOf(ESPWNET_DELIMITER); if (pos >= 0) name.remove(pos); if (name == topic) { _mqtt_subscribes.erase(_mqtt_subscribes.begin() + i); break; } } } bool ESPWNetClass::subscribe(const char* topic, uint8_t qos) { removeSubscribe(topic); String s = topic; s += ESPWNET_DELIMITER; s += qos; _mqtt_subscribes.push_back(s); return _mqtt_client.connected() ? _mqtt_client.subscribe(topic, qos) : true; } bool ESPWNetClass::unsubscribe(const char* topic) { removeSubscribe(topic); return _mqtt_client.connected() ? _mqtt_client.unsubscribe(topic) : true; } bool ESPWNetClass::MQTT_connect() { static const char* local = ".local"; if (_mqtt_service.length()) { String name = _mqtt_service; bool mdns = false; if (name.endsWith(local)) { name.remove(name.length() - strlen(local)); mdns = true; } // query DNS if (!mdns && WiFi.hostByName(name.c_str(), _mqtt_ipaddress)) { _mqtt_hostname = name; } // query mDNS else { _mqtt_ipaddress = INADDR_NONE; int num = MDNS.queryService(F("mqtt"), F("tcp")); for (int i = 0; i < num; ++i) { if ((name == F("*")) || name.equalsIgnoreCase(MDNS.hostname(0))) { _mqtt_hostname = MDNS.hostname(i); _mqtt_ipaddress = MDNS.IP(i); _mqtt_port = MDNS.port(i); break; } } } } // // connection // if (INADDR_NONE == _mqtt_ipaddress) return false; _mqtt_client.setServer(_mqtt_ipaddress, _mqtt_port); if (_mqtt_client.connect(getHostName().c_str())) { _mqtt_disconnected = 0; // // subscribe's // for (auto topic : _mqtt_subscribes) { String qos = "0"; int pos = topic.indexOf(ESPWNET_DELIMITER); if (pos >= 0) { qos = topic.substring(pos + 1); topic.remove(pos); } _mqtt_client.subscribe(topic.c_str(), (uint8_t)qos.toInt()); } return true; } return false; } void ESPWNetClass::MQTT_disconnect() { _mqtt_client.disconnect(); } bool ESPWNetClass::MQTT_handle() { static unsigned long start; unsigned long now = millis(); if (!_mqtt_service.length() && (INADDR_NONE == _mqtt_ipaddress)) return true; if (_mqtt_client.loop()) return true; if (!_mqtt_disconnected) { _mqtt_disconnected = (now ? now : -1); start = now; } if (now - start >= 3000) { start = now; return MQTT_connect(); } return false; } void ESPWNetClass::fireRestartEvent(void) { if (_restart_cb) _restart_cb(); } void ESPWNetClass::restart(void) { fireRestartEvent(); ESP.restart(); } void ESPWNetClass::setBuiltinLED(uint8_t pin) { _config.setPropertyInt(_LED, "gpio", pin); } void ESPWNetClass::begin(bool wifi_ap) { // load configuration file _config.load(ESPWNET_CONFIG_FILE); _node_name = _config.getProperty(_NODE, "name"); ESPWMAP.clear(); if (!wifi_ap) { for (int i = 1;; ++i) { char SSIDn[16], PSWDn[16]; snprintf(SSIDn, sizeof(SSIDn),"ssid%d", i); snprintf(PSWDn, sizeof(PSWDn),"pswd%d", i); String ssid = _config.getProperty(_WIFI, SSIDn); String pswd = _config.getProperty(_WIFI, PSWDn); if ((ssid.length() == 0) || (pswd.length() == 0)) break; ESPWMAP.add(ssid, pswd); } } _wifi_ssid_valid = (ESPWMAP.size() ? _config.getPropertyInt(_WIFI, "valid") : 0); _ntp_servers.clear(); for (int i = 1;; ++i) { char NTPn[16]; snprintf(NTPn, sizeof(NTPn),"ntp%d", i); const char* value = _config.getProperty(_NTP, NTPn); if (*value == 0) break; _ntp_servers.push_back(value); } _ntp_timezone = _config.getPropertyInt(_NTP, "timezoneoffset"); _ntp_daylightOffset = _config.getPropertyInt(_NTP, "daylightoffset"); _builtin_led = _config.getPropertyInt(_LED, "gpio", 255); _vcc_calibrate = _config.getPropertyInt(_VCC, "caribrate"); setMQTTServer0(_config.getProperty(_MQTT, "server")); // ESPWMAP.begin(); if (_builtin_led != 0xFF) pinMode(_builtin_led, OUTPUT); } bool ESPWNetClass::handle() { // // Running time // if (millis() - _sys_millis >= 1000) { _sys_millis += 1000; ++_sys_running; } // // Start time // if (!_sys_startup) { time_t t = time(nullptr); if ((localtime(&t)->tm_year + 1900) >= 2021) _sys_startup = t - _sys_running; } // // WiFi Handle // if ((_wifi_ssid_valid == 0) && ESPWMAP.timeouted()) { if ((WiFi.getMode() & WIFI_AP) == 0) { static const IPAddress IPADDR(192, 168, 119, 1); static const IPAddress SUBNET(255, 255, 255, 0); static const String PSWD = IPADDR.toString(); WiFi.mode(WIFI_AP); WiFi.softAPConfig(IPADDR, IPADDR, SUBNET); WiFi.softAP(getHostName().c_str(), PSWD.c_str()); WEB_setup(); #if ESPWNET_DEBUG Serial.println(F("WiFi AP Start")); #endif } ESPWeb.handleClient(); } else if (ESPWMAP.handle() == WL_CONNECTED) { if (_wifi_ssid_valid == 0) { _config.setPropertyInt(_WIFI, "valid", _wifi_ssid_valid = 1); _config.save(ESPWNET_CONFIG_FILE); } if (_setup_status <= 1) { #if ESPWNET_DEBUG Serial.printf("WiFi Connected (%s, %d, %d)\r\n", WiFi.SSID().c_str(), WiFi.channel(), WiFi.RSSI()); #endif NTP_setup(); OTA_setup(); // with mDNS WEB_setup(); } ArduinoOTA.handle(); ESPWeb.handleClient(); _setup_status = MQTT_handle() ? 3 : 2; } else if (_setup_status > 1) { #if ESPWNET_DEBUG Serial.println(F("WiFi Disconnected")); #endif _setup_status = 1; MQTT_disconnect(); ESPWeb.stop(); #if defined(ESP32) ArduinoOTA.end(); // with mDNS #endif } // // Control Builtin LED // if (_builtin_led != 0xFF) { static uint32_t start; uint32_t now = millis(); if (now - start >= (WiFi.getMode() & WIFI_AP ? 500 : ((ESPWMAP.size() == 0) || (_setup_status == 3) ? 1000 : 100))) { start = now; digitalWrite(_builtin_led, !digitalRead(_builtin_led)); } } return (ESPWMAP.size() == 0) || (_setup_status == 3); } void ESPWNetClass::addHtmlRootLink(String uri, String title) { String link = uri; link += ESPWNET_DELIMITER; link += title; _root_links.push_back(link); } void ESPWNetClass::WEB_setup() { const char* headerKeys[] = {"Cookie", "Host"}; // "cookie" is not run!! ESPWeb.begin(); ESPWeb.collectHeaders(headerKeys, sizeof(headerKeys) / sizeof(headerKeys[0])); if (_setup_status == 0) { ESPWeb.on("/" , [](){ESPWNet.onRootPage();}); ESPWeb.on("/favicon.ico", [](){ESPWNet.onFS();}); ESPWeb.on("/restart" , [](){ESPWNet.onRestartPage("/system");}); ESPWeb.on("/system" , [](){ESPWNet.onSystemPage();}); ESPWeb.on("/properties" , [](){ESPWNet.onPropertiesPage();}); ESPWeb.on("/log" , [](){ESPWNet.onLogPage();}); ESPWeb.onNotFound([](){ESPWNet.onNotFoundPage();}); } MDNS.addService("http", "tcp", ESPWNET_HTTP_PORT); } void ESPWNetClass::WEB_flush() { ESPWeb.client().flush(); } String ESPWNetClass::getContentType(String path) { if (path.endsWith(F(".html" ))) return F("text/html"); else if (path.endsWith(F(".htm" ))) return F("text/html"); else if (path.endsWith(F(".css" ))) return F("text/css"); else if (path.endsWith(F(".txt" ))) return F("text/plain"); else if (path.endsWith(F(".js" ))) return F("application/javascript"); else if (path.endsWith(F(".png" ))) return F("image/png"); else if (path.endsWith(F(".gif" ))) return F("image/gif"); else if (path.endsWith(F(".jpg" ))) return F("image/jpeg"); else if (path.endsWith(F(".ico" ))) return F("image/x-icon"); else if (path.endsWith(F(".xml" ))) return F("text/xml"); else if (path.endsWith(F(".pdf" ))) return F("application/x-pdf"); else if (path.endsWith(F(".zip" ))) return F("application/x-zip"); else if (path.endsWith(F(".gz" ))) return F("application/x-gzip"); else if (path.endsWith(F(".conf" ))) return F("text/plain"); return F("application/octet-stream"); } String ESPWNetClass::threeDigitFormat(String digit) { for (int i = digit.length() - 3; i > 0; i -= 3) digit = digit.substring(0, i) + ',' + digit.substring(i); return digit; } void ESPWNetClass::onNotFoundPage() { ESPWeb.client().setNoDelay(true); String message = F("File Not Found\n\n"); message += F("URI: "); message += ESPWeb.uri(); message += F("\nMethod: "); message += (ESPWeb.method() == HTTP_GET) ? F("GET") : F("POST"); message += F("\nArguments: "); message += ESPWeb.args(); message += F("\n"); for (uint8_t i = 0; i < ESPWeb.args(); i++) { message += F(" "); message += ESPWeb.argName(i); message += F(": "); message += ESPWeb.arg(i); message += F("\n"); } ESPWeb.send(ESPWNET_HTTP_STATUS_NOT_FOUND, F(ESPWNET_TEXT_CONTENT_TYPE), message); WEB_flush(); } void ESPWNetClass::onFS() { ESPWeb.client().setNoDelay(true); if (SPIFFS.begin()) { String uri = ESPWeb.uri(); File f = SPIFFS.open(uri, "r"); if (f) { ESPWeb.streamFile(f, getContentType(uri)); f.close(); } else ESPWeb.send(ESPWNET_HTTP_STATUS_OK, F(ESPWNET_TEXT_CONTENT_TYPE), "File Not Found: " + uri); SPIFFS.end(); } else ESPWeb.send(ESPWNET_HTTP_STATUS_INTERNAL_SERVER_ERROR, F(ESPWNET_TEXT_CONTENT_TYPE), F(FS_NAME " Failed.")); WEB_flush(); } void ESPWNetClass::onRestartPage(const char* url) { String html; ESPWeb.client().setNoDelay(true); html = F("<html lang='en'><head>"); html += F("<meta http-equiv='content-type' content='"); html += F(ESPWNET_HTML_CONTENT_TYPE); html += F("'>"); html += F("<meta http-equiv='refresh' content='30; url="); html += url; html += F("'></head><body>"); html += F("System Restarted...Wait for 30 seconds."); html += F("</body></html>"); ESPWeb.send(ESPWNET_HTTP_STATUS_OK, F(ESPWNET_HTML_CONTENT_TYPE), html); WEB_flush(); fireRestartEvent(); for (uint32_t t = millis(); (millis() - t < 3000) && ESPWeb.client().connected(); ) ESPWeb.handleClient(); ESP.restart(); } void ESPWNetClass::onRootPage() { String html; char tmp[128]; ESPWeb.client().setNoDelay(true); html = F("<html lang='en'><head>"); html += F("<meta http-equiv='content-type' content='"); html += F(ESPWNET_HTML_CONTENT_TYPE); html += F("'>"); html += F("<meta http-equiv='content-style-type' content='text/css'>"); html += F("<style type='text/css'>"); html += F("<!--"); html += F("td{padding: 5pt}"); html += F("hr{border-top: solid thin #000000}"); html += F("-->"); html += F("</style>"); html += F("<title>"); html += getNodeName(); html += F("</title>"); html += F("</head><body>"); // // Root Link // html += F("<h2 style='text-align: center;'>"); html += getNodeName(); html += F("</h2>"); String top; for (auto uri : _root_links) { String title = ""; int pos = uri.indexOf(ESPWNET_DELIMITER); if (pos >= 0) { title = uri.substring(pos + 1); uri.remove(pos); } sprintf(tmp, "<a target='contents' href='%s'>%s", uri.c_str(), title.c_str()); html += tmp; html += F("<span style='margin-right: 1em;'></span>"); if (top.length() == 0) top = uri; } if (top.length() == 0) top = "/system"; html += F("<a target='contents' href='/system'>System</a>"); html += F("<span style='margin-right: 1em;'></span>"); html += F("<a target='contents' href='/properties'>Properties</a>"); html += F("<span style='margin-right: 1em;'></span>"); html += F("<a target='contents' href='/log'>Log</a>"); html += F("<hr>"); html += F("<iframe frameborder='0' width='100%' height='100%' name='contents' src='"); html += top; html += F("' title='contents'></iframe>"); html += F("</body></html>"); ESPWeb.send(ESPWNET_HTTP_STATUS_OK, F(ESPWNET_HTML_CONTENT_TYPE), html); WEB_flush(); } void ESPWNetClass::onSystemPage() { static const char* WDAYS[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; String html; time_t t; struct tm lt; char tmp[128]; ESPWeb.client().setNoDelay(true); html = F("<html lang='en'><head>"); html += F("<meta http-equiv='content-type' content='"); html += F(ESPWNET_HTML_CONTENT_TYPE); html += F("'>"); html += F("<meta http-equiv='content-style-type' content='text/css'>"); html += F("<style type='text/css'>"); html += F("<!--"); html += F("table{border-collapse: collapse}"); html += F("th{background-color: #cccccc; border: solid thin #FFFFFF; padding: 2pt; width: 10em; text-align: left;}"); html += F("td{background-color: #eeeeee; border: solid thin #FFFFFF; padding: 2pt;}"); html += F("-->"); html += F("</style>"); html += F("<title>System</title>"); html += F("</head><body>"); ESPWeb.setContentLength(CONTENT_LENGTH_UNKNOWN); ESPWeb.send(ESPWNET_HTTP_STATUS_OK, F(ESPWNET_HTML_CONTENT_TYPE), html); // // Time Info // html = F("<h3>Time Info</h3>"); html += F("<table summary='time info'><tbody>"); html += F("<tr><th>Current Time</th><td>"); time(&t); lt = *localtime(&t); snprintf(tmp, sizeof(tmp), "%04d-%02d-%02d(%s) %02d:%02d:%02d", lt.tm_year + 1900, lt.tm_mon + 1, lt.tm_mday, WDAYS[lt.tm_wday], lt.tm_hour, lt.tm_min, lt.tm_sec); html += tmp; html += F("</td></tr><tr><th>Startup Time</th><td>"); if (_sys_startup) { lt = *localtime(&_sys_startup); snprintf(tmp, sizeof(tmp), "%04d-%02d-%02d(%s) %02d:%02d:%02d", lt.tm_year + 1900, lt.tm_mon + 1, lt.tm_mday, WDAYS[lt.tm_wday], lt.tm_hour, lt.tm_min, lt.tm_sec); html += tmp; } html += F("</td></tr><tr><th>Running Time</th><td>"); snprintf(tmp, sizeof(tmp), "%d days, %02d:%02d:%02d", _sys_running / 86400, _sys_running / 3600 % 24, _sys_running / 60 % 60, _sys_running % 60); html += tmp; html += F("</td></tr></tbody></table>"); ESPWeb.sendContent(html); // // ESP Info // html = F("<h3>ESP Info</h3>"); html += F("<table summary='cpu info'><tbody>"); #if defined(ESP8266) html += F("<tr><th>CPU Vcc</th><td>"); uint16_t vcc = getVcc(); if (vcc != 0xFFFF) { html += vcc / 1000.0; html += 'V'; } else { html += F("ADC_MODE(ADC_VCC); // add to Sketch"); } html += F("</td></tr>"); #endif html += F("<tr><th>CPU Id</th><td>"); sprintf(tmp, "%06X</td></tr>", getChipId()); html += tmp; html += F("<tr><th>CPU Speed</th><td>"); html += ESP.getCpuFreqMHz(); html += F("MHz</td></tr>"); #if defined(ESP32) html += F("<tr><th>CPU Cores</th><td>"); html += ESP.getChipCores(); html += F("</td></tr>"); html += F("<tr><th>CPU Model</th><td>"); html += ESP.getChipModel(); html += F("</td></tr>"); html += F("<tr><th>CPU Revision</th><td>"); html += ESP.getChipRevision(); html += F("</td></tr>"); html += F("<tr><th>Flush Chip Speed</th><td>"); html += ESP.getFlashChipSpeed() / 1000000; html += F("MHz</td></tr>"); html += F("<tr><th>Flush Chip Mode</th><td>"); switch (ESP.getFlashChipMode()) { case FM_QIO : html += F("QIO" ); break; case FM_QOUT: html += F("QOUT" ); break; case FM_DIO : html += F("DIO" ); break; case FM_DOUT: html += F("DOUT" ); break; default : html += F("UNKNOWN"); } html += F("</td></tr>"); html += F("<tr><th>Flush Chip Size</th><td>"); html += threeDigitFormat(String(ESP.getFlashChipSize() >> 10)); html += F(" KByte</td></tr>"); #elif defined(ESP8266) html += F("<tr><th>Flush Chip Id</th><td>"); sprintf(tmp, "%06X</td></tr>", ESP.getFlashChipId()); html += tmp; html += F("<tr><th>Flush Chip Speed</th><td>"); html += ESP.getFlashChipSpeed() / 1000000; html += F("MHz</td></tr>"); html += F("<tr><th>Flush Chip Mode</th><td>"); switch (ESP.getFlashChipMode()) { case FM_QIO : html += F("QIO" ); break; case FM_QOUT: html += F("QOUT" ); break; case FM_DIO : html += F("DIO" ); break; case FM_DOUT: html += F("DOUT" ); break; default : html += F("UNKNOWN"); } html += F("</td></tr>"); html += F("<tr><th>Flush Chip Size</th><td>"); html += threeDigitFormat(String(ESP.getFlashChipSize() >> 10)); html += F("/"); html += threeDigitFormat(String(ESP.getFlashChipRealSize() >> 10)); html += F(" KByte</td></tr>"); #endif html += F("<tr><th>Sketch Free Space</th><td>"); html += threeDigitFormat(String(ESP.getFreeSketchSpace())); html += " Byte</td></tr>"; html += F("<tr><th>Sketch Size</th><td>"); html += threeDigitFormat(String(ESP.getSketchSize())); html += " Byte</td></tr>"; html += F("<tr><th>Sketch MD5</th><td>"); html += ESP.getSketchMD5(); html += F("</td></tr>"); #if defined(ESP32) html += F("<tr><th>PSRAM Size</th><td>"); html += threeDigitFormat(String(ESP.getPsramSize())); html += F(" Byte</td></tr>"); html += F("<tr><th>PSRAM Free Size</th><td>"); html += threeDigitFormat(String(ESP.getFreePsram())); html += F(" Byte</td></tr>"); html += F("<tr><th>PSRAM Min Free Size</th><td>"); html += threeDigitFormat(String(ESP.getMinFreePsram())); html += F(" Byte</td></tr>"); html += F("<tr><th>PSRAM Max Alloc Size</th><td>"); html += threeDigitFormat(String(ESP.getMaxAllocPsram())); html += F(" Byte</td></tr>"); html += F("<tr><th>Heap Size</th><td>"); html += threeDigitFormat(String(ESP.getHeapSize())); html += F(" Byte</td></tr>"); html += F("<tr><th>Heap Free Size</th><td>"); html += threeDigitFormat(String(ESP.getFreeHeap())); html += F(" Byte</td></tr>"); html += F("<tr><th>Haap Min Free Size</th><td>"); html += threeDigitFormat(String(ESP.getMinFreeHeap())); html += F(" Byte</td></tr>"); html += F("<tr><th>Haap Max Alloc Size</th><td>"); html += threeDigitFormat(String(ESP.getMaxAllocHeap())); html += F(" Byte</td></tr>"); #elif defined(ESP8266) html += F("<tr><th>Heap Free Size</th><td>"); html += threeDigitFormat(String(ESP.getFreeHeap())); html += " Byte</td></tr>"; #endif html += F("<tr><th>SDK Version</th><td>"); html += ESP.getSdkVersion(); html += F("</td></tr>"); #if defined(ESP8266) html += F("<tr><th>Boot Version</th><td>"); html += ESP.getBootVersion(); html += F("</td></tr>"); html += F("<tr><th>Boot Mode</th><td>"); html += ESP.getBootMode(); html += F("</td></tr>"); html += F("<tr><th>Reset Reason</th><td>"); html += ESP.getResetReason(); html += F("</td></tr>"); html += F("<tr><th>Reset Info</th><td>"); html += ESP.getResetInfo(); html += F("</td></tr>"); #endif html += F("</tbody></table>"); ESPWeb.sendContent(html); // // Network Info // html = F("<h3>Network Info</h3>"); html += F("<table summary='network info'><tbody>"); html += F("<tr><th>Mac Address</th><td>"); html += WiFi.macAddress(); html += F("</td></tr>"); html += F("<tr><th>WiFi Access Point</th><td>"); html += WiFi.SSID(); html += F(" ["); html += WiFi.RSSI(); html += F("]"); html += F("</td></tr>"); html += F("<tr><th>Subnet Mask</th><td>"); html += WiFi.subnetMask().toString(); html += F("</td></tr>"); html += F("<tr><th>Gateway IP</th><td>"); html += WiFi.gatewayIP().toString(); html += F("</td></tr>"); html += F("<tr><th>Local IP</th><td>"); html += WiFi.localIP().toString(); html += F("</td></tr>"); html += F("<tr><th>MQTT Server</th><td>"); if (_mqtt_hostname.length()) { sprintf(tmp, "%s (%s:%d)</td></tr>", _mqtt_hostname.c_str(), _mqtt_ipaddress.toString().c_str(), _mqtt_port); html += tmp; } html += F("</tbody></table>"); ESPWeb.sendContent(html); // // Soft AP Info // html = F(""); if (WiFi.getMode() & WIFI_AP) { html += F("<h3>Soft AP Info</h3>"); html += F("<table summary='soft ap info'><tbody>"); html += F("<tr><th>Mac Address</th><td>"); html += WiFi.softAPmacAddress(); html += F("</td></tr>"); html += F("<tr><th>Local IP</th><td>"); html += WiFi.softAPIP().toString(); html += F("</td></tr>"); html += F("<tr><th>Client Connection's</th><td>"); html += WiFi.softAPgetStationNum(); html += F("</td></tr>"); html += F("</tbody></table>"); } // // Maintenance // html += F("<h3>Maintenance</h3>"); html += F("<form action='/restart' method='get'>"); html += F("<input type='submit' name='restart' value='Restart'>"); html += F("</form>"); // html += F("</body></html>"); ESPWeb.sendContent(html); WEB_flush(); } static void htmlWiFiAP(String &html, const char* SSIDn, const char* ssid, const char* PSWDn, const char* pswd) { html += F("<tr><td><input type='text' name='"); html += SSIDn; html += F("' value='"); html += ssid; html += F("'></td><td><input type='password' name='"); html += PSWDn; html += F("' value='"); html += pswd; html += F("'></td></tr>"); } void ESPWNetClass::onPropertiesPage() { char SSIDn[16], PSWDn[16], NTPn[16]; String html; // // Save Properties and Restart // if (ESPWeb.arg(F("rescan")).equalsIgnoreCase("rescan")) onRestartPage("/properties"); else if (ESPWeb.arg(F("apply")).equalsIgnoreCase("apply")) { int i, j; std::string ssid_old; _config.removeProperty(_WIFI, "valid"); _config.toString(ssid_old, _WIFI); _config.clear(); for (i = j = 1;; ++i) { snprintf(SSIDn, sizeof(SSIDn), "ssid%d", i); snprintf(PSWDn, sizeof(PSWDn), "pswd%d", i); String ssid = ESPWeb.arg(SSIDn); String pswd = ESPWeb.arg(PSWDn); ssid.trim(); pswd.trim(); if ((ssid.length() == 0) && (pswd.length() == 0)) break; if (ssid.length() && pswd.length()) { snprintf(SSIDn, sizeof(SSIDn), "ssid%d", j ); snprintf(PSWDn, sizeof(PSWDn), "pswd%d", j++); _config.setProperty(_WIFI, SSIDn, ssid.c_str()); _config.setProperty(_WIFI, PSWDn, pswd.c_str()); } } std::string ssid_new; _config.toString(ssid_new, _WIFI); _config.setPropertyInt(_WIFI, "valid", ssid_old == ssid_new ? _wifi_ssid_valid : 0); for (i = j = 1; i <= 3; ++i) { snprintf(NTPn, sizeof(NTPn), "ntp%d", i); String ntp = ESPWeb.arg(NTPn); ntp.trim(); if (ntp.length()) { snprintf(NTPn, sizeof(NTPn), "ntp%d", j++); _config.setProperty(_NTP, NTPn, ntp.c_str()); } } _config.setProperty(_NTP , "timezoneoffset", ESPWeb.arg(F("timezoneoffset")).c_str()); _config.setProperty(_NTP , "daylightoffset", ESPWeb.arg(F("daylightoffset")).c_str()); _config.setProperty(_MQTT, "server" , ESPWeb.arg(F("mqttserver" )).c_str()); _config.setProperty(_LED , "gpio" , ESPWeb.arg(F("builtinled" )).c_str()); _config.setProperty(_NODE, "name" , ESPWeb.arg(F("nodename" )).c_str()); _config.setProperty(_VCC , "caribrate" , ESPWeb.arg(F("vcccaribrate" )).c_str()); _config.save(ESPWNET_CONFIG_FILE); onRestartPage("/properties"); } // // Edit Properties // ESPWeb.client().setNoDelay(true); html = F("<html lang='en'><head><meta http-equiv='content-type' content='" ESPWNET_HTML_CONTENT_TYPE "'>"); html += F("<meta http-equiv='content-style-type' content='text/css'><style type='text/css'>"); html += F("<!--table{border-collapse: collapse}th{background-color: #cccccc; border: solid thin #FFFFFF; padding: 2pt; "); html += F("width: 8em; text-align: left;}td{background-color: #eeeeee; border: solid thin #FFFFFF; padding: 2pt;}-->"); html += F("</style><title>Config</title></head>"); html += F("<body><form action='/properties' method='post'>"); html += F("<h3>Node</h3><table><tbody><tr><th>Name</th><td><input type='text' name='nodename' value='"); html += _config.getProperty(_NODE, "name"); html += F("'></td><tr></tbody></table>"); html += F("<h3>WiFi AP</h3><table><tbody><tr><th>SSID</th><th>PASSWORD</th></tr>"); std::set<String> ssids; for (int i = 1;; ++i) { snprintf(SSIDn, sizeof(SSIDn), "ssid%d", i); snprintf(PSWDn, sizeof(PSWDn), "pswd%d", i); String ssid = _config.getProperty(_WIFI, SSIDn); String pswd = _config.getProperty(_WIFI, PSWDn); if (ssid.length() && pswd.length()) { htmlWiFiAP(html, SSIDn, ssid.c_str(), PSWDn, pswd.c_str()); ssids.insert(ssid.c_str()); } else { std::vector<String> names; ESPWMAP.ssid(names); for (auto name = names.begin(); name != names.end(); ++name) { if (ssids.count(*name) == 0) { snprintf(SSIDn, sizeof(SSIDn), "ssid%d", i ); snprintf(PSWDn, sizeof(PSWDn), "pswd%d", i++); htmlWiFiAP(html, SSIDn, name->c_str(), PSWDn, ""); } } for (int j = i + 3; i < j; ++i) { snprintf(SSIDn, sizeof(SSIDn), "ssid%d", i); snprintf(PSWDn, sizeof(PSWDn), "pswd%d", i); htmlWiFiAP(html, SSIDn, "", PSWDn, ""); } break; } } html += F("</tbody></table><h3>NTP</h3><table><tbody>"); for (int i = 1; i <= 3; ++i) { snprintf(NTPn, sizeof(NTPn), "ntp%d", i); html += F("<tr><th>Server "); html += i; html += F("</th><td><input type='text' name='"); html += NTPn; html += F("' value='"); html += _config.getProperty(_NTP, NTPn); html += F("'></td></tr>"); } html += F("<tr><th>TimeZoneOffset</th><td><input type='number' style='text-align:right' name='timezoneoffset' min='-43199' max='43199' value='"); html += _config.getProperty(_NTP, "timezoneoffset"); html += F("'> sec</td></tr>"); html += F("<tr><th>DaylightOffset</th><td><input type='number' style='text-align:right' name='daylightoffset' min='-43199' max='43199' value='"); html += _config.getProperty(_NTP, "daylightoffset"); html += F("'> sec</td></tr></tbody></table>"); html += F("<h3>MQTT (IP/DNS/mDNS)</h3><table><tbody>"); html += F("<tr><th>Server</th><td><input type='text' name='mqttserver' value='"); html += _config.getProperty(_MQTT, "server"); html += F("'></td></tr></tbody></table>"); html += F("<h3>Builtin LED</h3><table><tbody>"); html += F("<tr><th>GPIO</th><td><input type='number' style='text-align:right' name='builtinled' min='0' max='99' value='"); html += _config.getProperty(_LED, "gpio"); html += F("'></td></tr></tbody></table>"); if (getVcc() != 0xFFFF) { html += F("<h3>Caribrate</h3><table><tbody>"); html += F("<tr><th>CPU VCC</th><td><input type='number' style='text-align:right' name='vcccaribrate' min='-999' max='999' value='"); html += _config.getProperty(_VCC, "caribrate"); html += F("'> mV</td></tr></tbody></table>"); } html += F("<p><input type='submit' name='apply' value='apply' >"); html += F("<span style='margin-right: 1em;'></span>"); html += F("<input type='submit' name='rescan' value='rescan'></p>"); html += F("</form></body></html>"); ESPWeb.send(ESPWNET_HTTP_STATUS_OK, F(ESPWNET_HTML_CONTENT_TYPE), html); WEB_flush(); } void ESPWNetClass::onLogPage() { String html; ESPWeb.client().setNoDelay(true); html = F("<html lang='en'><head><meta http-equiv='content-type' content='" ESPWNET_HTML_CONTENT_TYPE "'>"); html += F("<meta http-equiv='content-style-type' content='text/css'><style type='text/css'>"); html += F("<!--table{border-collapse: collapse;}th{background-color: #cccccc; border: solid thin #FFFFFF; padding: 2pt; "); html += F("text-align: left;}td{background-color: #eeeeee; border: solid thin #FFFFFF; padding: 2pt;}-->"); html += F("</style><title>Config</title></head><body><table><tbody>"); html += F("<tr><th>TimeStamp</th><th>Level</th><th>Details</th></tr>"); for (bool start = true; ESPLog.next(start); start = false) { html += F("<tr><td><pre>"); html += ESPLog.TIME(); html += F("</pre></td><td><pre>"); html += ESPLog.LEVEL(); html += F("</pre></td><td><pre>"); html += ESPLog.TEXT(); html += F("</pre></td></tr>"); } html += F("</tbody></table></body></html>"); ESPWeb.send(ESPWNET_HTTP_STATUS_OK, F(ESPWNET_HTML_CONTENT_TYPE), html); WEB_flush(); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 |
/* espmwap.h - WiFi Multi AP Library for ESP8266/ESP32 Copyright (c) 2023 Sasapea's Lab. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef __ESPWMAP_H #define __ESPWMAP_H #include <vector> #if defined(ESP32) #include "WiFi.h" #elif defined(ESP8266) #include "ESP8266WiFi.h" #define WiFiScanClass ESP8266WiFiScanClass #else #error "not supported enviroment." #endif #define ESPWMAP_DEBUG 0 #define ESPWMAP_CONNECTION_TIMEOUT (3 * 60 * 1000) // ms class ESPWMAPClass : private WiFiScanClass { private: typedef struct { String ssid; String pswd; int32_t rssi; } ap_info_t; std::vector<ap_info_t> _aplist; std::vector<ap_info_t> _apscan; std::vector<ap_info_t*> _apnext; unsigned long _disconnect; bool _connecting; void complete(int scanCount) { _apscan.clear(); for (size_t i = 0; i < (size_t)scanCount; ++i) { auto scan = _apscan.begin(); for (; scan != _apscan.end(); ++scan) { if (scan->ssid.equalsIgnoreCase(SSID(i))) { if (scan->rssi < RSSI(i)) scan->rssi = RSSI(i); break; } } if (scan == _apscan.end()) { ap_info_t ap = {SSID(i).c_str(), "", RSSI(i)}; _apscan.push_back(ap); } } std::sort(_apscan.begin(), _apscan.end(), [](ap_info_t a, ap_info_t b) { return a.rssi > b.rssi; } ); scanDelete(); _apnext.clear(); for (auto scan = _apscan.begin(); scan != _apscan.end(); ++scan) { for (auto list = _aplist.begin(); list != _aplist.end(); ++list) { if (list->ssid.equalsIgnoreCase(scan->ssid)) { list->rssi = scan->rssi; _apnext.push_back(&*list); break; } } } } ap_info_t* next(void) { ap_info_t* rv = NULL; auto ap = _apnext.begin(); if (ap != _apnext.end()) { rv = *ap; _apnext.erase(ap); } return rv; } public: ESPWMAPClass(void) : _connecting(false) { _disconnect = millis(); } virtual ~ESPWMAPClass(void) { } std::vector<String>& ssid(std::vector<String>& names) { names.clear(); for (auto ap = _apscan.begin(); ap != _apscan.end(); ++ap) names.push_back(ap->ssid); return names; } bool timeouted(void) { return millis() - _disconnect >= ESPWMAP_CONNECTION_TIMEOUT; } void clear(void) { _aplist.clear(); } size_t size(void) { return _aplist.size(); } void add(const String& ssid, const String& pswd) { for (size_t i = 0; i < _aplist.size(); ++i) { if (_aplist[i].ssid.equalsIgnoreCase(ssid)) { _aplist[i].pswd = pswd; return; } } ap_info_t ap = {ssid, pswd, 0}; _aplist.push_back(ap); } void begin(void) { WiFi.persistent(false); WiFi.mode(WIFI_STA); _connecting = false; } wl_status_t handle(void) { yield(); // Run System Task switch (WiFi.status()) { case WL_CONNECTED: _apnext.clear(); _disconnect = millis(); _connecting = false; break; default: _connecting = false; /* Falls through. */ case WL_IDLE_STATUS: case WL_DISCONNECTED: if (_connecting) break; int scan = scanComplete(); if (scan >= 0) { complete(scan); #if ESPWMAP_DEBUG Serial.printf("WiFi Scan End (%d/%d)\r\n", (int)_apnext.size(), (int)_apscan.size()); #endif if (size() == 0) { _disconnect = millis() - ESPWMAP_CONNECTION_TIMEOUT; break; } } ap_info_t* ap = next(); if (ap) { #if ESPWMAP_DEBUG Serial.printf("WiFi Begin (%s)\r\n", ap->ssid.c_str()); #endif _connecting = true; WiFi.begin(ap->ssid.c_str(), ap->pswd.c_str()); } else if (scan != WIFI_SCAN_RUNNING) { #if ESPWMAP_DEBUG Serial.println("\r\nWiFi Scan Start"); #endif #if CONFIG_IDF_TARGET_ESP32C3 scanNetworks(true, false, false, 500); #else scanNetworks(true); #endif } break; } return WiFi.status(); } }; extern ESPWMAPClass ESPWMAP; #endif |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
/* espwmap.cpp - WiFi Multi AP Library for ESP8266/ESP32 Copyright (c) 2023 Sasapea's Lab. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "espwmap.h" ESPWMAPClass ESPWMAP; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 |
/* espconf.h - Configure Library for ESP8266/ESP32 Copyright (c) 2023 Sasapea's Lab. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef __ESPCONF_H #define __ESPCONF_H #include "properties.h" #if defined(ESP32) #include "SPIFFS.h" #elif defined(ESP8266) #include "LittleFS.h" #define SPIFFS LittleFS #endif class ESPConf : public Properties { public: ESPConf(void) { } virtual ~ESPConf(void) { } bool load(const char* path) override { bool rv = false; if (SPIFFS.begin(true)) { File f = SPIFFS.open(path, "r"); if (f) { char buf[256]; clear(); size_t size = f.size(); rv = true; while (rv && size) { size_t len = size < sizeof(buf) ? size : sizeof(buf); if ((size_t)f.read((uint8_t *)buf, len) != len) rv = false; else if (!parse(buf, len)) rv = false; size -= len; } finish(); f.close(); } SPIFFS.end(); } return rv; } bool save(const char* path, const char* header = nullptr) override { bool rv = false; if (SPIFFS.begin(true)) { SPIFFS.remove(path); File f = SPIFFS.open(path, "w"); if (f) { std::string str; toStringWithHeader(str, header); rv = (size_t)f.write((const uint8_t*)str.c_str(), str.length()) == str.length(); f.close(); } SPIFFS.end(); } return rv; } }; #endif |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 |
/* properties.h - Properties Library Copyright (c) 2023 Sasapea's Lab. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef __PROPERTIES_H #define __PROPERTIES_H #include <vector> #include <string> #include <string.h> #include <stdlib.h> class Properties { private: typedef struct { std::string name; std::string value; } property_t; typedef struct { std::string name; std::vector<property_t> properties; } section_t; std::vector<section_t> _sections; section_t _current; std::string _linebuf; protected: std::string& trim(std::string& str) { std::string::size_type pos; pos = str.find_first_not_of(' '); if (pos != std::string::npos) str.erase(0, pos); pos = str.find_last_not_of(' '); if (pos != std::string::npos) str.erase(pos + 1); return str; } section_t* getSection(const char* name) { if (name) { for (auto sec = _sections.begin(); sec != _sections.end(); ++sec) { if (strcasecmp(sec->name.c_str(), name) == 0) return &*sec; } } return nullptr; } void setSection(section_t &newSection) { section_t* sec = getSection(newSection.name.c_str()); if (!sec) _sections.push_back(newSection); else { for (auto prop = newSection.properties.begin(); prop != newSection.properties.end(); ++prop) setProperty(*sec, *prop); } } property_t* getProperty(section_t* section, const char* name) { if (section && name) { for (auto prop = section->properties.begin(); prop != section->properties.end(); ++prop) { if (strcasecmp(prop->name.c_str(), name) == 0) return &*prop; } } return nullptr; } void setProperty(section_t §ion, property_t &prop) { trim(prop.name); trim(prop.value); property_t* exists = getProperty(§ion, prop.name.c_str()); if (exists) exists->value = prop.value; else section.properties.push_back(prop); } bool parse(const char* buf, size_t len) { while (len--) { char c = *buf++; if (c >= ' ') _linebuf += c; else if (c == 0x0A) { trim(_linebuf); if (_linebuf.length()) { c = _linebuf[0]; if (c == '[') { if (_linebuf[_linebuf.length() - 1] != ']') return false; // format error. if (_current.properties.size() || _current.name.length()) setSection(_current); _current.name = _linebuf.substr(1, _linebuf.length() - 2); _current.properties.clear(); trim(_current.name); } else if ((c != ';') && (c != '#')) { int sep = _linebuf.find('='); if (sep < 0) sep = _linebuf.length(); property_t prop = {_linebuf.substr(0, sep), _linebuf.substr(sep + 1)}; setProperty(_current, prop); } _linebuf.clear(); } } } return true; } void finish(void) { if (_current.properties.size() || _current.name.length()) setSection(_current); _current.name.clear(); _current.properties.clear(); _linebuf.clear(); } public: Properties(void) { } virtual ~Properties(void) { } void clear(void) { _sections.clear(); _current.name.clear(); _current.properties.clear(); _linebuf.clear(); } std::vector<std::string>& getSectionNames(std::vector<std::string>& names) { names.clear(); for (auto sec = _sections.begin(); sec != _sections.end(); ++sec) names.push_back(sec->name); return names; } std::vector<std::string>& getPropertyNames(std::vector<std::string>& names, const char* section) { names.clear(); section_t* sec = getSection(section); if (sec) { for (auto prop = sec->properties.begin(); prop != sec->properties.end(); ++prop) names.push_back(prop->name); } return names; } void removeSection(const char* section) { if (section) { for (auto sec = _sections.begin(); sec != _sections.end(); ++sec) { if (strcasecmp(sec->name.c_str(), section) == 0) { _sections.erase(sec); break; } } } } void removeProperty(const char* section, const char* name) { if (name) { section_t* sec = getSection(section); if (sec) { for (auto prop = sec->properties.begin(); prop != sec->properties.end(); ++prop) { if (strcasecmp(prop->name.c_str(), name) == 0) { sec->properties.erase(prop); break; } } } } } void setProperty(const char* section, const char* name, const char* value) { if (section && name && value) { section_t newsec = {section, {{name, value}}}; setSection(newsec); } } void setPropertyInt(const char* section, const char* name, int value) { if (section && name) { char buf[16]; snprintf(buf, sizeof(buf), "%d", value); section_t newsec = {section, {{name, buf}}}; setSection(newsec); } } const char* getProperty(const char* section, const char* name, const char* defval = "") { property_t* prop = getProperty(getSection(section), name); return prop ? prop->value.c_str() : defval; } int getPropertyInt(const char* section, const char* name, int defval = 0) { const char* value = getProperty(section, name); return *value ? atoi(value) : defval; } std::string& toString(std::string &str) { std::vector<std::string> names; std::string props; str.clear(); getSectionNames(names); for (auto name = names.begin(); name != names.end(); ++name) str.append("[").append(*name).append("]\n").append(toString(props, name->c_str())); return str; } std::string& toString(std::string &str, const char* section) { if (section == nullptr) toString(str); else { std::vector<std::string> names; str.clear(); getPropertyNames(names, section); for (auto name = names.begin(); name != names.end(); ++name) str.append(*name).append("=").append(getProperty(section, name->c_str())).append("\n"); } return str; } std::string& toStringWithHeader(std::string &str, const char* header) { str.clear(); if (header && *header) { const char* p; const char* q; p = q = header; do { if ((*q == 0) || (*q == 0x0A)) { str.append("# ").append(p, (int)q - (int)p).append("\n"); p = q + 1; } } while (*q++); } std::string props; return str.append(toString(props)); } virtual bool load(const char* path) = 0; virtual bool save(const char* path, const char* header = nullptr) = 0; }; #endif |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 |
/* logging.h - Logging Library for ARDUINO Copyright (c) 2023 Sasapea's Lab. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef __LOGGING_H #define __LOGGING_H #include <stdio.h> #include <stdint.h> #include <stdbool.h> #include <string.h> #include <time.h> #include "Arduino.h" #ifndef LOG_SIZE #define LOG_SIZE 2048 #endif typedef enum : uint8_t { LOG_FATAL, LOG_ERROR, LOG_WARN, LOG_INFO, LOG_DEBUG, LOG_TRACE, } LOG_LEVEL; template<size_t SIZE> class Log : public Print { private: typedef struct __attribute__ ((packed)) { uint8_t prev; // previous data size LOG_LEVEL prio; time_t time; char text[1]; } log_t; char _buffer[SIZE]; size_t _tail; char _temp[64]; size_t _size; char *_next; String _time; String _level; String _text; public: Log(void) : _tail(0) , _size(0) , _next(_buffer) { ((log_t *)_buffer)->prev = 0; } size_t write(uint8_t b) override { if (_size < sizeof(_buffer)) { _temp[_size++] = (b < ' ' ? '?' : b); return 1; } return 0; } size_t write(const uint8_t *buffer, size_t size) override { size_t rv = 0; while (size--) rv += write(*buffer++); return rv; } void add(LOG_LEVEL level = LOG_INFO) { if (_size) { log_t *log; if (_tail) { size_t remove = 0; while (_size + _tail - remove > sizeof(_buffer) - sizeof(log_t) * 2) { log = (log_t *)&_buffer[remove]; size_t n = sizeof(log_t) + strlen(log->text); if (remove + n > _tail) break; remove += n; } if (remove) { _tail -= remove; memcpy(_buffer, &_buffer[remove], _tail + sizeof(log_t)); } } if (_size + _tail <= sizeof(_buffer) - sizeof(log_t) * 2) { time_t t = time(NULL); log = (log_t *)&_buffer[_tail]; log->prio = level; memcpy(&log->time, &t, sizeof(log->time)); memcpy(log->text, _temp, _size); _tail += sizeof(log_t) + _size; _buffer[_tail - 1] = 0; ((log_t *)&_buffer[_tail])->prev = sizeof(log_t) + _size; } _size = 0; } } String& TIME(void) { return _time; } String& LEVEL(void) { return _level; } String& TEXT(void) { return _text; } bool next(bool start) { char temp[128]; time_t t; if (start) _next = _buffer + _tail; if (_next <= _buffer) return false; size_t len = ((log_t *)_next)->prev; log_t *log = (log_t *)(_next -= len); memcpy(&t, &log->time, sizeof(t)); struct tm lt = *localtime(&t); snprintf(temp, sizeof(temp), "%04d-%02d-%02d %02d:%02d:%02d ", lt.tm_year + 1900, lt.tm_mon + 1, lt.tm_mday, lt.tm_hour, lt.tm_min, lt.tm_sec); _time = temp; switch (log->prio) { case LOG_FATAL: _level = "FATAL " ; break; case LOG_ERROR: _level = "ERROR " ; break; case LOG_WARN : _level = "WARN " ; break; case LOG_INFO : _level = "INFO " ; break; case LOG_DEBUG: _level = "DEBUG " ; break; case LOG_TRACE: _level = "TRACE " ; break; default: _level = "UNKNOWN "; break; } _text = log->text; return true; } }; extern Log<LOG_SIZE> ESPLog; #endif |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
/* logging.cpp - Logging Library for ARDUINO Copyright (c) 2023 Sasapea's Lab. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "logging.h" Log<LOG_SIZE> ESPLog; |