Add multi-meter energy sender schema with UART0/1/2 mode split

This commit is contained in:
2026-02-04 15:22:24 +01:00
parent 290ca55b8b
commit 938f490a32
10 changed files with 307 additions and 292 deletions

View File

@@ -32,7 +32,9 @@ constexpr uint8_t PIN_BAT_ADC = 35;
constexpr uint8_t PIN_ROLE = 14; constexpr uint8_t PIN_ROLE = 14;
constexpr uint8_t PIN_OLED_CTRL = 13; constexpr uint8_t PIN_OLED_CTRL = 13;
constexpr uint8_t PIN_METER_RX = 34; constexpr uint8_t PIN_METER1_RX = 34; // UART2 RX
constexpr uint8_t PIN_METER2_RX = 25; // UART1 RX
constexpr uint8_t PIN_METER3_RX = 3; // UART0 RX (prod only, when serial debug is off)
// LoRa settings // LoRa settings
#ifndef LORA_FREQUENCY_HZ #ifndef LORA_FREQUENCY_HZ
@@ -68,6 +70,9 @@ constexpr bool ENABLE_HA_DISCOVERY = true;
#define SERIAL_DEBUG_MODE_FLAG 0 #define SERIAL_DEBUG_MODE_FLAG 0
#endif #endif
constexpr bool SERIAL_DEBUG_MODE = SERIAL_DEBUG_MODE_FLAG != 0; constexpr bool SERIAL_DEBUG_MODE = SERIAL_DEBUG_MODE_FLAG != 0;
constexpr uint8_t METER_COUNT_DEBUG = 2;
constexpr uint8_t METER_COUNT_PROD = 3;
constexpr uint8_t METER_COUNT = SERIAL_DEBUG_MODE ? METER_COUNT_DEBUG : METER_COUNT_PROD;
constexpr bool SERIAL_DEBUG_DUMP_JSON = false; constexpr bool SERIAL_DEBUG_DUMP_JSON = false;
constexpr bool LORA_SEND_BYPASS = false; constexpr bool LORA_SEND_BYPASS = false;
constexpr bool ENABLE_SD_LOGGING = true; constexpr bool ENABLE_SD_LOGGING = true;

View File

