-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWifinfo.ino
More file actions
1210 lines (1047 loc) · 32.3 KB
/
Wifinfo.ino
File metadata and controls
1210 lines (1047 loc) · 32.3 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
// **********************************************************************************
// ESP8266 Teleinfo WEB Server
// **********************************************************************************
// Creative Commons Attrib Share-Alike License
// You are free to use/extend this library but please abide with the CC-BY-SA license:
// Attribution-NonCommercial-ShareAlike 4.0 International License
// http://creativecommons.org/licenses/by-nc-sa/4.0/
//
// For any explanation about teleinfo ou use , see my blog
// http://hallard.me/category/tinfo
//
// This program works with the Wifinfo board
// see schematic here https://github.com/hallard/teleinfo/tree/master/Wifinfo
//
// Written by Charles-Henri Hallard (http://hallard.me)
//
// History : V1.00 2015-06-14 - First release
//
// All text above must be included in any redistribution.
//
// Modifié par Dominique DAMBRAIN 2017-07-10 (http://www.dambrain.fr)
// Version 1.0.5
// Librairie LibTeleInfo : Allocation statique d'un tableau de stockage
// des variables (50 entrées) afin de proscrire les malloc/free
// pour éviter les altérations des noms & valeurs
// Modification en conséquence des séquences de scanning du tableau
// ATTENTION : Nécessite probablement un ESP-8266 type Wemos D1,
// car les variables globales occupent 42.284 octets
//
// Version 1.0.5a (11/01/2018)
// Permettre la mise à jour OTA à partir de fichiers .ino.bin (Auduino IDE 1.8.3)
// Ajout de la gestion d'un switch (Contact sec) relié à GND et D5 (GPIO-14)
// Décommenter le #define SENSOR dans Wifinfo.h
// Pour être utilisable avec Domoticz, au moins l'URL du serveur et le port
// doivent être renseignés dans la configuration HTTP Request, ainsi que
// l'index du switch (déclaré dans Domoticz)
// L'état du switch (On/Off) est envoyé à Domoticz au boot, et à chaque
// changement d'état
// Note : Nécessité de flasher le SPIFFS pour pouvoir configurer l'IDX du switch
// et flasher le sketch winfinfo.ino.bin via interface Web
// Rendre possible la compilation si define SENSOR en commentaire
// et DEFINE_DEBUG en commentaire (aucun debug, version Production...)
//
// Version 1.0.6 (04/02/2018) Branche 'syslog' du github
// Ajout de la fonctionnalité 'Remote Syslog'
// Pour utiliser un serveur du réseau comme collecteur des messages Debug
// Note : Nécessité de flasher le SPIFFS pour pouvoir configurer le remote syslog
// Affichage des options de compilation sélectionnées dans l'onglet 'Système'
// et au début du Debug + syslog éventuels
// **********************************************************************************
// Include Arduino header
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <Syslog.h>
#include <ArduinoOTA.h>
#include <EEPROM.h>
#include <Ticker.h>
//#include <WebSocketsServer.h>
//#include <Hash.h>
#include <NeoPixelBus.h>
#include <LibTeleinfo.h>
#include <FS.h>
#include <SPI.h>
// Global project file
#include "Wifinfo.h"
//WiFiManager wifi(0);
ESP8266WebServer server(80);
bool ota_blink;
char optval[48];
// Teleinfo
TInfo tinfo;
// RGB Led
#ifdef RGB_LED_PIN
//NeoPixelBus rgb_led = NeoPixelBus(1, RGB_LED_PIN, NEO_RGB | NEO_KHZ800);
//NeoPixelBus<NeoGrbFeature, NeoEsp8266BitBang800KbpsMethod> rgb_led(1, RGB_LED_PIN);
NeoPixelBus<NeoRgbFeature, NeoEsp8266BitBang800KbpsMethod> rgb_led(1, RGB_LED_PIN);
#endif
// define whole brigtness level for RGBLED (50%)
uint8_t rgb_brightness = 50;
// LED Blink timers
Ticker rgb_ticker;
Ticker blu_ticker;
Ticker red_ticker;
Ticker Every_1_Sec;
Ticker Tick_emoncms;
Ticker Tick_jeedom;
Ticker Tick_httpRequest;
volatile boolean task_1_sec = false;
volatile boolean task_emoncms = false;
volatile boolean task_jeedom = false;
volatile boolean task_httpRequest = false;
volatile boolean task_updsw = false;
unsigned long seconds = 0;
char buff[132]; //To format debug strings
// sysinfo data
_sysinfo sysinfo;
#ifdef SYSLOG
WiFiUDP udpClient;
Syslog syslog(udpClient, SYSLOG_PROTO_IETF);
#endif
// count Wifi connect attempts, to check stability
int nb_reconnect = 0;
bool need_reinit = false;
unsigned int nb_reinit = 0;
bool first_info_call=true;
#ifdef SIMU
//for tests
uint8_t flags = 8;
int loop_cpt = 60000;
String name2 = "HCHC";
char * s2 = (char *)name2.c_str();
String value2 = "000060000";
char * v2 = (char *) value2.c_str();
#endif
#ifdef SENSOR
// Le contact sec devra etre connecte entre GND et D5 (GPIO-14)
const int SensorPin = 14;
int reading ;
int SwitchState = -1; // the current reading from the input pin
int lastSwitchState = -1; // the previous reading from the input pin
unsigned long lastChangeTime = 0; // the last time the input pin was toggled
unsigned long tempo = 200; // temps necessaire a la stabilisation du switch (0,2 seconde)
#endif
/////////////////////////// uniquement si DEBUG ou SYSLOG //////////
#ifdef MACRO
// Versions polymorphes des appels au debugging
// non liées au port Serial ou Serial1
char logbuffer[255];
#ifdef SYSLOG
char waitbuffer[255];
char *lines[50];
int in=-1;
int out=-1;
#endif
unsigned int pending = 0 ;
volatile boolean SYSLOGusable=false;
volatile boolean SYSLOGselected=false;
int plog=0;
FS* _fs; //Pointeur objet File System
void convert(const __FlashStringHelper *ifsh)
{
PGM_P p = reinterpret_cast<PGM_P>(ifsh);
plog=0;
while (1) {
unsigned char c = pgm_read_byte(p++);
if (c == 0) {
logbuffer[plog]=0;
break;
}
logbuffer[plog]=c;
plog++;
}
}
#ifdef SYSLOG
void process_line(char *msg) {
strcat(waitbuffer,msg);
pending=strlen(waitbuffer);
if( waitbuffer[pending-1] == 0x0D || waitbuffer[pending-1] == 0x0A) {
//Cette ligne est complete : l'envoyer !
for(int i=0; i < pending-1; i++) {
if(waitbuffer[i] <= 0x20)
waitbuffer[i] = 0x20;
}
syslog.log(LOG_INFO,waitbuffer);
delay(2*pending);
memset(waitbuffer,0,255);
pending=0;
}
}
#endif
// Toutes les fonctions aboutissent sur la suivante :
void Myprint(char *msg) {
#ifdef DEBUG
DEBUG_SERIAL.print(msg);
#endif
#ifdef SYSLOG
if( SYSLOGusable ) {
process_line(msg);
} else if ( SYSLOGselected) {
//syslog non encore disponible
//stocker les messages à envoyer plus tard
in++;
if(in >= 50) {
//table saturée !
in=0;
}
if(lines[in]) {
//entrée occupée : l'écraser, tant pis !
free(lines[in]);
}
lines[in]=(char *)malloc(strlen(msg)+2);
memset(lines[in],0,strlen(msg+1));
strcpy(lines[in],msg);
}
#endif
}
void Myprint() {
logbuffer[0] = 0;
Myprint(logbuffer);
}
void Myprint(String msg) {
sprintf(logbuffer,"%s",msg.c_str());
Myprint(logbuffer);
}
void Myprint(const __FlashStringHelper *msg) {
convert(msg);
Myprint(logbuffer);
}
void Myprint(long i) {
sprintf(logbuffer,"%ld", i);
Myprint(logbuffer);
}
void Myprint(unsigned int i) {
sprintf(logbuffer,"%d", i);
Myprint(logbuffer);
}
void Myprint(int i) {
sprintf(logbuffer,"%d", i);
Myprint(logbuffer);
}
void Myprintln() {
sprintf(logbuffer,"\n");
Myprint(logbuffer);
}
void Myprintln(unsigned char *msg) {
sprintf(logbuffer,"%s\n",msg);
Myprint(logbuffer);
}
void Myprintln(String msg) {
sprintf(logbuffer,"%s\n",msg.c_str());
Myprint(logbuffer);
}
void Myprintln(const __FlashStringHelper *msg) {
convert(msg);
logbuffer[plog]=(char)'\n';
logbuffer[plog+1]=0;
Myprint(logbuffer);
}
void Myprintln(long i) {
sprintf((char *)logbuffer,"%ld\n", i);
Myprint(logbuffer);
}
void Myprintln(unsigned int i) {
sprintf(logbuffer,"%d\n", i);
Myprint(logbuffer);
}
void Myprintln(int i) {
sprintf(logbuffer,"%d\n", i);
Myprint(logbuffer);
}
void Myflush() {
}
#endif //MACRO
/////////////////////////////////////////////////////////////////////////
/* ======================================================================
Function: UpdateSysinfo
Purpose : update sysinfo variables
Input : true if first call
true if needed to print on serial debug
Output : -
Comments: -
====================================================================== */
void UpdateSysinfo(boolean first_call, boolean show_debug)
{
char buff[64];
int32_t adc;
int sec = seconds;
int min = sec / 60;
int hr = min / 60;
long day = hr / 24;
sprintf_P( buff, PSTR("%ld days %02d h %02d m %02d sec"),day, hr % 24, min % 60, sec % 60);
sysinfo.sys_uptime = buff;
}
/* ======================================================================
Function: Task_1_Sec
Purpose : update our second ticker
Input : -
Output : -
Comments: -
====================================================================== */
void Task_1_Sec()
{
task_1_sec = true;
seconds++;
}
/* ======================================================================
Function: Task_emoncms
Purpose : callback of emoncms ticker
Input :
Output : -
Comments: Like an Interrupt, need to be short, we set flag for main loop
====================================================================== */
void Task_emoncms()
{
task_emoncms = true;
}
/* ======================================================================
Function: Task_jeedom
Purpose : callback of jeedom ticker
Input :
Output : -
Comments: Like an Interrupt, need to be short, we set flag for main loop
====================================================================== */
void Task_jeedom()
{
task_jeedom = true;
}
/* ======================================================================
Function: Task_httpRequest
Purpose : callback of http request ticker
Input :
Output : -
Comments: Like an Interrupt, need to be short, we set flag for main loop
====================================================================== */
void Task_httpRequest()
{
task_httpRequest = true;
}
/* ======================================================================
Function: LedOff
Purpose : callback called after led blink delay
Input : led (defined in term of PIN)
Output : -
Comments: -
====================================================================== */
void LedOff(int led)
{
#ifdef BLU_LED_PIN
if (led==BLU_LED_PIN)
LedBluOFF();
#endif
if (led==RED_LED_PIN)
LedRedOFF();
if (led==RGB_LED_PIN)
LedRGBOFF();
}
// Light off the RGB LED
#ifdef RGB_LED_PIN
/* ======================================================================
Function: LedRGBON
Purpose : Light RGB Led with HSB value
Input : Hue (0..255)
Saturation (0..255)
Brightness (0..255)
Output : -
Comments:
====================================================================== */
void LedRGBON (uint16_t hue)
{
if (config.config & CFG_RGB_LED) {
// Convert to neoPixel API values
// H (is color from 0..360) should be between 0.0 and 1.0
// L (is brightness from 0..100) should be between 0.0 and 0.5
RgbColor target = HslColor( hue / 360.0f, 1.0f, rgb_brightness * 0.005f );
// Set RGB Led
rgb_led.SetPixelColor(0, target);
rgb_led.Show();
}
}
/* ======================================================================
Function: LedRGBOFF
Purpose : light off the RGN LED
Input : -
Output : -
Comments: -
====================================================================== */
//void LedOff(int led)
void LedRGBOFF(void)
{
if (config.config & CFG_RGB_LED) {
rgb_led.SetPixelColor(0,RgbColor(0));
rgb_led.Show();
}
}
#endif
/* ======================================================================
Function: ADPSCallback
Purpose : called by library when we detected a ADPS on any phased
Input : phase number
0 for ADPS (monophase)
1 for ADIR1 triphase
2 for ADIR2 triphase
3 for ADIR3 triphase
Output : -
Comments: should have been initialised in the main sketch with a
tinfo.attachADPSCallback(ADPSCallback())
====================================================================== */
void ADPSCallback(uint8_t phase)
{
// Monophasé
if (phase == 0 ) {
Debugln(F("ADPS"));
} else {
Debug(F("ADPS Phase "));
Debugln('0' + phase);
}
}
/* ======================================================================
Function: DataCallback
Purpose : callback when we detected new or modified data received
Input : linked list pointer on the concerned data
value current state being TINFO_VALUE_ADDED/TINFO_VALUE_UPDATED
Output : -
Comments: -
====================================================================== */
void DataCallback(ValueList * me, uint8_t flags)
{
// This is for simulating ADPS during my tests
// ===========================================
/*
static uint8_t test = 0;
// Each new/updated values
if (++test >= 20) {
test=0;
uint8_t anotherflag = TINFO_FLAGS_NONE;
ValueList * anotherme = tinfo.addCustomValue("ADPS", "46", &anotherflag);
// Do our job (mainly debug)
DataCallback(anotherme, anotherflag);
}
Debugf("%02d:",test);
*/
// ===========================================
/*
// Do whatever you want there
Debug(me->name);
Debug('=');
Debug(me->value);
if ( flags & TINFO_FLAGS_NOTHING ) Debug(F(" Nothing"));
if ( flags & TINFO_FLAGS_ADDED ) Debug(F(" Added"));
if ( flags & TINFO_FLAGS_UPDATED ) Debug(F(" Updated"));
if ( flags & TINFO_FLAGS_EXIST ) Debug(F(" Exist"));
if ( flags & TINFO_FLAGS_ALERT ) Debug(F(" Alert"));
Debugln();
*/
}
/* ======================================================================
Function: NewFrame
Purpose : callback when we received a complete teleinfo frame
Input : linked list pointer on the concerned data
Output : -
Comments: -
====================================================================== */
void NewFrame(ValueList * me)
{
// Light the RGB LED
if ( config.config & CFG_RGB_LED) {
LedRGBON(COLOR_GREEN);
// led off after delay
rgb_ticker.once_ms( (uint32_t) BLINK_LED_MS, LedOff, (int) RGB_LED_PIN);
}
Debugln("NewFrame received");
}
/* ======================================================================
Function: NewFrame
Purpose : callback when we received a complete teleinfo frame
Input : linked list pointer on the concerned data
Output : -
Comments: it's called only if one data in the frame is different than
the previous frame
====================================================================== */
void UpdatedFrame(ValueList * me)
{
// Light the RGB LED (purple)
if ( config.config & CFG_RGB_LED) {
LedRGBON(COLOR_MAGENTA);
// led off after delay
rgb_ticker.once_ms(BLINK_LED_MS, LedOff, RGB_LED_PIN);
}
Debugln("UpdatedFrame received");
/*
// Got at least one ?
if (me) {
WiFiUDP myudp;
IPAddress ip = WiFi.localIP();
// start UDP server
myudp.begin(1201);
ip[3] = 255;
// transmit broadcast package
myudp.beginPacket(ip, 1201);
// start of frame
myudp.write(TINFO_STX);
// Loop thru the node
while (me->next) {
me = me->next;
// prepare line and write it
sprintf_P( buff, PSTR("%s %s %c\n"),me->name, me->value, me->checksum );
myudp.write( buff);
}
// End of frame
myudp.write(TINFO_ETX);
myudp.endPacket();
myudp.flush();
}
*/
}
/* ======================================================================
Function: ResetConfig
Purpose : Set configuration to default values
Input : -
Output : -
Comments: -
====================================================================== */
void ResetConfig(void)
{
// Start cleaning all that stuff
memset(&config, 0, sizeof(_Config));
// Set default Hostname
sprintf_P(config.host, PSTR("WifInfo-%06X"), ESP.getChipId());
strcpy_P(config.ota_auth, PSTR(DEFAULT_OTA_AUTH));
config.ota_port = DEFAULT_OTA_PORT ;
// Add other init default config here
// Emoncms
strcpy_P(config.emoncms.host, CFG_EMON_DEFAULT_HOST);
config.emoncms.port = CFG_EMON_DEFAULT_PORT;
strcpy_P(config.emoncms.url, CFG_EMON_DEFAULT_URL);
// Jeedom
strcpy_P(config.jeedom.host, CFG_JDOM_DEFAULT_HOST);
config.jeedom.port = CFG_JDOM_DEFAULT_PORT;
strcpy_P(config.jeedom.url, CFG_JDOM_DEFAULT_URL);
//strcpy_P(config.jeedom.adco, CFG_JDOM_DEFAULT_ADCO);
// HTTP Request
strcpy_P(config.httpReq.host, CFG_HTTPREQ_DEFAULT_HOST);
config.httpReq.port = CFG_HTTPREQ_DEFAULT_PORT;
strcpy_P(config.httpReq.path, CFG_HTTPREQ_DEFAULT_PATH);
config.config |= CFG_RGB_LED;
// save back
saveConfig();
}
/* ======================================================================
Function: WifiHandleConn
Purpose : Handle Wifi connection / reconnection and OTA updates
Input : setup true if we're called 1st Time from setup
Output : state of the wifi status
Comments: -
====================================================================== */
int WifiHandleConn(boolean setup = false)
{
int ret = WiFi.status();
char toprint[20];
IPAddress ad;
if (setup) {
#ifdef DEBUG
DebuglnF("========== WiFi diags start");
WiFi.printDiag(DEBUG_SERIAL);
DebuglnF("========== WiFi diags end");
Debugflush();
#endif
// no correct SSID
if (!*config.ssid) {
DebugF("no Wifi SSID in config, trying to get SDK ones...");
// Let's see of SDK one is okay
if ( WiFi.SSID() == "" ) {
DebuglnF("Not found may be blank chip!");
} else {
*config.psk = '\0';
// Copy SDK SSID
strcpy(config.ssid, WiFi.SSID().c_str());
// Copy SDK password if any
if (WiFi.psk() != "")
strcpy(config.psk, WiFi.psk().c_str());
DebuglnF("found one!");
// save back new config
saveConfig();
}
}
// correct SSID
if (*config.ssid) {
uint8_t timeout ;
DebugF("Connecting to: ");
Debug(config.ssid);
Debugflush();
// Do wa have a PSK ?
if (*config.psk) {
// protected network
Debug(F(" with key '"));
Debug(config.psk);
Debug(F("'..."));
Debugflush();
WiFi.begin(config.ssid, config.psk);
} else {
// Open network
Debug(F("unsecure AP"));
Debugflush();
WiFi.begin(config.ssid);
}
timeout = 50; // 50 * 200 ms = 5 sec time out
// 200 ms loop
while ( ((ret = WiFi.status()) != WL_CONNECTED) && timeout )
{
// Orange LED
LedRGBON(COLOR_ORANGE);
delay(50);
LedRGBOFF();
delay(150);
--timeout;
}
}
// connected ? disable AP, client mode only
if (ret == WL_CONNECTED)
{
nb_reconnect++; // increase reconnections count
DebuglnF("connected!");
WiFi.mode(WIFI_STA);
ad = WiFi.localIP();
sprintf(toprint,"%d.%d.%d.%d", ad[0],ad[1],ad[2],ad[3]);
DebugF("IP address : "); Debugln(toprint);
DebugF("MAC address : "); Debugln(WiFi.macAddress());
#ifdef SYSLOG
if (*config.syslog_host) {
SYSLOGselected=true;
// Create a new syslog instance with LOG_KERN facility
syslog.server(config.syslog_host, config.syslog_port);
syslog.deviceHostname(config.host);
syslog.appName(APP_NAME);
syslog.defaultPriority(LOG_KERN);
memset(waitbuffer,0,255);
pending=0;
SYSLOGusable=true;
} else {
SYSLOGusable=false;
SYSLOGselected=false;
}
#endif
// not connected ? start AP
} else {
char ap_ssid[32];
DebuglnF("Error!");
Debugflush();
// STA+AP Mode without connected to STA, autoconnect will search
// other frequencies while trying to connect, this is causing issue
// to AP mode, so disconnect will avoid this
// Disable auto retry search channel
WiFi.disconnect();
// SSID = hostname
strcpy(ap_ssid, config.host );
DebugF("Switching to AP ");
Debugln(ap_ssid);
Debugflush();
// protected network
if (*config.ap_psk) {
DebugF(" with key '");
Debug(config.ap_psk);
DebuglnF("'");
WiFi.softAP(ap_ssid, config.ap_psk);
// Open network
} else {
DebuglnF(" with no password");
WiFi.softAP(ap_ssid);
}
WiFi.mode(WIFI_AP_STA);
DebugF("IP address : "); Debugln(WiFi.softAPIP());
DebugF("MAC address : "); Debugln(WiFi.softAPmacAddress());
}
// Set OTA parameters
ArduinoOTA.setPort(config.ota_port);
ArduinoOTA.setHostname(config.host);
ArduinoOTA.setPassword(config.ota_auth);
ArduinoOTA.begin();
// just in case your sketch sucks, keep update OTA Available
// Trust me, when coding and testing it happens, this could save
// the need to connect FTDI to reflash
// Usefull just after 1st connexion when called from setup() before
// launching potentially buggy main()
for (uint8_t i=0; i<= 10; i++) {
LedRGBON(COLOR_MAGENTA);
delay(100);
LedRGBOFF();
delay(200);
ArduinoOTA.handle();
}
} // if setup
return WiFi.status();
}
/* ======================================================================
Function: setup
Purpose : Setup I/O and other one time startup stuff
Input : -
Output : -
Comments: -
====================================================================== */
void setup() {
boolean reset_config = true;
// Set CPU speed to 160MHz
system_update_cpu_freq(160);
#ifdef SYSLOG
SYSLOGselected=true; //Par défaut, au moins stocker les premiers msg debug
SYSLOGusable=false; //Tant que non connecté, ne pas émettre sur réseau
#endif
memset(optval,0,48);
#ifdef SIMU
strcat(optval,"SIMU, ");
#else
strcat(optval, "No SIMU, ");
#endif
#ifdef DEBUG
strcat(optval,"DEBUG, ");
#else
strcat(optval, "No DEBUG, ");
#endif
#ifdef SYSLOG
strcat(optval,"SYSLOG, ");
#else
strcat(optval, "No SYSLOG, ");
#endif
#ifdef SENSOR
strcat(optval,"SENSOR");
#else
strcat(optval, "No SENSOR");
#endif
#ifdef DEBUG
DEBUG_SERIAL.begin(115200);
#endif
#ifdef SYSLOG
for(int i=0; i<50; i++)
lines[i]=0;
in=-1;
out=-1;
#endif
// Teleinfo is connected to RXD2 (GPIO13 or D7) to
// avoid conflict when flashing, this is why
// we swap RXD1/TXD1 to RXD2/TXD2
// Note that TXD2 is not used : teleinfo is "receive only"
#ifdef DEBUG_SERIAL1
Serial.begin(1200, SERIAL_7E1);
Serial.swap();
Debugln("Sortie Debug sur D4 (TXD2), entrée Teleinfo sur D7 (RXD1)");
#else
Debugln("Sortie Debug sur Serial (TXD1), pas de Teleinfo possible");
#endif
// Init the RGB Led, and set it off
rgb_led.Begin();
LedRGBOFF();
Debugln(F("=============="));
Debug(F("WifInfo V"));
Debugln(F(WIFINFO_VERSION));
Debug(F("Options : "));
Debugln(optval);
Debugln();
// Clear our global flags
config.config = 0;
// Our configuration is stored into EEPROM
//EEPROM.begin(sizeof(_Config));
EEPROM.begin(1024);
DebugF("Config size="); Debug(sizeof(_Config));
DebugF(" (emoncms="); Debug(sizeof(_emoncms));
DebugF(" jeedom="); Debug(sizeof(_jeedom));
DebugF(" http request="); Debug(sizeof(_httpRequest));
Debugln(" )");
// Debugflush();
// Read Configuration from EEP
if (readConfig()) {
DebuglnF("Good CRC, not set! From now, we can use EEPROM config !");
} else {
// Reset Configuration
ResetConfig();
// save back
saveConfig();
// Indicate the error in global flags
config.config |= CFG_BAD_CRC;
DebuglnF("Reset to default");
}
// We'll drive our onboard LED
// old TXD1, not used anymore, has been swapped
pinMode(RED_LED_PIN, OUTPUT);
LedRedOFF();
// start Wifi connect or soft AP
WifiHandleConn(true);
//purge previous debug message,
#ifdef SYSLOG
if(SYSLOGselected) {
if(in != out && in != -1) {
//Il y a des messages en attente d'envoi
out++;
while( out <= in ) {
process_line(lines[out]);
free(lines[out]);
lines[out]=0;
out++;
}
DebuglnF("syslog buffer empty");
}
} else {
DebuglnF("syslog not activated !");
}
#endif
// Init SPIFFS filesystem, to use web server static files
if (! SPIFFS.begin() )
{
// Serious problem
DebuglnF("SPIFFS Mount failed !");
} else {
DebuglnF("");
DebuglnF("SPIFFS Mount succesfull");
Dir dir = SPIFFS.openDir("/");
while (dir.next()) {
String fileName = dir.fileName();
size_t fileSize = dir.fileSize();
sprintf(buff,"FS File: %s, size: %d\n", fileName.c_str(), fileSize);
Debug(buff);
}
//DebuglnF("");
}
// OTA callbacks
ArduinoOTA.onStart([]() {
LedRGBON(COLOR_MAGENTA);
DebuglnF("Update Started");
ota_blink = true;
});
ArduinoOTA.onEnd([]() {
LedRGBOFF();
DebuglnF("Update finished : restarting");
});
ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
if (ota_blink) {
LedRGBON(COLOR_MAGENTA);
} else {
LedRGBOFF();
}
ota_blink = !ota_blink;
//Serial.printf("Progress: %u%%\n", (progress / (total / 100)));
});
ArduinoOTA.onError([](ota_error_t error) {
LedRGBON(COLOR_RED);
#ifdef DEBUG
sprintf(buff,"Update Error[%u]: ", error);
Debug(buff);
if (error == OTA_AUTH_ERROR) DebuglnF("Auth Failed");
else if (error == OTA_BEGIN_ERROR) DebuglnF("Begin Failed");
else if (error == OTA_CONNECT_ERROR) DebuglnF("Connect Failed");
else if (error == OTA_RECEIVE_ERROR) DebuglnF("Receive Failed");
else if (error == OTA_END_ERROR) DebuglnF("End Failed");
#endif
ESP.restart();
});
// Update sysinfo variable and print them
UpdateSysinfo(true, true);
server.on("/", handleRoot);
server.on("/config_form.json", handleFormConfig);
server.on("/json", sendJSON);
server.on("/tinfo.json", tinfoJSONTable);
server.on("/emoncms.json", emoncmsJSONTable);
server.on("/system.json", sysJSONTable);
server.on("/config.json", confJSONTable);
server.on("/spiffs.json", spiffsJSONTable);
server.on("/wifiscan.json", wifiScanJSON);
server.on("/factory_reset", handleFactoryReset);
server.on("/reset", handleReset);
// handler for the hearbeat
server.on("/hb.htm", HTTP_GET, [&](){
server.sendHeader("Connection", "close");
server.sendHeader("Access-Control-Allow-Origin", "*");
server.send(200, "text/html", R"(OK)");
});
// handler for the /update form POST (once file upload finishes)
server.on("/update", HTTP_POST,
// handler once file upload finishes
[&]() {
server.sendHeader("Connection", "close");
server.sendHeader("Access-Control-Allow-Origin", "*");
server.send(200, "text/plain", (Update.hasError())?"FAIL":"OK");
ESP.restart();
},
// handler for upload, get's the sketch bytes,
// and writes them through the Update object
[&]() {
HTTPUpload& upload = server.upload();
if(upload.status == UPLOAD_FILE_START) {