Subversion Repositories ESP32_P1_Meter

Rev

Rev 2 | Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
1 raymond 1
 
2
 
3
#include <FS.h>
4
#include <LittleFS.h>
5
#include <AsyncFsWebServer.h>  //https://github.com/cotestatnt/async-esp-fs-webserver
6
 
7
#define FILESYSTEM LittleFS
8
bool captiveRun = false;
9
 
10
// AsyncFsWebServer server(80, FILESYSTEM, "esphost");
11
AsyncFsWebServer server(80, FILESYSTEM);
12
 
13
#ifndef LED_BUILTIN
14
#define LED_BUILTIN 2
15
#endif
16
 
17
#define BTN_SAVE  5
18
 
19
// Test "options" values
20
uint8_t ledPin = LED_BUILTIN;
21
bool boolVar = true;
22
uint32_t longVar = 1234567890;
23
float floatVar = 15.5F;
24
String stringVar = "Test option String";
25
 
26
// In order to show a dropdown list box in /setup page
27
// we need a list of values and a variable to store the selected option
28
#define LIST_SIZE  7
29
const char* dropdownList[LIST_SIZE] =
30
{"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
31
String dropdownSelected;
32
 
33
// Var labels (in /setup webpage)
34
#define LED_LABEL "The LED pin number"
35
#define BOOL_LABEL "A bool variable"
36
#define LONG_LABEL "A long variable"
37
#define FLOAT_LABEL "A float variable"
38
#define STRING_LABEL "A String variable"
39
#define DROPDOWN_LABEL "A dropdown listbox"
40
 
41
// Timezone definition to get properly time from NTP server
42
#define MYTZ "CET-1CEST,M3.5.0,M10.5.0/3"
43
struct tm Time;
44
 
45
static const char save_btn_htm[] PROGMEM = R"EOF(
46
<div class="btn-bar">
47
  <a class="btn" id="reload-btn">Reload options</a>
48
</div>
49
)EOF";
50
 
51
static const char button_script[] PROGMEM = R"EOF(
52
/* Add click listener to button */
53
document.getElementById('reload-btn').addEventListener('click', reload);
54
function reload() {
55
  console.log('Reload configuration options');
56
  fetch('/reload')
57
  .then((response) => {
58
    if (response.ok) {
59
      openModalMessage('Options loaded', 'Options was reloaded from configuration file');
60
      return;
61
    }
62
    throw new Error('Something goes wrong with fetch');
63
  })
64
  .catch((error) => {
65
    openModalMessage('Error', 'Something goes wrong with your request');
66
  });
67
}
68
)EOF";
69
 
70
 
71
////////////////////////////////  Filesystem  /////////////////////////////////////////
72
bool startFilesystem() {
73
  if (FILESYSTEM.begin()){
74
    server.printFileList(FILESYSTEM, "/", 2);
75
    return true;
76
  }
77
  else {
78
    Serial.println("ERROR on mounting filesystem. It will be reformatted!");
79
    FILESYSTEM.format();
80
    ESP.restart();
81
  }
82
  return false;
83
}
84
 
85
/*
86
* Getting FS info (total and free bytes) is strictly related to
87
* filesystem library used (LittleFS, FFat, SPIFFS etc etc) and ESP framework
88
*/
89
#ifdef ESP32
90
void getFsInfo(fsInfo_t* fsInfo) {
91
	fsInfo->fsName = "LittleFS";
92
	fsInfo->totalBytes = LittleFS.totalBytes();
93
	fsInfo->usedBytes = LittleFS.usedBytes();
94
}
95
#endif
96
 
97
 
98
////////////////////  Load application options from filesystem  ////////////////////
99
bool loadOptions() {
100
  if (FILESYSTEM.exists(server.getConfiFileName())) {
101
    server.getOptionValue(LED_LABEL, ledPin);
102
    server.getOptionValue(BOOL_LABEL, boolVar);
103
    server.getOptionValue(LONG_LABEL, longVar);
104
    server.getOptionValue(FLOAT_LABEL, floatVar);
105
    server.getOptionValue(STRING_LABEL, stringVar);
106
    server.getOptionValue(DROPDOWN_LABEL, dropdownSelected);
107
 
108
    Serial.println("\nThis are the current values stored: \n");
109
    Serial.printf("LED pin value: %d\n", ledPin);
110
    Serial.printf("Bool value: %s\n", boolVar ? "true" : "false");
111
    Serial.printf("Long value: %u\n", longVar);
112
    Serial.printf("Float value: %d.%d\n", (int)floatVar, (int)(floatVar*1000)%1000);
113
    Serial.printf("String value: %s\n", stringVar.c_str());
114
    Serial.printf("Dropdown selected value: %s\n\n", dropdownSelected.c_str());
115
    return true;
116
  }
117
  else
118
    Serial.println(F("Config file not exist"));
119
  return false;
120
}
121
 
