Subversion Repositories ESP32_P1_Meter

Rev

Rev 2 | Show entire file | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

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