Repository navigation
Expand file tree
/
Copy pathltc2983_handler.h
More file actions
executable file
·633 lines (569 loc) · 23.4 KB
/
Copy pathltc2983_handler.h
File metadata and controls
executable file
·633 lines (569 loc) · 23.4 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
#pragma once
#include "esphome.h"
#include "esphome/core/log.h"
#include "driver/gpio.h"
#include "driver/spi_master.h"
#include <cmath>
#include <cstring>
static const char *const TAG = "LTC2983";
// RULE: always 5 RTD + 5 TC slots — never trim entities.
// RTD1–5 → CH4, CH6, CH8, CH10, CH12 (2-wire PT1000). Each RTD's return leg
// lands on the odd channel below it (CH3/5/7/9/11), all tied to CH2
// — the top of the shared 2k RSENSE that spans CH1–CH2. CH1 floats:
// grounding it is only correct when RSENSE is NOT shared (B18=0).
// TC1–5 → CH13, CH14, CH15, CH16, CH17 (Type-K, single-ended, TC− → COM)
// CJC → CH20 (2N3906, anode CH20, base+collector → COM). COM → GND.
// Per-channel conversion (not multi-channel batch) for SPI reliability.
// Published temps are °F.
#define LTC2983_COMMAND_STATUS_REG 0x0000
#define LTC2983_GLOBAL_CONFIG_REG 0x00F0
#define LTC2983_MUX_CONFIG_REG 0x00FF
#define LTC2983_CH_ASSIGN_BASE 0x0200
#define LTC2983_DATA_BASE 0x0010
#define LTC2983_CONV_SINGLE(ch) (0x80 | (ch))
#define STATUS_DONE_MASK 0x40
#define STATUS_START_MASK 0x80
#define LTC2983_CS_PIN GPIO_NUM_2
#define LTC2983_SPI_HOST SPI2_HOST
#define LTC2983_SPI_CLK GPIO_NUM_9
#define LTC2983_SPI_MOSI GPIO_NUM_5
#define LTC2983_SPI_MISO GPIO_NUM_4
// 250kHz. The chip handles 2MHz on a clean board, but this one reaches the
// LTC2983 over unshielded jumper leads with no ground plane between them, so
// slow edges buy noise margin. Sensors only need a few seconds per update.
#define LTC2983_SPI_HZ 250000
#define CH_RSENSE 2
#define CH_RTD_1 4
#define CH_RTD_2 6
#define CH_RTD_3 8
#define CH_RTD_4 10
#define CH_RTD_5 12
#define CH_TC_1 13
#define CH_TC_2 14
#define CH_TC_3 15
#define CH_TC_4 16
#define CH_TC_5 17
#define CH_DIODE_P 20
#define NUM_RTD 5
#define NUM_TC 5
// RSENSE value field is B26:B0 at 1/1024 Ω. 0x001F4000 = 2000.000 Ω.
// Replace with the DMM-measured value of the installed resistor for best
// RTD accuracy — its tolerance lands directly on every RTD reading.
#define CFG_RSENSE (((uint32_t)0x1D << 27) | 0x001F4000UL)
// 2-wire (B21:B20=00), no rotation (B19=0), shared RSENSE (B18=1),
// 250µA excitation (B17:B14=0110), European curve (B13:B12=00).
#define CFG_RTD_PT1000 (((uint32_t)0x0F << 27) | ((uint32_t)CH_RSENSE << 22) \
| (0x1UL << 18) | (0x6UL << 14))
// Extra MUX settle, 100µs per LSB, on top of the chip's internal 2ms.
// Inputs carry only 100pF, so no extra settling is needed.
#define MUX_SETTLE_LSB 0
// Diode: single-ended, 3 conversion cycles, averaging on, 80µA excitation.
// Ideality factor left at 0 — datasheet Table 20: all zeros selects the
// factory default of 1.003, which is correct for the 2N3906.
#define CFG_DIODE_CJC (((uint32_t)0x1C << 27) | (7UL << 24) | (3UL << 22))
// Type K, CJC on CH20, single-ended (B21=1), open-circuit detect on (B20=1)
// with the default 10µA test current (B19:B18=00).
#define CFG_TC_K_SE (((uint32_t)0x02 << 27) | ((uint32_t)CH_DIODE_P << 22) \
| (1UL << 21) | (0x1UL << 20))
// Direct ADC single-ended is B26, not B21 (B21 is the thermocouple field).
#define CFG_DIRECT_ADC (((uint32_t)0x1E << 27) | (1UL << 26))
static constexpr uint8_t RTD_CHANNELS[NUM_RTD] = {
CH_RTD_1, CH_RTD_2, CH_RTD_3, CH_RTD_4, CH_RTD_5,
};
static constexpr uint8_t TC_CHANNELS[NUM_TC] = {
CH_TC_1, CH_TC_2, CH_TC_3, CH_TC_4, CH_TC_5,
};
static constexpr float TC_TEMP_MIN_C = -200.0f;
static constexpr float TC_TEMP_MAX_C = 1370.0f;
static constexpr float RTD_TEMP_MIN_C = -50.0f; // -58 °F
static constexpr float RTD_TEMP_MAX_C = 300.0f; // 572 °F
static constexpr float CJC_TEMP_MIN_C = -40.0f;
static constexpr float CJC_TEMP_MAX_C = 125.0f;
static inline float c_to_f(float c) { return c * 1.8f + 32.0f; }
// Fault bits are datasheet Table 10 (result word D31:D24). There is no
// "open circuit" or "short to VDD" bit — an open sensor shows up as
// Sensor Hard Fault + Sensor Over Range.
enum FaultCode : uint8_t {
FAULT_OK = 0,
FAULT_SENSOR_HARD, // D31 open/shorted/backwards sensor, or bad ADC read
FAULT_ADC_HARD, // D30 bad ADC reading (open sensor or ESD/noise event)
FAULT_CJ_HARD, // D29 cold junction sensor hard fault
FAULT_CJ_SOFT, // D28 cold junction beyond its normal range
FAULT_OVER_RANGE, // D27 sensor reading above normal range
FAULT_UNDER_RANGE, // D26 sensor reading below normal range
FAULT_ADC_RANGE, // D25 |Vin| beyond 1.125 * VREF/2
FAULT_TIMEOUT,
FAULT_INVALID, // D24 clear
FAULT_OFFLINE, // chip not answering on SPI at all
};
static const char *const FAULT_TEXT[] = {
"OK",
"Sensor Hard Fault",
"ADC Hard Fault",
"CJ Hard Fault",
"CJ Soft Fault",
"Over Range",
"Under Range",
"ADC Out of Range",
"Timeout",
"Invalid",
"Chip Offline",
};
enum ChKind : uint8_t { KIND_RTD, KIND_TC, KIND_DIODE };
struct LtcSensors {
esphome::template_::TemplateSensor *rtd[NUM_RTD];
esphome::template_::TemplateSensor *tc[NUM_TC];
esphome::template_::TemplateSensor *cjc;
esphome::text_sensor::TextSensor *fault_rtd[NUM_RTD];
esphome::text_sensor::TextSensor *fault_tc[NUM_TC];
esphome::text_sensor::TextSensor *fault_cjc;
esphome::template_::TemplateSensor *diag_spi_errors;
esphome::template_::TemplateSensor *diag_reconfigs;
esphome::text_sensor::TextSensor *diag_link;
};
static spi_device_handle_t ltc2983_spi_device = nullptr;
static bool ltc2983_spi_bus_ready = false;
static uint8_t ltc2983_fail_streak = 0;
// Health counters. The LTC2983's SPI has no framing, parity or CRC — a bounced
// contact shifts the byte stream and the chip acts on whatever it decodes, so a
// corrupt write can land in a channel assignment register and silently unconfigure
// a sensor. These count how often the wire misbehaves; publish them so a
// degrading connection is visible before it starts dropping readings.
static uint32_t ltc2983_spi_errors = 0;
static uint32_t ltc2983_reconfigs = 0;
// Number of agreeing retries before a transfer is trusted or abandoned.
static constexpr uint8_t SPI_RETRIES = 3;
static void ltc2983_cs_low() { gpio_set_level(LTC2983_CS_PIN, 0); }
static void ltc2983_cs_high() { gpio_set_level(LTC2983_CS_PIN, 1); }
static bool ltc2983_spi_transfer(uint8_t data, uint8_t *rx_out = nullptr) {
if (ltc2983_spi_device == nullptr) return false;
uint8_t rx = 0;
spi_transaction_t t = {};
t.length = 8;
t.tx_buffer = &data;
t.rx_buffer = ℞
if (spi_device_polling_transmit(ltc2983_spi_device, &t) != ESP_OK) return false;
if (rx_out) *rx_out = rx;
return true;
}
static bool spi_addr(uint8_t cmd, uint16_t reg) {
return ltc2983_spi_transfer(cmd) &&
ltc2983_spi_transfer((reg >> 8) & 0xFF) &&
ltc2983_spi_transfer(reg & 0xFF);
}
static bool write_byte_raw(uint16_t reg, uint8_t data) {
ltc2983_cs_low();
bool ok = spi_addr(0x02, reg) && ltc2983_spi_transfer(data);
ltc2983_cs_high();
return ok;
}
static bool write_dword_raw(uint16_t reg, uint32_t data) {
ltc2983_cs_low();
bool ok = spi_addr(0x02, reg) &&
ltc2983_spi_transfer((data >> 24) & 0xFF) &&
ltc2983_spi_transfer((data >> 16) & 0xFF) &&
ltc2983_spi_transfer((data >> 8) & 0xFF) &&
ltc2983_spi_transfer(data & 0xFF);
ltc2983_cs_high();
return ok;
}
static bool read_byte_raw(uint16_t reg, uint8_t *out) {
ltc2983_cs_low();
bool ok = spi_addr(0x03, reg) && ltc2983_spi_transfer(0x00, out);
ltc2983_cs_high();
return ok;
}
static bool read_dword_raw(uint16_t reg, uint32_t *out) {
uint8_t b[4] = {0, 0, 0, 0};
ltc2983_cs_low();
bool ok = spi_addr(0x03, reg) &&
ltc2983_spi_transfer(0x00, &b[0]) &&
ltc2983_spi_transfer(0x00, &b[1]) &&
ltc2983_spi_transfer(0x00, &b[2]) &&
ltc2983_spi_transfer(0x00, &b[3]);
ltc2983_cs_high();
if (!ok) return false;
*out = ((uint32_t)b[0] << 24) | ((uint32_t)b[1] << 16) |
((uint32_t)b[2] << 8) | (uint32_t)b[3];
return true;
}
// Every register we read this way holds still between conversions, so two reads
// must agree. A disagreement means the bus corrupted one of them — the failure
// mode that was quietly feeding us bad data. Retry rather than trust either.
static bool read_dword(uint16_t reg, uint32_t *out) {
for (uint8_t attempt = 0; attempt < SPI_RETRIES; ++attempt) {
uint32_t a = 0, b = 0;
if (read_dword_raw(reg, &a) && read_dword_raw(reg, &b) && a == b) {
*out = a;
return true;
}
ltc2983_spi_errors++;
}
ESP_LOGW(TAG, "SPI read of 0x%04X unstable after %d tries", reg, SPI_RETRIES);
return false;
}
// Writes are the dangerous direction: a corrupted one silently changes chip
// state. Read back and retry until the chip agrees it received what we sent.
static bool write_dword(uint16_t reg, uint32_t data) {
for (uint8_t attempt = 0; attempt < SPI_RETRIES; ++attempt) {
uint32_t check = 0;
if (write_dword_raw(reg, data) && read_dword_raw(reg, &check) && check == data)
return true;
ltc2983_spi_errors++;
}
ESP_LOGE(TAG, "SPI write of 0x%04X did not stick after %d tries", reg, SPI_RETRIES);
return false;
}
// The status register is volatile, so it cannot be verified by reading twice.
// 0x00 and 0xFF are both impossible for a live chip (bit D6 is always set once
// started) and are exactly what a floating MISO returns, so reject them.
static bool read_status(uint8_t *out) {
for (uint8_t attempt = 0; attempt < SPI_RETRIES; ++attempt) {
uint8_t st = 0;
if (read_byte_raw(LTC2983_COMMAND_STATUS_REG, &st) && st != 0x00 && st != 0xFF) {
*out = st;
return true;
}
ltc2983_spi_errors++;
}
return false;
}
static bool write_byte(uint16_t reg, uint8_t data) {
for (uint8_t attempt = 0; attempt < SPI_RETRIES; ++attempt) {
if (write_byte_raw(reg, data)) return true;
ltc2983_spi_errors++;
}
return false;
}
static inline uint16_t ch_assign_addr(uint8_t ch) {
return LTC2983_CH_ASSIGN_BASE + (uint16_t)(ch - 1) * 4;
}
static inline uint16_t ch_data_addr(uint8_t ch) {
return LTC2983_DATA_BASE + (uint16_t)(ch - 1) * 4;
}
static void ltc2983_reset() {
if (ltc2983_spi_device != nullptr) {
spi_bus_remove_device(ltc2983_spi_device);
ltc2983_spi_device = nullptr;
}
}
// SPI bus/device bring-up only. Does not touch the chip, so it never blocks.
static bool spi_setup() {
gpio_config_t cs_cfg = {};
cs_cfg.pin_bit_mask = (1ULL << LTC2983_CS_PIN);
cs_cfg.mode = GPIO_MODE_OUTPUT;
cs_cfg.pull_up_en = GPIO_PULLUP_DISABLE;
cs_cfg.pull_down_en = GPIO_PULLDOWN_DISABLE;
cs_cfg.intr_type = GPIO_INTR_DISABLE;
gpio_config(&cs_cfg);
ltc2983_cs_high();
if (!ltc2983_spi_bus_ready) {
spi_bus_config_t bus = {};
bus.mosi_io_num = LTC2983_SPI_MOSI;
bus.miso_io_num = LTC2983_SPI_MISO;
bus.sclk_io_num = LTC2983_SPI_CLK;
bus.quadwp_io_num = -1;
bus.quadhd_io_num = -1;
bus.max_transfer_sz = 32;
esp_err_t err = spi_bus_initialize(LTC2983_SPI_HOST, &bus, SPI_DMA_DISABLED);
if (err != ESP_OK && err != ESP_ERR_INVALID_STATE) {
ESP_LOGE(TAG, "SPI bus init failed: %s", esp_err_to_name(err));
return false;
}
ltc2983_spi_bus_ready = true;
}
if (ltc2983_spi_device == nullptr) {
spi_device_interface_config_t dev = {};
dev.clock_speed_hz = LTC2983_SPI_HZ;
dev.mode = 0;
dev.spics_io_num = -1;
dev.queue_size = 1;
dev.input_delay_ns = 200; // allow for round-trip delay over long leads
esp_err_t err = spi_bus_add_device(LTC2983_SPI_HOST, &dev, <c2983_spi_device);
if (err != ESP_OK) {
ESP_LOGE(TAG, "SPI device add failed: %s", esp_err_to_name(err));
return false;
}
}
return true;
}
// True when the chip has finished start-up and is idle. A floating bus reads
// 0x00 or 0xFF, neither of which can satisfy this, so it doubles as a
// presence check.
static bool chip_ready() {
uint8_t st = 0;
if (!read_status(&st)) return false;
return (st & STATUS_START_MASK) == 0 && (st & STATUS_DONE_MASK) != 0;
}
// The assignment every configured channel must hold. Anything else means the
// chip lost it, and its readings are meaningless until it is rewritten.
static uint32_t expected_cfg(uint8_t ch) {
if (ch == CH_RSENSE) return (uint32_t) CFG_RSENSE;
if (ch == CH_DIODE_P) return (uint32_t) CFG_DIODE_CJC;
for (uint8_t c : RTD_CHANNELS) if (c == ch) return (uint32_t) CFG_RTD_PT1000;
for (uint8_t c : TC_CHANNELS) if (c == ch) return (uint32_t) CFG_TC_K_SE;
return 0;
}
static bool write_all_config() {
bool ok = true;
for (uint8_t ch = 1; ch <= 20; ++ch)
ok &= write_dword(ch_assign_addr(ch), 0);
ok &= write_dword(ch_assign_addr(CH_RSENSE), CFG_RSENSE);
for (uint8_t ch : RTD_CHANNELS)
ok &= write_dword(ch_assign_addr(ch), CFG_RTD_PT1000);
for (uint8_t ch : TC_CHANNELS)
ok &= write_dword(ch_assign_addr(ch), CFG_TC_K_SE);
ok &= write_dword(ch_assign_addr(CH_DIODE_P), CFG_DIODE_CJC);
ok &= write_byte(LTC2983_MUX_CONFIG_REG, MUX_SETTLE_LSB);
// 0x01 = 120dB rejection at 60Hz. Default 0x00 is simultaneous 50/60Hz at
// only 75dB; this board runs on US mains next to motor/igniter loads.
ok &= write_byte(LTC2983_GLOBAL_CONFIG_REG, 0x01);
if (!ok) {
ESP_LOGE(TAG, "configuration did not verify — SPI errors=%u", ltc2983_spi_errors);
return false;
}
ESP_LOGI(TAG, "ready — RTD %d/%d/%d/%d/%d TC %d–%d CJC %d SPI=%dHz MUX=+%.1fms",
CH_RTD_1, CH_RTD_2, CH_RTD_3, CH_RTD_4, CH_RTD_5,
CH_TC_1, CH_TC_5, CH_DIODE_P, LTC2983_SPI_HZ, MUX_SETTLE_LSB / 10.0f);
ESP_LOGI(TAG, "all 12 assignments verified — SPI errors=%u reloads=%u",
ltc2983_spi_errors, ltc2983_reconfigs);
return true;
}
// The chip can brown out, be reset, or have an assignment register overwritten
// by a corrupted SPI write, all without the ESP32 noticing. SPI keeps working,
// so nothing times out — the affected channel just reports -999 with every
// fault bit set, forever. Verify the channel we are about to trust, every time:
// one extra read per conversion covers all 12 registers each scan, where the
// old single check of CH4 would have missed corruption on any other channel.
static bool channel_config_ok(uint8_t ch) {
uint32_t cfg = 0;
if (!read_dword(ch_assign_addr(ch), &cfg)) return false;
uint32_t want = expected_cfg(ch);
if (cfg == want) return true;
ESP_LOGW(TAG, "CH%d assignment is 0x%08X, expected 0x%08X", ch, cfg, want);
return false;
}
static float parse_temperature(uint32_t raw) {
if (!(raw & (1UL << 24))) return NAN;
int32_t t = (int32_t)(raw & 0x00FFFFFFUL);
if (t & 0x00800000L) t |= (int32_t)0xFF000000;
return (float)t / 1024.0f;
}
static FaultCode decode_fault(uint32_t raw) {
if (!(raw & (1UL << 24))) return FAULT_INVALID;
uint8_t fb = (raw >> 24) & 0xFF;
if (fb & 0x80) return FAULT_SENSOR_HARD; // D31
if (fb & 0x40) return FAULT_ADC_HARD; // D30
if (fb & 0x20) return FAULT_CJ_HARD; // D29
if (fb & 0x08) return FAULT_OVER_RANGE; // D27
if (fb & 0x04) return FAULT_UNDER_RANGE; // D26
if (fb & 0x02) return FAULT_ADC_RANGE; // D25
if (fb & 0x10) return FAULT_CJ_SOFT; // D28
return FAULT_OK;
}
// Hard faults mean the result is -999 and must be discarded. Soft faults still
// carry a usable number with degraded accuracy. Thermocouples additionally treat
// a cold junction hard fault (D29) as hard, since CJC feeds their result.
static bool is_hard_fault(uint32_t raw, bool is_tc) {
if (!(raw & (1UL << 24))) return true;
return (raw & (is_tc ? 0xE0000000UL : 0xC0000000UL)) != 0;
}
static void publish_channel(uint8_t ch, esphome::template_::TemplateSensor *sensor,
esphome::text_sensor::TextSensor *fault_sensor,
ChKind kind, uint32_t raw) {
FaultCode fault = decode_fault(raw);
float temp = parse_temperature(raw);
float min_c = RTD_TEMP_MIN_C, max_c = RTD_TEMP_MAX_C;
if (kind == KIND_TC) {
min_c = TC_TEMP_MIN_C; max_c = TC_TEMP_MAX_C;
} else if (kind == KIND_DIODE) {
min_c = CJC_TEMP_MIN_C; max_c = CJC_TEMP_MAX_C;
}
bool ok = !is_hard_fault(raw, kind == KIND_TC) && !std::isnan(temp) &&
temp > min_c && temp < max_c;
float temp_f = c_to_f(temp);
if (ok) {
if (fault == FAULT_OK) {
ESP_LOGI(TAG, "CH%d: %.1f°F OK", ch, temp_f);
} else {
ESP_LOGW(TAG, "CH%d: %.1f°F raw=0x%08X soft fault=%s — accuracy degraded",
ch, temp_f, raw, FAULT_TEXT[fault]);
}
if (sensor) sensor->publish_state(temp_f);
if (fault_sensor) fault_sensor->publish_state(FAULT_TEXT[fault]);
} else {
ESP_LOGW(TAG, "CH%d: raw=0x%08X fb=0x%02X %.1f°C (%.1f°F) fault=%s — rejected",
ch, raw, (uint8_t)((raw >> 24) & 0xFF), temp, temp_f, FAULT_TEXT[fault]);
if (sensor) sensor->publish_state(NAN);
if (fault_sensor) fault_sensor->publish_state(FAULT_TEXT[fault]);
}
}
// ---------------------------------------------------------------------------
// Tick-driven scan. One conversion spans several ticks; each tick does at most
// a few SPI byte transfers, so the ESPHome main loop is never blocked. The old
// version ran all 11 conversions inline and stalled the loop for ~2.9s.
// ---------------------------------------------------------------------------
struct ScanEntry { uint8_t ch; ChKind kind; };
static constexpr ScanEntry SCAN[] = {
{CH_DIODE_P, KIND_DIODE},
{CH_RTD_1, KIND_RTD}, {CH_RTD_2, KIND_RTD}, {CH_RTD_3, KIND_RTD},
{CH_RTD_4, KIND_RTD}, {CH_RTD_5, KIND_RTD},
{CH_TC_1, KIND_TC}, {CH_TC_2, KIND_TC}, {CH_TC_3, KIND_TC},
{CH_TC_4, KIND_TC}, {CH_TC_5, KIND_TC},
};
static constexpr uint8_t SCAN_LEN = sizeof(SCAN) / sizeof(SCAN[0]);
// Tick period is LTC_TICK_MS (see the interval in the YAML).
static constexpr uint16_t READY_MAX_TICKS = 40; // ~10s waiting for start-up
static constexpr uint16_t CONV_MAX_TICKS = 16; // ~4s for one conversion
enum LtcState : uint8_t {
ST_SPI_SETUP,
ST_WAIT_READY,
ST_START_CONV,
ST_WAIT_CONV,
};
static LtcState ltc_state = ST_SPI_SETUP;
static uint8_t ltc_idx = 0;
static uint16_t ltc_waits = 0;
static bool ltc_offline = false;
static void sensors_for(const LtcSensors &s, uint8_t idx,
esphome::template_::TemplateSensor **sens,
esphome::text_sensor::TextSensor **flt) {
if (idx == 0) {
*sens = s.cjc; *flt = s.fault_cjc;
} else if (idx <= NUM_RTD) {
*sens = s.rtd[idx - 1]; *flt = s.fault_rtd[idx - 1];
} else {
*sens = s.tc[idx - 1 - NUM_RTD]; *flt = s.fault_tc[idx - 1 - NUM_RTD];
}
}
// Blank every entity so a dead bus shows as unknown across the board instead of
// leaving a mix of frozen readings and stale faults on the dashboard.
static void publish_offline(const LtcSensors &s) {
if (ltc_offline) return;
ltc_offline = true;
ESP_LOGE(TAG, "chip offline — blanking all channels");
for (uint8_t i = 0; i < SCAN_LEN; ++i) {
esphome::template_::TemplateSensor *sens = nullptr;
esphome::text_sensor::TextSensor *flt = nullptr;
sensors_for(s, i, &sens, &flt);
if (sens) sens->publish_state(NAN);
if (flt) flt->publish_state(FAULT_TEXT[FAULT_OFFLINE]);
}
}
// Counters and link state, so a connection that is degrading but still working
// is visible in Home Assistant rather than only in the serial log.
static void publish_health(const LtcSensors &s, const char *link) {
static uint32_t last_errors = 0xFFFFFFFF;
static uint32_t last_reconfigs = 0xFFFFFFFF;
static const char *last_link = nullptr;
if (s.diag_spi_errors && ltc2983_spi_errors != last_errors) {
s.diag_spi_errors->publish_state((float) ltc2983_spi_errors);
last_errors = ltc2983_spi_errors;
}
if (s.diag_reconfigs && ltc2983_reconfigs != last_reconfigs) {
s.diag_reconfigs->publish_state((float) ltc2983_reconfigs);
last_reconfigs = ltc2983_reconfigs;
}
if (s.diag_link && (last_link == nullptr || strcmp(link, last_link) != 0)) {
s.diag_link->publish_state(link);
last_link = link;
}
}
inline void read_ltc2983_sensors(const LtcSensors &s) {
switch (ltc_state) {
case ST_SPI_SETUP:
if (!spi_setup()) return;
ltc_waits = 0;
ltc_state = ST_WAIT_READY;
return;
case ST_WAIT_READY:
if (chip_ready()) {
// A reconfigure that cannot be verified means the bus is too corrupt to
// trust. Stay offline rather than run against unknown chip state.
if (!write_all_config()) {
publish_offline(s);
publish_health(s, "Fault");
ltc_waits = 0;
return;
}
if (ltc_offline) {
ESP_LOGI(TAG, "chip back online");
ltc_offline = false;
}
publish_health(s, ltc2983_spi_errors ? "Online (degraded)" : "Online");
ltc_idx = 0;
ltc_state = ST_START_CONV;
return;
}
if (++ltc_waits > READY_MAX_TICKS) {
uint8_t st = 0;
bool got = read_status(&st);
ESP_LOGE(TAG, "chip not ready — status=%s", got ? "invalid" : "no response");
publish_offline(s);
publish_health(s, "Offline");
ltc_waits = 0;
ltc2983_reset();
ltc_state = ST_SPI_SETUP;
}
return;
case ST_START_CONV:
// Verify this channel's assignment before trusting the conversion it is
// about to produce. Rotating through the scan covers every register.
if (!channel_config_ok(SCAN[ltc_idx].ch) ||
(SCAN[ltc_idx].kind == KIND_RTD && !channel_config_ok(CH_RSENSE))) {
ltc2983_reconfigs++;
ESP_LOGW(TAG, "channel assignments lost — reconfiguring chip (reload #%u)",
ltc2983_reconfigs);
publish_health(s, "Online (degraded)");
ltc_waits = 0;
ltc_state = ST_WAIT_READY;
return;
}
if (!write_byte(LTC2983_COMMAND_STATUS_REG, LTC2983_CONV_SINGLE(SCAN[ltc_idx].ch))) {
ltc_state = ST_WAIT_READY;
ltc_waits = 0;
return;
}
ltc_waits = 0;
ltc_state = ST_WAIT_CONV;
return;
case ST_WAIT_CONV: {
esphome::template_::TemplateSensor *sens = nullptr;
esphome::text_sensor::TextSensor *flt = nullptr;
sensors_for(s, ltc_idx, &sens, &flt);
if (!chip_ready()) {
if (++ltc_waits > CONV_MAX_TICKS) {
ESP_LOGW(TAG, "CH%d: conversion timeout", SCAN[ltc_idx].ch);
if (sens) sens->publish_state(NAN);
if (flt) flt->publish_state(FAULT_TEXT[FAULT_TIMEOUT]);
if (++ltc2983_fail_streak >= 3) {
ESP_LOGW(TAG, "resetting chip after %d timeouts", ltc2983_fail_streak);
ltc2983_fail_streak = 0;
ltc2983_reset();
ltc_state = ST_SPI_SETUP;
return;
}
ltc_idx = (ltc_idx + 1) % SCAN_LEN;
ltc_state = ST_START_CONV;
}
return;
}
ltc2983_fail_streak = 0;
uint32_t raw = 0;
if (!read_dword(ch_data_addr(SCAN[ltc_idx].ch), &raw)) {
// Two reads never agreed, so no value here is trustworthy. Blank the
// channel instead of publishing one of the disagreeing samples.
ESP_LOGW(TAG, "CH%d: result unreadable — rejected", SCAN[ltc_idx].ch);
if (sens) sens->publish_state(NAN);
if (flt) flt->publish_state(FAULT_TEXT[FAULT_OFFLINE]);
} else {
publish_channel(SCAN[ltc_idx].ch, sens, flt, SCAN[ltc_idx].kind, raw);
}
ltc_idx = (ltc_idx + 1) % SCAN_LEN;
if (ltc_idx == 0)
publish_health(s, ltc2983_spi_errors ? "Online (degraded)" : "Online");
ltc_state = ST_START_CONV;
return;
}
}
}