122
void saveOptions() {
123
  // server.saveOptionValue(LED_LABEL, ledPin);
124
  // server.saveOptionValue(BOOL_LABEL, boolVar);
125
  // server.saveOptionValue(LONG_LABEL, longVar);
126
  // server.saveOptionValue(FLOAT_LABEL, floatVar);
127
  // server.saveOptionValue(STRING_LABEL, stringVar);
128
  // server.saveOptionValue(DROPDOWN_LABEL, dropdownSelected);
129
  Serial.println(F("Application options saved."));
130
}
131
 
132
////////////////////////////  HTTP Request Handlers  ////////////////////////////////////
133
void handleLoadOptions(AsyncWebServerRequest *request) {
134
  request->send(200, "text/plain", "Options loaded");
135
  loadOptions();
136
  Serial.println("Application option loaded after web request");
137
}
138
 
139
 
140
void setup() {
141
  Serial.begin(115200);
142
  pinMode(BTN_SAVE, INPUT_PULLUP);
143
 
144
  // FILESYSTEM INIT
145
  if (startFilesystem()){
146
    // Load configuration (if not present, default will be created when webserver will start)
147
    if (loadOptions())
148
      Serial.println(F("Application option loaded"));
149
    else
150
      Serial.println(F("Application options NOT loaded!"));
151
  }
152
 
153
  // Try to connect to stored SSID, start AP with captive portal if fails after timeout
154
  IPAddress myIP = server.startWiFi(15000);
155
  if (!myIP) {
156
    Serial.println("\n\nNo WiFi connection, start AP and Captive Portal\n");
157
    server.startCaptivePortal("ESP_AP", "123456789", "/setup");
158
    myIP = WiFi.softAPIP();
159
    captiveRun = true;
160
  }
161
 
162
  // Add custom page handlers to webserver
163
  server.on("/reload", HTTP_GET, handleLoadOptions);
164
 
165
  // Configure /setup page and start Web Server
166
  server.addOptionBox("My Options");
167
 
168
  server.addOption(BOOL_LABEL, boolVar);
169
  server.addOption(LED_LABEL, ledPin);
170
  server.addOption(LONG_LABEL, longVar);
171
  server.addOption(FLOAT_LABEL, floatVar, 1.0, 100.0, 0.01);
172
  server.addOption(STRING_LABEL, stringVar);
173
  server.addDropdownList(DROPDOWN_LABEL, dropdownList, LIST_SIZE);
174
 
175
  server.addHTML(save_btn_htm, "buttons", /*overwrite*/ false);
176
  server.addJavascript(button_script, "js", /*overwrite*/ false);
177
 
178
  // Enable ACE FS file web editor and add FS info callback function
179
  server.enableFsCodeEditor();
180
  #ifdef ESP32
181
  server.setFsInfoCallback(getFsInfo);
182
  #endif
183
 
184
  // set /setup and /edit page authentication
185
  server.setAuthentication("admin", "admin");
186
 
187
  // Start server
188
  server.init();
189
  Serial.print(F("ESP Web Server started on IP Address: "));
190
  Serial.println(myIP);
191
  Serial.println(F(
192
      "This is \"customOptions.ino\" example.\n"
193
      "Open /setup page to configure optional parameters.\n"
194
      "Open /edit page to view, edit or upload example or your custom webserver source files."
195
  ));
196
}
197
 
198
void loop() {
199
  if (captiveRun)
200
    server.updateDNS();
201
 
202
  // Savew options also on button click
203
  if (! digitalRead(BTN_SAVE)) {
204
    saveOptions();
205
    delay(1000);
206
  }
207
}