-
Notifications
You must be signed in to change notification settings - Fork 11
/
main.cpp
415 lines (336 loc) · 10.4 KB
/
main.cpp
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
#include <ArduinoOTA.h>
#include <IotWebConf.h>
#include <IotWebConfUsing.h>
#include "main.hpp"
#include "enhanced.hpp"
#include "bus.hpp"
#include <Preferences.h>
Preferences preferences;
#ifdef ESP32
#include <esp_task_wdt.h>
#include <ESPmDNS.h>
#include "esp32c3/rom/rtc.h"
#include <IotWebConfESP32HTTPUpdateServer.h>
HTTPUpdateServer httpUpdater;
#else
#include <ESP8266mDNS.h>
#include <ESP8266TrueRandom.h>
#include <ESP8266HTTPUpdateServer.h>
ESP8266HTTPUpdateServer httpUpdater;
#endif
#define ALPHA 0.3
#define PWM_CHANNEL 0
#define PWM_FREQ 10000
#define PWM_RESOLUTION 8
#define DEFAULT_AP "ebus-test"
#define DEFAULT_PASS "lectronz"
#define DEFAULT_APMODE_PASS "ebusebus"
#ifdef ESP32
TaskHandle_t Task1;
#endif
#define CONFIG_VERSION "eea"
DNSServer dnsServer;
WebServer configServer(80);
char pwm_value_string[8];
IotWebConf iotWebConf(HOSTNAME, &dnsServer, &configServer, "", CONFIG_VERSION);
IotWebConfNumberParameter pwm_value_param = IotWebConfNumberParameter("PWM value", "pwm_value", pwm_value_string, 8, "130", "1..255", "min='1' max='255' step='1'");
WiFiServer wifiServer(3333);
WiFiServer wifiServerRO(3334);
WiFiServer wifiServerEnh(3335);
WiFiServer statusServer(5555);
WiFiClient serverClients[MAX_SRV_CLIENTS];
WiFiClient serverClientsRO[MAX_SRV_CLIENTS];
WiFiClient enhClients[MAX_SRV_CLIENTS];
unsigned long last_comms = 0;
int last_reset_code = -1;
unsigned long loopDuration = 0;
unsigned long maxLoopDuration = 0;
unsigned long lastConnectTime = 0;
int reconnectCount = 0;
int random_ch(){
#ifdef ESP32
return esp_random() % 13 + 1 ;
#elif defined(ESP8266)
return ESP8266TrueRandom.random(1, 13);
#endif
}
#ifdef ESP32
void on_connected(WiFiEvent_t event, WiFiEventInfo_t info){
lastConnectTime = millis();
reconnectCount++;
}
#endif
void wdt_start() {
#ifdef ESP32
esp_task_wdt_init(6, true);
#elif defined(ESP8266)
ESP.wdtDisable();
#endif
}
void wdt_feed() {
#ifdef ESP32
esp_task_wdt_reset();
#elif defined(ESP8266)
ESP.wdtFeed();
#else
#error UNKNOWN PLATFORM
#endif
}
inline void disableTX() {
#ifdef TX_DISABLE_PIN
pinMode(TX_DISABLE_PIN, OUTPUT);
digitalWrite(TX_DISABLE_PIN, HIGH);
#endif
}
inline void enableTX() {
#ifdef TX_DISABLE_PIN
digitalWrite(TX_DISABLE_PIN, LOW);
#endif
}
void set_pwm(uint8_t value){
#ifdef PWM_PIN
ledcWrite(PWM_CHANNEL, value);
#endif
}
uint32_t get_pwm(){
#ifdef PWM_PIN
return ledcRead(PWM_CHANNEL);
#endif
return 0;
}
void reset(){
disableTX();
ESP.restart();
}
void reset_config() {
preferences.clear();
reset();
}
void check_reset() {
// check if RESET_PIN being hold low and reset
pinMode(RESET_PIN, INPUT_PULLUP);
unsigned long resetStart = millis();
while(digitalRead(RESET_PIN) == 0){
if (millis() > resetStart + RESET_MS){
reset_config();
}
}
}
void loop_duration() {
static unsigned long lastTime = 0;
unsigned long now = micros();
unsigned long delta = now - lastTime;
lastTime = now;
loopDuration = ((1 - ALPHA) * loopDuration + (ALPHA * delta));
if (delta > maxLoopDuration) {
maxLoopDuration = delta;
}
}
void data_process(){
loop_duration();
//check clients for data
for (int i = 0; i < MAX_SRV_CLIENTS; i++){
handleClient(&serverClients[i]);
handleEnhClient(&enhClients[i]);
}
//check queue for data
BusType::data d;
if (Bus.read(d)) {
for (int i = 0; i < MAX_SRV_CLIENTS; i++){
if (d._enhanced) {
if (d._client == &enhClients[i]) {
if (pushEnhClient(&enhClients[i], d._c, d._d, true)) {
last_comms = millis();
}
}
}
else {
if (pushClient(&serverClients[i], d._d)){
last_comms = millis();
}
if (pushClient(&serverClientsRO[i], d._d)){
last_comms = millis();
}
if (d._client != &enhClients[i]) {
if (pushEnhClient(&enhClients[i], d._c, d._d, d._logtoclient == &enhClients[i])){
last_comms = millis();
}
}
}
}
}
}
void data_loop(void * pvParameters){
while(1){
data_process();
}
}
void saveParamsCallback () {
uint8_t new_pwm_value = atoi(pwm_value_string);
if (new_pwm_value > 0){
set_pwm(new_pwm_value);
preferences.putUInt("pwm_value", new_pwm_value);
}
DebugSer.printf("pwm_value set: %s %d\n", pwm_value_string, new_pwm_value);
}
char* status_string(){
static char status[1024];
int pos = 0;
pos += sprintf(status + pos, "async mode: %s\n", USE_ASYNCHRONOUS ? "true" : "false");
pos += sprintf(status + pos, "software serial mode: %s\n", USE_SOFTWARE_SERIAL ? "true" : "false");
pos += sprintf(status + pos, "uptime: %ld ms\n", millis());
pos += sprintf(status + pos, "last_connect_time: %ld ms\n", lastConnectTime);
pos += sprintf(status + pos, "reconnect_count: %d \n", reconnectCount);
pos += sprintf(status + pos, "rssi: %d dBm\n", WiFi.RSSI());
pos += sprintf(status + pos, "free_heap: %d B\n", ESP.getFreeHeap());
pos += sprintf(status + pos, "reset_code: %d\n", last_reset_code);
pos += sprintf(status + pos, "loop_duration: %ld us\r\n", loopDuration);
pos += sprintf(status + pos, "max_loop_duration: %ld us\r\n", maxLoopDuration);
pos += sprintf(status + pos, "version: %s\r\n", AUTO_VERSION);
pos += sprintf(status + pos, "nbr arbitrations: %i\r\n", (int)Bus._nbrArbitrations);
pos += sprintf(status + pos, "nbr restarts1: %i\r\n", (int)Bus._nbrRestarts1);
pos += sprintf(status + pos, "nbr restarts2: %i\r\n", (int)Bus._nbrRestarts2);
pos += sprintf(status + pos, "nbr lost1: %i\r\n", (int)Bus._nbrLost1);
pos += sprintf(status + pos, "nbr lost2: %i\r\n", (int)Bus._nbrLost2);
pos += sprintf(status + pos, "nbr won1: %i\r\n", (int)Bus._nbrWon1);
pos += sprintf(status + pos, "nbr won2: %i\r\n", (int)Bus._nbrWon2);
pos += sprintf(status + pos, "nbr late: %i\r\n", (int)Bus._nbrLate);
pos += sprintf(status + pos, "nbr errors: %i\r\n", (int)Bus._nbrErrors);
pos += sprintf(status + pos, "pwm_value: %i\r\n", get_pwm());
return status;
}
void handleStatus()
{
configServer.send(200, "text/plain", status_string());
}
void handleRoot()
{
// -- Let IotWebConf test and handle captive portal requests.
if (iotWebConf.handleCaptivePortal())
{
// -- Captive portal request were already served.
return;
}
String s = "<html><head><title>esp-eBus adapter</title>";
s += "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, user-scalable=no\"/>";
s += "</head><body>";
s += "<a href='/status'>Adapter status</a><br>";
s += "<a href='/config'>Configuration</a> - user: admin password: your configured AP mode password or default: ";
s += DEFAULT_APMODE_PASS;
s += "<br>";
s += "<a href='/firmware'>Firmware update</a><br>";
s += "<br>";
s += "For more info see project page: <a href='https://github.com/danielkucera/esp-arduino-ebus'>https://github.com/danielkucera/esp-arduino-ebus</a>";
s += "</body></html>";
configServer.send(200, "text/html", s);
}
void setup() {
preferences.begin("esp-ebus", false);
check_reset();
#ifdef ESP32
last_reset_code = rtc_get_reset_reason(0);
#elif defined(ESP8266)
last_reset_code = (int) ESP.getResetInfoPtr();
#endif
Bus.begin();
DebugSer.begin(115200);
DebugSer.setDebugOutput(true);
disableTX();
#ifdef PWM_PIN
ledcSetup(PWM_CHANNEL, PWM_FREQ, PWM_RESOLUTION);
ledcAttachPin(PWM_PIN, PWM_CHANNEL);
#endif
set_pwm(preferences.getUInt("pwm_value", 130));
if (preferences.getBool("firstboot", true)){
preferences.putBool("firstboot", false);
iotWebConf.init();
strncpy(iotWebConf.getApPasswordParameter()->valueBuffer, DEFAULT_APMODE_PASS, IOTWEBCONF_WORD_LEN);
strncpy(iotWebConf.getWifiSsidParameter()->valueBuffer, "ebus-test", IOTWEBCONF_WORD_LEN);
strncpy(iotWebConf.getWifiPasswordParameter()->valueBuffer, "lectronz", IOTWEBCONF_WORD_LEN);
iotWebConf.saveConfig();
} else {
iotWebConf.skipApStartup();
}
#ifdef ESP32
WiFi.onEvent(on_connected, WiFiEvent_t::ARDUINO_EVENT_WIFI_STA_CONNECTED);
#endif
int wifi_ch = random_ch();
DebugSer.printf("Channel for AP mode: %d\n", wifi_ch);
WiFi.channel(wifi_ch); // doesn't work, https://github.com/prampec/IotWebConf/issues/286
iotWebConf.addSystemParameter(&pwm_value_param);
iotWebConf.setConfigSavedCallback(&saveParamsCallback);
iotWebConf.getApTimeoutParameter()->visible = true;
iotWebConf.setWifiConnectionTimeoutMs(7000);
#ifdef STATUS_LED_PIN
iotWebConf.setStatusPin(STATUS_LED_PIN);
#endif
// -- Initializing the configuration.
iotWebConf.init();
// -- Set up required URL handlers on the web server.
configServer.on("/", []{ handleRoot(); });
configServer.on("/config", []{ iotWebConf.handleConfig(); });
configServer.on("/param", []{ iotWebConf.handleConfig(); });
configServer.on("/status", []{ handleStatus(); });
configServer.onNotFound([](){ iotWebConf.handleNotFound(); });
iotWebConf.setupUpdateServer(
[](const char* updatePath) { httpUpdater.setup(&configServer, updatePath); },
[](const char* userName, char* password) { httpUpdater.updateCredentials(userName, password); });
while (iotWebConf.getState() != iotwebconf::NetworkState::OnLine){
iotWebConf.doLoop();
}
wifiServer.begin();
wifiServerRO.begin();
wifiServerEnh.begin();
statusServer.begin();
ArduinoOTA.begin();
MDNS.end();
MDNS.begin(HOSTNAME);
wdt_start();
last_comms = millis();
#ifdef ESP32
xTaskCreate(data_loop, "data_loop", 10000, NULL, 1, &Task1);
#endif
}
bool handleStatusServerRequests() {
if (!statusServer.hasClient())
return false;
WiFiClient client = statusServer.accept();
if (client.availableForWrite() >= AVAILABLE_THRESHOLD) {
client.print(status_string());
client.flush();
client.stop();
}
return true;
}
void loop() {
ArduinoOTA.handle();
#ifdef ESP8266
MDNS.update();
data_process();
#endif
wdt_feed();
#ifdef ESP32
iotWebConf.doLoop();
#endif
if (WiFi.status() != WL_CONNECTED) {
reset();
}
if (millis() > last_comms + 200*1000 ) {
reset();
}
// Check if new client on the status server
if (handleStatusServerRequests()) {
// exclude handleStatusServerRequests from maxLoopDuration calculation
// as it skews the typical loop duration and set maxLoopDuration to 0
loop_duration();
maxLoopDuration = 0;
}
// Check if there are any new clients on the eBUS servers
if (handleNewClient(wifiServer, serverClients)){
enableTX();
}
if (handleNewClient(wifiServerEnh, enhClients)){
enableTX();
}
handleNewClient(wifiServerRO, serverClientsRO);
}