forked from vitotai/BrewPiLess
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBrewPiLess.cpp
More file actions
2117 lines (1779 loc) · 56.1 KB
/
Copy pathBrewPiLess.cpp
File metadata and controls
2117 lines (1779 loc) · 56.1 KB
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#ifdef ESP8266
#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#elif defined(ESP32)
#include <WiFi.h>
#include <ESPmDNS.h>
#endif
#include <ArduinoOTA.h>
#include <FS.h>
#if defined(ESP32)
#include <AsyncTCP.h>
#else
#include <ESPAsyncTCP.h>
#endif
#include <ESPAsyncWebServer.h>
#include <ArduinoJson.h>
//{ brewpi
#include <OneWire.h>
#include "Ticks.h"
#include "Display.h"
#include "TempControl.h"
#include "PiLink.h"
#include "Menu.h"
#include "Pins.h"
#include "RotaryEncoder.h"
#include "Buzzer.h"
#include "TempSensor.h"
#include "TempSensorMock.h"
#include "TempSensorExternal.h"
#include "Ticks.h"
#include "Sensor.h"
#include "SettingsManager.h"
#include "EepromFormat.h"
#if BREWPI_SIMULATE
#include "Simulator.h"
#endif
//}brewpi
#if AUTO_CAP
#include "AutoCapControl.h"
#endif
#include "TimeKeeper.h"
#include "mystrlib.h"
#include "GravityTracker.h"
#include "BrewKeeper.h"
#ifdef ENABLE_LOGGING
#include "DataLogger.h"
#endif
extern "C" {
#if defined(ESP32)
//#include "lwip/apps/sntp.h"
#else
#include <sntp.h>
#endif
}
#include "BPLSettings.h"
#include "ESPUpdateServer.h"
#include "WiFiSetup.h"
#include "BrewPiProxy.h"
#include "BrewLogger.h"
#include "ExternalData.h"
#if SupportMqttRemoteControl
#include "MqttRemoteControl.h"
#endif
#if EanbleParasiteTempControl
#include "ParasiteTempController.h"
#endif
#if SupportPressureTransducer
#include "PressureMonitor.h"
#endif
#if SupportTiltHydrometer
#include "TiltListener.h"
#endif
#if UseLittleFS
#include <LittleFS.h>
#else
#if defined(ESP32)
#include <SPIFFS.h>
#endif
#endif
#if EnableDHTSensorSupport
#include "HumidityControl.h"
#endif
//WebSocket seems to be unstable, at least on iPhone.
//Go back to ServerSide Event.
#define UseWebSocket true
#define UseServerSideEvent false
#define ResponseAppleCNA true
#define CaptivePortalTimeout 180
#ifndef LegacyEspAsyncLibraries
#define LegacyEspAsyncLibraries false
#endif
/**************************************************************************************/
/* Start of Configuration */
/**************************************************************************************/
#define JSON_BUFFER_SIZE 1024
#define WS_PATH "/ws"
#define SSE_PATH "/getline"
#define POLLING_PATH "/getline_p"
#define PUTLINE_PATH "/putline"
#ifdef ENABLE_LOGGING
#define LOGGING_PATH "/log"
#endif
#define LOGLIST_PATH "/loglist.php"
#define CHART_DATA_PATH "/chart.php"
#define CONFIG_PATH "/config"
#define TIME_PATH "/time"
#define RESETWIFI_PATH "/erasewifisetting"
#define FPUTS_PATH "/fputs"
#define FLIST_PATH "/list"
#define DELETE_PATH "/rm"
#define CHART_LIB_PATH "/dygraph-combined.js"
#define BEER_PROFILE_PATH "/tschedule"
#define GETSTATUS_PATH "/getstatus"
#define DEFAULT_INDEX_FILE "index.htm"
#if EanbleParasiteTempControl
#define ParasiteTempControlPath "/ptc"
#endif
#define GRAVITY_PATH "/gravity"
#define GravityDeviceConfigPath "/gdc"
#define GravityFormulaPath "/coeff"
#if SupportTiltHydrometer
#define TiltCommandPath "/tcmd"
#endif
#if AUTO_CAP
#define CAPPER_PATH "/cap"
#endif
#define WIFI_SCAN_PATH "/wifiscan"
#define WIFI_CONNECT_PATH "/wificon"
#define WIFI_DISC_PATH "/wifidisc"
#define MQTT_PATH "/mqtt"
#if SupportPressureTransducer
#define PRESSURE_PATH "/psi"
#endif
#define HUMIDITY_CONTROL_PATH "/rh"
const char *public_list[]={
"/bwf.js",
"/brewing.json"
};
const char *nocache_list[]={
"/brewing.json",
"/brewpi.cfg"
};
#if UseLittleFS
FS& FileSystem = LittleFS;
#else
FS& FileSystem =SPIFFS;
#endif
//*******************************************
String getContentType(String filename){
if(filename.endsWith(".htm")) return "text/html";
else if(filename.endsWith(".html")) return "text/html";
else if(filename.endsWith(".css")) return "text/css";
else if(filename.endsWith(".js")) return "application/javascript";
else if(filename.endsWith(".png")) return "image/png";
else if(filename.endsWith(".gif")) return "image/gif";
else if(filename.endsWith(".jpg")) return "image/jpeg";
else if(filename.endsWith(".ico")) return "image/x-icon";
else if(filename.endsWith(".xml")) return "text/xml";
else if(filename.endsWith(".pdf")) return "application/x-pdf";
else if(filename.endsWith(".zip")) return "application/x-zip";
else if(filename.endsWith(".gz")) return "application/x-gzip";
else if(filename.endsWith(".jgz")) return "application/javascript";
return "text/plain";
}
GravityTracker gravityTracker;
AsyncWebServer *webServer;
BrewPiProxy brewPi;
BrewKeeper brewKeeper([](const char* str){ brewPi.putLine(str);});
#ifdef ENABLE_LOGGING
DataLogger dataLogger;
#endif
#if UseServerSideEvent == true
AsyncEventSource sse(SSE_PATH);
#endif
extern const uint8_t* getEmbeddedFile(const char* filename,bool &gzip, unsigned int &size);
void requestRestart(bool disc);
void tiltScanResult(String& result);
void initTime(bool apmode)
{
/* if(apmode){
DBG_PRINTF("initTime in ap mode\n");
TimeKeeper.begin();
}else{
DBG_PRINTF("connect to Time server\n");
TimeKeeper.begin((char*)"time.google.com",(char*)"pool.ntp.org",(char*)"time.windows.com");
}
*/
TimeKeeper.begin((char*)"time.google.com",(char*)"pool.ntp.org",(char*)"time.windows.com");
}
#if AUTO_CAP
void capStatusReport(void);
#endif
class BrewPiWebHandler: public AsyncWebHandler
{
void handleFileList(AsyncWebServerRequest *request) {
if(request->hasParam("dir",true)){
String path = request->getParam("dir",true)->value();
#if defined(ESP32)
File dir = FileSystem.open(path);
String output = "[";
if(dir.isDirectory()){
File entry = dir.openNextFile();
while(entry){
if (output != "[") output += ',';
bool isDir = false;
output += "{\"type\":\"";
output += (isDir)?"dir":"file";
output += "\",\"name\":\"";
#if UseLittleFS
output += String(entry.name());
#else
output += String(entry.name()).substring(1);
#endif
output += "\"}";
entry.close();
entry = dir.openNextFile();
}
}
output += "]";
request->send(200, "text/json", output);
output = String();
#else
Dir dir = FileSystem.openDir(path);
path = String();
String output = "[";
while(dir.next()){
File entry = dir.openFile("r");
if (output != "[") output += ',';
bool isDir = false;
output += "{\"type\":\"";
output += (isDir)?"dir":"file";
output += "\",\"name\":\"";
#if UseLittleFS
output += String(entry.name());
#else
output += String(entry.name()).substring(1);
#endif
output += "\"}";
entry.close();
}
output += "]";
request->send(200, "text/json", output);
output = String();
#endif
}
else
request->send(400);
}
void handleFileDelete(AsyncWebServerRequest *request){
if(request->hasParam("path", true)){
#if !defined(ESP32)
ESP.wdtDisable();
#endif
FileSystem.remove(request->getParam("path", true)->value());
#if !defined(ESP32)
ESP.wdtEnable(10);
#endif
request->send(200, "", "DELETE: "+request->getParam("path", true)->value());
} else
request->send(404);
}
void handleFilePuts(AsyncWebServerRequest *request){
if(request->hasParam("path", true)
&& request->hasParam("content", true)){
#if !defined(ESP32)
ESP.wdtDisable();
#endif
String file=request->getParam("path", true)->value();
File fh= FileSystem.open(file, "w");
if(!fh){
request->send(500);
return;
}
String c=request->getParam("content", true)->value();
fh.print(c.c_str());
fh.close();
#if !defined(ESP32)
ESP.wdtEnable(10);
#endif
request->send(200,"application/json","{}");
DBG_PRINTF("fputs path=%s\n",file.c_str());
} else
request->send(404);
}
bool fileExists(String path)
{
if(FileSystem.exists(path)) return true;
bool dum;
unsigned int dum2;
if(getEmbeddedFile(path.c_str(),dum,dum2)) return true;
if(path.endsWith(CHART_LIB_PATH) && FileSystem.exists(CHART_LIB_PATH)) return true;
// safari workaround.
if(path.endsWith(".js")){
String pathWithJgz = path.substring(0,path.lastIndexOf('.')) + ".jgz";
//DBG_PRINTF("checking with:%s\n",pathWithJgz.c_str());
if(FileSystem.exists(pathWithJgz)) return true;
}
String pathWithGz = path + ".gz";
if(FileSystem.exists(pathWithGz)) return true;
return false;
}
void sendProgmem(AsyncWebServerRequest *request,const char* html,String contentType)
{
AsyncWebServerResponse *response = request->beginResponse(contentType,
strlen_P(html),
[=](uint8_t *buffer, size_t maxLen, size_t alreadySent) -> size_t {
if (strlen_P(html+alreadySent)>maxLen) {
memcpy_P((char*)buffer, html+alreadySent, maxLen);
return maxLen;
}
// Ok, last chunk
memcpy_P((char*)buffer, html+alreadySent, strlen_P(html+alreadySent));
return strlen_P(html+alreadySent); // Return from here to end of indexhtml
});
response->addHeader("Cache-Control","max-age=2592000");
request->send(response);
}
void sendFile(AsyncWebServerRequest *request,String path)
{
//workaround for safari
if(path.endsWith(".js")){
String pathWithJgz = path.substring(0,path.lastIndexOf('.')) + ".jgz";
if(FileSystem.exists(pathWithJgz)){
AsyncWebServerResponse * response = request->beginResponse(FileSystem, pathWithJgz,"application/javascript");
response->addHeader("Content-Encoding", "gzip");
response->addHeader("Cache-Control","max-age=2592000");
request->send(response);
return;
}
}
String pathWithGz = path + String(".gz");
if(FileSystem.exists(pathWithGz)){
#if 0
AsyncWebServerResponse * response = request->beginResponse(FileSystem, pathWithGz,getContentType(path));
// AsyncFileResonse will add "content-disposion" header, result in "download" of Safari, instead of "render"
#else
File file=FileSystem.open(pathWithGz,"r");
if(!file){
request->send(500);
return;
}
AsyncWebServerResponse * response = request->beginResponse(file, path,getContentType(path));
#endif
// response->addHeader("Content-Encoding", "gzip");
response->addHeader("Cache-Control","max-age=2592000");
request->send(response);
return;
}
if(FileSystem.exists(path)){
//request->send(FileSystem, path);
bool nocache=false;
for(byte i=0;i< sizeof(nocache_list)/sizeof(const char*);i++){
if(path.equals(nocache_list[i])){
nocache=true;
break;
}
}
AsyncWebServerResponse *response = request->beginResponse(FileSystem, path);
if(nocache)
response->addHeader("Cache-Control","no-cache");
else
response->addHeader("Cache-Control","max-age=2592000");
request->send(response);
return;
}
//else, embedded html file
bool gzip;
uint32_t size;
const uint8_t* file=getEmbeddedFile(path.c_str(),gzip,size);
if(file){
DBG_PRINTF("using embedded file:%s\n",path.c_str());
if(gzip){
#if defined(ESP32)
AsyncWebServerResponse *response = request->beginResponse("text/html", size,[=](uint8_t *buffer, size_t maxLen, size_t index) -> size_t {
//Write up to "maxLen" bytes into "buffer" and return the amount written.
//index equals the amount of bytes that have been already sent
//You will not be asked for more bytes once the content length has been reached.
//Keep in mind that you can not delay or yield waiting for more data!
//Send what you currently have and you will be asked for more again
memcpy(buffer,file + index, maxLen);
return maxLen;
});
#else
AsyncWebServerResponse *response = request->beginResponse_P(200, "text/html", file, size);
#endif
response->addHeader("Content-Encoding", "gzip");
request->send(response);
}else sendProgmem(request,(const char*)file,getContentType(path));
}
}
public:
BrewPiWebHandler(void){}
#if LegacyEspAsyncLibraries != true
virtual bool isRequestHandlerTrivial() override final {return false;}
#endif
void handleRequest(AsyncWebServerRequest *request){
SystemConfiguration *syscfg=theSettings.systemConfiguration();
#if UseServerSideEvent == true
if(request->method() == HTTP_GET && request->url() == POLLING_PATH) {
char *line=brewPi.getLastLine();
if(line[0]!=0) request->send(200, "text/plain", line);
else request->send(200, "text/plain;", "");
}
else if(request->method() == HTTP_POST && request->url() == PUTLINE_PATH){
String data=request->getParam("data", true, false)->value();
//DBG_PRINTF("putline:%s\n",data.c_str());
if(data.startsWith("j") && !request->authenticate((const char*)syscfg->username,(const char*) syscfg->password))
return request->requestAuthentication();
brewPi.putLine(data.c_str());
request->send(200,"application/json","{}");
}
else
#endif
#if SupportMqttRemoteControl
if(request->method() == HTTP_GET && request->url() == MQTT_PATH){
request->send(200,"application/json",theSettings.jsonMqttRemoteControlSettings());
}else if(request->method() == HTTP_POST && request->url() == MQTT_PATH){
if(!request->authenticate(syscfg->username, syscfg->password))
return request->requestAuthentication();
if(request->hasParam("data", true)){
if(theSettings.dejsonMqttRemoteControlSettings(request->getParam("data", true)->value())){
theSettings.save();
request->send(200,"application/json","{}");
mqttRemoteControl.reset();
}else{
request->send(500);
DBG_PRINTF("json format error\n");
return;
}
}else{
request->send(400);
DBG_PRINTF("no data in post\n");
}
}else
#endif
if(request->method() == HTTP_GET && request->url() == CONFIG_PATH){
if(!request->authenticate(syscfg->username, syscfg->password)) return request->requestAuthentication();
if(request->hasParam("cfg"))
request->send(200,"application/json",theSettings.jsonSystemConfiguration());
else
request->redirect(request->url() + ".htm");
}else if(request->method() == HTTP_POST && request->url() == CONFIG_PATH){
if(!request->authenticate(syscfg->username, syscfg->password))
return request->requestAuthentication();
if(request->hasParam("data", true)){
uint8_t oldMode = theSettings.systemConfiguration()->wifiMode;
DBG_PRINTF("config to save: %s\n",request->getParam("data", true)->value().c_str());
if(theSettings.dejsonSystemConfiguration(request->getParam("data", true)->value())){
theSettings.save();
DBG_PRINTF("config saved: %s\n",theSettings.systemConfiguration()->hostnetworkname);
request->send(200,"application/json","{}");
display.setAutoOffPeriod(theSettings.systemConfiguration()->backlite);
if(oldMode != theSettings.systemConfiguration()->wifiMode){
DBG_PRINTF("change from %d to %d\n",oldMode,theSettings.systemConfiguration()->wifiMode);
WiFiSetup.setMode((WiFiMode) (theSettings.systemConfiguration()->wifiMode));
}
if(!request->hasParam("nb")){
requestRestart(false);
}
}else{
request->send(500);
DBG_PRINTF("json format error\n");
return;
}
}else{
request->send(400);
DBG_PRINTF("no data in post\n");
}
}else if(request->method() == HTTP_GET && request->url() == TIME_PATH){
AsyncResponseStream *response = request->beginResponseStream("application/json");
response->printf("{\"t\":\"%s\",\"e\":%lu,\"o\":%d}",TimeKeeper.getDateTimeStr(),TimeKeeper.getTimeSeconds(),TimeKeeper.getTimezoneOffset());
request->send(response);
}else if(request->method() == HTTP_POST && request->url() == TIME_PATH){
if(request->hasParam("time", true)){
AsyncWebParameter* tvalue = request->getParam("time", true);
time_t time=(time_t)tvalue->value().toInt();
DBG_PRINTF("Set Time:%lu from:%s\n",time,tvalue->value().c_str());
TimeKeeper.setCurrentTime(time);
}
if(request->hasParam("off", true)){
AsyncWebParameter* tvalue = request->getParam("off", true);
DBG_PRINTF("Set timezone:%ld\n",tvalue->value().toInt());
TimeKeeper.setTimezoneOffset(tvalue->value().toInt());
}
request->send(200,"application/json","{}");
}else if(request->method() == HTTP_GET && request->url() == RESETWIFI_PATH){
if(!request->authenticate(syscfg->username, syscfg->password))
return request->requestAuthentication();
request->send(200,"text/html","Done, restarting..");
#if SaveWiFiConfiguration
WiFiConfiguration *wifiCon=theSettings.getWifiConfiguration();
wifiCon->ssid[0]='\0';
wifiCon->pass[0]='\0';
theSettings.save();
#endif
requestRestart(true);
}else if(request->method() == HTTP_POST && request->url() == FLIST_PATH){
if(!request->authenticate(syscfg->username, syscfg->password))
return request->requestAuthentication();
handleFileList(request);
}else if(request->method() == HTTP_DELETE && request->url() == DELETE_PATH){
if(!request->authenticate(syscfg->username, syscfg->password))
return request->requestAuthentication();
handleFileDelete(request);
}else if(request->method() == HTTP_POST && request->url() == FPUTS_PATH){
if(!request->authenticate(syscfg->username, syscfg->password))
return request->requestAuthentication();
handleFilePuts(request);
}else if(request->method() == HTTP_GET && request->url() == GETSTATUS_PATH){
uint8_t mode, state;
float beerSet, beerTemp, fridgeTemp, fridgeSet, roomTemp;
brewPi.getAllStatus(&state, &mode, &beerTemp, &beerSet, &fridgeTemp, &fridgeSet, &roomTemp);
#define TEMPorNull(a) (IS_FLOAT_TEMP_VALID(a)? String(a):String("null"))
String json=String("{\"mode\":\"") + String((char) mode)
+ String("\",\"state\":") + String(state)
+ String(",\"beerSet\":") + TEMPorNull(beerSet)
+ String(",\"beerTemp\":") + TEMPorNull(beerTemp)
+ String(",\"fridgeSet\":") + TEMPorNull(fridgeSet)
+ String(",\"fridgeTemp\":") + TEMPorNull(fridgeTemp)
+ String(",\"roomTemp\":") + TEMPorNull(roomTemp)
+String("}");
request->send(200,"application/json",json);
}
#ifdef ENABLE_LOGGING
else if (request->url() == LOGGING_PATH){
if(request->method() == HTTP_POST){
if(!request->authenticate(syscfg->username, syscfg->password)) return request->requestAuthentication();
if(request->hasParam("data", true)){
if(theSettings.dejsonRemoteLogging(request->getParam("data", true)->value())){
request->send(200,"application/json","{}");
theSettings.save();
}else{
request->send(401);
}
} else{
request->send(404);
}
}else{
if(request->hasParam("data")){
request->send(200,"application/json",theSettings.jsonRemoteLogging());
}else{
request->redirect(request->url() + ".htm");
}
}
}
#endif
#if EanbleParasiteTempControl
else if(request->url() == ParasiteTempControlPath){
if(request->method() == HTTP_POST){
if(request->hasParam("c", true)){
String content=request->getParam("c", true)->value();
if(parasiteTempController.updateSettings(content))
request->send(200,"application/json","{}");
else
request->send(400);
} else
request->send(404);
}else{
String status=parasiteTempController.getSettings();
request->send(200,"application/json",status);
}
}
#endif
#if AUTO_CAP
else if(request->url() == CAPPER_PATH){
if(!request->authenticate(syscfg->username, syscfg->password))
return request->requestAuthentication();
// auto cap.
if(request->hasParam("psi")){
theSettings.pressureMonitorSettings()->psi=request->getParam("psi")->value().toInt();
DBG_PRINTF("set pressure:%d",theSettings.pressureMonitorSettings()->psi);
theSettings.save();
PressureMonitor.configChanged();
}
bool response=true;
if(request->hasParam("cap")){
AsyncWebParameter* value = request->getParam("cap");
autoCapControl.capManualSet(value->value().toInt()!=0);
// manual
}else if(request->hasParam("at")){
// time
AsyncWebParameter* value = request->getParam("at");
autoCapControl.capAtTime(value->value().toInt());
}else if(request->hasParam("sg")){
// gravity
AsyncWebParameter* value = request->getParam("sg");
autoCapControl.catOnGravity(value->value().toFloat());
}else{
request->send(400);
response=false;
}
if(response) request->send(200,"application/json","{}");
capStatusReport();
}
#endif
#if SupportPressureTransducer
else if(request->url() == PRESSURE_PATH){
if(!request->authenticate(syscfg->username, syscfg->password))
return request->requestAuthentication();
if(request->method() == HTTP_GET){
if(request->hasParam("r")){
int reading=PressureMonitor.currentAdcReading();
request->send(200,"application/json",String("{\"a0\":")+String(reading)+String("}"));
}else{
request->send(200,"application/json",theSettings.jsonPressureMonitorSettings());
}
}else{
// post
if(!request->authenticate(syscfg->username, syscfg->password)) return request->requestAuthentication();
if(request->hasParam("data",true)){
if(theSettings.dejsonPressureMonitorSettings(request->getParam("data",true)->value())){
theSettings.save();
PressureMonitor.configChanged();
request->send(200,"application/json","{}");
}else
DBG_PRINTF("invalid Json\n");
request->send(402);
}else{
DBG_PRINTF("no data\n");
request->send(401);
}
}
}
#endif
#if EnableDHTSensorSupport
else if(request->url() == HUMIDITY_CONTROL_PATH){
if(request->hasParam("m",true) && request->hasParam("t",true) ){
uint8_t mode=(uint8_t) request->getParam("m",true)->value().toInt();
uint8_t target=(uint8_t) request->getParam("t",true)->value().toInt();
humidityControl.setMode(mode);
humidityControl.setTarget(target);
theSettings.save();
request->send(200,"application/json","{}");
}else{
request->send(404);
DBG_PRINTF("missing parameter:m =%d, t=%d\n",request->hasParam("m",true), request->hasParam("t",true) );
}
}
#endif
else if(request->url() == BEER_PROFILE_PATH){
if(request->method() == HTTP_GET){
request->send(200,"application/json",theSettings.jsonBeerProfile());
}else{ //if(request->method() == HTTP_POST){
if(!request->authenticate(syscfg->username, syscfg->password)) return request->requestAuthentication();
if(request->hasParam("data",true)){
if(theSettings.dejsonBeerProfile(request->getParam("data",true)->value())){
theSettings.save();
brewKeeper.profileUpdated();
request->send(200,"application/json","{}");
}else
request->send(402);
}else{
request->send(401);
}
}
}else if(request->method() == HTTP_GET){
String path=request->url();
if(path.endsWith("/")) path +=DEFAULT_INDEX_FILE;
else if(path.endsWith(CHART_LIB_PATH)) path = CHART_LIB_PATH;
if(request->url().equals("/")){
SystemConfiguration *syscfg=theSettings.systemConfiguration();
if(!syscfg->passwordLcd){
sendFile(request,path); //request->send(FileSystem, path);
return;
}
}
/*
bool auth=true;
for(byte i=0;i< sizeof(public_list)/sizeof(const char*);i++){
if(path.equals(public_list[i])){
auth=false;
break;
}
}
*/
if(syscfg->passwordLcd && !request->authenticate(syscfg->username, syscfg->password))
return request->requestAuthentication();
sendFile(request,path); //request->send(FileSystem, path);
}
}
bool canHandle(AsyncWebServerRequest *request){
if(request->method() == HTTP_GET){
if( request->url() == CONFIG_PATH || request->url() == TIME_PATH
#if UseServerSideEvent == true
|| request->url() == POLLING_PATH
#endif
|| request->url() == RESETWIFI_PATH
|| request->url() == GETSTATUS_PATH
|| request->url() == BEER_PROFILE_PATH
|| request->url() == MQTT_PATH
#ifdef ENABLE_LOGGING
|| request->url() == LOGGING_PATH
#endif
#if EanbleParasiteTempControl
|| request->url() == ParasiteTempControlPath
#endif
#if AUTO_CAP
|| request->url() == CAPPER_PATH
#endif
#if SupportPressureTransducer
|| request->url() == PRESSURE_PATH
#endif
){
return true;
}else{
// get file
String path=request->url();
if(path.endsWith("/")) path +=DEFAULT_INDEX_FILE;
//DBG_PRINTF("request:%s\n",path.c_str());
if(fileExists(path)) return true; //if(FileSystem.exists(path)) return true;
//DBG_PRINTF("request:%s not found\n",path.c_str());
}
}else if(request->method() == HTTP_DELETE && request->url() == DELETE_PATH){
return true;
}else if(request->method() == HTTP_POST){
if(
#if UseServerSideEvent == true
request->url() == PUTLINE_PATH ||
#endif
request->url() == CONFIG_PATH
|| request->url() == FPUTS_PATH || request->url() == FLIST_PATH
|| request->url() == TIME_PATH
|| request->url() == BEER_PROFILE_PATH
|| request->url() == MQTT_PATH
#ifdef ENABLE_LOGGING
|| request->url() == LOGGING_PATH
#endif
#if EanbleParasiteTempControl
|| request->url() == ParasiteTempControlPath
#endif
#if SupportPressureTransducer
|| request->url() == PRESSURE_PATH
#endif
#if EnableDHTSensorSupport
|| request->url() == HUMIDITY_CONTROL_PATH
#endif
)
return true;
}
return false;
}
};
BrewPiWebHandler brewPiWebHandler;
#if ResponseAppleCNA == true
class AppleCNAHandler: public AsyncWebHandler
{
public:
AppleCNAHandler(){}
void handleRequest(AsyncWebServerRequest *request){
request->send(200, "text/html", "<HTML><HEAD><TITLE>Success</TITLE></HEAD><BODY>Success</BODY></HTML>");
}
bool canHandle(AsyncWebServerRequest *request){
String host=request->host();
//DBG_PRINTF("Request host:");
//DBG_PRINTF(host.c_str());
//DBG_PRINTF("\n");
if(host.indexOf(String("apple")) >=0
|| host.indexOf(String("itools")) >=0
|| host.indexOf(String("ibook")) >=0
|| host.indexOf(String("airport")) >=0
|| host.indexOf(String("thinkdifferent")) >=0
|| host.indexOf(String("akamai")) >=0 ){
return true;
}
return false;
}
};
AppleCNAHandler appleCNAHandler;
#endif //#if ResponseAppleCNA == true
#if AUTO_CAP
void capControlStatusJson(JsonObject& obj){
uint8_t mode=autoCapControl.mode();
obj["m"] = mode;
obj["c"] = autoCapControl.isCapOn()? 1:0;
if(mode == AutoCapModeGravity){
obj["g"]=autoCapControl.targetGravity();
}else if (mode ==AutoCapModeTime){
obj["t"]=autoCapControl.targetTime();
}
#if SupportPressureTransducer
PressureMonitorSettings* ps=theSettings.pressureMonitorSettings();
if(ps->mode == PMModeControl){
obj["pm"]=2;
obj["psi"]= ps->psi;
}
#endif
}
void stringAvailable(const char*);
void capStatusReport(void)
{
DynamicJsonDocument doc(1024);
JsonObject cap = doc.createNestedObject("cap");
capControlStatusJson(cap);
String out="A:";
serializeJson(doc,out);
stringAvailable(out.c_str());
}
#endif
void greeting(std::function<void(const char*)> sendFunc)
{
char buf[512];
// gravity related info., starting from "G"
if(externalData.gravityDeviceEnabled()){
externalData.sseNotify(buf);
sendFunc(buf);
}
// misc informatoin, including
// RSSI &&
const char *logname= brewLogger.currentLog();
if(logname == NULL) logname="";
SystemConfiguration *syscfg= theSettings.systemConfiguration();
DynamicJsonDocument doc(1024);
doc["nn"] = String(syscfg->titlelabel);
doc["ver"] = String(BPL_VERSION);
doc["rssi"]= WiFi.RSSI();
doc["tm"] = TimeKeeper.getTimeSeconds();
doc["off"]= TimeKeeper.getTimezoneOffset();
doc["log"] = String(logname);
#if AUTO_CAP
JsonObject cap = doc.createNestedObject("cap");
capControlStatusJson(cap);
#endif
#if EanbleParasiteTempControl
doc["ptc"]= serialized(parasiteTempController.getSettings());
#endif
#if EnableDHTSensorSupport
JsonObject hum = doc.createNestedObject("rh");
hum["m"] = humidityControl.mode();
hum["t"] = humidityControl.targetRH();
#endif
String out="A:";
serializeJson(doc,out);
sendFunc(out.c_str());
// beer profile:
String profile=String("B:") + theSettings.jsonBeerProfile();
sendFunc(profile.c_str());
//network status:
String nwstatus=String("W:") + WiFiSetup.status();
sendFunc(nwstatus.c_str());
}
#define GreetingInMainLoop 1
#if UseWebSocket == true
class AWSClient{
uint32_t _clientId;
public:
AWSClient(AsyncWebSocketClient* client){
_clientId=client->id();
}
void text(AsyncWebSocket *websocket,const char* msg){
websocket->text(_clientId,msg);
}
uint32_t clientId(void){ return _clientId; }
};
AsyncWebSocket ws(WS_PATH);
#if GreetingInMainLoop
AsyncWebSocketClient * _lastWSclient=NULL;
void sayHelloWS()
{
if(! _lastWSclient) return;
greeting([=](const char* msg){
_lastWSclient->text(msg);
});