forked from dingo35/SmartEVSE-3.5
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathesp32.cpp
More file actions
3017 lines (2612 loc) · 140 KB
/
esp32.cpp
File metadata and controls
3017 lines (2612 loc) · 140 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
#if MODEM
#include <stdint.h>
#include <stdio.h>
int8_t InitialSoC = -1; // State of charge of car
int8_t FullSoC = -1; // SoC car considers itself fully charged
int8_t ComputedSoC = -1; // Estimated SoC, based on charged kWh
int8_t RemainingSoC = -1; // Remaining SoC, based on ComputedSoC
int32_t TimeUntilFull = -1; // Remaining time until car reaches FullSoC, in seconds
int32_t EnergyCapacity = -1; // Car's total battery capacity
int32_t EnergyRequest = -1; // Requested amount of energy by car
char EVCCID[32]; // Car's EVCCID (EV Communication Controller Identifer)
char RequiredEVCCID[32] = ""; // Required EVCCID before allowing charging
#endif
#ifdef SMARTEVSE_VERSION //ESP32
#include <ArduinoJson.h>
#include <SPI.h>
#include <Preferences.h>
#include <FS.h>
#include <LittleFS.h>
#include <WiFi.h>
#include "network_common.h"
#include "esp_ota_ops.h"
#include "mbedtls/md_internal.h"
#include <HTTPClient.h>
#include <ESPmDNS.h>
#include <Update.h>
#include <glcd.h>
#include <Logging.h>
#include <ModbusServerRTU.h> // Slave/node
#include <ModbusClientRTU.h> // Master
#include <time.h>
#include <soc/sens_reg.h>
#include <soc/sens_struct.h>
#include <driver/adc.h>
#include <esp_adc_cal.h>
#include <soc/rtc_io_struct.h>
#include "esp32.h"
#include "glcd.h"
#include "utils.h"
#include "OneWire.h"
#include "OneWireESP32.h"
#include "modbus.h"
#include "meter.h"
#include "evse_bridge.h"
#include "solar_debug_json.h"
#include "session_log.h"
#include "diag_sampler.h"
#include "diag_storage.h"
#include "mqtt_parser.h"
#include "mqtt_publish.h"
#include "http_api.h"
#include "capacity_peak.h"
//OCPP includes
#if ENABLE_OCPP && defined(SMARTEVSE_VERSION) //run OCPP only on ESP32
#include <MicroOcpp.h>
#include <MicroOcppMongooseClient.h>
#include <MicroOcpp/Core/Configuration.h>
#include <MicroOcpp/Core/Context.h>
#include "ocpp_logic.h"
#include "ocpp_telemetry.h"
#endif //ENABLE_OCPP
#if SMARTEVSE_VERSION >= 40
#include <esp_sleep.h>
#include <driver/uart.h>
#include "wchisp.h"
#include "qca.h"
SPIClass QCA_SPI1(FSPI); // The ESP32-S3 has two usable SPI busses FSPI and HSPI
SPIClass LCD_SPI2(HSPI);
/* Commands send from ESP32 to CH32V203 over Uart
/ cmd Name Answer/data Comments
/---------------------------------------------------------------------------------------------------------------------------------
/ Ver? Version 0001 Version of CH32 software
/ Stat? Status State, Amperage, PP pin, SSR outputs, ACT outputs, VCC enable, Lock input, RCM, Temperature, Error
/ Amp: Set AMP 160 Set Chargecurrent A (*10)
/ Con: Set Contactors 0-3 0= Both Off, 1= SSR1 ON, 2= SSR2 ON, 3= Both ON
/ Vcc: Set VCC 0-1 0= VCC Off, 1= VCC ON
/ Sol: Set Solenoid 0-3 0= Both Off, 1= LOCK_R ON, 2= LOCK_W ON, 3= Both ON (or only lock/unlock?)
/ Led: Set Led color RGB, Fade speed, Blink
/ 485: Modbus data
/
/ Bij wegvallen ZC -> Solenoid unlock (indien locked)
*/
// Power Panic handler
// Shut down ESP to conserve the power we have left. RTC will automatically store powerdown timestamp
// We can store some important data in flash storage or the RTC chip (2 bytes)
//
void PowerPanicESP() {
_LOG_D("Power Panic!\n");
ledcWrite(LCD_CHANNEL, 0); // LCD Backlight off
// Stop SPI bus, and set all QCA data lines low
// TODO: store important information.
gpio_wakeup_enable(GPIO_NUM_8, GPIO_INTR_LOW_LEVEL);
esp_sleep_enable_gpio_wakeup();
esp_light_sleep_start();
// ESP32 is now in light sleep mode
// It will re-enable everything as soon it has woken up again.
// When using USB, you will have to unplug, and replug to re-establish the connection
_LOG_D("Power Back up!\n");
ledcWrite(LCD_CHANNEL, 50); // LCD Backlight on
}
extern void SendConfigToCH32(void);
#endif //SMARTEVSE_VERSION
#if SMARTEVSE_VERSION >=30 && SMARTEVSE_VERSION < 40
// Create a ModbusRTU server, client and bridge instance on Serial1
ModbusServerRTU MBserver(2000, PIN_RS485_DIR); // TCP timeout set to 2000 ms
ModbusClientRTU MBclient(PIN_RS485_DIR);
static esp_adc_cal_characteristics_t * adc_chars_PP;
static esp_adc_cal_characteristics_t * adc_chars_Temperature;
extern ModbusMessage MBEVMeterResponse(ModbusMessage request);
#endif //SMARTEVSE_VERSION
hw_timer_t * timerA = NULL;
Preferences preferences;
#if DIAG_LOG
volatile uint32_t cpPulseCount = 0; // Count CP rising edge interrupts
#endif
// delayed write settings - reduces flash wear by combining multiple writes into one
static bool SettingsDirty = false; // Flag indicating settings need to be written
static unsigned long LastSettingsWriteTime = 0; // millis() timestamp of last write
// Cache structure for detecting changed values - only write values that actually changed
struct SettingsCache {
uint8_t Config, Lock, Mode, AccessStatus;
uint16_t CardOffset;
uint32_t DelayedStartTime, DelayedStopTime;
uint16_t DelayedRepeat;
uint8_t LoadBl;
uint16_t MaxMains, MaxSumMains, MaxSumMainsTime, MaxCurrent, MinCurrent, MaxCircuit;
uint8_t Switch, RCmon;
uint16_t StartCurrent, StopTime, ImportCurrent;
uint8_t Grid, SB2_WIFImode, RFIDReader;
uint8_t MainsMeterType, MainsMeterAddress, EVMeterType, EVMeterAddress, CircuitMeterType, CircuitMeterAddress;
uint16_t MaxCircuitMains;
uint8_t EMEndianness, EMIDivisor, EMUDivisor, EMPDivisor, EMEDivisor, EMDataType, EMFunction;
uint16_t EMIRegister, EMURegister, EMPRegister, EMERegister;
uint8_t WIFImode;
uint16_t EnableC2;
#if MODEM
char RequiredEVCCID[32];
#endif
uint16_t maxTemp;
uint8_t PrioStrategy;
uint16_t RotationInterval;
uint16_t IdleTimeout;
uint8_t AutoUpdate, LCDlock, CableLock;
uint16_t LCDPin;
bool MQTTSmartServer;
#if MQTT
bool MQTTChangeOnly;
uint16_t MQTTHeartbeat;
#endif
#if ENABLE_OCPP && defined(SMARTEVSE_VERSION)
uint8_t OcppMode;
#endif
uint16_t CapacityLimit;
bool valid; // True once cache is populated from read_settings()
};
static SettingsCache settingsCache = {};
// MQTT change-only publishing cache and settings
#if MQTT
mqtt_cache_t mqtt_cache;
bool MQTTChangeOnly = true; // Master toggle: true = change-only, false = publish all
uint16_t MQTTHeartbeat = 60; // Heartbeat interval (seconds) for unchanged values
static uint32_t MQTTMsgCount = 0; // Count of MQTT messages published since boot
#endif
// Macros to only write if value changed
#define PREFS_PUT_UCHAR_IF_CHANGED(key, value, cacheVar) \
if (!settingsCache.valid || (value) != settingsCache.cacheVar) { \
preferences.putUChar(key, value); \
settingsCache.cacheVar = (value); \
}
#define PREFS_PUT_USHORT_IF_CHANGED(key, value, cacheVar) \
if (!settingsCache.valid || (value) != settingsCache.cacheVar) { \
preferences.putUShort(key, value); \
settingsCache.cacheVar = (value); \
}
#define PREFS_PUT_ULONG_IF_CHANGED(key, value, cacheVar) \
if (!settingsCache.valid || (value) != settingsCache.cacheVar) { \
preferences.putULong(key, value); \
settingsCache.cacheVar = (value); \
}
#define PREFS_PUT_BOOL_IF_CHANGED(key, value, cacheVar) \
if (!settingsCache.valid || (value) != settingsCache.cacheVar) { \
preferences.putBool(key, value); \
settingsCache.cacheVar = (value); \
}
uint16_t LCDPin = 0; // PINcode to operate LCD keys from web-interface
uint8_t PIN_SW_IN, PIN_ACTA, PIN_ACTB, PIN_RCM_FAULT, PIN_RS485_RX; //these pins have to be assigned dynamically because of hw version v3.1
extern esp_adc_cal_characteristics_t * adc_chars_CP;
extern void setStatePowerUnavailable(void);
extern char IsCurrentAvailable(void);
extern uint8_t Force_Single_Phase_Charging(void);
extern unsigned char RFID[8];
extern uint8_t pilot;
extern const char StrStateName[15][13];
const char StrStateNameWeb[15][17] = {"Ready to Charge", "Connected to EV", "Charging", "D", "Request State B", "State B OK", "Request State C", "State C OK", "Activate", "Charging Stopped", "Stop Charging", "Modem Setup", "Modem Request", "Modem Done", "Modem Denied"};
const char StrErrorNameWeb[9][20] = {"None", "No Power Available", "Communication Error", "Temperature High", "EV Meter Comm Error", "RCM Tripped", "RCM Test", "Test IO", "Flash Error"};
const char StrMode[3][8] = {"Normal", "Smart", "Solar"};
const char StrRFIDStatusWeb[8][20] = {"Ready to read card","Present", "Card Stored", "Card Deleted", "Card already stored", "Card not in storage", "Card Storage full", "Invalid" };
extern const char StrRFIDReader[7][10] = {"Disabled", "EnableAll", "EnableOne", "Learn", "Delete", "DeleteAll", "Rmt/OCPP"};
bool BuzzerPresent = false;
// The following data will be updated by eeprom/storage data at powerup:
extern uint16_t MaxMains;
extern uint16_t MaxCircuitMains;
extern uint16_t MaxSumMains;
// see https://github.com/serkri/SmartEVSE-3/issues/215
// 0 means disabled, allowed value 10 - 600 A
extern uint8_t MaxSumMainsTime;
extern uint16_t MaxSumMainsTimer;
extern uint16_t GridRelayMaxSumMains;
// Meant to obey par 14a of Energy Industry Act, where the provider can switch a device
// down to 4.2kW by a relay connected to the "switch" connectors.
// you will have to set the "Switch" setting to "GridRelay",
// and connect the relay to the switch terminals
// When the relay opens its contacts, power will be reduced to 4.2kW
// The relay is only allowed on the Master
extern bool CustomButton;
extern uint16_t CapacityLimit;
extern capacity_state_t CapacityState;
extern uint16_t MaxCurrent;
extern uint16_t MinCurrent;
extern uint8_t Mode;
extern uint32_t CurrentPWM;
extern void SetCurrent(uint16_t current);
extern bool CPDutyOverride;
extern uint8_t Lock;
extern uint16_t MaxCircuit;
extern uint8_t Config;
extern uint8_t Switch;
// 3:Smart-Solar B / 4:Smart-Solar S / 5: Grid Relay
// 6:Custom B / 7:Custom S)
// B=momentary push <B>utton, S=toggle <S>witch
extern uint8_t RCmon;
extern uint8_t AutoUpdate;
extern uint16_t StartCurrent;
extern uint16_t StopTime;
extern uint16_t ImportCurrent;
extern struct DelayedTimeStruct DelayedStopTime;
extern uint8_t DelayedRepeat;
extern uint8_t LCDlock;
extern uint8_t Lock;
extern uint8_t CableLock;
extern EnableC2_t EnableC2;
extern uint8_t RFIDReader;
extern uint16_t maxTemp;
extern uint8_t PrioStrategy;
extern uint16_t RotationInterval;
extern uint16_t IdleTimeout;
extern uint32_t ConnectedTime[];
extern uint8_t ScheduleState[];
extern uint16_t RotationTimer;
extern uint16_t MaxCapacity; // Cable limit (A) (limited by the wire in the charge cable, set automatically, or manually if Config=Fixed Cable)
extern uint16_t ChargeCurrent; // Calculated Charge Current (Amps *10)
extern uint16_t OverrideCurrent;
// Load Balance variables
extern int16_t IsetBalanced;
extern uint16_t Balanced[NR_EVSES];
#if SMARTEVSE_VERSION < 40 //v3
extern uint16_t BalancedMax[NR_EVSES];
extern uint8_t BalancedState[NR_EVSES];
extern uint16_t BalancedError[NR_EVSES];
#endif
extern Node_t Node[NR_EVSES];
extern uint16_t BacklightTimer;
extern uint8_t BacklightSet;
extern int8_t TempEVSE;
String PairingPin = "";
SemaphoreHandle_t buttonMutex = xSemaphoreCreateMutex();
uint8_t ButtonStateOverride = 0x07; // Possibility to override the buttons via API
uint32_t LastBtnOverrideTime = 0; // Avoid UI buttons getting stuck
bool LCDPasswordOK = false; // LCD web control PIN verification state
extern uint8_t ChargeDelay;
extern uint8_t NoCurrent;
extern uint8_t ModbusRequest;
extern uint16_t CardOffset;
extern uint8_t ConfigChanged;
extern uint16_t SolarStopTimer;
extern uint8_t State;
extern uint8_t ErrorFlags;
extern uint8_t LoadBl;
extern AccessStatus_t AccessStatus;
extern uint8_t Nr_Of_Phases_Charging;
extern uint8_t ActivationMode, ActivationTimer;
extern volatile uint16_t adcsample;
extern volatile uint16_t ADCsamples[25]; // declared volatile, as they are used in a ISR
extern volatile uint8_t sampleidx;
extern char str[20];
extern int phasesLastUpdate;
extern bool phasesLastUpdateFlag;
extern int16_t IrmsOriginal[3];
extern int16_t homeBatteryCurrent;
extern time_t homeBatteryLastUpdate;
// set by EXTERNAL logic through MQTT/REST to indicate cheap tariffs ahead until unix time indicated
extern uint8_t ColorOff[3] ;
extern uint8_t ColorNormal[3] ;
extern uint8_t ColorSmart[3] ;
extern uint8_t ColorSolar[3] ;
extern uint8_t ColorCustom[3];
#define FW_UPDATE_DELAY 3600 // time between detection of new version and actual update in seconds
extern uint16_t firmwareUpdateTimer;
// 0 means timer inactive
// 0 < timer < FW_UPDATE_DELAY means we are in countdown for an actual update
// FW_UPDATE_DELAY <= timer <= 0xffff means we are in countdown for checking
// whether an update is necessary
extern OneWire32& ds();
#if ENABLE_OCPP && defined(SMARTEVSE_VERSION) //run OCPP only on ESP32
extern unsigned char OcppRfidUuid [7];
extern size_t OcppRfidUuidLen;
extern unsigned long OcppLastRfidUpdate;
extern unsigned long OcppTrackLastRfidUpdate;
extern bool OcppForcesLock;
extern std::shared_ptr<MicroOcpp::Configuration> OcppUnlockConnectorOnEVSideDisconnect; // OCPP Config for RFID-based transactions: if false, demand same RFID card again to unlock connector
extern std::shared_ptr<MicroOcpp::Transaction> OcppLockingTx; // Transaction which locks connector until same RFID card is presented again
extern bool OcppTrackPermitsCharge;
extern bool OcppTrackAccessBit;
extern uint8_t OcppTrackCPvoltage;
extern MicroOcpp::MOcppMongooseClient *OcppWsClient;
extern float OcppCurrentLimit;
extern bool OcppWasStandalone;
extern ocpp_telemetry_t OcppTelemetry;
extern unsigned long OcppStopReadingSyncTime; // Stop value synchronization: delay StopTransaction by a few seconds so it reports an accurate energy reading
extern bool OcppDefinedTxNotification;
extern MicroOcpp::TxNotification OcppTrackTxNotification;
extern unsigned long OcppLastTxNotification;
#endif //ENABLE_OCPP
#if SMARTEVSE_VERSION >=30 && SMARTEVSE_VERSION < 40
// Some low level stuff here to setup the ADC, and perform the conversion.
//
//
uint16_t IRAM_ATTR local_adc1_read(int channel) {
uint16_t adc_value;
SENS.sar_read_ctrl.sar1_dig_force = 0; // switch SARADC into RTC channel
SENS.sar_meas_wait2.force_xpd_sar = SENS_FORCE_XPD_SAR_PU; // adc_power_on
RTCIO.hall_sens.xpd_hall = false; // disable other peripherals
//adc_ll_amp_disable() // Close ADC AMP module if don't use it for power save.
SENS.sar_meas_wait2.force_xpd_amp = SENS_FORCE_XPD_AMP_PD; // channel is set in the convert function
// disable FSM, it's only used by the LNA.
SENS.sar_meas_ctrl.amp_rst_fb_fsm = 0;
SENS.sar_meas_ctrl.amp_short_ref_fsm = 0;
SENS.sar_meas_ctrl.amp_short_ref_gnd_fsm = 0;
SENS.sar_meas_wait1.sar_amp_wait1 = 1;
SENS.sar_meas_wait1.sar_amp_wait2 = 1;
SENS.sar_meas_wait2.sar_amp_wait3 = 1;
// adc_hal_set_controller(ADC_NUM_1, ADC_CTRL_RTC); //Set controller
// see esp-idf/components/hal/esp32/include/hal/adc_ll.h
SENS.sar_read_ctrl.sar1_dig_force = 0; // 1: Select digital control; 0: Select RTC control.
SENS.sar_meas_start1.meas1_start_force = 1; // 1: SW control RTC ADC start; 0: ULP control RTC ADC start.
SENS.sar_meas_start1.sar1_en_pad_force = 1; // 1: SW control RTC ADC bit map; 0: ULP control RTC ADC bit map;
SENS.sar_touch_ctrl1.xpd_hall_force = 1; // 1: SW control HALL power; 0: ULP FSM control HALL power.
SENS.sar_touch_ctrl1.hall_phase_force = 1; // 1: SW control HALL phase; 0: ULP FSM control HALL phase.
// adc_hal_convert(ADC_NUM_1, channel, &adc_value);
// see esp-idf/components/hal/esp32/include/hal/adc_ll.h
SENS.sar_meas_start1.sar1_en_pad = (1 << channel); // select ADC channel to sample on
while (SENS.sar_slave_addr1.meas_status != 0); // wait for conversion to be idle (blocking)
SENS.sar_meas_start1.meas1_start_sar = 0;
SENS.sar_meas_start1.meas1_start_sar = 1; // start ADC conversion
while (SENS.sar_meas_start1.meas1_done_sar == 0); // wait (blocking) for conversion to finish
adc_value = SENS.sar_meas_start1.meas1_data_sar; // read ADC value from register
return adc_value;
}
// CP pin low to high transition ISR
//
//
void IRAM_ATTR onCPpulse() {
// reset timer, these functions are in IRAM !
timerWrite(timerA, 0);
timerAlarmEnable(timerA);
#if DIAG_LOG
cpPulseCount++;
#endif
}
// Timer interrupt handler
// in STATE A this is called every 1ms (autoreload)
// in STATE B/C there is a PWM signal, and the Alarm is set to 5% after the low-> high transition of the PWM signal
void IRAM_ATTR onTimerA() {
RTC_ENTER_CRITICAL();
adcsample = local_adc1_read(ADC1_CHANNEL_3);
RTC_EXIT_CRITICAL();
ADCsamples[sampleidx++] = adcsample;
if (sampleidx == 25) sampleidx = 0;
}
#endif //SMARTEVSE_VERSION
// --------------------------- END of ISR's -----------------------------------------------------
#if ENABLE_OCPP && defined(SMARTEVSE_VERSION) //run OCPP only on ESP32
// Inverse function of SetCurrent (for monitoring and debugging purposes)
uint16_t GetCurrent() {
uint32_t DutyCycle = CurrentPWM;
if (DutyCycle < 102) {
return 0; //PWM off or ISO15118 modem enabled
} else if (DutyCycle < 870) {
return (DutyCycle * 1000 / 1024) * 0.6 + 1; // invert duty cycle formula + fixed rounding error correction
} else if (DutyCycle <= 983) {
return ((DutyCycle * 1000 / 1024)- 640) * 2.5 + 3; // invert duty cycle formula + fixed rounding error correction
} else {
return 0; //constant +12V
}
}
#endif //ENABLE_OCPP
#if SMARTEVSE_VERSION >=30 && SMARTEVSE_VERSION < 40
// Sample the Temperature sensor.
//
int8_t TemperatureSensor() {
uint32_t sample, voltage;
signed char Temperature;
RTC_ENTER_CRITICAL();
// Sample Temperature Sensor
sample = local_adc1_read(ADC1_CHANNEL_0);
RTC_EXIT_CRITICAL();
// voltage range is from 0-2200mV
voltage = esp_adc_cal_raw_to_voltage(sample, adc_chars_Temperature);
// The MCP9700A temperature sensor outputs 500mV at 0C, and has a 10mV/C change in output voltage.
// so 750mV is 25C, 400mV = -10C
Temperature = (signed int)(voltage - 500)/10;
//_LOG_A("\nTemp: %i C (%u mV) ", Temperature , voltage);
return Temperature;
}
// Sample the Proximity Pin, and determine the maximum current the cable can handle.
//
uint8_t ProximityPin() {
uint32_t sample, voltage;
uint8_t MaxCap = 13; // No resistor, Max cable current = 13A
RTC_ENTER_CRITICAL();
// Sample Proximity Pilot (PP)
sample = local_adc1_read(ADC1_CHANNEL_6);
RTC_EXIT_CRITICAL();
voltage = esp_adc_cal_raw_to_voltage(sample, adc_chars_PP);
if (!Config) { // Configuration (0:Socket / 1:Fixed Cable)
//socket
_LOG_A("PP pin: %u (%u mV)\n", sample, voltage);
} else {
//fixed cable
_LOG_A("PP pin: %u (%u mV) (warning: fixed cable configured so PP probably disconnected, making this reading void)\n", sample, voltage);
}
if ((voltage > 1200) && (voltage < 1400)) MaxCap = 16; // Max cable current = 16A 680R -> should be around 1.3V
if ((voltage > 500) && (voltage < 700)) MaxCap = 32; // Max cable current = 32A 220R -> should be around 0.6V
if ((voltage > 200) && (voltage < 400)) MaxCap = 63; // Max cable current = 63A 100R -> should be around 0.3V
if (Config) MaxCap = MaxCurrent; // Override with MaxCurrent when Fixed Cable is used.
return MaxCap;
}
#endif
/**
* Get name of a state
*
* @param uint8_t State
* @return uint8_t[] Name
*/
const char * getStateName(uint8_t StateCode) {
if(StateCode < 15) return StrStateName[StateCode];
else return "NOSTATE";
}
const char * getStateNameWeb(uint8_t StateCode) {
if(StateCode < 15) return StrStateNameWeb[StateCode];
else return "NOSTATE";
}
uint8_t getErrorId(uint8_t ErrorCode) {
uint8_t count = 0;
//find the error bit that is set
while (ErrorCode) {
count++;
ErrorCode = ErrorCode >> 1;
}
return count;
}
const char * getErrorNameWeb(uint8_t ErrorCode) {
uint8_t count = 0;
count = getErrorId(ErrorCode);
if(count < 9) return StrErrorNameWeb[count];
else return "Multiple Errors";
}
void getButtonState() {
// Sample the three < o > buttons.
// As the buttons are shared with the SPI lines going to the LCD,
// we have to make sure that this does not interfere by write actions to the LCD.
// Therefore updating the LCD is also done in this task.
xSemaphoreTake(buttonMutex, portMAX_DELAY);
if (ButtonStateOverride != 7 && millis() - LastBtnOverrideTime < 4000)
ButtonState = ButtonStateOverride;
else {
#if SMARTEVSE_VERSION >=30 && SMARTEVSE_VERSION < 40
pinMatrixOutDetach(PIN_LCD_SDO_B3, false, false); // disconnect MOSI pin
pinMode(PIN_LCD_SDO_B3, INPUT);
pinMode(PIN_LCD_A0_B2, INPUT);
// sample buttons < o >
ButtonState = (digitalRead(PIN_LCD_SDO_B3) ? 4 : 0) | // > (right)
(digitalRead(PIN_LCD_A0_B2) ? 2 : 0) | // o (middle)
(digitalRead(PIN_IO0_B1) ? 1 : 0); // < (left)
pinMode(PIN_LCD_SDO_B3, OUTPUT);
pinMatrixOutAttach(PIN_LCD_SDO_B3, VSPID_IN_IDX, false, false); // re-attach MOSI pin
#else
pinMode(PIN_LCD_A0_B2, INPUT_PULLUP); // Switch the shared pin for the middle button to input
ButtonState = (digitalRead(BUTTON3) ? 4 : 0) | // > (right)
(digitalRead(PIN_LCD_A0_B2) ? 2 : 0) | // o (middle)
(digitalRead(BUTTON1) ? 1 : 0); // < (left)
#endif
pinMode(PIN_LCD_A0_B2, OUTPUT); // switch pin back to output
}
xSemaphoreGive(buttonMutex);
}
String readMqttCaCert() {
if (!LittleFS.exists("/mqtt_ca.pem")) {
_LOG_A("No /mqtt_ca.pem found.\n");
return "";
}
File file = LittleFS.open("/mqtt_ca.pem", "r");
if (!file) {
_LOG_A("Failed to open /mqtt_ca.pem for reading.\n");
return "";
}
String cert = file.readString();
file.close();
return cert;
}
void writeMqttCaCert(const String& cert) {
if (cert.isEmpty()) {
LittleFS.remove("/mqtt_ca.pem");
_LOG_D("Removed /mqtt_ca.pem.\n");
return;
}
File file = LittleFS.open("/mqtt_ca.pem", "w");
if (!file) {
_LOG_A("Failed to open /mqtt_ca.pem for writing.\n");
return;
}
file.print(cert);
file.close();
_LOG_D("Wrote %d bytes to /mqtt_ca.pem.\n", cert.length());
}
#if MQTT
static void mqttSetSolarDebug(bool enabled); // forward declaration
void mqtt_receive_callback(const String topic, const String payload) {
mqtt_command_t cmd;
if (!mqtt_parse_command(MQTTprefix.c_str(), topic.c_str(), payload.c_str(), &cmd))
return;
uint8_t *color_target = NULL; // used by MQTT_CMD_COLOR
switch (cmd.cmd) {
case MQTT_CMD_MODE:
if (cmd.mode == MQTT_MODE_OFF) {
#if SMARTEVSE_VERSION >= 40
Serial1.printf("@ResetModemTimers\n");
#endif
setAccess(OFF);
} else if (cmd.mode == MQTT_MODE_PAUSE) {
setAccess(PAUSE);
} else if (cmd.mode == MQTT_MODE_SOLAR) {
setOverrideCurrent(0);
setMode(cmd.mode);
} else {
setMode(cmd.mode);
}
break;
case MQTT_CMD_CUSTOM_BUTTON:
CustomButton = cmd.custom_button;
break;
case MQTT_CMD_CURRENT_OVERRIDE:
if (cmd.current_override == 0) {
setOverrideCurrent(0);
} else if (LoadBl < 2 && (Mode == MODE_NORMAL || Mode == MODE_SMART)) {
if (cmd.current_override >= (MinCurrent * 10) && cmd.current_override <= (MaxCurrent * 10)) {
setOverrideCurrent(cmd.current_override);
}
}
break;
case MQTT_CMD_MAX_SUM_MAINS:
if (LoadBl < 2)
MaxSumMains = cmd.max_sum_mains;
break;
case MQTT_CMD_CP_PWM_OVERRIDE:
if (cmd.cp_pwm == -1) {
SetCPDuty(1024);
PILOT_CONNECTED;
CPDutyOverride = false;
} else if (cmd.cp_pwm == 0) {
SetCPDuty(0);
PILOT_DISCONNECTED;
CPDutyOverride = true;
} else {
SetCPDuty(cmd.cp_pwm);
PILOT_CONNECTED;
CPDutyOverride = true;
}
break;
case MQTT_CMD_MAINS_METER:
if (MainsMeter.Type != EM_API || LoadBl >= 2)
return;
#if SMARTEVSE_VERSION < 40
if (LoadBl < 2) {
MainsMeter.setTimeout(COMM_TIMEOUT);
MainsMeter.Irms[0] = cmd.mains_meter.L1;
MainsMeter.Irms[1] = cmd.mains_meter.L2;
MainsMeter.Irms[2] = cmd.mains_meter.L3;
CalcIsum();
}
#else
Serial1.printf("@Irms:%03u,%d,%d,%d\n", MainsMeter.Address,
(int)cmd.mains_meter.L1, (int)cmd.mains_meter.L2, (int)cmd.mains_meter.L3);
#endif
break;
case MQTT_CMD_EV_METER:
if (EVMeter.Type != EM_API)
return;
if ((cmd.ev_meter.L1 > -1 && cmd.ev_meter.L1 < 1000) &&
(cmd.ev_meter.L2 > -1 && cmd.ev_meter.L2 < 1000) &&
(cmd.ev_meter.L3 > -1 && cmd.ev_meter.L3 < 1000)) {
#if SMARTEVSE_VERSION < 40
EVMeter.Irms[0] = cmd.ev_meter.L1;
EVMeter.Irms[1] = cmd.ev_meter.L2;
EVMeter.Irms[2] = cmd.ev_meter.L3;
EVMeter.CalcImeasured();
EVMeter.Timeout = COMM_EVTIMEOUT;
#else
Serial1.printf("@Irms:%03u,%d,%d,%d\n", EVMeter.Address,
(int)cmd.ev_meter.L1, (int)cmd.ev_meter.L2, (int)cmd.ev_meter.L3);
#endif
}
if (cmd.ev_meter.W > -1) {
#if SMARTEVSE_VERSION < 40
EVMeter.PowerMeasured = cmd.ev_meter.W;
#else
Serial1.printf("@PowerMeasured:%03u,%d\n", EVMeter.Address, (int)cmd.ev_meter.W);
#endif
}
if (cmd.ev_meter.Wh > -1) {
EVMeter.Import_active_energy = cmd.ev_meter.Wh;
EVMeter.Export_active_energy = 0;
EVMeter.UpdateEnergies();
}
break;
case MQTT_CMD_HOME_BATTERY_CURRENT:
if (LoadBl >= 2)
return;
homeBatteryCurrent = cmd.home_battery_current;
homeBatteryLastUpdate = time(NULL);
#if SMARTEVSE_VERSION >= 40
SEND_TO_CH32(homeBatteryCurrent);
#endif
break;
case MQTT_CMD_REQUIRED_EVCCID:
#if MODEM
strncpy(RequiredEVCCID, cmd.evccid, sizeof(RequiredEVCCID));
Serial1.printf("@RequiredEVCCID:%s\n", RequiredEVCCID);
request_write_settings();
#endif
break;
case MQTT_CMD_COLOR:
switch (cmd.color.index) {
case MQTT_COLOR_OFF: color_target = ColorOff; break;
case MQTT_COLOR_NORMAL: color_target = ColorNormal; break;
case MQTT_COLOR_SMART: color_target = ColorSmart; break;
case MQTT_COLOR_SOLAR: color_target = ColorSolar; break;
case MQTT_COLOR_CUSTOM: color_target = ColorCustom; break;
default: return;
}
color_target[0] = cmd.color.r;
color_target[1] = cmd.color.g;
color_target[2] = cmd.color.b;
break;
case MQTT_CMD_CABLE_LOCK:
CableLock = cmd.cable_lock;
request_write_settings();
break;
case MQTT_CMD_ENABLE_C2:
EnableC2 = (EnableC2_t)cmd.enable_c2;
request_write_settings();
break;
case MQTT_CMD_PRIO_STRATEGY:
if (LoadBl < 2) {
setItemValue(MENU_PRIO, cmd.prio_strategy);
request_write_settings();
}
break;
case MQTT_CMD_ROTATION_INTERVAL:
if (LoadBl < 2) {
setItemValue(MENU_ROTATION, cmd.rotation_interval);
request_write_settings();
}
break;
case MQTT_CMD_IDLE_TIMEOUT:
if (LoadBl < 2) {
setItemValue(MENU_IDLE_TIMEOUT, cmd.idle_timeout);
request_write_settings();
}
break;
case MQTT_CMD_MQTT_HEARTBEAT:
MQTTHeartbeat = cmd.mqtt_heartbeat;
mqtt_cache.heartbeat_s = MQTTHeartbeat;
request_write_settings();
break;
case MQTT_CMD_MQTT_CHANGE_ONLY:
MQTTChangeOnly = cmd.mqtt_change_only;
request_write_settings();
break;
case MQTT_CMD_SOLAR_DEBUG:
mqttSetSolarDebug(cmd.solar_debug);
break;
// BEGIN PLAN-06: Diagnostic telemetry
case MQTT_CMD_DIAG_PROFILE:
if (cmd.diag_profile == 0)
diag_stop();
else
diag_start((diag_profile_t)cmd.diag_profile);
break;
// END PLAN-06
// BEGIN PLAN-13: Capacity tariff limit
case MQTT_CMD_CAPACITY_LIMIT:
CapacityLimit = cmd.capacity_limit;
capacity_set_limit(&CapacityState, (int32_t)CapacityLimit);
request_write_settings();
break;
// END PLAN-13
// BEGIN PLAN-09: API staleness timeout
case MQTT_CMD_MAINS_METER_TIMEOUT:
// Applied via bridge layer to evse_ctx.api_mains_timeout
break;
// END PLAN-09
// BEGIN PLAN-14: CircuitMeter MQTT commands
case MQTT_CMD_MAX_CIRCUIT_MAINS:
if (LoadBl < 2)
MaxCircuitMains = cmd.max_circuit_mains;
break;
case MQTT_CMD_CIRCUIT_METER:
if (CircuitMeter.Type != EM_API || LoadBl >= 2)
return;
#if SMARTEVSE_VERSION < 40
CircuitMeter.setTimeout(COMM_TIMEOUT);
CircuitMeter.Irms[0] = cmd.circuit_meter.L1;
CircuitMeter.Irms[1] = cmd.circuit_meter.L2;
CircuitMeter.Irms[2] = cmd.circuit_meter.L3;
CircuitMeter.CalcImeasured();
#else
Serial1.printf("@Irms:%03u,%d,%d,%d\n", CircuitMeter.Address,
(int)cmd.circuit_meter.L1, (int)cmd.circuit_meter.L2, (int)cmd.circuit_meter.L3);
#endif
break;
// END PLAN-14
// BEGIN PLAN-09: HomeWizard manual IP fallback
case MQTT_CMD_HOMEWIZARD_IP:
homeWizardManualIP = cmd.homewizard_ip;
// Clear cached mDNS result so next poll uses the new IP
homeWizardHost = "";
_LOG_A("HomeWizard manual IP set to '%s'\n", cmd.homewizard_ip);
break;
// END PLAN-09
// BEGIN PLAN-15: SoC MQTT commands
#if MODEM
case MQTT_CMD_INITIAL_SOC:
InitialSoC = cmd.initial_soc;
RecomputeSoC();
break;
case MQTT_CMD_FULL_SOC:
FullSoC = cmd.full_soc;
RecomputeSoC();
break;
case MQTT_CMD_ENERGY_CAPACITY:
EnergyCapacity = cmd.energy_capacity;
RecomputeSoC();
break;
case MQTT_CMD_ENERGY_REQUEST:
EnergyRequest = cmd.energy_request;
RecomputeSoC();
break;
case MQTT_CMD_EVCCID_SET:
strncpy(EVCCID, cmd.evccid, sizeof(EVCCID) - 1);
EVCCID[sizeof(EVCCID) - 1] = '\0';
break;
#endif
// END PLAN-15
default:
return;
}
// Handle RFID via MQTT (not part of mqtt_parser — uses Arduino String for hex parsing)
if (topic == MQTTprefix + "/Set/RFID") {
// Accept RFID card via MQTT to start/stop session
// Payload should be hex string: 12 or 14 characters for 6 or 7 byte UID
// Examples: "010203040506" (6 bytes) or "01020304050607" (7 bytes)
uint8_t RFIDReader = getItemValue(MENU_RFIDREADER);
if (!RFIDReader) {
_LOG_A("RFID reader not enabled, ignoring MQTT RFID\n");
} else {
String hexString = payload;
hexString.trim();
// Check if payload is valid hex and correct length
bool validHex = true;
for (size_t i = 0; i < hexString.length(); i++) {
if (!isxdigit(hexString[i])) {
validHex = false;
break;
}
}
if (!validHex) {
_LOG_A("Invalid RFID hex string received via MQTT: %s\n", hexString.c_str());
} else if (hexString.length() == 12 || hexString.length() == 14) {
// Parse hex string into RFID array
memset(RFID, 0, 8);
if (hexString.length() == 12) {
// 6 byte UID (old reader format, starts at RFID[1])
RFID[0] = 0x01; // Family code for old reader
for (int i = 0; i < 6; i++) {
RFID[i + 1] = (uint8_t)strtol(hexString.substring(i * 2, i * 2 + 2).c_str(), NULL, 16);
}
RFID[7] = crc8((unsigned char *)RFID, 7);
} else {
// 7 byte UID (new reader format)
for (int i = 0; i < 7; i++) {
RFID[i] = (uint8_t)strtol(hexString.substring(i * 2, i * 2 + 2).c_str(), NULL, 16);
}
RFID[7] = crc8((unsigned char *)RFID, 7);
}
_LOG_A("RFID received via MQTT: %s\n", hexString.c_str());
// Reset RFIDstatus so CheckRFID processes the card as new
RFIDstatus = 0;
// Process RFID using existing logic (whitelist check, OCPP, etc.)
CheckRFID();
} else {
_LOG_A("Invalid RFID length received via MQTT (expected 12 or 14 hex chars): %s\n", hexString.c_str());
}
}
}
// Make sure MQTT updates directly to prevent debounces
lastMqttUpdate = 10;
}
//print RFID in hex format
void printRFID(char *buf, size_t bufsize) {
if (RFID[0] == 0x01) { // old reader 6 byte UID starts at RFID[1]
snprintf(buf, bufsize, "%02X%02X%02X%02X%02X%02X", RFID[1], RFID[2], RFID[3], RFID[4], RFID[5], RFID[6]);
} else {
snprintf(buf, bufsize, "%02X%02X%02X%02X%02X%02X%02X", RFID[0], RFID[1], RFID[2], RFID[3], RFID[4], RFID[5], RFID[6]);
}
}
void SetupMQTTClient() {
// Initialize MQTT change-only publish cache
mqtt_cache_init(&mqtt_cache, MQTTHeartbeat);
// Set up subscriptions
MQTTclient.subscribe(MQTTprefix + "/Set/#",1);
MQTTclient.publish(MQTTprefix+"/connected", "online", true, 0);
//set the parameters for and announce sensors with device class 'current':
String optional_payload = MQTTclient.jsna("device_class","current") + MQTTclient.jsna("state_class","measurement") + MQTTclient.jsna("unit_of_measurement","A") + MQTTclient.jsna("value_template", R"({{ value | int / 10 }})");
MQTTclient.announce("Charge Current", "sensor", optional_payload);
MQTTclient.announce("Max Current", "sensor", optional_payload);
if (MainsMeter.Type) {
MQTTclient.announce("Mains Current L1", "sensor", optional_payload);
MQTTclient.announce("Mains Current L2", "sensor", optional_payload);
MQTTclient.announce("Mains Current L3", "sensor", optional_payload);
}
if (EVMeter.Type) {
MQTTclient.announce("EV Current L1", "sensor", optional_payload);
MQTTclient.announce("EV Current L2", "sensor", optional_payload);
MQTTclient.announce("EV Current L3", "sensor", optional_payload);
}
if (homeBatteryLastUpdate) {
MQTTclient.announce("Home Battery Current", "sensor", optional_payload);
}
//set the parameters for and announce sensors with device class 'power':
optional_payload = MQTTclient.jsna("device_class","power") + MQTTclient.jsna("state_class","measurement") + MQTTclient.jsna("unit_of_measurement","W");
if (MainsMeter.Type) {
MQTTclient.announce("Mains Power L1", "sensor", optional_payload);
MQTTclient.announce("Mains Power L2", "sensor", optional_payload);