Repository navigation
Expand file tree
/
Copy pathxsns_53_sml.ino
More file actions
6056 lines (5623 loc) · 193 KB
/
Copy pathxsns_53_sml.ino
File metadata and controls
6056 lines (5623 loc) · 193 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
/*
xsns_53_sml.ino - SML,OBIS,EBUS,RAW,COUNTER interface for Tasmota
Created by Gerhard Mutz on 07.10.11.
adapted for Tasmota
Copyright (C) 2021 Gerhard Mutz and Theo Arends
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef USE_SML_M
#define XSNS_53 53
// this driver works with USE_SCRIPT or standalone with USE_UFILESYS (file: /sml_meter.def)
// fixes some modbus tcp errors (dynamic MBAP SIZE for write FCs)
#ifdef ESP32
#define USE_BAT_CTRL
#endif
// provide SCRIPT_EOL if scripter is not compiled
#ifndef SCRIPT_EOL
#define SCRIPT_EOL '\n'
#endif
// debug counter input to led for counter1 and 2
//#define DEBUG_CNT_LED1 2
//#define DEBUG_CNT_LED1 2
#include <TasmotaSerial.h>
// SOL_SOCKET / SO_LINGER / struct linger for setSocketOption() in SML_Clean_Meters.
// ESP32 Arduino core only forward-declares `struct linger` via its Network stack,
// so we pull in lwIP's definitions here (ESP32-only; ESP8266 path doesn't use TCP meters).
#ifdef ESP32
#include <lwip/sockets.h>
// IDF UART RX-interrupt control — used by SmlUploadPause/Resume to silence the
// per-meter UART ISR during a long /ufsu flash write (otherwise the ISR keeps
// firing through the cache-disabled close(), starving WiFi/LwIP and OsWatch,
// and the device hangs hard despite SML_Poll being paused — Andreas .104 repro).
#include <driver/uart.h>
#endif
// use special no wait serial driver, should be always on
#ifndef ESP32
#define SPECIAL_SS
#endif
// max number of meters , may be adjusted
#ifndef MAX_METERS
#define MAX_METERS 5
#endif
/* additional defines
USE_ESP32_SW_SERIAL
default off, uses a special combo driver that allows more then 3 serial ports on ESP32.
define rec pins as negativ to use software serial
USE_SML_AUTHKEY
rarely used , thus off by default
*/
// if you have to save more RAM you may disable these options by defines in user_config_override
#ifndef NO_SML_REPLACE_VARS
#ifdef USE_SCRIPT
// allows to replace values in decoder section with script string variables
#undef SML_REPLACE_VARS
#define SML_REPLACE_VARS
#endif
#endif
#ifndef NO_USE_SML_SPECOPT
// allows to define special option 1 for meters that use a direction bit
#undef USE_SML_SPECOPT
#define USE_SML_SPECOPT
#endif
#ifndef NO_USE_SML_SCRIPT_CMD
// allows several sml cmds from scripts, as well as access to sml registers
#undef USE_SML_SCRIPT_CMD
#define USE_SML_SCRIPT_CMD
#endif
#ifndef NO_USE_SML_DECRYPT
// allows 256 bit AES decryption
#define USE_SML_DECRYPT
#endif
#ifndef NO_USE_SML_TCP
// modbus over TCP
#define USE_SML_TCP
#endif
#ifndef NO_SML_OBIS_LINE
// obis in line mode
#define SML_OBIS_LINE
#endif
#ifdef ESP32
#ifndef NO_USE_SML_CANBUS
// canbus support
#undef USE_SML_CANBUS
#define USE_SML_CANBUS
#endif
#endif
#ifdef USE_SML_TCP_SECURE
#define USE_SML_TCP_IP_STR
#endif
// median filter eliminates outliers, but uses much RAM and CPU cycles
// 672 bytes extra RAM with SML_MAX_VARS = 16
// default compile on, but must be enabled by descriptor flag 16
// may be undefined if RAM must be saved
#ifndef NO_USE_SML_MEDIAN_FILTER
#undef USE_SML_MEDIAN_FILTER
#define USE_SML_MEDIAN_FILTER
#endif
// on ESP32 binary SML CRC check compile enabled by default
// adds 17936 bytes due to large crc tables
#ifdef ESP32
#ifndef NO_USE_SML_CRC
#undef USE_SML_CRC
#define USE_SML_CRC
#endif
#endif
#ifdef USE_SML_DECRYPT
#include "han_Parser.h"
#endif
#ifdef USE_SML_CRC
#include "FastCRC.h"
FastCRC16 FastCRC;
#endif
#ifndef SML_TRX_BUFF_SIZE
#define SML_TRX_BUFF_SIZE 1024
#endif
#ifdef USE_SML_CANBUS
#ifdef ESP8266
// esp8266 uses SPI MPC2515
#undef SML_CAN_MASKS
#undef SML_CAN_FILTERS
#define SML_CAN_MASKS 2
#define SML_CAN_FILTERS 6
#include "mcp2515.h"
#else
// esp32 uses native twai
#undef SML_CAN_MASKS
#undef SML_CAN_FILTERS
#define SML_CAN_MASKS 1
#define SML_CAN_FILTERS 1
#include <can.h>
#include "driver/twai.h"
#endif
#endif // USE_SML_CANBUS
/* special options per meter
1:
special binary SML option for meters that use a bit in the status register to sign import or export like ED300L, AS2020 or DTZ541
a. obis code that holds the direction bit,
b. Flag identifier,
c. direction bit,
d. second Flag identifier (some meters use 2 different flags),
e. second bit,
f. obis code of value to be inverted on direction bit.
e.g. 1,=so1,00010800,65,11,65,11,00100700 for DTZ541
2:
flags, currently only bit 0 and 1
if 1 fix DWS74 bug
if 2 use asci obis line compare instead a pattern compare
e.g. 1,=so2,2 set obis line mode on meter 1
3:
serial buffers
a. serial buffer size
b. serial irq buffer size, a must be given
c. dumplog buffer size, default is 128 , a and b must be given
e.g. 1,=so3,256,256 set serial buffers on meter 1
4:
decrytion key, 16 bytes hex btw 32 chars without spaces or commas
defining key switches decryption mode on
5:
authentication key, 16 bytes hex btw 32 chars without spaces or commas
needs USE_SML_AUTHKEY
6:
synchronisation timout in milliseconds, after no serial data within this
time serial pointer is reset to zero
7:
on esp32 the uart index may be set, normally it is allocated from 2 down to 0 automatically
thus you can combine serial SML with serial script , berry or serial drivers.
8:
on esp32 1 filter mask
on esp8266 2 filter masks
9:
on esp32 1 filter
on esp8266 6 filters
A:
decryption flags (8 bits)
C:
crc buffers and algorithm (available when compiled with USE_SML_CRC)
a. crc buffer size (bytes), must hold one full file
b. crc-algorithm: 0=x25, 1=ccitt, 15=autodetect
e.g. 1,=soC,1024,15
*/
//#define MODBUS_DEBUG
// ESP32 combined hardware and software serial driver, software read only
#ifdef ESP32
#ifdef USE_ESP32_SW_SERIAL
#ifndef ESP32_SWS_BUFFER_SIZE
#define ESP32_SWS_BUFFER_SIZE 256
#endif
class SML_ESP32_SERIAL : public Stream {
public:
SML_ESP32_SERIAL(uint32_t uart_index);
virtual ~SML_ESP32_SERIAL();
bool begin(uint32_t speed, uint32_t smode, int32_t recpin, int32_t trxpin, int32_t invert);
int peek(void);
int read(void) override;
size_t write(uint8_t byte) override;
int available(void) override;
void flush(void) override;
void setRxBufferSize(uint32_t size);
void updateBaudRate(uint32_t baud);
void rxRead(void);
void end();
// Silence the RX-side interrupt for the duration of a long blocking task
// (the /ufsu LittleFS flush is the motivating case — see SmlUploadPause).
// Idempotent. HW-serial path disables the IDF UART RX interrupt; SW-serial
// path detaches the GPIO change interrupt. The RX FIFO may overflow during
// the silence — fine, the SML decoder resyncs on the next SYNC after enable.
void rx_intr_disable(void);
void rx_intr_enable(void);
#ifdef USE_SML_EBUS_ARB
HardwareSerial *get_hws(void) { return hws; } // eBUS arb RX-event wiring needs the raw UART
#endif
using Print::write;
private:
// Member variables
void setbaud(uint32_t speed);
uint32_t uart_index;
int8_t m_rx_pin;
int8_t m_tx_pin;
uint32_t cfgmode;
uint32_t ss_byte;
uint32_t ss_bstart;
uint32_t ss_index;
uint32_t m_bit_time;
uint32_t m_in_pos;
uint32_t m_out_pos;
uint16_t serial_buffer_size;
bool m_valid;
uint8_t *m_buffer;
HardwareSerial *hws;
};
void IRAM_ATTR sml_callRxRead(void *self);
void sml_callRxRead(void *self) { ((SML_ESP32_SERIAL*)self)->rxRead(); };
SML_ESP32_SERIAL::SML_ESP32_SERIAL(uint32_t index) {
uart_index = index;
m_valid = true;
}
SML_ESP32_SERIAL::~SML_ESP32_SERIAL(void) {
if (hws) {
hws->end();
delete(hws);
} else {
detachInterrupt(m_rx_pin);
if (m_buffer) {
free(m_buffer);
}
}
}
void SML_ESP32_SERIAL::setbaud(uint32_t speed) {
#ifdef __riscv
m_bit_time = 1000000 / speed;
#else
m_bit_time = ESP.getCpuFreqMHz() * 1000000 / speed;
#endif
}
void SML_ESP32_SERIAL::end(void) {
if (m_buffer) {
free(m_buffer);
}
}
void SML_ESP32_SERIAL::rx_intr_disable(void) {
if (hws) {
uart_disable_rx_intr((uart_port_t)uart_index);
} else if (m_rx_pin >= 0) {
detachInterrupt(m_rx_pin);
}
}
void SML_ESP32_SERIAL::rx_intr_enable(void) {
if (hws) {
uart_enable_rx_intr((uart_port_t)uart_index);
} else if (m_rx_pin >= 0) {
attachInterruptArg(m_rx_pin, sml_callRxRead, this, CHANGE);
}
}
bool SML_ESP32_SERIAL::begin(uint32_t speed, uint32_t smode, int32_t recpin, int32_t trxpin, int32_t invert) {
if (!m_valid) { return false; }
m_buffer = 0;
if (recpin < 0) {
setbaud(speed);
m_rx_pin = -recpin;
serial_buffer_size = ESP32_SWS_BUFFER_SIZE;
m_buffer = (uint8_t*)malloc(serial_buffer_size);
if (m_buffer == NULL) return false;
pinMode(m_rx_pin, INPUT_PULLUP);
attachInterruptArg(m_rx_pin, sml_callRxRead, this, CHANGE);
m_in_pos = m_out_pos = 0;
hws = nullptr;
} else {
cfgmode = smode;
m_rx_pin = recpin;
m_tx_pin = trxpin;
hws = new HardwareSerial(uart_index);
if (hws) {
hws->begin(speed, cfgmode, m_rx_pin, m_tx_pin, invert);
}
}
return true;
}
void SML_ESP32_SERIAL::flush(void) {
if (hws) {
hws->flush();
} else {
m_in_pos = m_out_pos = 0;
}
}
int SML_ESP32_SERIAL::peek(void) {
if (hws) {
return hws->peek();
} else {
if (m_in_pos == m_out_pos) return -1;
return m_buffer[m_out_pos];
}
}
int SML_ESP32_SERIAL::read(void) {
if (hws) {
return hws->read();
} else {
if (m_in_pos == m_out_pos) return -1;
uint32_t ch = m_buffer[m_out_pos];
m_out_pos = (m_out_pos + 1) % serial_buffer_size;
return ch;
}
}
int SML_ESP32_SERIAL::available(void) {
if (hws) {
return hws->available();
} else {
int avail = m_in_pos - m_out_pos;
if (avail < 0) avail += serial_buffer_size;
return avail;
}
}
size_t SML_ESP32_SERIAL::write(uint8_t byte) {
if (hws) {
return hws->write(byte);
}
return 0;
}
void SML_ESP32_SERIAL::setRxBufferSize(uint32_t size) {
if (hws) {
hws->setRxBufferSize(size);
} else {
if (m_buffer) {
free(m_buffer);
}
serial_buffer_size = size;
m_buffer = (uint8_t*)malloc(size);
}
}
void SML_ESP32_SERIAL::updateBaudRate(uint32_t baud) {
if (hws) {
hws->updateBaudRate(baud);
} else {
setbaud(baud);
}
}
// no wait mode only 8N1 (or 7X1, obis only, ignoring parity)
void SML_ESP32_SERIAL::rxRead(void) {
uint32_t diff;
uint32_t level;
#define SML_LASTBIT 9
level = digitalRead(m_rx_pin);
if (!level && !ss_index) {
// start condition
#ifdef __riscv
ss_bstart = micros() - (m_bit_time / 4);
#else
ss_bstart = ESP.getCycleCount() - (m_bit_time / 4);
#endif
ss_byte = 0;
ss_index++;
} else {
// now any bit changes go here
// calc bit number
#ifdef __riscv
diff = (micros() - ss_bstart) / m_bit_time;
#else
diff = (ESP.getCycleCount() - ss_bstart) / m_bit_time;
#endif
if (!level && diff > SML_LASTBIT) {
// start bit of next byte, store and restart
// leave irq at change
for (uint32_t i = ss_index; i <= SML_LASTBIT; i++) {
ss_byte |= (1 << i);
}
uint32_t next = (m_in_pos + 1) % serial_buffer_size;
if (next != (uint32_t)m_out_pos) {
m_buffer[m_in_pos] = ss_byte >> 1;
m_in_pos = next;
}
#ifdef __riscv
ss_bstart = micros() - (m_bit_time / 4);
#else
ss_bstart = ESP.getCycleCount() - (m_bit_time / 4);
#endif
ss_byte = 0;
ss_index = 1;
return;
}
if (diff >= SML_LASTBIT) {
// bit zero was 0,
uint32_t next = (m_in_pos + 1) % serial_buffer_size;
if (next != (uint32_t)m_out_pos) {
m_buffer[m_in_pos] = ss_byte >> 1;
m_in_pos = next;
}
ss_byte = 0;
ss_index = 0;
} else {
// shift in
for (uint32_t i = ss_index; i < diff; i++) {
if (!level) ss_byte |= (1 << i);
}
ss_index = diff;
}
}
}
#endif // USE_ESP32_SW_SERIAL
#endif // ESP32
typedef union {
uint8_t data;
struct {
uint8_t trxenpol : 1; // string or number
uint8_t trxen : 1;
uint8_t trxenpin : 6;
};
} TRX_EN_TYPE;
typedef union {
uint8_t data;
struct {
uint8_t SO_DWS74_BUG : 1;
uint8_t SO_OBIS_LINE : 1;
uint8_t SO_TRX_INVERT : 1;
uint8_t SO_DISS_PULL : 1;
uint8_t SO_NU : 1;
uint8_t SO_NOPAR : 1;
};
} SO_FLAGS;
#ifndef TMSBSIZ
#define TMSBSIZ 256
#endif
#ifndef SML_STIMEOUT
#define SML_STIMEOUT 1000
#endif
#define METER_ID_SIZE 24
#define SML_CRYPT_SIZE 16
#ifndef SML_PREFIX_SIZE
#define SML_PREFIX_SIZE 8
#endif
#ifdef USE_SML_CRC
struct SML_CRC_DATA {
uint8_t crcmode; //currently used mode
uint8_t crcdetectstate; //current auto-detection state
uint8_t *crcbuff; //buffer, only allocated on meter that have crc enabled
uint16_t crcbuff_pos; //current buffer wiring position
uint32_t crcfailcnt; //cnt bad-crc telegrams
uint32_t crcfinecnt; //cnt good-crc telegrams
uint32_t overflowcnt; //cnt good-crc telegrams
sint8_t telestartpos; //-1=still searching, 0=found
sint16_t teleendpos; //end of the telegram in the buffer or -1 when waiting for it
};
#endif // USE_SML_CRC
struct METER_DESC {
int8_t srcpin;
uint8_t type;
uint16_t flag;
int32_t params;
char prefix[SML_PREFIX_SIZE];
int8_t trxpin;
uint8_t tsecs;
char *txmem;
uint8_t index;
uint8_t max_index;
char *script_str;
uint8_t sopt;
TRX_EN_TYPE trx_en;
bool shift_mode;
uint16_t sbsiz;
uint8_t *sbuff;
uint16_t spos;
uint16_t sibsiz;
uint32_t lastms;
uint16_t tout_ms;
SO_FLAGS so_flags;
char meter_id[METER_ID_SIZE];
#ifdef USE_SML_CRC
uint16_t so_sml_crc = 0;
struct SML_CRC_DATA* sml_crc_data;
#endif
#ifdef USE_SML_SPECOPT
uint32_t so_obis1;
uint32_t so_obis2;
uint8_t so_fcode1;
uint8_t so_bpos1;
uint8_t so_fcode2;
uint8_t so_bpos2;
#endif // USE_SML_SPECOPT
#ifdef ESP32
#ifndef USE_ESP32_SW_SERIAL
HardwareSerial *meter_ss;
#else
SML_ESP32_SERIAL *meter_ss;
#endif
// UART hardware number this meter is bound to (0..2), -1 = none / SW / TCP.
// Captured at serial-create time so SmlUploadPause/Resume can disable RX IRQs
// by IDF call directly on the raw-HardwareSerial path (Arduino-ESP32's
// HardwareSerial does not expose its uart_nr; SML_ESP32_SERIAL has its own
// helper). Without this, the ufsu RX-IRQ kill only covers USE_ESP32_SW_SERIAL
// builds — Andreas's .104 (raw HardwareSerial path) is exactly where the hang
// lives, so the fix HAS to reach this branch.
int8_t hw_uart_index = -1;
#endif // ESP32
// software serial pointers
#ifdef ESP8266
TasmotaSerial *meter_ss;
#endif // ESP8266
#ifdef USE_SML_DECRYPT
bool use_crypt = false;
uint8_t crypflags;
uint8_t last_iob;
uint8_t key[SML_CRYPT_SIZE];
Han_Parser *hp;
#ifdef USE_SML_AUTHKEY
uint8_t auth[SML_CRYPT_SIZE];
#endif // USE_SML_AUTHKEY
#endif // USE_SML_DECRYPT
#ifdef USE_SML_TCP
#ifdef USE_SML_TCP_IP_STR
char ip_addr[16];
#else
IPAddress ip_addr;
#endif // USE_SML_TCP_IP_STR
#ifdef USE_SML_TCP_SECURE
WiFiClientSecure *client;
#else
WiFiClient *client;
#endif // USE_SML_TCP_SECURE
#endif // USE_SML_TCP
#ifdef USE_SML_CANBUS
#ifdef ESP8266
MCP2515 *mcp2515;
#else
//twai_handle_t *canp;
#endif
uint32_t can_masks[SML_CAN_MASKS];
uint32_t can_filters[SML_CAN_FILTERS];
#endif // USE_SML_CANBUS
#ifdef ESP32
int8_t uart_index;
#endif
#ifdef USE_SML_EBUS_MASTER
uint8_t ebm_enh; // 0=off, 1=requested (handshaking), 2=confirmed enhanced
uint8_t ebm_raw; // 1 = raw active-master TEST mode (no adapter/arbitration; Mac-UART harness)
uint8_t ebm_qq; // our master address (QQ)
uint8_t ebm_state; // EBM_* state
uint8_t ebm_retry; // arbitration / init retry counter
uint8_t ebm_haveb1; // 1 = a pending enhanced byte1 is held
uint8_t ebm_b1; // the pending enhanced byte1
uint8_t ebm_txbuf[48]; // active telegram QQ..CRC (main task owns)
uint8_t ebm_txlen; // bytes in ebm_txbuf incl. CRC
uint8_t ebm_txpos; // next byte index to push to the adapter
uint8_t ebm_reqbuf[48]; // staging buffer (producer fills, incl. CRC)
uint8_t ebm_reqlen;
volatile uint8_t ebm_req; // request pending — producer sets this LAST
uint32_t ebm_t0; // millis() of last state transition (timeout base)
#ifdef USE_SML_EBUS_ARB
uint8_t ebm_arb; // 1 = in-firmware arbitration master (soA)
uint8_t eba_bus; // EBA_BUS_* bus-sequence state
uint8_t eba_phase; // EBA_* arbitration phase for this meter
uint8_t eba_restart; // restart-on-clobber counter
uint32_t eba_syn_us; // esp_timer_get_time() at the last observed SYN start
uint32_t eba_won, eba_lost, eba_late, eba_restarts; // diagnostics
uint32_t eba_arm_ms; // millis() when the current request was armed (watchdog base)
uint32_t eba_giveup; // requests the watchdog dropped (never won the bus)
#endif
#endif
};
#define TCP_MODE_FLG 0x7f
// Meter flags
#define PULLUP_FLG 0x01
#define ANALOG_FLG 0x02
#define MEDIAN_FILTER_FLG 0x10
#define NO_SYNC_FLG 0x20
struct METER_DESC meter_desc[MAX_METERS];
// this driver uses double because some meter vars would not fit in float
//=====================================================
// serial buffers, may be made larger depending on telegram lenght
#ifndef SML_BSIZ
#define SML_BSIZ 48
#endif
#define VBUS_SYNC 0xaa
#define SML_SYNC 0x77
#define EBUS_SYNC 0xaa
#define EBUS_ESC 0xa9
#ifdef USE_SML_EBUS_MASTER
// ebusd "enhanced protocol" — the eBUS adapter (https://adapter.ebusd.eu) does the
// timing-critical bus arbitration itself; the host exchanges 2-byte protocol symbols.
// byte1 = ENH_BYTE1 | (cmd<<2) | ((data&0xc0)>>6)
// byte2 = ENH_BYTE2 | (data&0x3f)
#define ENH_BYTE_FLAG 0x80
#define ENH_BYTE_MASK 0xc0
#define ENH_BYTE1 0xc0
#define ENH_BYTE2 0x80
// host -> device
#define ENH_REQ_INIT 0x0
#define ENH_REQ_SEND 0x1
#define ENH_REQ_START 0x2
#define ENH_REQ_INFO 0x3
// device -> host
#define ENH_RES_RESETTED 0x0
#define ENH_RES_RECEIVED 0x1
#define ENH_RES_STARTED 0x2
#define ENH_RES_INFO 0x3
#define ENH_RES_FAILED 0xa
#define ENH_RES_ERR_EBUS 0xb
#define ENH_RES_ERR_HOST 0xc
// active-master state machine
#define EBM_OFF 0
#define EBM_NEED_INIT 1
#define EBM_INIT_WAIT 2
#define EBM_IDLE 3
#define EBM_ARB_REQ 4
#define EBM_AWAIT_RESP 5
#define EBM_RELEASE 6
// events
#define EBM_EV_TICK 0
#define EBM_EV_ARB_WON 1
#define EBM_EV_ARB_LOST 2
#define EBM_EV_ERR 3
// tuning (ms / counts)
#define EBM_INIT_TMO 1500
#define EBM_ARB_TMO 150
#define EBM_RESP_TMO 300
#define EBM_ARB_MAX_RETRY 4
#define EBM_TX_START 1 // 1 = QQ already placed on bus by ENH_RES_STARTED; set 0 if not
#ifdef USE_SML_EBUS_ARB
// In-firmware eBUS bus arbitration (soA) — CLEAN-ROOM from the public eBUS spec, NOT copied from any
// implementation. eBUS facts used: SYN delimiter = 0xAA; a master wanting the bus writes its address
// (QQ) into the window 4300..4456 us after the SYN start bit (SYN symbol = 4167 us @2400 baud); the
// line is wired-AND (dominant 0) so the numerically-lowest address wins; arbitration runs in two
// priority rounds keyed on the address low nibble (same class -> second round). Read back our own
// byte from the shared wire to learn the winner. This MUST run in a dedicated per-symbol hot path
// (Eba_OnSymbol), never the ~50 ms SML_Poll loop.
//
// Bus sequence (which symbol slot we expect next), advanced per received symbol:
#define EBA_BUS_IDLE 0 // waiting for the first SYN
#define EBA_BUS_SYN 1 // saw a SYN; next non-SYN byte is a round-1 master address
#define EBA_BUS_ADDR1 2 // saw SYN+ADDR; next SYN opens round 2, else bus goes busy
#define EBA_BUS_SYN2 3 // saw SYN ADDR SYN; next byte is a round-2 master address
#define EBA_BUS_BUSY 4 // a telegram is in progress (until the next SYN)
// Arbitration phase for THIS meter:
#define EBA_OFF 0 // soA not enabled
#define EBA_IDLE 1 // enabled, nothing to send
#define EBA_ARMED 2 // telegram staged (ebm_req) — write QQ on the next first-SYN
#define EBA_R1 3 // wrote QQ in round 1, awaiting read-back
#define EBA_R2WAIT 4 // tied on priority class — will write QQ in round 2
#define EBA_R2 5 // wrote QQ in round 2, awaiting read-back
#define EBA_WON 6 // we own the bus — stream the staged telegram (from byte 1)
#define EBA_LOST 7 // lost this round — retry on a later SYN
// Timing (microseconds), per eBUS spec test_1 v1.1.1 section 3.2:
#define EBA_ARB_MIN_US 4300
#define EBA_ARB_MAX_US 4456
#ifndef EBM_ARB_TX_LEAD_US
#define EBM_ARB_TX_LEAD_US 700 // ESP32-C3 UART write()->wire latency; SCOPE-TUNE per target chip
#endif
#define EBA_MAX_RESTART 3 // restart arbitration up to N times if our byte gets clobbered
#define EBA_REQ_TMO_MS 3000 // watchdog: drop a queued request that never wins, freeing the slot
#endif // USE_SML_EBUS_ARB
#endif // USE_SML_EBUS_MASTER
// calulate deltas
#define MAX_DVARS MAX_METERS*2
#ifndef SML_DUMP_SIZE
#define SML_DUMP_SIZE 128
#endif
// median filter, should be odd size
#define MEDIAN_SIZE 5
struct SML_MEDIAN_FILTER {
double buffer[MEDIAN_SIZE];
int8_t index;
};
#define SML_OPTIONS_JSON_ENABLE 1
struct SML_GLOBS {
uint8_t sml_send_blocks;
uint8_t sml_100ms_cnt;
uint8_t sml_desc_cnt;
uint8_t meters_used;
uint8_t maxvars;
uint8_t *meter_p;
double *meter_vars;
uint8_t *dvalid;
double dvalues[MAX_DVARS];
uint32_t dtimes[MAX_DVARS];
char sml_start;
uint8_t dump2log = 0;
uint8_t ser_act_LED_pin = 255;
uint8_t ser_act_meter_num = 0;
uint16_t sml_logindex;
char *log_data;
uint16_t logsize = SML_DUMP_SIZE;
#if defined(ED300L) || defined(AS2020) || defined(DTZ541) || defined(USE_SML_SPECOPT)
uint8_t sml_status[MAX_METERS];
uint8_t g_mindex;
#endif
#ifdef USE_SML_MEDIAN_FILTER
struct SML_MEDIAN_FILTER *sml_mf;
#endif
uint8_t *script_meter;
struct METER_DESC *mp;
uint8_t to_cnt;
#ifdef USE_BAT_CTRL
uint8_t meter_switch_cooldown; // cooldown after meter switch (in 100ms ticks)
char sml_write_buf[2][96]; // 2-slot write queue for script commands
uint8_t sml_write_head; // next slot to write into (0 or 1)
uint8_t sml_write_tail; // next slot to send from (0 or 1)
uint8_t sml_write_meter; // meter index for queued writes
#endif // USE_BAT_CTRL
bool ready;
#ifdef USE_SML_CANBUS
uint8_t twai_installed;
#endif // USE_SML_CANBUS
uint8_t sml_options = SML_OPTIONS_JSON_ENABLE;
} sml_globs;
#ifdef USE_SML_MEDIAN_FILTER
#ifndef FLT_MAX
#define FLT_MAX 99999999
#endif
double sml_median_array(double *array, uint8_t len) {
uint8_t ind[len];
uint8_t mind = 0, index = 0, flg;
double min = FLT_MAX;
for (uint8_t hcnt = 0; hcnt < len / 2 + 1; hcnt++) {
for (uint8_t mcnt = 0; mcnt < len; mcnt++) {
flg = 0;
for (uint8_t icnt = 0; icnt < index; icnt++) {
if (ind[icnt] == mcnt) {
flg = 1;
}
}
if (!flg) {
if (array[mcnt] < min) {
min = array[mcnt];
mind = mcnt;
}
}
}
ind[index] = mind;
index++;
min = FLT_MAX;
}
return array[ind[len / 2]];
}
// calc median
double sml_median(struct SML_MEDIAN_FILTER* mf, double in) {
//double tbuff[MEDIAN_SIZE],tmp;
//uint8_t flag;
mf->buffer[mf->index] = in;
mf->index++;
if (mf->index >= MEDIAN_SIZE) mf->index = 0;
return sml_median_array(mf->buffer, MEDIAN_SIZE);
/*
// sort list and take median
memmove(tbuff,mf->buffer,sizeof(tbuff));
for (byte ocnt=0; ocnt<MEDIAN_SIZE; ocnt++) {
flag=0;
for (byte count=0; count<MEDIAN_SIZE-1; count++) {
if (tbuff[count]>tbuff[count+1]) {
tmp=tbuff[count];
tbuff[count]=tbuff[count+1];
tbuff[count+1]=tmp;
flag=1;
}
}
if (!flag) break;
}
return tbuff[MEDIAN_SIZE/2];
*/
}
#endif
#define SML_SAVAILABLE Serial_available()
#define SML_SREAD Serial_read()
#define SML_SPEEK Serial_peek()
uint16_t Serial_available() {
uint8_t num = sml_globs.dump2log & 7;
if (num < 1 || num > sml_globs.meters_used) num = 1;
num--;
if (meter_desc[num].srcpin != TCP_MODE_FLG) {
if (!meter_desc[num].meter_ss) return 0;
return meter_desc[num].meter_ss->available();
} else {
if (meter_desc[num].client) {
return meter_desc[num].client->available();
} else {
return 0;
}
}
}
uint8_t Serial_read() {
uint8_t num = sml_globs.dump2log & 7;
if (num < 1 || num > sml_globs.meters_used) num = 1;
num--;
if (meter_desc[num].srcpin != TCP_MODE_FLG) {
if (!meter_desc[num].meter_ss) return 0;
return meter_desc[num].meter_ss->read();
} else {
if (meter_desc[num].client) {
return meter_desc[num].client->read();
} else {
return 0;
}
}
}
uint8_t Serial_peek() {
uint8_t num = sml_globs.dump2log & 7;
if (num < 1 || num > sml_globs.meters_used) num = 1;
num--;
if (meter_desc[num].srcpin != TCP_MODE_FLG) {
if (!meter_desc[num].meter_ss) return 0;
return meter_desc[num].meter_ss->peek();
} else {
if (meter_desc[num].client) {
return meter_desc[num].client->peek();
} else {
return 0;
}
}
}
void sml_dump_start(char c) {
sml_globs.log_data[0] = ':';
sml_globs.log_data[1] = c;
sml_globs.sml_logindex = 2;
}
#define SML_EBUS_SKIP_SYNC_DUMPS
void dump2log(void) {
int16_t index = 0, hcnt = 0;
uint32_t d_lastms;
uint8_t dchars[16];
uint8_t meter = (sml_globs.dump2log & 7) - 1;
uint8_t type = sml_globs.mp[meter].type;
//if (!SML_SAVAILABLE) return;
if (!sml_globs.log_data) return;
struct METER_DESC *mp = &meter_desc[meter];
#ifdef USE_SML_DECRYPT
if (mp->use_crypt == true) {
d_lastms = millis();
while ((millis() - d_lastms) < 50) {
while (SML_SAVAILABLE) {
d_lastms = millis();
uint16_t logsiz;
uint8_t *payload;
if (mp->hp->readHanPort(&payload, &logsiz, mp->crypflags)) {
if (logsiz > mp->sbsiz) {
logsiz = mp->sbsiz;
}
memmove(mp->sbuff, payload, logsiz);
AddLog(LOG_LEVEL_INFO, PSTR("SML: decrypted block: %d bytes"), logsiz);
uint16_t index = 0;
while (logsiz) {
sml_dump_start('>');