OnDemandConfigPortal.ino 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. /**
  2. * This is a kind of unit test for DEV for now
  3. * It contains many of the public methods
  4. *
  5. */
  6. #include <WiFiManager.h> // https://github.com/tzapu/WiFiManager
  7. #include <time.h>
  8. #include <stdio.h>
  9. #define USEOTA
  10. // enable OTA
  11. #ifdef USEOTA
  12. #include <WiFiUdp.h>
  13. #include <ArduinoOTA.h>
  14. #endif
  15. #define TRIGGER_PIN 0
  16. const char* modes[] = { "NULL", "STA", "AP", "STA+AP" };
  17. unsigned long mtime = 0;
  18. // // #define MYOLED
  19. // #include <Wire.h>
  20. // #include <Adafruit_GFX.h>
  21. // #include <Adafruit_SSD1306.h>
  22. // #ifdef MYOLED
  23. // #define SCREEN_WIDTH 128 // OLED display width, in pixels
  24. // #define SCREEN_HEIGHT 32 // OLED display height, in pixels
  25. // // Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
  26. // #define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin)
  27. // Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
  28. // void init_oled(){
  29. // Wire.begin(SCL,SDA); // begin(sda, scl) SWAP!
  30. // // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
  31. // if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3C for 128x32
  32. // Serial.println(F("SSD1306 allocation failed"));
  33. // }
  34. // display.clearDisplay();
  35. // display.setTextSize(1); // Normal 1:1 pixepl scale
  36. // display.setTextColor(WHITE); // Draw white text
  37. // display.setCursor(0,0); // Start at top-left corner
  38. // display.display();
  39. // }
  40. // void print_oled(String str,uint8_t size){
  41. // display.clearDisplay();
  42. // display.setTextSize(size);
  43. // display.setTextColor(WHITE);
  44. // display.setCursor(0,0);
  45. // display.println(str);
  46. // display.display();
  47. // }
  48. // #else
  49. // void print_oled(String str,uint8_t size){
  50. // (void)str;
  51. // (void)size;
  52. // }
  53. // #endif
  54. void print_oled(String str,uint8_t size){
  55. (void)str;
  56. (void)size;
  57. }
  58. WiFiManager wm;
  59. // OPTION FLAGS
  60. bool TEST_CP = true; // always start the configportal, even if ap found
  61. bool TEST_NET = true; // do a network test after connect, (gets ntp time)
  62. bool ALLOWONDEMAND = true;
  63. // char ssid[] = "*************"; // your network SSID (name)
  64. // char pass[] = "********"; // your network password
  65. void saveWifiCallback(){
  66. Serial.println("[CALLBACK] saveCallback fired");
  67. }
  68. //gets called when WiFiManager enters configuration mode
  69. void configModeCallback (WiFiManager *myWiFiManager) {
  70. Serial.println("[CALLBACK] configModeCallback fired");
  71. #ifdef ESP8266
  72. print_oled("WiFiManager Waiting\nIP: " + WiFi.softAPIP().toString() + "\nSSID: " + WiFi.softAPSSID(),1);
  73. #endif
  74. // myWiFiManager->setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0));
  75. // Serial.println(WiFi.softAPIP());
  76. //if you used auto generated SSID, print it
  77. // Serial.println(myWiFiManager->getConfigPortalSSID());
  78. }
  79. void saveParamCallback(){
  80. Serial.println("[CALLBACK] saveParamCallback fired");
  81. // wm.stopConfigPortal();
  82. }
  83. void bindServerCallback(){
  84. wm.server->on("/custom",handleRoute);
  85. // wm.server->on("/info",handleRoute); // can override wm!
  86. }
  87. void handleRoute(){
  88. Serial.println("[HTTP] handle route");
  89. wm.server->send(200, "text/plain", "hello from user code");
  90. }
  91. void setup() {
  92. WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP
  93. // put your setup code here, to run once:
  94. Serial.begin(115200);
  95. // Serial1.begin(115200);
  96. // Serial.setDebugOutput(true);
  97. delay(1000);
  98. // Serial1.println("TXD1 Enabled");
  99. Serial.println("\n Starting");
  100. // WiFi.setSleepMode(WIFI_NONE_SLEEP); // disable sleep, can improve ap stability
  101. #ifdef OLED
  102. init_oled();
  103. #endif
  104. print_oled(F("Starting..."),2);
  105. wm.debugPlatformInfo();
  106. //Local intialization. Once its business is done, there is no need to keep it around
  107. //reset settings - for testing
  108. // wm.resetSettings();
  109. // wm.erase();
  110. wm.setClass("invert");
  111. WiFiManagerParameter custom_html("<p>This Is Custom HTML</p>"); // only custom html
  112. WiFiManagerParameter custom_mqtt_server("server", "mqtt server", "", 40);
  113. WiFiManagerParameter custom_mqtt_port("port", "mqtt port", "", 6);
  114. WiFiManagerParameter custom_token("api_token", "api token", "", 16);
  115. WiFiManagerParameter custom_tokenb("invalid token", "invalid token", "", 0); // id is invalid, cannot contain spaces
  116. WiFiManagerParameter custom_ipaddress("input_ip", "input IP", "", 15,"pattern='\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}'"); // custom input attrs (ip mask)
  117. const char _customHtml_checkbox[] = "type=\"checkbox\"";
  118. WiFiManagerParameter custom_checkbox("checkbox", "my checkbox", "T", 2, _customHtml_checkbox, WFM_LABEL_AFTER);
  119. // callbacks
  120. wm.setAPCallback(configModeCallback);
  121. wm.setWebServerCallback(bindServerCallback);
  122. wm.setSaveConfigCallback(saveWifiCallback);
  123. wm.setSaveParamsCallback(saveParamCallback);
  124. //add all your parameters here
  125. wm.addParameter(&custom_html);
  126. wm.addParameter(&custom_mqtt_server);
  127. wm.addParameter(&custom_mqtt_port);
  128. wm.addParameter(&custom_token);
  129. wm.addParameter(&custom_tokenb);
  130. wm.addParameter(&custom_ipaddress);
  131. wm.addParameter(&custom_checkbox);
  132. custom_html.setValue("test",4);
  133. custom_token.setValue("test",4);
  134. // Set cutom menu via menu[] or vector
  135. // const char* menu[] = {"wifi","wifinoscan","info","param","close","sep","erase","restart","exit"};
  136. // wm.setMenu(menu,9); // custom menu array must provide length
  137. std::vector<const char *> menu = {"wifi","wifinoscan","info","param","close","sep","erase","restart","exit"};
  138. // wm.setMenu(menu); // custom menu, pass vector
  139. wm.setParamsPage(true); // move params to seperate page, not wifi, do not combine with setmenu!
  140. // set static sta ip
  141. // wm.setSTAStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0));
  142. // wm.setShowStaticFields(false);
  143. // wm.setShowDnsFields(false);
  144. // set static ip
  145. // wm.setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0));
  146. // wm.setAPStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0));
  147. // set country
  148. wm.setCountry("US"); // setting wifi country seems to improve OSX soft ap connectivity, may help others as well
  149. // set channel
  150. // wm.setWiFiAPChannel(13);
  151. // set AP hidden
  152. // wm.setAPHidden(true);
  153. // show password publicly!
  154. // wm.setShowPassword(true);
  155. //sets timeout until configuration portal gets turned off
  156. //useful to make it all retry or go to sleep in seconds
  157. wm.setConfigPortalTimeout(120);
  158. // wm.setConnectTimeout(20);
  159. // wm.setShowStaticFields(true);
  160. // wm.startConfigPortal("AutoConnectAP", "password");
  161. // wm.setCleanConnect(true); // disconenct before connect, clean connect
  162. // wm.setBreakAfterConfig(true);
  163. //fetches ssid and pass and tries to connect
  164. //if it does not connect it starts an access point with the specified name
  165. //here "AutoConnectAP"
  166. //and goes into a blocking loop awaiting configuration
  167. wifiInfo();
  168. print_oled(F("Connecting..."),2);
  169. if(!wm.autoConnect("WM_AutoConnectAP")) {
  170. Serial.println("failed to connect and hit timeout");
  171. print_oled("Not Connected",2);
  172. }
  173. else if(TEST_CP) {
  174. delay(1000);
  175. Serial.println("TEST_CP ENABLED");
  176. // start configportal always
  177. wm.setConfigPortalTimeout(60);
  178. wm.startConfigPortal("WM_ConnectAP");
  179. }
  180. else {
  181. //if you get here you have connected to the WiFi
  182. Serial.println("connected...yeey :)");
  183. print_oled("Connected\nIP: " + WiFi.localIP().toString() + "\nSSID: " + WiFi.SSID(),1);
  184. }
  185. wifiInfo();
  186. pinMode(TRIGGER_PIN, INPUT_PULLUP);
  187. #ifdef USEOTA
  188. ArduinoOTA.begin();
  189. #endif
  190. }
  191. void wifiInfo(){
  192. WiFi.printDiag(Serial);
  193. Serial.println("SAVED: " + (String)wm.getWiFiIsSaved() ? "YES" : "NO");
  194. Serial.println("SSID: " + (String)wm.getWiFiSSID());
  195. Serial.println("PASS: " + (String)wm.getWiFiPass());
  196. }
  197. void loop() {
  198. #ifdef USEOTA
  199. ArduinoOTA.handle();
  200. #endif
  201. // is configuration portal requested?
  202. if (ALLOWONDEMAND && digitalRead(TRIGGER_PIN) == LOW ) {
  203. delay(100);
  204. if ( digitalRead(TRIGGER_PIN) == LOW ){
  205. Serial.println("BUTTON PRESSED");
  206. wm.setConfigPortalTimeout(140);
  207. wm.setParamsPage(false); // move params to seperate page, not wifi, do not combine with setmenu!
  208. // disable captive portal redirection
  209. // wm.setCaptivePortalEnable(false);
  210. if (!wm.startConfigPortal("OnDemandAP","12345678")) {
  211. Serial.println("failed to connect and hit timeout");
  212. delay(3000);
  213. }
  214. }
  215. else {
  216. //if you get here you have connected to the WiFi
  217. Serial.println("connected...yeey :)");
  218. print_oled("Connected\nIP: " + WiFi.localIP().toString() + "\nSSID: " + WiFi.SSID(),1);
  219. getTime();
  220. }
  221. }
  222. if(WiFi.status() == WL_CONNECTED && millis()-mtime > 10000 ){
  223. getTime();
  224. mtime = millis();
  225. }
  226. // put your main code here, to run repeatedly:
  227. delay(100);
  228. }
  229. void getTime() {
  230. int tz = -5;
  231. int dst = 0;
  232. time_t now = time(nullptr);
  233. unsigned timeout = 5000;
  234. unsigned start = millis();
  235. configTime(tz * 3600, dst * 3600, "pool.ntp.org", "time.nist.gov");
  236. Serial.print("Waiting for NTP time sync: ");
  237. while (now < 8 * 3600 * 2 ) {
  238. delay(100);
  239. Serial.print(".");
  240. now = time(nullptr);
  241. if((millis() - start) > timeout){
  242. Serial.println("[ERROR] Failed to get NTP time.");
  243. return;
  244. }
  245. }
  246. Serial.println("");
  247. struct tm timeinfo;
  248. gmtime_r(&now, &timeinfo);
  249. Serial.print("Current time: ");
  250. Serial.print(asctime(&timeinfo));
  251. }
  252. void debugchipid(){
  253. // WiFi.mode(WIFI_STA);
  254. // WiFi.printDiag(Serial);
  255. // Serial.println(modes[WiFi.getMode()]);
  256. // ESP.eraseConfig();
  257. // wm.resetSettings();
  258. // wm.erase(true);
  259. WiFi.mode(WIFI_AP);
  260. // WiFi.softAP();
  261. WiFi.enableAP(true);
  262. delay(500);
  263. // esp_wifi_start();
  264. delay(1000);
  265. WiFi.printDiag(Serial);
  266. delay(60000);
  267. ESP.restart();
  268. // AP esp_267751
  269. // 507726A4AE30
  270. // ESP32 Chip ID = 507726A4AE30
  271. }