Subversion Repositories ESP32_P1_Meter

Rev

Rev 2 | Details | Compare with Previous | Last modification | View Log | RSS feed

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