組み込み系を初めた頃に作ったライブラリ。頻繁に仕様変更してきたのでコードにはまとまりがないがよく使う機能を集約したライブラリで基本機能としてSTA(マルチAP)/APモード、NTP、OTA、WEB、MQTTに対応している。各設定値はフラッシュに保存するため基本機能に関するプログラミングは必要なくWiFiやMQTTの通信切断に伴う再接続処理も自動で行う便利なライブラリだ。再接続時にはMQTTのsubscribe()の再設定も行っている。
最初はフラッシュに保存するログ機能もあったのだが頻繁に書き込むと直ぐにフラッシュが壊れてしまうため削除してしまった。でも少量であったとしてもオンメモリでログする機能くらいは欲しいところ。今後の検討課題としておこう。
なお、MQTTにはPubSubClientライブラリを利用しており、頻繁な切断を防ぐためタイムアウト値を規定の15秒からmosquittoサーバーを前提とした10秒に変更している。
設定画面については、画面設計が大の苦手な私ではこの程度が限界...誰かもっとかっこいいのを作ってくれないかなぁ。(笑)
【esp8266 – システム・ページ】
【esp8266 – プロパティ・ページ】
【esp32 – システム・ページ】
【esp32 – プロパティ・ページ】
【ライブラリ概要】
1 |
void begin(bool wifi_ap = false) |
ライブラリを初期化する。wifi_apをfalse指定(省略時)した場合、フラッシュに接続情報が保存されていればSTAモード、保存されていなければAPモードでWiFiを開始し、true指定すると強制的にAPモードを開始する。APモードではWeb経由でAP情報(SSID/PASSWORD)が登録可能。AP情報が登録されていて3分経過しても接続できない場合はAPモードに移行するが、モバイル対応のため一度でも接続に成功すると無限に接続を試行する仕様となっている。
APモードのアドレスとパスワードは、192.168.119.1
1 |
bool handle(); |
基本機能をハンドリングし戻り値にWiFi接続状態を返す。但し、MQTTサーバーを登録している場合はMQTTサーバーへの接続状態を返す。可能な限り頻繁に呼び出す必要がある。
1 |
bool publish(const char* topic, const uint8_t* payload = nullptr, size_t length = 0, uint8_t qos = 1, bool retain = false); |
MQTT送信を行う。詳細はMQTT/PubSubClientのドキュメントを参照。
1 |
bool subscribe(const char* topic, uint8_t qos = 1); |
MQTT受信トピックの登録。詳細はMQTT/PubSubClientのドキュメントを参照。
1 |
bool unsubscribe(const char* topic); |
MQTT受信トピックの登録を取り消す。
1 |
void setMQTTCallback(ESPWNET_MQTT_CALLBACK cb); |
MQTT受信コールバック関数を登録する。詳細はMQTT/PubSubClientのドキュメントを参照。
1 |
void addHtmlRootLink(String uri, String name); |
Webルートページにリンクを登録する。アプリ用のページを追加するときに利用する。
1 |
void onRestartPage(const char* url = "/system") |
Web再起動処理を実行する。urlは再起動完了後に表示するページを指定する。
1 |
void onFS(); |
Webのファイル・リクエスト(SPIFFS/LittleFS)を処理する。
1 |
void restart(void); |
再起動を行う。
1 |
void setRestartCallback(ESPWNET_RESTART_CALLBACK cb); |
再起動直前に呼び出されるコールバック関数を登録する。コールバック関数では、restart()呼び出し、Web操作による再起動、OTA開始など再起動直前に実行したい処理を行う。
1 |
String getHostName(); |
ホスト名(mDNS名)を取得する。
1 |
String getNodeName(); |
ノード名(表示名)を取得する。
1 |
uint32_t getChipId(); |
CPUチップIDを取得する。IDはMACアドレスの下位3バイト。
1 |
uint16_t getVcc(); |
ESP8266のみ。CPUの電源電圧を取得する。スケッチにADC_MODE(ADC_VCC);の追加が必要。
1 |
void setVccCaribrate(int16_t val); |
初期値設定用。getVcc()用の補正値を設定する。
1 |
void setNodeName(const char* name); |
初期値設定用。ノード名を設定する。
1 |
void addWiFiAP(const char* ssid, const char* pswd); |
初期値設定用。AP情報を追加する。
1 |
void addNTPServer(const char* name); |
初期値設定用。NTPサーバーを追加する。
1 |
void setTimeZone(int timezone, int daylightOffset_sec); |
初期値設定用。タイムゾーンを設定する。
1 |
void getTimeZone(int *timezone,int *daylightOffset); |
タイムゾーンを取得する。begin()呼び出し以降に利用可能。
1 |
void setMQTTServer(const char* host); |
初期値設定用。MQTTサーバーを登録する。
1 |
void setBuiltinLED(uint8_t pin); |
初期値設定用。ビルトインLEDの出力ポートを指定する。
【サンプル・スケッチ】
1 2 3 4 5 6 7 8 9 10 11 |
#include "espwnet.h" void setup() { ESPWNet.begin(); } void loop() { ESPWNet.handle(); } |
【ライブラリ】
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 |
/* espwnet.h - WiFi Network Library for ESP8266/ESP32 Copyright (c) 2021 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" #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(); 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 |
/* espwnet.cpp - WiFi Network Library for ESP8266/ESP32 Copyright (c) 2021 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 1 #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]; snprintf(name, sizeof(name), CHIP_NAME "-%06x", getChipId()); _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.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("<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(); } |
【参照ライブラリ】
ESP8266/ESP32用のプロパティ・ライブラリを作ってみた。
ESP8266/ESP32用のMultiAPライブラリを作ってみた。
PubSubClient – Arduino Reference