@@ -28,6 +28,9 @@ struct MeterData {
uint32_t ts_utc; uint32_t ts_utc;
uint16_t short_id; uint16_t short_id;
char device_id[16]; char device_id[16];
bool energy_multi;
uint8_t energy_meter_count;
uint32_t energy_kwh_int[3];
float energy_total_kwh; float energy_total_kwh;
float phase_power_w[3]; float phase_power_w[3];
float total_power_w; float total_power_w;

View File

@@ -1,9 +1,8 @@
#pragma once #pragma once
#include <Arduino.h> #include <Arduino.h>
#include "data_model.h"
void meter_init(); void meter_init();
bool meter_read(MeterData &data); void meter_poll();
bool meter_poll_frame(const char *&frame, size_t &len); uint8_t meter_count();
bool meter_parse_frame(const char *frame, size_t len, MeterData &data); bool meter_get_last_energy_kwh(uint8_t meter_idx, uint32_t &out_energy_kwh);

View File

@@ -350,9 +350,18 @@ static void render_receiver_sender(uint8_t index) {
#endif #endif
display.setCursor(0, 12); display.setCursor(0, 12);
display.printf("E %.2f kWh", status.last_data.energy_total_kwh); if (status.last_data.energy_multi) {
display.printf("E1 %lu E2 %lu", static_cast<unsigned long>(status.last_data.energy_kwh_int[0]),
static_cast<unsigned long>(status.last_data.energy_kwh_int[1]));
} else {
display.printf("E %.2f kWh", status.last_data.energy_total_kwh);
}
display.setCursor(0, 22); display.setCursor(0, 22);
display.printf("L1 %dW", static_cast<int>(round_power_w(status.last_data.phase_power_w[0]))); if (status.last_data.energy_multi && status.last_data.energy_meter_count >= 3) {
display.printf("E3 %lu", static_cast<unsigned long>(status.last_data.energy_kwh_int[2]));
} else {
display.printf("L1 %dW", static_cast<int>(round_power_w(status.last_data.phase_power_w[0])));
}
display.setCursor(0, 32); display.setCursor(0, 32);
display.printf("L2 %dW", static_cast<int>(round_power_w(status.last_data.phase_power_w[1]))); display.printf("L2 %dW", static_cast<int>(round_power_w(status.last_data.phase_power_w[1])));
display.setCursor(0, 42); display.setCursor(0, 42);

View File

@@ -58,16 +58,24 @@ static void set_int_or_null(JsonDocument &doc, const char *key, float value) {
} }
bool meterDataToJson(const MeterData &data, String &out_json) { bool meterDataToJson(const MeterData &data, String &out_json) {
StaticJsonDocument<256> doc; StaticJsonDocument<320> doc;
doc["id"] = short_id_from_device_id(data.device_id); doc["id"] = short_id_from_device_id(data.device_id);
doc["ts"] = data.ts_utc; doc["ts"] = data.ts_utc;
char buf[16]; char buf[16];
format_float_2(buf, sizeof(buf), data.energy_total_kwh); if (data.energy_multi) {
doc["e_kwh"] = serialized(buf); doc["energy1_kwh"] = data.energy_kwh_int[0];
set_int_or_null(doc, "p_w", data.total_power_w); doc["energy2_kwh"] = data.energy_kwh_int[1];
set_int_or_null(doc, "p1_w", data.phase_power_w[0]); if (data.energy_meter_count >= 3) {
set_int_or_null(doc, "p2_w", data.phase_power_w[1]); doc["energy3_kwh"] = data.energy_kwh_int[2];
set_int_or_null(doc, "p3_w", data.phase_power_w[2]); }
} else {
format_float_2(buf, sizeof(buf), data.energy_total_kwh);
doc["e_kwh"] = serialized(buf);
set_int_or_null(doc, "p_w", data.total_power_w);
set_int_or_null(doc, "p1_w", data.phase_power_w[0]);
set_int_or_null(doc, "p2_w", data.phase_power_w[1]);
set_int_or_null(doc, "p3_w", data.phase_power_w[2]);
}
format_float_2(buf, sizeof(buf), data.battery_voltage_v); format_float_2(buf, sizeof(buf), data.battery_voltage_v);
doc["bat_v"] = serialized(buf); doc["bat_v"] = serialized(buf);
doc["bat_pct"] = data.battery_percent; doc["bat_pct"] = data.battery_percent;
@@ -90,5 +98,5 @@ bool meterDataToJson(const MeterData &data, String &out_json) {
out_json = ""; out_json = "";
size_t len = serializeJson(doc, out_json); size_t len = serializeJson(doc, out_json);
return len > 0 && len < 256; return len > 0 && len < 320;
} }

View File

@@ -55,7 +55,10 @@ struct BatchBuffer {
uint16_t batch_id; uint16_t batch_id;
bool batch_id_valid; bool batch_id_valid;
uint8_t count; uint8_t count;
MeterData samples[METER_BATCH_MAX_SAMPLES]; struct EnergySample {
uint32_t ts_utc;
uint32_t energy_kwh[3];
} samples[METER_BATCH_MAX_SAMPLES];
}; };
static BatchBuffer g_batch_queue[BATCH_QUEUE_DEPTH]; static BatchBuffer g_batch_queue[BATCH_QUEUE_DEPTH];
@@ -63,7 +66,7 @@ static uint8_t g_batch_head = 0;
static uint8_t g_batch_tail = 0; static uint8_t g_batch_tail = 0;
static uint8_t g_batch_count = 0; static uint8_t g_batch_count = 0;
static MeterData g_build_samples[METER_BATCH_MAX_SAMPLES]; static BatchBuffer::EnergySample g_build_samples[METER_BATCH_MAX_SAMPLES];
static uint8_t g_build_count = 0; static uint8_t g_build_count = 0;
static uint32_t g_last_sample_ms = 0; static uint32_t g_last_sample_ms = 0;
@@ -79,7 +82,7 @@ static uint16_t g_last_acked_batch_id = 0;
static uint8_t g_batch_retry_count = 0; static uint8_t g_batch_retry_count = 0;
static bool g_batch_ack_pending = false; static bool g_batch_ack_pending = false;
static uint32_t g_batch_ack_timeout_ms = BATCH_ACK_TIMEOUT_MS; static uint32_t g_batch_ack_timeout_ms = BATCH_ACK_TIMEOUT_MS;
static MeterData g_inflight_samples[METER_BATCH_MAX_SAMPLES]; static BatchBuffer::EnergySample g_inflight_samples[METER_BATCH_MAX_SAMPLES];
static uint8_t g_inflight_count = 0; static uint8_t g_inflight_count = 0;
static uint16_t g_inflight_batch_id = 0; static uint16_t g_inflight_batch_id = 0;
static bool g_inflight_active = false; static bool g_inflight_active = false;
@@ -90,10 +93,8 @@ static uint32_t g_sender_sleep_ms = 0;
static uint32_t g_sender_power_log_ms = 0; static uint32_t g_sender_power_log_ms = 0;
static RxRejectReason g_sender_rx_reject_reason = RxRejectReason::None; static RxRejectReason g_sender_rx_reject_reason = RxRejectReason::None;
static uint32_t g_sender_rx_reject_log_ms = 0; static uint32_t g_sender_rx_reject_log_ms = 0;
static MeterData g_last_meter_data = {}; static uint32_t g_last_energy_kwh[3] = {};
static bool g_last_meter_valid = false; static bool g_last_energy_valid[3] = {};
static uint32_t g_last_meter_rx_ms = 0;
static uint32_t g_meter_stale_seconds = 0;
static bool g_time_acquired = false; static bool g_time_acquired = false;
static uint32_t g_last_sync_request_ms = 0; static uint32_t g_last_sync_request_ms = 0;
@@ -194,7 +195,7 @@ static BatchBuffer *batch_queue_peek() {
return &g_batch_queue[g_batch_tail]; return &g_batch_queue[g_batch_tail];
} }
static void batch_queue_enqueue(const MeterData *samples, uint8_t count) { static void batch_queue_enqueue(const BatchBuffer::EnergySample *samples, uint8_t count) {
if (!samples || count == 0) { if (!samples || count == 0) {
return; return;
} }
@@ -329,33 +330,6 @@ static uint16_t short_id_from_sender_id(uint16_t sender_id) {
return EXPECTED_SENDER_IDS[sender_id - 1]; return EXPECTED_SENDER_IDS[sender_id - 1];
} }
static uint32_t kwh_to_wh_from_float(float value) {
if (isnan(value)) {
return 0;
}
double wh = static_cast<double>(value) * 1000.0;
if (wh < 0.0) {
wh = 0.0;
}
if (wh > static_cast<double>(UINT32_MAX)) {
wh = static_cast<double>(UINT32_MAX);
}
return static_cast<uint32_t>(llround(wh));
}
static bool float_to_i16_w(float value, int16_t &out) {
if (isnan(value)) {
out = 0;
return true;
}
long rounded = lroundf(value);
if (rounded < INT16_MIN || rounded > INT16_MAX) {
return false;
}
out = static_cast<int16_t>(rounded);
return true;
}
static uint16_t battery_mv_from_voltage(float value) { static uint16_t battery_mv_from_voltage(float value) {
if (isnan(value) || value <= 0.0f) { if (isnan(value) || value <= 0.0f) {
return 0; return 0;
@@ -496,6 +470,7 @@ static bool send_inflight_batch(uint32_t ts_for_display) {
return false; return false;
} }
BatchInput input = {}; BatchInput input = {};
input.schema_id = 1;
input.sender_id = sender_id_from_short_id(g_short_id); input.sender_id = sender_id_from_short_id(g_short_id);
input.batch_id = g_inflight_batch_id; input.batch_id = g_inflight_batch_id;
input.t_last = g_inflight_sync_request ? time_get_utc() : input.t_last = g_inflight_sync_request ? time_get_utc() :
@@ -503,20 +478,17 @@ static bool send_inflight_batch(uint32_t ts_for_display) {
uint32_t dt_s = METER_SAMPLE_INTERVAL_MS / 1000; uint32_t dt_s = METER_SAMPLE_INTERVAL_MS / 1000;
input.dt_s = dt_s > 0 ? static_cast<uint8_t>(dt_s) : 1; input.dt_s = dt_s > 0 ? static_cast<uint8_t>(dt_s) : 1;
input.n = g_inflight_sync_request ? 0 : g_inflight_count; input.n = g_inflight_sync_request ? 0 : g_inflight_count;
input.battery_mV = g_inflight_sync_request ? battery_mv_from_voltage(g_last_battery_voltage_v) : input.meter_count = METER_COUNT;
battery_mv_from_voltage(g_inflight_samples[g_inflight_count - 1].battery_voltage_v); input.battery_mV = battery_mv_from_voltage(g_last_battery_voltage_v);
input.err_m = g_sender_faults.meter_read_fail > 255 ? 255 : static_cast<uint8_t>(g_sender_faults.meter_read_fail); input.err_m = g_sender_faults.meter_read_fail > 255 ? 255 : static_cast<uint8_t>(g_sender_faults.meter_read_fail);
input.err_d = g_sender_faults.decode_fail > 255 ? 255 : static_cast<uint8_t>(g_sender_faults.decode_fail); input.err_d = g_sender_faults.decode_fail > 255 ? 255 : static_cast<uint8_t>(g_sender_faults.decode_fail);
input.err_tx = g_sender_faults.lora_tx_fail > 255 ? 255 : static_cast<uint8_t>(g_sender_faults.lora_tx_fail); input.err_tx = g_sender_faults.lora_tx_fail > 255 ? 255 : static_cast<uint8_t>(g_sender_faults.lora_tx_fail);
input.err_last = static_cast<uint8_t>(g_sender_last_error); input.err_last = static_cast<uint8_t>(g_sender_last_error);
input.err_rx_reject = static_cast<uint8_t>(g_sender_rx_reject_reason); input.err_rx_reject = static_cast<uint8_t>(g_sender_rx_reject_reason);
for (uint8_t i = 0; i < input.n; ++i) { for (uint8_t i = 0; i < input.n; ++i) {
input.energy_wh[i] = kwh_to_wh_from_float(g_inflight_samples[i].energy_total_kwh); input.energy1_kwh[i] = g_inflight_samples[i].energy_kwh[0];
if (!float_to_i16_w(g_inflight_samples[i].phase_power_w[0], input.p1_w[i]) || input.energy2_kwh[i] = g_inflight_samples[i].energy_kwh[1];
!float_to_i16_w(g_inflight_samples[i].phase_power_w[1], input.p2_w[i]) || input.energy3_kwh[i] = g_inflight_samples[i].energy_kwh[2];
!float_to_i16_w(g_inflight_samples[i].phase_power_w[2], input.p3_w[i])) {
return false;
}
} }
static uint8_t encoded[BATCH_MAX_COMPRESSED]; static uint8_t encoded[BATCH_MAX_COMPRESSED];
@@ -691,8 +663,10 @@ static bool process_batch_packet(const LoraPacket &pkt, BatchInput &out_batch, b
} }
void setup() { void setup() {
Serial.begin(115200); if (SERIAL_DEBUG_MODE) {
delay(200); Serial.begin(115200);
delay(200);
}
#ifdef PAYLOAD_CODEC_TEST #ifdef PAYLOAD_CODEC_TEST
payload_codec_self_test(); payload_codec_self_test();
#endif #endif
@@ -776,63 +750,60 @@ static void sender_loop() {
} }
if (g_time_acquired) { if (g_time_acquired) {
const char *frame = nullptr; meter_poll();
size_t frame_len = 0; for (uint8_t i = 0; i < meter_count() && i < 3; ++i) {
if (meter_poll_frame(frame, frame_len)) { uint32_t e_kwh = 0;
MeterData parsed = {}; if (meter_get_last_energy_kwh(i, e_kwh)) {
parsed.energy_total_kwh = NAN; g_last_energy_kwh[i] = e_kwh;
parsed.total_power_w = NAN; g_last_energy_valid[i] = true;
parsed.phase_power_w[0] = NAN;
parsed.phase_power_w[1] = NAN;
parsed.phase_power_w[2] = NAN;
parsed.valid = false;
if (meter_parse_frame(frame, frame_len, parsed)) {
g_last_meter_data = parsed;
g_last_meter_valid = true;
g_last_meter_rx_ms = now_ms;
g_meter_stale_seconds = 0;
} }
} }
if (now_ms - g_last_sample_ms >= METER_SAMPLE_INTERVAL_MS) { if (now_ms - g_last_sample_ms >= METER_SAMPLE_INTERVAL_MS) {
g_last_sample_ms = now_ms; g_last_sample_ms = now_ms;
MeterData data = {}; bool any_meter_valid = false;
data.short_id = g_short_id; for (uint8_t i = 0; i < meter_count() && i < 3; ++i) {
strncpy(data.device_id, g_device_id, sizeof(data.device_id)); if (g_last_energy_valid[i]) {
any_meter_valid = true;
bool meter_ok = g_last_meter_valid; break;
if (meter_ok) { }
data.energy_total_kwh = g_last_meter_data.energy_total_kwh;
data.total_power_w = g_last_meter_data.total_power_w;
data.phase_power_w[0] = g_last_meter_data.phase_power_w[0];
data.phase_power_w[1] = g_last_meter_data.phase_power_w[1];
data.phase_power_w[2] = g_last_meter_data.phase_power_w[2];
uint32_t age_ms = now_ms - g_last_meter_rx_ms;
g_meter_stale_seconds = age_ms >= 1000 ? (age_ms / 1000) : 0;
} else {
g_meter_stale_seconds++;
} }
if (!meter_ok) { if (!any_meter_valid) {
note_fault(g_sender_faults, g_sender_last_error, g_sender_last_error_utc, g_sender_last_error_ms, FaultType::MeterRead); note_fault(g_sender_faults, g_sender_last_error, g_sender_last_error_utc, g_sender_last_error_ms, FaultType::MeterRead);
display_set_last_error(g_sender_last_error, g_sender_last_error_utc, g_sender_last_error_ms); display_set_last_error(g_sender_last_error, g_sender_last_error_utc, g_sender_last_error_ms);
} else {
BatchBuffer::EnergySample sample = {};
sample.ts_utc = time_get_utc();
sample.energy_kwh[0] = g_last_energy_valid[0] ? g_last_energy_kwh[0] : 0;
sample.energy_kwh[1] = g_last_energy_valid[1] ? g_last_energy_kwh[1] : 0;
sample.energy_kwh[2] = (meter_count() >= 3 && g_last_energy_valid[2]) ? g_last_energy_kwh[2] : 0;
g_last_sample_ts_utc = sample.ts_utc;
g_build_samples[g_build_count++] = sample;
if (g_build_count >= METER_BATCH_MAX_SAMPLES) {
batch_queue_enqueue(g_build_samples, g_build_count);
g_build_count = 0;
}
MeterData view = {};
view.short_id = g_short_id;
strncpy(view.device_id, g_device_id, sizeof(view.device_id));
view.ts_utc = sample.ts_utc;
view.energy_multi = true;
view.energy_meter_count = meter_count();
view.energy_kwh_int[0] = sample.energy_kwh[0];
view.energy_kwh_int[1] = sample.energy_kwh[1];
view.energy_kwh_int[2] = sample.energy_kwh[2];
view.energy_total_kwh = static_cast<float>(sample.energy_kwh[0]);
view.valid = true;
view.battery_voltage_v = g_last_battery_voltage_v;
view.battery_percent = g_last_battery_percent;
display_set_last_meter(view);
display_set_last_read(true, view.ts_utc);
} }
if (g_build_count == 0 && battery_sample_due(now_ms)) { if (g_build_count == 0 && battery_sample_due(now_ms)) {
update_battery_cache(); update_battery_cache();
} }
data.battery_voltage_v = g_last_battery_voltage_v;
data.battery_percent = g_last_battery_percent;
data.rx_reject_reason = static_cast<uint8_t>(g_sender_rx_reject_reason);
data.ts_utc = time_get_utc();
data.valid = meter_ok;
g_last_sample_ts_utc = data.ts_utc;
g_build_samples[g_build_count++] = data;
if (g_build_count >= METER_BATCH_MAX_SAMPLES) {
batch_queue_enqueue(g_build_samples, g_build_count);
g_build_count = 0;
}
display_set_last_meter(data);
display_set_last_read(meter_ok, data.ts_utc);
} }
if (!g_batch_ack_pending && now_ms - g_last_send_ms >= METER_SEND_INTERVAL_MS) { if (!g_batch_ack_pending && now_ms - g_last_send_ms >= METER_SEND_INTERVAL_MS) {
@@ -1052,11 +1023,24 @@ static void receiver_loop() {
snprintf(data.device_id, sizeof(data.device_id), "dd3-0000"); snprintf(data.device_id, sizeof(data.device_id), "dd3-0000");
} }
data.ts_utc = t_first + static_cast<uint32_t>(s) * batch.dt_s; data.ts_utc = t_first + static_cast<uint32_t>(s) * batch.dt_s;
data.energy_total_kwh = static_cast<float>(batch.energy_wh[s]) / 1000.0f; if (batch.schema_id == 1) {
data.phase_power_w[0] = static_cast<float>(batch.p1_w[s]); data.energy_multi = true;
data.phase_power_w[1] = static_cast<float>(batch.p2_w[s]); data.energy_meter_count = batch.meter_count;
data.phase_power_w[2] = static_cast<float>(batch.p3_w[s]); data.energy_kwh_int[0] = batch.energy1_kwh[s];
data.total_power_w = data.phase_power_w[0] + data.phase_power_w[1] + data.phase_power_w[2]; data.energy_kwh_int[1] = batch.energy2_kwh[s];
data.energy_kwh_int[2] = batch.energy3_kwh[s];
data.energy_total_kwh = static_cast<float>(batch.energy1_kwh[s]);
data.phase_power_w[0] = 0.0f;
data.phase_power_w[1] = 0.0f;
data.phase_power_w[2] = 0.0f;
data.total_power_w = 0.0f;
} else {
data.energy_total_kwh = static_cast<float>(batch.energy_wh[s]) / 1000.0f;
data.phase_power_w[0] = static_cast<float>(batch.p1_w[s]);
data.phase_power_w[1] = static_cast<float>(batch.p2_w[s]);
data.phase_power_w[2] = static_cast<float>(batch.p3_w[s]);
data.total_power_w = data.phase_power_w[0] + data.phase_power_w[1] + data.phase_power_w[2];
}
data.battery_voltage_v = bat_v; data.battery_voltage_v = bat_v;
data.battery_percent = !isnan(bat_v) ? battery_percent_from_voltage(bat_v) : 0; data.battery_percent = !isnan(bat_v) ? battery_percent_from_voltage(bat_v) : 0;
data.valid = true; data.valid = true;

View File

@@ -12,20 +12,23 @@ enum class MeterRxState : uint8_t {
InFrame = 1 InFrame = 1
}; };
static MeterRxState g_rx_state = MeterRxState::WaitStart; struct MeterPort {
static char g_frame_buf[METER_FRAME_MAX + 1]; HardwareSerial *serial;
static size_t g_frame_len = 0; MeterRxState state;
static uint32_t g_last_rx_ms = 0; char frame_buf[METER_FRAME_MAX + 1];
static uint32_t g_bytes_rx = 0; size_t frame_len;
static uint32_t g_frames_ok = 0; uint32_t last_rx_ms;
static uint32_t g_frames_parse_fail = 0; uint32_t bytes_rx;
static uint32_t g_rx_overflow = 0; uint32_t frames_ok;
static uint32_t g_rx_timeout = 0; uint32_t frames_parse_fail;
static uint32_t g_last_log_ms = 0; uint32_t rx_overflow;
uint32_t rx_timeout;
uint32_t last_energy_kwh;
bool has_energy;
};
void meter_init() { static MeterPort g_ports[METER_COUNT] = {};
Serial2.begin(9600, SERIAL_7E1, PIN_METER_RX, -1); static uint32_t g_last_log_ms = 0;
}
static bool parse_obis_ascii_value(const char *line, const char *obis, float &out_value) { static bool parse_obis_ascii_value(const char *line, const char *obis, float &out_value) {
const char *p = strstr(line, obis); const char *p = strstr(line, obis);
@@ -62,34 +65,30 @@ static bool parse_obis_ascii_value(const char *line, const char *obis, float &ou
return true; return true;
} }
static bool parse_obis_ascii_unit_scale(const char *line, const char *obis, float &value) { static bool parse_energy_kwh_floor(const char *frame, size_t len, uint32_t &out_kwh) {
const char *p = strstr(line, obis); char line[128];
if (!p) { size_t line_len = 0;
return false; for (size_t i = 0; i < len; ++i) {
} char c = frame[i];
const char *asterisk = strchr(p, '*'); if (c == '\r') {
if (!asterisk) {
return false;
}
const char *end = strchr(asterisk, ')');
if (!end) {
return false;
}
char unit_buf[8];
size_t ulen = 0;
for (const char *c = asterisk + 1; c < end && ulen + 1 < sizeof(unit_buf); ++c) {
if (*c == ' ') {
continue; continue;
} }
unit_buf[ulen++] = *c; if (c == '\n' || c == '!') {
} line[line_len] = '\0';
unit_buf[ulen] = '\0'; float value = NAN;
if (ulen == 0) { if (parse_obis_ascii_value(line, "1-0:1.8.0", value) && !isnan(value) && value >= 0.0f) {
return false; out_kwh = static_cast<uint32_t>(floorf(value));
} return true;
if (strcmp(unit_buf, "Wh") == 0) { }
value *= 0.001f; line_len = 0;
return true; if (c == '!') {
break;
}
continue;
}
if (line_len + 1 < sizeof(line)) {
line[line_len++] = c;
}
} }
return false; return false;
} }
@@ -103,162 +102,105 @@ static void meter_debug_log() {
return; return;
} }
g_last_log_ms = now_ms; g_last_log_ms = now_ms;
Serial.printf("meter: ok=%lu parse_fail=%lu overflow=%lu timeout=%lu bytes=%lu\n", for (uint8_t i = 0; i < METER_COUNT; ++i) {
static_cast<unsigned long>(g_frames_ok), const MeterPort &p = g_ports[i];
static_cast<unsigned long>(g_frames_parse_fail), Serial.printf("meter%u: ok=%lu parse_fail=%lu overflow=%lu timeout=%lu bytes=%lu e=%lu valid=%u\n",
static_cast<unsigned long>(g_rx_overflow), static_cast<unsigned>(i + 1),
static_cast<unsigned long>(g_rx_timeout), static_cast<unsigned long>(p.frames_ok),
static_cast<unsigned long>(g_bytes_rx)); static_cast<unsigned long>(p.frames_parse_fail),
static_cast<unsigned long>(p.rx_overflow),
static_cast<unsigned long>(p.rx_timeout),
static_cast<unsigned long>(p.bytes_rx),
static_cast<unsigned long>(p.last_energy_kwh),
p.has_energy ? 1 : 0);
}
} }
bool meter_poll_frame(const char *&frame, size_t &len) { void meter_init() {
frame = nullptr; g_ports[0].serial = &Serial2;
len = 0; g_ports[0].serial->begin(9600, SERIAL_7E1, PIN_METER1_RX, -1);
g_ports[0].state = MeterRxState::WaitStart;
if (METER_COUNT >= 2) {
g_ports[1].serial = &Serial1;
g_ports[1].serial->begin(9600, SERIAL_7E1, PIN_METER2_RX, -1);
g_ports[1].state = MeterRxState::WaitStart;
}
if (METER_COUNT >= 3) {
g_ports[2].serial = &Serial;
g_ports[2].serial->begin(9600, SERIAL_7E1, PIN_METER3_RX, -1);
g_ports[2].state = MeterRxState::WaitStart;
}
}
static void meter_poll_port(MeterPort &port) {
if (!port.serial) {
return;
}
uint32_t now_ms = millis(); uint32_t now_ms = millis();
if (port.state == MeterRxState::InFrame && (now_ms - port.last_rx_ms > METER_FRAME_TIMEOUT_MS)) {
if (g_rx_state == MeterRxState::InFrame && (now_ms - g_last_rx_ms > METER_FRAME_TIMEOUT_MS)) { port.rx_timeout++;
g_rx_timeout++; port.state = MeterRxState::WaitStart;
g_rx_state = MeterRxState::WaitStart; port.frame_len = 0;
g_frame_len = 0;
} }
while (Serial2.available()) { while (port.serial->available()) {
char c = static_cast<char>(Serial2.read()); char c = static_cast<char>(port.serial->read());
g_bytes_rx++; port.bytes_rx++;
g_last_rx_ms = now_ms; port.last_rx_ms = now_ms;
if (g_rx_state == MeterRxState::WaitStart) { if (port.state == MeterRxState::WaitStart) {
if (c == '/') { if (c == '/') {
g_rx_state = MeterRxState::InFrame; port.state = MeterRxState::InFrame;
g_frame_len = 0; port.frame_len = 0;
g_frame_buf[g_frame_len++] = c; port.frame_buf[port.frame_len++] = c;
} }
continue; continue;
} }
if (g_frame_len + 1 >= sizeof(g_frame_buf)) { if (port.frame_len + 1 >= sizeof(port.frame_buf)) {
g_rx_overflow++; port.rx_overflow++;
g_rx_state = MeterRxState::WaitStart; port.state = MeterRxState::WaitStart;
g_frame_len = 0; port.frame_len = 0;
continue; continue;
} }
g_frame_buf[g_frame_len++] = c; port.frame_buf[port.frame_len++] = c;
if (c == '!') { if (c == '!') {
g_frame_buf[g_frame_len] = '\0'; port.frame_buf[port.frame_len] = '\0';
frame = g_frame_buf; uint32_t energy_kwh = 0;
len = g_frame_len; if (parse_energy_kwh_floor(port.frame_buf, port.frame_len, energy_kwh)) {
g_rx_state = MeterRxState::WaitStart; port.last_energy_kwh = energy_kwh;
g_frame_len = 0; port.has_energy = true;
meter_debug_log(); port.frames_ok++;
return true;
}
}
meter_debug_log();
return false;
}
bool meter_parse_frame(const char *frame, size_t len, MeterData &data) {
if (!frame || len == 0) {
return false;
}
bool got_any = false;
bool energy_ok = false;
bool total_p_ok = false;
bool p1_ok = false;
bool p2_ok = false;
bool p3_ok = false;
char line[128];
size_t line_len = 0;
for (size_t i = 0; i < len; ++i) {
char c = frame[i];
if (c == '\r') {
continue;
}
if (c == '!') {
if (line_len + 1 < sizeof(line)) {
line[line_len++] = c;
}
line[line_len] = '\0';
data.valid = energy_ok || total_p_ok || p1_ok || p2_ok || p3_ok;
if (data.valid) {
g_frames_ok++;
} else { } else {
g_frames_parse_fail++; port.frames_parse_fail++;
} }
return data.valid; port.state = MeterRxState::WaitStart;
} port.frame_len = 0;
if (c == '\n') {
line[line_len] = '\0';
if (line[0] == '!') {
data.valid = energy_ok || total_p_ok || p1_ok || p2_ok || p3_ok;
if (data.valid) {
g_frames_ok++;
} else {
g_frames_parse_fail++;
}
return data.valid;
}
float value = NAN;
if (parse_obis_ascii_value(line, "1-0:1.8.0", value)) {
parse_obis_ascii_unit_scale(line, "1-0:1.8.0", value);
data.energy_total_kwh = value;
energy_ok = true;
got_any = true;
}
if (parse_obis_ascii_value(line, "1-0:16.7.0", value)) {
data.total_power_w = value;
total_p_ok = true;
got_any = true;
}
if (parse_obis_ascii_value(line, "1-0:36.7.0", value)) {
data.phase_power_w[0] = value;
p1_ok = true;
got_any = true;
}
if (parse_obis_ascii_value(line, "1-0:56.7.0", value)) {
data.phase_power_w[1] = value;
p2_ok = true;
got_any = true;
}
if (parse_obis_ascii_value(line, "1-0:76.7.0", value)) {
data.phase_power_w[2] = value;
p3_ok = true;
got_any = true;
}
line_len = 0;
continue;
}
if (line_len + 1 < sizeof(line)) {
line[line_len++] = c;
} }
} }
data.valid = got_any;
if (data.valid) {
g_frames_ok++;
} else {
g_frames_parse_fail++;
}
return data.valid;
} }
bool meter_read(MeterData &data) { void meter_poll() {
data.energy_total_kwh = NAN; for (uint8_t i = 0; i < METER_COUNT; ++i) {
data.total_power_w = NAN; meter_poll_port(g_ports[i]);
data.phase_power_w[0] = NAN; }
data.phase_power_w[1] = NAN; meter_debug_log();
data.phase_power_w[2] = NAN; }
data.valid = false;
const char *frame = nullptr; uint8_t meter_count() {
size_t len = 0; return METER_COUNT;
if (!meter_poll_frame(frame, len)) { }
bool meter_get_last_energy_kwh(uint8_t meter_idx, uint32_t &out_energy_kwh) {
if (meter_idx >= METER_COUNT) {
return false; return false;
} }
return meter_parse_frame(frame, len, data); if (!g_ports[meter_idx].has_energy) {
return false;
}
out_energy_kwh = g_ports[meter_idx].last_energy_kwh;
return true;
} }

View File

@@ -5,6 +5,8 @@ static constexpr uint16_t kMagic = 0xDDB3;
static constexpr uint8_t kSchema = 2; static constexpr uint8_t kSchema = 2;
static constexpr uint8_t kFlags = 0x01; static constexpr uint8_t kFlags = 0x01;
static constexpr size_t kMaxSamples = 30; static constexpr size_t kMaxSamples = 30;
static constexpr uint8_t kPayloadSchemaLegacy = 0;
static constexpr uint8_t kPayloadSchemaEnergyMulti = 1;
static void write_u16_le(uint8_t *dst, uint16_t value) { static void write_u16_le(uint8_t *dst, uint16_t value) {
dst[0] = static_cast<uint8_t>(value & 0xFF); dst[0] = static_cast<uint8_t>(value & 0xFF);
@@ -108,13 +110,14 @@ bool encode_batch(const BatchInput &in, uint8_t *out, size_t out_cap, size_t *ou
return false; return false;
} }
size_t pos = 0; size_t pos = 0;
if (!ensure_capacity(21, out_cap, pos)) { if (!ensure_capacity(23, out_cap, pos)) {
return false; return false;
} }
write_u16_le(&out[pos], kMagic); write_u16_le(&out[pos], kMagic);
pos += 2; pos += 2;
out[pos++] = kSchema; out[pos++] = kSchema;
out[pos++] = kFlags; out[pos++] = kFlags;
out[pos++] = in.schema_id;
write_u16_le(&out[pos], in.sender_id); write_u16_le(&out[pos], in.sender_id);
pos += 2; pos += 2;
write_u16_le(&out[pos], in.batch_id); write_u16_le(&out[pos], in.batch_id);
@@ -130,12 +133,32 @@ bool encode_batch(const BatchInput &in, uint8_t *out, size_t out_cap, size_t *ou
out[pos++] = in.err_tx; out[pos++] = in.err_tx;
out[pos++] = in.err_last; out[pos++] = in.err_last;
out[pos++] = in.err_rx_reject; out[pos++] = in.err_rx_reject;
out[pos++] = in.meter_count;
if (in.n == 0) { if (in.n == 0) {
*out_len = pos; *out_len = pos;
return true; return true;
} }
if (in.schema_id == kPayloadSchemaEnergyMulti) {
if (in.meter_count == 0 || in.meter_count > 3) {
return false;
}
if (!ensure_capacity(static_cast<size_t>(in.n) * 12, out_cap, pos)) {
return false;
}
for (uint8_t i = 0; i < in.n; ++i) {
write_u32_le(&out[pos], in.energy1_kwh[i]);
pos += 4;
write_u32_le(&out[pos], in.energy2_kwh[i]);
pos += 4;
write_u32_le(&out[pos], in.energy3_kwh[i]);
pos += 4;
}
*out_len = pos;
return true;
}
if (!ensure_capacity(4, out_cap, pos)) { if (!ensure_capacity(4, out_cap, pos)) {
return false; return false;
} }
@@ -189,7 +212,7 @@ bool decode_batch(const uint8_t *buf, size_t len, BatchInput *out) {
return false; return false;
} }
size_t pos = 0; size_t pos = 0;
if (len < 21) { if (len < 23) {
return false; return false;
} }
uint16_t magic = read_u16_le(&buf[pos]); uint16_t magic = read_u16_le(&buf[pos]);
@@ -199,6 +222,7 @@ bool decode_batch(const uint8_t *buf, size_t len, BatchInput *out) {
if (magic != kMagic || schema != kSchema || (flags & 0x01) == 0) { if (magic != kMagic || schema != kSchema || (flags & 0x01) == 0) {
return false; return false;
} }
out->schema_id = buf[pos++];
out->sender_id = read_u16_le(&buf[pos]); out->sender_id = read_u16_le(&buf[pos]);
pos += 2; pos += 2;
out->batch_id = read_u16_le(&buf[pos]); out->batch_id = read_u16_le(&buf[pos]);
@@ -214,6 +238,7 @@ bool decode_batch(const uint8_t *buf, size_t len, BatchInput *out) {
out->err_tx = buf[pos++]; out->err_tx = buf[pos++];
out->err_last = buf[pos++]; out->err_last = buf[pos++];
out->err_rx_reject = buf[pos++]; out->err_rx_reject = buf[pos++];
out->meter_count = buf[pos++];
if (out->n > kMaxSamples || out->dt_s == 0) { if (out->n > kMaxSamples || out->dt_s == 0) {
return false; return false;
@@ -227,6 +252,29 @@ bool decode_batch(const uint8_t *buf, size_t len, BatchInput *out) {
} }
return pos == len; return pos == len;
} }
if (out->schema_id == kPayloadSchemaEnergyMulti) {
if (out->meter_count == 0 || out->meter_count > 3) {
return false;
}
if (pos + static_cast<size_t>(out->n) * 12 > len) {
return false;
}
for (uint8_t i = 0; i < out->n; ++i) {
out->energy1_kwh[i] = read_u32_le(&buf[pos]);
pos += 4;
out->energy2_kwh[i] = read_u32_le(&buf[pos]);
pos += 4;
out->energy3_kwh[i] = read_u32_le(&buf[pos]);
pos += 4;
}
for (uint8_t i = out->n; i < kMaxSamples; ++i) {
out->energy1_kwh[i] = 0;
out->energy2_kwh[i] = 0;
out->energy3_kwh[i] = 0;
}
return pos == len;
}
if (pos + 4 > len) { if (pos + 4 > len) {
return false; return false;
} }
@@ -289,6 +337,7 @@ bool decode_batch(const uint8_t *buf, size_t len, BatchInput *out) {
#ifdef PAYLOAD_CODEC_TEST #ifdef PAYLOAD_CODEC_TEST
bool payload_codec_self_test() { bool payload_codec_self_test() {
BatchInput in = {}; BatchInput in = {};
in.schema_id = kPayloadSchemaLegacy;
in.sender_id = 1; in.sender_id = 1;
in.batch_id = 42; in.batch_id = 42;
in.t_last = 1700000000; in.t_last = 1700000000;
@@ -300,6 +349,7 @@ bool payload_codec_self_test() {
in.err_tx = 3; in.err_tx = 3;
in.err_last = 2; in.err_last = 2;
in.err_rx_reject = 1; in.err_rx_reject = 1;
in.meter_count = 0;
in.energy_wh[0] = 100000; in.energy_wh[0] = 100000;
in.energy_wh[1] = 100001; in.energy_wh[1] = 100001;
in.energy_wh[2] = 100050; in.energy_wh[2] = 100050;

View File

@@ -3,17 +3,22 @@
#include <Arduino.h> #include <Arduino.h>
struct BatchInput { struct BatchInput {
uint8_t schema_id;
uint16_t sender_id; uint16_t sender_id;
uint16_t batch_id; uint16_t batch_id;
uint32_t t_last; uint32_t t_last;
uint8_t dt_s; uint8_t dt_s;
uint8_t n; uint8_t n;
uint8_t meter_count;
uint16_t battery_mV; uint16_t battery_mV;
uint8_t err_m; uint8_t err_m;
uint8_t err_d; uint8_t err_d;
uint8_t err_tx; uint8_t err_tx;
uint8_t err_last; uint8_t err_last;
uint8_t err_rx_reject; uint8_t err_rx_reject;
uint32_t energy1_kwh[30];
uint32_t energy2_kwh[30];
uint32_t energy3_kwh[30];
uint32_t energy_wh[30]; uint32_t energy_wh[30];
int16_t p1_w[30]; int16_t p1_w[30];
int16_t p2_w[30]; int16_t p2_w[30];

View File

@@ -374,11 +374,19 @@ static String render_sender_block(const SenderStatus &status) {
if (!status.has_data) { if (!status.has_data) {
s += "No data"; s += "No data";
} else { } else {
s += "Energy: " + String(status.last_data.energy_total_kwh, 2) + " kWh<br>"; if (status.last_data.energy_multi) {
s += "Power: " + String(round_power_w(status.last_data.total_power_w)) + " W<br>"; s += "Energy1: " + String(status.last_data.energy_kwh_int[0]) + " kWh<br>";
s += "P1/P2/P3: " + String(round_power_w(status.last_data.phase_power_w[0])) + " / " + s += "Energy2: " + String(status.last_data.energy_kwh_int[1]) + " kWh<br>";
String(round_power_w(status.last_data.phase_power_w[1])) + " / " + if (status.last_data.energy_meter_count >= 3) {
String(round_power_w(status.last_data.phase_power_w[2])) + " W<br>"; s += "Energy3: " + String(status.last_data.energy_kwh_int[2]) + " kWh<br>";
}
} else {
s += "Energy: " + String(status.last_data.energy_total_kwh, 2) + " kWh<br>";
s += "Power: " + String(round_power_w(status.last_data.total_power_w)) + " W<br>";
s += "P1/P2/P3: " + String(round_power_w(status.last_data.phase_power_w[0])) + " / " +
String(round_power_w(status.last_data.phase_power_w[1])) + " / " +
String(round_power_w(status.last_data.phase_power_w[2])) + " W<br>";
}
s += "Battery: " + String(status.last_data.battery_percent) + "% (" + String(status.last_data.battery_voltage_v, 2) + " V)"; s += "Battery: " + String(status.last_data.battery_percent) + "% (" + String(status.last_data.battery_voltage_v, 2) + " V)";
} }
s += "</div>"; s += "</div>";
@@ -605,14 +613,16 @@ static void handle_sender() {
if (g_last_batch_count[i] > 0) { if (g_last_batch_count[i] > 0) {
html += "<h3>Last batch (" + String(g_last_batch_count[i]) + " samples)</h3>"; html += "<h3>Last batch (" + String(g_last_batch_count[i]) + " samples)</h3>";
html += "<table border='1' cellspacing='0' cellpadding='3'>"; html += "<table border='1' cellspacing='0' cellpadding='3'>";
html += "<tr><th>#</th><th>ts</th><th>e_kwh</th><th>p_w</th><th>p1_w</th><th>p2_w</th><th>p3_w</th>"; html += "<tr><th>#</th><th>ts</th><th>energy1_kwh</th><th>energy2_kwh</th><th>energy3_kwh</th><th>p_w</th><th>p1_w</th><th>p2_w</th><th>p3_w</th>";
html += "<th>bat_v</th><th>bat_pct</th><th>rssi</th><th>snr</th><th>err_tx</th><th>err_last</th><th>rx_reject</th></tr>"; html += "<th>bat_v</th><th>bat_pct</th><th>rssi</th><th>snr</th><th>err_tx</th><th>err_last</th><th>rx_reject</th></tr>";
for (uint8_t r = 0; r < g_last_batch_count[i]; ++r) { for (uint8_t r = 0; r < g_last_batch_count[i]; ++r) {
const MeterData &d = g_last_batch[i][r]; const MeterData &d = g_last_batch[i][r];
html += "<tr>"; html += "<tr>";
html += "<td>" + String(r) + "</td>"; html += "<td>" + String(r) + "</td>";
html += "<td>" + String(d.ts_utc) + "</td>"; html += "<td>" + String(d.ts_utc) + "</td>";
html += "<td>" + String(d.energy_total_kwh, 2) + "</td>"; html += "<td>" + String(d.energy_kwh_int[0]) + "</td>";
html += "<td>" + String(d.energy_kwh_int[1]) + "</td>";
html += "<td>" + String(d.energy_kwh_int[2]) + "</td>";
html += "<td>" + String(round_power_w(d.total_power_w)) + "</td>"; html += "<td>" + String(round_power_w(d.total_power_w)) + "</td>";
html += "<td>" + String(round_power_w(d.phase_power_w[0])) + "</td>"; html += "<td>" + String(round_power_w(d.phase_power_w[0])) + "</td>";
html += "<td>" + String(round_power_w(d.phase_power_w[1])) + "</td>"; html += "<td>" + String(round_power_w(d.phase_power_w[1])) + "</td>";