Initial commit
This commit is contained in:
71
src/compressor.cpp
Normal file
71
src/compressor.cpp
Normal file
@@ -0,0 +1,71 @@
|
||||
#include "compressor.h"
|
||||
|
||||
static constexpr uint8_t RLE_MARKER = 0xFF;
|
||||
|
||||
bool compressBuffer(const uint8_t *in, size_t in_len, uint8_t *out, size_t out_max, size_t &out_len) {
|
||||
out_len = 0;
|
||||
if (!in || !out) {
|
||||
return false;
|
||||
}
|
||||
|
||||
size_t i = 0;
|
||||
while (i < in_len) {
|
||||
uint8_t value = in[i];
|
||||
size_t run = 1;
|
||||
while (i + run < in_len && in[i + run] == value && run < 255) {
|
||||
run++;
|
||||
}
|
||||
|
||||
if (value == RLE_MARKER || run >= 4) {
|
||||
if (out_len + 3 > out_max) {
|
||||
return false;
|
||||
}
|
||||
out[out_len++] = RLE_MARKER;
|
||||
out[out_len++] = static_cast<uint8_t>(run);
|
||||
out[out_len++] = value;
|
||||
} else {
|
||||
if (out_len + run > out_max) {
|
||||
return false;
|
||||
}
|
||||
for (size_t j = 0; j < run; ++j) {
|
||||
out[out_len++] = value;
|
||||
}
|
||||
}
|
||||
|
||||
i += run;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool decompressBuffer(const uint8_t *in, size_t in_len, uint8_t *out, size_t out_max, size_t &out_len) {
|
||||
out_len = 0;
|
||||
if (!in || !out) {
|
||||
return false;
|
||||
}
|
||||
|
||||
size_t i = 0;
|
||||
while (i < in_len) {
|
||||
uint8_t value = in[i++];
|
||||
if (value == RLE_MARKER) {
|
||||
if (i + 1 >= in_len) {
|
||||
return false;
|
||||
}
|
||||
uint8_t run = in[i++];
|
||||
uint8_t data = in[i++];
|
||||
if (out_len + run > out_max) {
|
||||
return false;
|
||||
}
|
||||
for (uint8_t j = 0; j < run; ++j) {
|
||||
out[out_len++] = data;
|
||||
}
|
||||
} else {
|
||||
if (out_len + 1 > out_max) {
|
||||
return false;
|
||||
}
|
||||
out[out_len++] = value;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
6
src/config.cpp
Normal file
6
src/config.cpp
Normal file
@@ -0,0 +1,6 @@
|
||||
#include "config.h"
|
||||
|
||||
DeviceRole detect_role() {
|
||||
pinMode(PIN_ROLE, INPUT_PULLDOWN);
|
||||
return digitalRead(PIN_ROLE) == HIGH ? DeviceRole::Receiver : DeviceRole::Sender;
|
||||
}
|
||||
9
src/data_model.cpp
Normal file
9
src/data_model.cpp
Normal file
@@ -0,0 +1,9 @@
|
||||
#include "data_model.h"
|
||||
#include <WiFi.h>
|
||||
|
||||
void init_device_ids(uint16_t &short_id, char *device_id, size_t device_id_len) {
|
||||
uint8_t mac[6] = {0};
|
||||
WiFi.macAddress(mac);
|
||||
short_id = (static_cast<uint16_t>(mac[4]) << 8) | mac[5];
|
||||
snprintf(device_id, device_id_len, "dd3-%04X", short_id);
|
||||
}
|
||||
322
src/display_ui.cpp
Normal file
322
src/display_ui.cpp
Normal file
@@ -0,0 +1,322 @@
|
||||
#include "display_ui.h"
|
||||
#include "config.h"
|
||||
#include "time_manager.h"
|
||||
#include <Wire.h>
|
||||
#include <Adafruit_GFX.h>
|
||||
#include <Adafruit_SSD1306.h>
|
||||
#include <time.h>
|
||||
|
||||
static Adafruit_SSD1306 display(OLED_WIDTH, OLED_HEIGHT, &Wire, -1);
|
||||
|
||||
static DeviceRole g_role = DeviceRole::Sender;
|
||||
static uint16_t g_short_id = 0;
|
||||
static char g_device_id[16] = "";
|
||||
|
||||
static MeterData g_last_meter = {};
|
||||
static bool g_last_read_ok = false;
|
||||
static bool g_last_tx_ok = false;
|
||||
static uint32_t g_last_read_ts = 0;
|
||||
static uint32_t g_last_tx_ts = 0;
|
||||
static uint32_t g_last_read_ms = 0;
|
||||
static uint32_t g_last_tx_ms = 0;
|
||||
|
||||
static const SenderStatus *g_statuses = nullptr;
|
||||
static uint8_t g_status_count = 0;
|
||||
|
||||
static bool g_ap_mode = false;
|
||||
static String g_wifi_ssid;
|
||||
static bool g_mqtt_ok = false;
|
||||
|
||||
static bool g_oled_on = true;
|
||||
static bool g_prev_ctrl_high = false;
|
||||
static uint32_t g_oled_off_start = 0;
|
||||
static uint32_t g_last_page_ms = 0;
|
||||
static uint8_t g_page = 0;
|
||||
static uint32_t g_boot_ms = 0;
|
||||
static bool g_display_ready = false;
|
||||
static uint32_t g_last_init_attempt_ms = 0;
|
||||
|
||||
#ifdef ENABLE_TEST_MODE
|
||||
static char g_test_code[8] = "";
|
||||
static char g_test_codes[NUM_SENDERS][8] = {};
|
||||
#endif
|
||||
|
||||
static void oled_set_power(bool on) {
|
||||
if (on) {
|
||||
display.ssd1306_command(SSD1306_DISPLAYON);
|
||||
} else {
|
||||
display.ssd1306_command(SSD1306_DISPLAYOFF);
|
||||
}
|
||||
}
|
||||
|
||||
void display_init() {
|
||||
pinMode(PIN_OLED_CTRL, INPUT_PULLDOWN);
|
||||
Wire.begin(PIN_OLED_SDA, PIN_OLED_SCL);
|
||||
Wire.setClock(100000);
|
||||
g_display_ready = display.begin(SSD1306_SWITCHCAPVCC, OLED_I2C_ADDR);
|
||||
if (g_display_ready) {
|
||||
display.clearDisplay();
|
||||
display.setTextSize(1);
|
||||
display.setTextColor(SSD1306_WHITE);
|
||||
display.ssd1306_command(SSD1306_DISPLAYON);
|
||||
display.display();
|
||||
}
|
||||
g_last_init_attempt_ms = millis();
|
||||
g_boot_ms = millis();
|
||||
}
|
||||
|
||||
void display_set_role(DeviceRole role) {
|
||||
g_role = role;
|
||||
}
|
||||
|
||||
void display_set_self_ids(uint16_t short_id, const char *device_id) {
|
||||
g_short_id = short_id;
|
||||
strncpy(g_device_id, device_id, sizeof(g_device_id));
|
||||
g_device_id[sizeof(g_device_id) - 1] = '\0';
|
||||
}
|
||||
|
||||
void display_set_sender_statuses(const SenderStatus *statuses, uint8_t count) {
|
||||
g_statuses = statuses;
|
||||
g_status_count = count;
|
||||
}
|
||||
|
||||
void display_set_last_meter(const MeterData &data) {
|
||||
g_last_meter = data;
|
||||
}
|
||||
|
||||
void display_set_last_read(bool ok, uint32_t ts_utc) {
|
||||
g_last_read_ok = ok;
|
||||
g_last_read_ts = ts_utc;
|
||||
g_last_read_ms = millis();
|
||||
}
|
||||
|
||||
void display_set_last_tx(bool ok, uint32_t ts_utc) {
|
||||
g_last_tx_ok = ok;
|
||||
g_last_tx_ts = ts_utc;
|
||||
g_last_tx_ms = millis();
|
||||
}
|
||||
|
||||
void display_set_receiver_status(bool ap_mode, const char *ssid, bool mqtt_ok) {
|
||||
g_ap_mode = ap_mode;
|
||||
g_wifi_ssid = ssid ? ssid : "";
|
||||
g_mqtt_ok = mqtt_ok;
|
||||
}
|
||||
|
||||
#ifdef ENABLE_TEST_MODE
|
||||
void display_set_test_code(const char *code) {
|
||||
strncpy(g_test_code, code, sizeof(g_test_code));
|
||||
g_test_code[sizeof(g_test_code) - 1] = '\0';
|
||||
}
|
||||
|
||||
void display_set_test_code_for_sender(uint8_t index, const char *code) {
|
||||
if (index >= NUM_SENDERS) {
|
||||
return;
|
||||
}
|
||||
strncpy(g_test_codes[index], code, sizeof(g_test_codes[index]));
|
||||
g_test_codes[index][sizeof(g_test_codes[index]) - 1] = '\0';
|
||||
}
|
||||
#endif
|
||||
|
||||
static uint32_t age_seconds(uint32_t ts_utc, uint32_t ts_ms) {
|
||||
if (time_is_synced() && ts_utc > 0) {
|
||||
uint32_t now = time_get_utc();
|
||||
return now > ts_utc ? now - ts_utc : 0;
|
||||
}
|
||||
return (millis() - ts_ms) / 1000;
|
||||
}
|
||||
|
||||
static void render_sender_status() {
|
||||
display.clearDisplay();
|
||||
display.setCursor(0, 0);
|
||||
display.printf("SENDER %s", g_device_id);
|
||||
|
||||
char time_buf[8];
|
||||
time_get_local_hhmm(time_buf, sizeof(time_buf));
|
||||
display.setCursor(0, 12);
|
||||
display.printf("%s %.2fV %u%%", time_buf, g_last_meter.battery_voltage_v, g_last_meter.battery_percent);
|
||||
|
||||
display.setCursor(0, 24);
|
||||
display.printf("Read %s %lus ago", g_last_read_ok ? "OK" : "ERR", static_cast<unsigned long>(age_seconds(g_last_read_ts, g_last_read_ms)));
|
||||
|
||||
display.setCursor(0, 36);
|
||||
display.printf("TX %s %lus ago", g_last_tx_ok ? "OK" : "ERR", static_cast<unsigned long>(age_seconds(g_last_tx_ts, g_last_tx_ms)));
|
||||
|
||||
#ifdef ENABLE_TEST_MODE
|
||||
if (strlen(g_test_code) > 0) {
|
||||
display.setCursor(0, 48);
|
||||
display.printf("Test %s", g_test_code);
|
||||
}
|
||||
#endif
|
||||
|
||||
display.display();
|
||||
}
|
||||
|
||||
static void render_sender_measurement() {
|
||||
display.clearDisplay();
|
||||
display.setCursor(0, 0);
|
||||
display.printf("E %.1f kWh", g_last_meter.energy_total_kwh);
|
||||
display.setCursor(0, 12);
|
||||
display.printf("P %.0fW", g_last_meter.total_power_w);
|
||||
display.setCursor(0, 24);
|
||||
display.printf("L1 %.0fV %.0fW", g_last_meter.phase_voltage_v[0], g_last_meter.phase_power_w[0]);
|
||||
display.setCursor(0, 36);
|
||||
display.printf("L2 %.0fV %.0fW", g_last_meter.phase_voltage_v[1], g_last_meter.phase_power_w[1]);
|
||||
display.setCursor(0, 48);
|
||||
display.printf("L3 %.0fV %.0fW", g_last_meter.phase_voltage_v[2], g_last_meter.phase_power_w[2]);
|
||||
display.display();
|
||||
}
|
||||
|
||||
static void render_receiver_status() {
|
||||
display.clearDisplay();
|
||||
display.setCursor(0, 0);
|
||||
display.printf("RECEIVER %s", g_device_id);
|
||||
|
||||
display.setCursor(0, 12);
|
||||
if (g_ap_mode) {
|
||||
display.print("WiFi: AP");
|
||||
} else {
|
||||
display.printf("WiFi: %s", g_wifi_ssid.c_str());
|
||||
}
|
||||
|
||||
display.setCursor(0, 24);
|
||||
display.printf("MQTT: %s", g_mqtt_ok ? "OK" : "RETRY");
|
||||
|
||||
uint32_t latest = 0;
|
||||
if (g_statuses) {
|
||||
for (uint8_t i = 0; i < g_status_count; ++i) {
|
||||
if (g_statuses[i].has_data && g_statuses[i].last_update_ts_utc > latest) {
|
||||
latest = g_statuses[i].last_update_ts_utc;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
display.setCursor(0, 36);
|
||||
if (latest == 0 || !time_is_synced()) {
|
||||
display.print("Last upd: --:--");
|
||||
} else {
|
||||
time_t t = latest;
|
||||
struct tm timeinfo;
|
||||
localtime_r(&t, &timeinfo);
|
||||
display.printf("Last upd: %02d:%02d", timeinfo.tm_hour, timeinfo.tm_min);
|
||||
}
|
||||
|
||||
display.display();
|
||||
}
|
||||
|
||||
static void render_receiver_sender(uint8_t index) {
|
||||
display.clearDisplay();
|
||||
if (!g_statuses || index >= g_status_count) {
|
||||
display.setCursor(0, 0);
|
||||
display.print("No sender");
|
||||
display.display();
|
||||
return;
|
||||
}
|
||||
|
||||
const SenderStatus &status = g_statuses[index];
|
||||
display.setCursor(0, 0);
|
||||
uint8_t bat = status.has_data ? status.last_data.battery_percent : 0;
|
||||
if (status.has_data) {
|
||||
display.printf("%s B%u", status.last_data.device_id, bat);
|
||||
} else {
|
||||
display.printf("%s B--", status.last_data.device_id);
|
||||
}
|
||||
|
||||
if (!status.has_data) {
|
||||
display.setCursor(0, 12);
|
||||
display.print("No data");
|
||||
display.display();
|
||||
return;
|
||||
}
|
||||
|
||||
#ifdef ENABLE_TEST_MODE
|
||||
if (strlen(g_test_codes[index]) > 0) {
|
||||
display.setCursor(0, 12);
|
||||
display.printf("Test %s", g_test_codes[index]);
|
||||
display.display();
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
|
||||
display.setCursor(0, 12);
|
||||
display.printf("E %.1f kWh", status.last_data.energy_total_kwh);
|
||||
display.setCursor(0, 24);
|
||||
display.printf("P %.0fW", status.last_data.total_power_w);
|
||||
display.setCursor(0, 36);
|
||||
display.printf("L1 %.0fV %.0fW", status.last_data.phase_voltage_v[0], status.last_data.phase_power_w[0]);
|
||||
display.setCursor(0, 48);
|
||||
display.printf("L2 %.0fV %.0fW", status.last_data.phase_voltage_v[1], status.last_data.phase_power_w[1]);
|
||||
display.setCursor(0, 56);
|
||||
display.printf("L3 %.0fV %.0fW", status.last_data.phase_voltage_v[2], status.last_data.phase_power_w[2]);
|
||||
display.display();
|
||||
}
|
||||
|
||||
void display_tick() {
|
||||
if (!g_display_ready) {
|
||||
if (millis() - g_last_init_attempt_ms > 1000) {
|
||||
g_last_init_attempt_ms = millis();
|
||||
g_display_ready = display.begin(SSD1306_SWITCHCAPVCC, OLED_I2C_ADDR);
|
||||
if (g_display_ready) {
|
||||
display.clearDisplay();
|
||||
display.setTextSize(1);
|
||||
display.setTextColor(SSD1306_WHITE);
|
||||
display.ssd1306_command(SSD1306_DISPLAYON);
|
||||
display.display();
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
bool ctrl_high = digitalRead(PIN_OLED_CTRL) == HIGH;
|
||||
|
||||
bool in_boot_window = (millis() - g_boot_ms) < OLED_AUTO_OFF_MS;
|
||||
if (in_boot_window) {
|
||||
g_oled_on = true;
|
||||
oled_set_power(true);
|
||||
} else {
|
||||
if (ctrl_high) {
|
||||
g_oled_on = true;
|
||||
g_oled_off_start = 0;
|
||||
} else if (g_prev_ctrl_high && !ctrl_high) {
|
||||
g_oled_off_start = millis();
|
||||
} else if (!g_prev_ctrl_high && !ctrl_high && g_oled_off_start == 0) {
|
||||
g_oled_off_start = millis();
|
||||
}
|
||||
|
||||
if (!ctrl_high && g_oled_off_start > 0 && millis() - g_oled_off_start > OLED_AUTO_OFF_MS) {
|
||||
g_oled_on = false;
|
||||
}
|
||||
|
||||
if (g_oled_on) {
|
||||
oled_set_power(true);
|
||||
} else {
|
||||
oled_set_power(false);
|
||||
g_prev_ctrl_high = ctrl_high;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
uint32_t now = millis();
|
||||
uint8_t page_count = g_role == DeviceRole::Sender ? 2 : (1 + g_status_count);
|
||||
if (page_count == 0) {
|
||||
page_count = 1;
|
||||
}
|
||||
if (now - g_last_page_ms > OLED_PAGE_INTERVAL_MS) {
|
||||
g_last_page_ms = now;
|
||||
g_page = (g_page + 1) % page_count;
|
||||
}
|
||||
|
||||
if (g_role == DeviceRole::Sender) {
|
||||
if (g_page == 0) {
|
||||
render_sender_status();
|
||||
} else {
|
||||
render_sender_measurement();
|
||||
}
|
||||
} else {
|
||||
if (g_page == 0) {
|
||||
render_receiver_status();
|
||||
} else {
|
||||
render_receiver_sender(g_page - 1);
|
||||
}
|
||||
}
|
||||
|
||||
g_prev_ctrl_high = ctrl_high;
|
||||
}
|
||||
55
src/json_codec.cpp
Normal file
55
src/json_codec.cpp
Normal file
@@ -0,0 +1,55 @@
|
||||
#include "json_codec.h"
|
||||
#include <ArduinoJson.h>
|
||||
#include <math.h>
|
||||
|
||||
bool meterDataToJson(const MeterData &data, String &out_json) {
|
||||
StaticJsonDocument<256> doc;
|
||||
doc["id"] = data.device_id;
|
||||
doc["ts"] = data.ts_utc;
|
||||
doc["energy_kwh"] = data.energy_total_kwh;
|
||||
doc["p_total_w"] = data.total_power_w;
|
||||
doc["p1_w"] = data.phase_power_w[0];
|
||||
doc["p2_w"] = data.phase_power_w[1];
|
||||
doc["p3_w"] = data.phase_power_w[2];
|
||||
doc["v1_v"] = data.phase_voltage_v[0];
|
||||
doc["v2_v"] = data.phase_voltage_v[1];
|
||||
doc["v3_v"] = data.phase_voltage_v[2];
|
||||
doc["bat_v"] = data.battery_voltage_v;
|
||||
doc["bat_pct"] = data.battery_percent;
|
||||
|
||||
out_json = "";
|
||||
size_t len = serializeJson(doc, out_json);
|
||||
return len > 0 && len < 256;
|
||||
}
|
||||
|
||||
bool jsonToMeterData(const String &json, MeterData &data) {
|
||||
StaticJsonDocument<256> doc;
|
||||
DeserializationError err = deserializeJson(doc, json);
|
||||
if (err) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const char *id = doc["id"] | "";
|
||||
strncpy(data.device_id, id, sizeof(data.device_id));
|
||||
data.device_id[sizeof(data.device_id) - 1] = '\0';
|
||||
|
||||
data.ts_utc = doc["ts"] | 0;
|
||||
data.energy_total_kwh = doc["energy_kwh"] | NAN;
|
||||
data.total_power_w = doc["p_total_w"] | NAN;
|
||||
data.phase_power_w[0] = doc["p1_w"] | NAN;
|
||||
data.phase_power_w[1] = doc["p2_w"] | NAN;
|
||||
data.phase_power_w[2] = doc["p3_w"] | NAN;
|
||||
data.phase_voltage_v[0] = doc["v1_v"] | NAN;
|
||||
data.phase_voltage_v[1] = doc["v2_v"] | NAN;
|
||||
data.phase_voltage_v[2] = doc["v3_v"] | NAN;
|
||||
data.battery_voltage_v = doc["bat_v"] | NAN;
|
||||
data.battery_percent = doc["bat_pct"] | 0;
|
||||
data.valid = true;
|
||||
|
||||
if (strlen(data.device_id) >= 8) {
|
||||
const char *suffix = data.device_id + strlen(data.device_id) - 4;
|
||||
data.short_id = static_cast<uint16_t>(strtoul(suffix, nullptr, 16));
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
102
src/lora_transport.cpp
Normal file
102
src/lora_transport.cpp
Normal file
@@ -0,0 +1,102 @@
|
||||
#include "lora_transport.h"
|
||||
#include <LoRa.h>
|
||||
#include <SPI.h>
|
||||
|
||||
static uint16_t crc16_ccitt(const uint8_t *data, size_t len) {
|
||||
uint16_t crc = 0xFFFF;
|
||||
for (size_t i = 0; i < len; ++i) {
|
||||
crc ^= static_cast<uint16_t>(data[i]) << 8;
|
||||
for (uint8_t b = 0; b < 8; ++b) {
|
||||
if (crc & 0x8000) {
|
||||
crc = (crc << 1) ^ 0x1021;
|
||||
} else {
|
||||
crc <<= 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
return crc;
|
||||
}
|
||||
|
||||
void lora_init() {
|
||||
SPI.begin(PIN_LORA_SCK, PIN_LORA_MISO, PIN_LORA_MOSI, PIN_LORA_NSS);
|
||||
LoRa.setPins(PIN_LORA_NSS, PIN_LORA_RST, PIN_LORA_DIO0);
|
||||
LoRa.begin(LORA_FREQUENCY);
|
||||
LoRa.setSpreadingFactor(LORA_SPREADING_FACTOR);
|
||||
LoRa.setSignalBandwidth(LORA_BANDWIDTH);
|
||||
LoRa.setCodingRate4(LORA_CODING_RATE);
|
||||
LoRa.enableCrc();
|
||||
LoRa.setSyncWord(LORA_SYNC_WORD);
|
||||
}
|
||||
|
||||
bool lora_send(const LoraPacket &pkt) {
|
||||
uint8_t buffer[5 + LORA_MAX_PAYLOAD + 2];
|
||||
size_t idx = 0;
|
||||
buffer[idx++] = pkt.protocol_version;
|
||||
buffer[idx++] = static_cast<uint8_t>(pkt.role);
|
||||
buffer[idx++] = static_cast<uint8_t>(pkt.device_id_short >> 8);
|
||||
buffer[idx++] = static_cast<uint8_t>(pkt.device_id_short & 0xFF);
|
||||
buffer[idx++] = static_cast<uint8_t>(pkt.payload_type);
|
||||
|
||||
if (pkt.payload_len > LORA_MAX_PAYLOAD) {
|
||||
return false;
|
||||
}
|
||||
|
||||
memcpy(&buffer[idx], pkt.payload, pkt.payload_len);
|
||||
idx += pkt.payload_len;
|
||||
|
||||
uint16_t crc = crc16_ccitt(buffer, idx);
|
||||
buffer[idx++] = static_cast<uint8_t>(crc >> 8);
|
||||
buffer[idx++] = static_cast<uint8_t>(crc & 0xFF);
|
||||
|
||||
LoRa.beginPacket();
|
||||
LoRa.write(buffer, idx);
|
||||
LoRa.endPacket();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool lora_receive(LoraPacket &pkt, uint32_t timeout_ms) {
|
||||
uint32_t start = millis();
|
||||
while (true) {
|
||||
int packet_size = LoRa.parsePacket();
|
||||
if (packet_size > 0) {
|
||||
if (packet_size < 7) {
|
||||
while (LoRa.available()) {
|
||||
LoRa.read();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
uint8_t buffer[5 + LORA_MAX_PAYLOAD + 2];
|
||||
size_t len = 0;
|
||||
while (LoRa.available() && len < sizeof(buffer)) {
|
||||
buffer[len++] = LoRa.read();
|
||||
}
|
||||
|
||||
if (len < 7) {
|
||||
return false;
|
||||
}
|
||||
|
||||
uint16_t crc_calc = crc16_ccitt(buffer, len - 2);
|
||||
uint16_t crc_rx = static_cast<uint16_t>(buffer[len - 2] << 8) | buffer[len - 1];
|
||||
if (crc_calc != crc_rx) {
|
||||
return false;
|
||||
}
|
||||
|
||||
pkt.protocol_version = buffer[0];
|
||||
pkt.role = static_cast<DeviceRole>(buffer[1]);
|
||||
pkt.device_id_short = static_cast<uint16_t>(buffer[2] << 8) | buffer[3];
|
||||
pkt.payload_type = static_cast<PayloadType>(buffer[4]);
|
||||
pkt.payload_len = len - 7;
|
||||
if (pkt.payload_len > LORA_MAX_PAYLOAD) {
|
||||
return false;
|
||||
}
|
||||
memcpy(pkt.payload, &buffer[5], pkt.payload_len);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (timeout_ms == 0 || millis() - start >= timeout_ms) {
|
||||
return false;
|
||||
}
|
||||
delay(5);
|
||||
}
|
||||
}
|
||||
182
src/main.cpp
Normal file
182
src/main.cpp
Normal file
@@ -0,0 +1,182 @@
|
||||
#include <Arduino.h>
|
||||
#include "config.h"
|
||||
#include "data_model.h"
|
||||
#include "json_codec.h"
|
||||
#include "compressor.h"
|
||||
#include "lora_transport.h"
|
||||
#include "meter_driver.h"
|
||||
#include "power_manager.h"
|
||||
#include "time_manager.h"
|
||||
#include "wifi_manager.h"
|
||||
#include "mqtt_client.h"
|
||||
#include "web_server.h"
|
||||
#include "display_ui.h"
|
||||
#include "test_mode.h"
|
||||
|
||||
static DeviceRole g_role = DeviceRole::Sender;
|
||||
static uint16_t g_short_id = 0;
|
||||
static char g_device_id[16] = "";
|
||||
|
||||
static SenderStatus g_sender_statuses[NUM_SENDERS];
|
||||
static bool g_ap_mode = false;
|
||||
static WifiMqttConfig g_cfg;
|
||||
static uint32_t g_last_timesync_ms = 0;
|
||||
|
||||
static void init_sender_statuses() {
|
||||
for (uint8_t i = 0; i < NUM_SENDERS; ++i) {
|
||||
g_sender_statuses[i] = {};
|
||||
g_sender_statuses[i].has_data = false;
|
||||
g_sender_statuses[i].last_update_ts_utc = 0;
|
||||
g_sender_statuses[i].last_data.short_id = EXPECTED_SENDER_IDS[i];
|
||||
snprintf(g_sender_statuses[i].last_data.device_id, sizeof(g_sender_statuses[i].last_data.device_id), "dd3-%04X", EXPECTED_SENDER_IDS[i]);
|
||||
}
|
||||
}
|
||||
|
||||
void setup() {
|
||||
Serial.begin(115200);
|
||||
delay(200);
|
||||
|
||||
g_role = detect_role();
|
||||
init_device_ids(g_short_id, g_device_id, sizeof(g_device_id));
|
||||
|
||||
lora_init();
|
||||
display_init();
|
||||
display_set_role(g_role);
|
||||
display_set_self_ids(g_short_id, g_device_id);
|
||||
|
||||
if (g_role == DeviceRole::Sender) {
|
||||
power_sender_init();
|
||||
meter_init();
|
||||
} else {
|
||||
power_receiver_init();
|
||||
wifi_manager_init();
|
||||
init_sender_statuses();
|
||||
display_set_sender_statuses(g_sender_statuses, NUM_SENDERS);
|
||||
|
||||
bool has_cfg = wifi_load_config(g_cfg);
|
||||
if (has_cfg && wifi_connect_sta(g_cfg)) {
|
||||
g_ap_mode = false;
|
||||
time_receiver_init(g_cfg.ntp_server_1.c_str(), g_cfg.ntp_server_2.c_str());
|
||||
mqtt_init(g_cfg, g_device_id);
|
||||
web_server_set_config(g_cfg);
|
||||
web_server_begin_sta(g_sender_statuses, NUM_SENDERS);
|
||||
} else {
|
||||
g_ap_mode = true;
|
||||
char ap_ssid[32];
|
||||
snprintf(ap_ssid, sizeof(ap_ssid), "DD3-Bridge-%04X", g_short_id);
|
||||
wifi_start_ap(ap_ssid, "changeme123");
|
||||
if (g_cfg.ntp_server_1.isEmpty()) {
|
||||
g_cfg.ntp_server_1 = "pool.ntp.org";
|
||||
}
|
||||
if (g_cfg.ntp_server_2.isEmpty()) {
|
||||
g_cfg.ntp_server_2 = "time.nist.gov";
|
||||
}
|
||||
web_server_set_config(g_cfg);
|
||||
web_server_begin_ap(g_sender_statuses, NUM_SENDERS);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void sender_cycle() {
|
||||
MeterData data = {};
|
||||
data.short_id = g_short_id;
|
||||
strncpy(data.device_id, g_device_id, sizeof(data.device_id));
|
||||
|
||||
bool meter_ok = meter_read(data);
|
||||
read_battery(data);
|
||||
|
||||
uint32_t now_utc = time_get_utc();
|
||||
data.ts_utc = now_utc > 0 ? now_utc : millis() / 1000;
|
||||
data.valid = meter_ok;
|
||||
|
||||
display_set_last_meter(data);
|
||||
display_set_last_read(meter_ok, data.ts_utc);
|
||||
|
||||
String json;
|
||||
bool json_ok = meterDataToJson(data, json);
|
||||
|
||||
bool tx_ok = false;
|
||||
if (json_ok) {
|
||||
uint8_t compressed[LORA_MAX_PAYLOAD];
|
||||
size_t compressed_len = 0;
|
||||
if (compressBuffer(reinterpret_cast<const uint8_t *>(json.c_str()), json.length(), compressed, sizeof(compressed), compressed_len)) {
|
||||
LoraPacket pkt = {};
|
||||
pkt.protocol_version = PROTOCOL_VERSION;
|
||||
pkt.role = DeviceRole::Sender;
|
||||
pkt.device_id_short = g_short_id;
|
||||
pkt.payload_type = PayloadType::MeterData;
|
||||
pkt.payload_len = compressed_len;
|
||||
memcpy(pkt.payload, compressed, compressed_len);
|
||||
tx_ok = lora_send(pkt);
|
||||
}
|
||||
}
|
||||
|
||||
display_set_last_tx(tx_ok, data.ts_utc);
|
||||
display_tick();
|
||||
|
||||
LoraPacket rx = {};
|
||||
if (lora_receive(rx, 200) && rx.protocol_version == PROTOCOL_VERSION && rx.payload_type == PayloadType::TimeSync) {
|
||||
time_handle_timesync_payload(rx.payload, rx.payload_len);
|
||||
}
|
||||
|
||||
delay(50);
|
||||
go_to_deep_sleep(SENDER_WAKE_INTERVAL_SEC);
|
||||
}
|
||||
|
||||
static void receiver_loop() {
|
||||
LoraPacket pkt = {};
|
||||
if (lora_receive(pkt, 0) && pkt.protocol_version == PROTOCOL_VERSION && pkt.payload_type == PayloadType::MeterData) {
|
||||
uint8_t decompressed[256];
|
||||
size_t decompressed_len = 0;
|
||||
if (decompressBuffer(pkt.payload, pkt.payload_len, decompressed, sizeof(decompressed), decompressed_len)) {
|
||||
decompressed[decompressed_len] = '\0';
|
||||
MeterData data = {};
|
||||
if (jsonToMeterData(String(reinterpret_cast<const char *>(decompressed)), data)) {
|
||||
for (uint8_t i = 0; i < NUM_SENDERS; ++i) {
|
||||
if (pkt.device_id_short == EXPECTED_SENDER_IDS[i]) {
|
||||
data.short_id = pkt.device_id_short;
|
||||
g_sender_statuses[i].last_data = data;
|
||||
g_sender_statuses[i].last_update_ts_utc = data.ts_utc;
|
||||
g_sender_statuses[i].has_data = true;
|
||||
mqtt_publish_state(data);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!g_ap_mode && millis() - g_last_timesync_ms > TIME_SYNC_INTERVAL_SEC * 1000UL) {
|
||||
g_last_timesync_ms = millis();
|
||||
time_send_timesync(g_short_id);
|
||||
}
|
||||
|
||||
mqtt_loop();
|
||||
web_server_loop();
|
||||
display_set_receiver_status(g_ap_mode, wifi_is_connected() ? wifi_get_ssid().c_str() : "AP", mqtt_is_connected());
|
||||
display_tick();
|
||||
}
|
||||
|
||||
void loop() {
|
||||
#ifdef ENABLE_TEST_MODE
|
||||
if (g_role == DeviceRole::Sender) {
|
||||
test_sender_loop(g_short_id, g_device_id);
|
||||
display_tick();
|
||||
delay(50);
|
||||
} else {
|
||||
test_receiver_loop(g_sender_statuses, NUM_SENDERS);
|
||||
mqtt_loop();
|
||||
web_server_loop();
|
||||
display_set_receiver_status(g_ap_mode, wifi_is_connected() ? wifi_get_ssid().c_str() : "AP", mqtt_is_connected());
|
||||
display_tick();
|
||||
delay(50);
|
||||
}
|
||||
return;
|
||||
#endif
|
||||
|
||||
if (g_role == DeviceRole::Sender) {
|
||||
sender_cycle();
|
||||
} else {
|
||||
receiver_loop();
|
||||
}
|
||||
}
|
||||
166
src/meter_driver.cpp
Normal file
166
src/meter_driver.cpp
Normal file
@@ -0,0 +1,166 @@
|
||||
#include "meter_driver.h"
|
||||
#include "config.h"
|
||||
#include <math.h>
|
||||
#include <string.h>
|
||||
|
||||
static constexpr uint32_t METER_READ_TIMEOUT_MS = 2000;
|
||||
static constexpr size_t SML_BUFFER_SIZE = 2048;
|
||||
|
||||
static const uint8_t OBIS_ENERGY_TOTAL[6] = {0x01, 0x00, 0x01, 0x08, 0x00, 0xFF};
|
||||
static const uint8_t OBIS_TOTAL_POWER[6] = {0x01, 0x00, 0x10, 0x07, 0x00, 0xFF};
|
||||
static const uint8_t OBIS_P1[6] = {0x01, 0x00, 0x24, 0x07, 0x00, 0xFF};
|
||||
static const uint8_t OBIS_P2[6] = {0x01, 0x00, 0x38, 0x07, 0x00, 0xFF};
|
||||
static const uint8_t OBIS_P3[6] = {0x01, 0x00, 0x4C, 0x07, 0x00, 0xFF};
|
||||
static const uint8_t OBIS_V1[6] = {0x01, 0x00, 0x20, 0x07, 0x00, 0xFF};
|
||||
static const uint8_t OBIS_V2[6] = {0x01, 0x00, 0x34, 0x07, 0x00, 0xFF};
|
||||
static const uint8_t OBIS_V3[6] = {0x01, 0x00, 0x48, 0x07, 0x00, 0xFF};
|
||||
|
||||
static bool find_obis_value(const uint8_t *buf, size_t len, const uint8_t *obis, float &out_value) {
|
||||
for (size_t i = 0; i + 6 < len; ++i) {
|
||||
if (memcmp(&buf[i], obis, 6) == 0) {
|
||||
int8_t scaler = 0;
|
||||
bool scaler_found = false;
|
||||
bool value_found = false;
|
||||
int64_t value = 0;
|
||||
size_t cursor = i + 6;
|
||||
size_t limit = (i + 6 + 120 < len) ? i + 6 + 120 : len;
|
||||
|
||||
while (cursor < limit) {
|
||||
uint8_t tl = buf[cursor++];
|
||||
if (tl == 0x00) {
|
||||
continue;
|
||||
}
|
||||
uint8_t type = (tl >> 4) & 0x0F;
|
||||
uint8_t tlen = tl & 0x0F;
|
||||
if (tlen == 0 || cursor + tlen > len) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (type == 0x05 || type == 0x06) {
|
||||
int64_t val = 0;
|
||||
for (uint8_t b = 0; b < tlen; ++b) {
|
||||
val = (val << 8) | buf[cursor + b];
|
||||
}
|
||||
if (type == 0x05) {
|
||||
int64_t sign_bit = 1LL << ((tlen * 8) - 1);
|
||||
if (val & sign_bit) {
|
||||
int64_t mask = (1LL << (tlen * 8)) - 1;
|
||||
val = -((~val + 1) & mask);
|
||||
}
|
||||
}
|
||||
|
||||
if (!scaler_found && tlen <= 2 && val >= -6 && val <= 6) {
|
||||
scaler = static_cast<int8_t>(val);
|
||||
scaler_found = true;
|
||||
} else if (!value_found) {
|
||||
value = val;
|
||||
value_found = true;
|
||||
}
|
||||
}
|
||||
cursor += tlen;
|
||||
if (value_found && scaler_found) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (value_found) {
|
||||
out_value = static_cast<float>(value) * powf(10.0f, scaler);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void meter_init() {
|
||||
Serial2.begin(9600, SERIAL_7E1, PIN_METER_RX, -1);
|
||||
}
|
||||
|
||||
bool meter_read(MeterData &data) {
|
||||
uint8_t buffer[SML_BUFFER_SIZE];
|
||||
size_t len = 0;
|
||||
bool started = false;
|
||||
uint32_t start = millis();
|
||||
const uint8_t start_seq[] = {0x1B, 0x1B, 0x1B, 0x1B, 0x01, 0x01, 0x01, 0x01};
|
||||
const uint8_t end_seq[] = {0x1B, 0x1B, 0x1B, 0x1B, 0x1A};
|
||||
|
||||
while (millis() - start < METER_READ_TIMEOUT_MS) {
|
||||
while (Serial2.available()) {
|
||||
uint8_t b = Serial2.read();
|
||||
if (!started) {
|
||||
buffer[len++] = b;
|
||||
if (len >= sizeof(start_seq)) {
|
||||
if (memcmp(&buffer[len - sizeof(start_seq)], start_seq, sizeof(start_seq)) == 0) {
|
||||
started = true;
|
||||
len = 0;
|
||||
}
|
||||
}
|
||||
if (len >= sizeof(buffer)) {
|
||||
len = 0;
|
||||
}
|
||||
} else {
|
||||
if (len < sizeof(buffer)) {
|
||||
buffer[len++] = b;
|
||||
if (len >= sizeof(end_seq)) {
|
||||
if (memcmp(&buffer[len - sizeof(end_seq)], end_seq, sizeof(end_seq)) == 0) {
|
||||
start = millis();
|
||||
goto parse_frame;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
delay(5);
|
||||
}
|
||||
|
||||
parse_frame:
|
||||
if (!started || len == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
data.energy_total_kwh = NAN;
|
||||
data.total_power_w = NAN;
|
||||
data.phase_power_w[0] = NAN;
|
||||
data.phase_power_w[1] = NAN;
|
||||
data.phase_power_w[2] = NAN;
|
||||
data.phase_voltage_v[0] = NAN;
|
||||
data.phase_voltage_v[1] = NAN;
|
||||
data.phase_voltage_v[2] = NAN;
|
||||
|
||||
bool ok = true;
|
||||
float value = 0.0f;
|
||||
|
||||
if (find_obis_value(buffer, len, OBIS_ENERGY_TOTAL, value)) {
|
||||
data.energy_total_kwh = value;
|
||||
} else {
|
||||
ok = false;
|
||||
}
|
||||
|
||||
if (find_obis_value(buffer, len, OBIS_TOTAL_POWER, value)) {
|
||||
data.total_power_w = value;
|
||||
} else {
|
||||
ok = false;
|
||||
}
|
||||
|
||||
if (find_obis_value(buffer, len, OBIS_P1, value)) {
|
||||
data.phase_power_w[0] = value;
|
||||
}
|
||||
if (find_obis_value(buffer, len, OBIS_P2, value)) {
|
||||
data.phase_power_w[1] = value;
|
||||
}
|
||||
if (find_obis_value(buffer, len, OBIS_P3, value)) {
|
||||
data.phase_power_w[2] = value;
|
||||
}
|
||||
if (find_obis_value(buffer, len, OBIS_V1, value)) {
|
||||
data.phase_voltage_v[0] = value;
|
||||
}
|
||||
if (find_obis_value(buffer, len, OBIS_V2, value)) {
|
||||
data.phase_voltage_v[1] = value;
|
||||
}
|
||||
if (find_obis_value(buffer, len, OBIS_V3, value)) {
|
||||
data.phase_voltage_v[2] = value;
|
||||
}
|
||||
|
||||
data.valid = ok;
|
||||
return ok;
|
||||
}
|
||||
63
src/mqtt_client.cpp
Normal file
63
src/mqtt_client.cpp
Normal file
@@ -0,0 +1,63 @@
|
||||
#include "mqtt_client.h"
|
||||
#include <WiFi.h>
|
||||
#include <PubSubClient.h>
|
||||
#include "json_codec.h"
|
||||
|
||||
static WiFiClient wifi_client;
|
||||
static PubSubClient mqtt_client(wifi_client);
|
||||
static WifiMqttConfig g_cfg;
|
||||
static String g_client_id;
|
||||
|
||||
void mqtt_init(const WifiMqttConfig &config, const char *device_id) {
|
||||
g_cfg = config;
|
||||
mqtt_client.setServer(config.mqtt_host.c_str(), config.mqtt_port);
|
||||
if (device_id && device_id[0] != '\0') {
|
||||
g_client_id = String("dd3-bridge-") + device_id;
|
||||
} else {
|
||||
g_client_id = String("dd3-bridge-") + String(random(0xffff), HEX);
|
||||
}
|
||||
}
|
||||
|
||||
static bool mqtt_connect() {
|
||||
if (mqtt_client.connected()) {
|
||||
return true;
|
||||
}
|
||||
String client_id = g_client_id.length() > 0 ? g_client_id : String("dd3-bridge-") + String(random(0xffff), HEX);
|
||||
if (g_cfg.mqtt_user.length() > 0) {
|
||||
return mqtt_client.connect(client_id.c_str(), g_cfg.mqtt_user.c_str(), g_cfg.mqtt_pass.c_str());
|
||||
}
|
||||
return mqtt_client.connect(client_id.c_str());
|
||||
}
|
||||
|
||||
void mqtt_loop() {
|
||||
if (!mqtt_connect()) {
|
||||
return;
|
||||
}
|
||||
mqtt_client.loop();
|
||||
}
|
||||
|
||||
bool mqtt_is_connected() {
|
||||
return mqtt_client.connected();
|
||||
}
|
||||
|
||||
bool mqtt_publish_state(const MeterData &data) {
|
||||
if (!mqtt_connect()) {
|
||||
return false;
|
||||
}
|
||||
String payload;
|
||||
if (!meterDataToJson(data, payload)) {
|
||||
return false;
|
||||
}
|
||||
String topic = String("smartmeter/") + data.device_id + "/state";
|
||||
return mqtt_client.publish(topic.c_str(), payload.c_str());
|
||||
}
|
||||
|
||||
#ifdef ENABLE_TEST_MODE
|
||||
bool mqtt_publish_test(const char *device_id, const String &payload) {
|
||||
if (!mqtt_connect()) {
|
||||
return false;
|
||||
}
|
||||
String topic = String("smartmeter/") + device_id + "/test";
|
||||
return mqtt_client.publish(topic.c_str(), payload.c_str());
|
||||
}
|
||||
#endif
|
||||
48
src/power_manager.cpp
Normal file
48
src/power_manager.cpp
Normal file
@@ -0,0 +1,48 @@
|
||||
#include "power_manager.h"
|
||||
#include "config.h"
|
||||
#include <WiFi.h>
|
||||
#include <esp_wifi.h>
|
||||
#include <esp_bt.h>
|
||||
#include <esp_sleep.h>
|
||||
|
||||
static constexpr float BATTERY_DIVIDER = 2.0f;
|
||||
static constexpr float BATTERY_CAL = 1.0f;
|
||||
static constexpr float ADC_REF_V = 3.3f;
|
||||
|
||||
void power_sender_init() {
|
||||
esp_wifi_stop();
|
||||
btStop();
|
||||
analogReadResolution(12);
|
||||
pinMode(PIN_BAT_ADC, INPUT);
|
||||
}
|
||||
|
||||
void power_receiver_init() {
|
||||
analogReadResolution(12);
|
||||
pinMode(PIN_BAT_ADC, INPUT);
|
||||
}
|
||||
|
||||
void read_battery(MeterData &data) {
|
||||
const int samples = 8;
|
||||
uint32_t sum = 0;
|
||||
for (int i = 0; i < samples; ++i) {
|
||||
sum += analogRead(PIN_BAT_ADC);
|
||||
delay(5);
|
||||
}
|
||||
float avg = static_cast<float>(sum) / samples;
|
||||
float v = (avg / 4095.0f) * ADC_REF_V * BATTERY_DIVIDER * BATTERY_CAL;
|
||||
|
||||
data.battery_voltage_v = v;
|
||||
float pct = (v - 3.0f) / (4.2f - 3.0f) * 100.0f;
|
||||
if (pct < 0.0f) {
|
||||
pct = 0.0f;
|
||||
}
|
||||
if (pct > 100.0f) {
|
||||
pct = 100.0f;
|
||||
}
|
||||
data.battery_percent = static_cast<uint8_t>(pct + 0.5f);
|
||||
}
|
||||
|
||||
void go_to_deep_sleep(uint32_t seconds) {
|
||||
esp_sleep_enable_timer_wakeup(static_cast<uint64_t>(seconds) * 1000000ULL);
|
||||
esp_deep_sleep_start();
|
||||
}
|
||||
97
src/test_mode.cpp
Normal file
97
src/test_mode.cpp
Normal file
@@ -0,0 +1,97 @@
|
||||
#include "test_mode.h"
|
||||
|
||||
#ifdef ENABLE_TEST_MODE
|
||||
#include "config.h"
|
||||
#include "compressor.h"
|
||||
#include "lora_transport.h"
|
||||
#include "json_codec.h"
|
||||
#include "time_manager.h"
|
||||
#include "display_ui.h"
|
||||
#include "mqtt_client.h"
|
||||
#include <ArduinoJson.h>
|
||||
|
||||
static uint32_t g_last_test_ms = 0;
|
||||
static uint32_t g_last_timesync_ms = 0;
|
||||
|
||||
void test_sender_loop(uint16_t short_id, const char *device_id) {
|
||||
LoraPacket rx = {};
|
||||
if (lora_receive(rx, 0) && rx.payload_type == PayloadType::TimeSync) {
|
||||
time_handle_timesync_payload(rx.payload, rx.payload_len);
|
||||
}
|
||||
|
||||
if (millis() - g_last_test_ms < 30000) {
|
||||
return;
|
||||
}
|
||||
g_last_test_ms = millis();
|
||||
|
||||
char code[5];
|
||||
uint16_t val = random(0, 9999);
|
||||
snprintf(code, sizeof(code), "%04u", val);
|
||||
display_set_test_code(code);
|
||||
|
||||
StaticJsonDocument<128> doc;
|
||||
doc["id"] = device_id;
|
||||
doc["role"] = "sender";
|
||||
doc["test_code"] = code;
|
||||
doc["ts"] = time_get_utc();
|
||||
|
||||
String json;
|
||||
serializeJson(doc, json);
|
||||
|
||||
uint8_t compressed[LORA_MAX_PAYLOAD];
|
||||
size_t compressed_len = 0;
|
||||
if (!compressBuffer(reinterpret_cast<const uint8_t *>(json.c_str()), json.length(), compressed, sizeof(compressed), compressed_len)) {
|
||||
return;
|
||||
}
|
||||
|
||||
LoraPacket pkt = {};
|
||||
pkt.protocol_version = PROTOCOL_VERSION;
|
||||
pkt.role = DeviceRole::Sender;
|
||||
pkt.device_id_short = short_id;
|
||||
pkt.payload_type = PayloadType::TestCode;
|
||||
pkt.payload_len = compressed_len;
|
||||
memcpy(pkt.payload, compressed, compressed_len);
|
||||
lora_send(pkt);
|
||||
}
|
||||
|
||||
void test_receiver_loop(SenderStatus *statuses, uint8_t count) {
|
||||
if (millis() - g_last_timesync_ms > TIME_SYNC_INTERVAL_SEC * 1000UL) {
|
||||
g_last_timesync_ms = millis();
|
||||
time_send_timesync(0);
|
||||
}
|
||||
|
||||
LoraPacket pkt = {};
|
||||
if (!lora_receive(pkt, 0)) {
|
||||
return;
|
||||
}
|
||||
if (pkt.payload_type != PayloadType::TestCode) {
|
||||
return;
|
||||
}
|
||||
|
||||
uint8_t decompressed[128];
|
||||
size_t decompressed_len = 0;
|
||||
if (!decompressBuffer(pkt.payload, pkt.payload_len, decompressed, sizeof(decompressed), decompressed_len)) {
|
||||
return;
|
||||
}
|
||||
decompressed[decompressed_len] = '\0';
|
||||
|
||||
StaticJsonDocument<128> doc;
|
||||
if (deserializeJson(doc, reinterpret_cast<const char *>(decompressed)) != DeserializationError::Ok) {
|
||||
return;
|
||||
}
|
||||
|
||||
const char *id = doc["id"] | "";
|
||||
const char *code = doc["test_code"] | "";
|
||||
|
||||
for (uint8_t i = 0; i < count; ++i) {
|
||||
if (strncmp(statuses[i].last_data.device_id, id, sizeof(statuses[i].last_data.device_id)) == 0) {
|
||||
display_set_test_code_for_sender(i, code);
|
||||
statuses[i].has_data = true;
|
||||
statuses[i].last_update_ts_utc = time_get_utc();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
mqtt_publish_test(id, String(reinterpret_cast<const char *>(decompressed)));
|
||||
}
|
||||
#endif
|
||||
103
src/time_manager.cpp
Normal file
103
src/time_manager.cpp
Normal file
@@ -0,0 +1,103 @@
|
||||
#include "time_manager.h"
|
||||
#include "compressor.h"
|
||||
#include "config.h"
|
||||
#include <time.h>
|
||||
|
||||
static bool g_time_synced = false;
|
||||
static bool g_tz_set = false;
|
||||
|
||||
void time_receiver_init(const char *ntp_server_1, const char *ntp_server_2) {
|
||||
const char *server1 = (ntp_server_1 && ntp_server_1[0] != '\0') ? ntp_server_1 : "pool.ntp.org";
|
||||
const char *server2 = (ntp_server_2 && ntp_server_2[0] != '\0') ? ntp_server_2 : "time.nist.gov";
|
||||
configTime(0, 0, server1, server2);
|
||||
if (!g_tz_set) {
|
||||
setenv("TZ", "CET-1CEST,M3.5.0/2,M10.5.0/3", 1);
|
||||
tzset();
|
||||
g_tz_set = true;
|
||||
}
|
||||
}
|
||||
|
||||
uint32_t time_get_utc() {
|
||||
time_t now = time(nullptr);
|
||||
if (now < 1672531200) {
|
||||
return 0;
|
||||
}
|
||||
return static_cast<uint32_t>(now);
|
||||
}
|
||||
|
||||
bool time_is_synced() {
|
||||
return g_time_synced || time_get_utc() > 0;
|
||||
}
|
||||
|
||||
void time_set_utc(uint32_t epoch) {
|
||||
if (!g_tz_set) {
|
||||
setenv("TZ", "CET-1CEST,M3.5.0/2,M10.5.0/3", 1);
|
||||
tzset();
|
||||
g_tz_set = true;
|
||||
}
|
||||
struct timeval tv;
|
||||
tv.tv_sec = epoch;
|
||||
tv.tv_usec = 0;
|
||||
settimeofday(&tv, nullptr);
|
||||
g_time_synced = true;
|
||||
}
|
||||
|
||||
void time_send_timesync(uint16_t device_id_short) {
|
||||
uint32_t epoch = time_get_utc();
|
||||
if (epoch == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
char payload_str[32];
|
||||
snprintf(payload_str, sizeof(payload_str), "T:%lu", static_cast<unsigned long>(epoch));
|
||||
|
||||
uint8_t compressed[LORA_MAX_PAYLOAD];
|
||||
size_t compressed_len = 0;
|
||||
if (!compressBuffer(reinterpret_cast<const uint8_t *>(payload_str), strlen(payload_str), compressed, sizeof(compressed), compressed_len)) {
|
||||
return;
|
||||
}
|
||||
|
||||
LoraPacket pkt = {};
|
||||
pkt.protocol_version = PROTOCOL_VERSION;
|
||||
pkt.role = DeviceRole::Receiver;
|
||||
pkt.device_id_short = device_id_short;
|
||||
pkt.payload_type = PayloadType::TimeSync;
|
||||
pkt.payload_len = compressed_len;
|
||||
memcpy(pkt.payload, compressed, compressed_len);
|
||||
lora_send(pkt);
|
||||
}
|
||||
|
||||
bool time_handle_timesync_payload(const uint8_t *payload, size_t len) {
|
||||
uint8_t decompressed[64];
|
||||
size_t decompressed_len = 0;
|
||||
if (!decompressBuffer(payload, len, decompressed, sizeof(decompressed), decompressed_len)) {
|
||||
return false;
|
||||
}
|
||||
if (decompressed_len >= sizeof(decompressed)) {
|
||||
return false;
|
||||
}
|
||||
decompressed[decompressed_len] = '\0';
|
||||
|
||||
if (decompressed_len < 3 || decompressed[0] != 'T' || decompressed[1] != ':') {
|
||||
return false;
|
||||
}
|
||||
|
||||
uint32_t epoch = static_cast<uint32_t>(strtoul(reinterpret_cast<const char *>(decompressed + 2), nullptr, 10));
|
||||
if (epoch == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
time_set_utc(epoch);
|
||||
return true;
|
||||
}
|
||||
|
||||
void time_get_local_hhmm(char *out, size_t out_len) {
|
||||
if (!time_is_synced()) {
|
||||
snprintf(out, out_len, "--:--");
|
||||
return;
|
||||
}
|
||||
time_t now = time(nullptr);
|
||||
struct tm timeinfo;
|
||||
localtime_r(&now, &timeinfo);
|
||||
snprintf(out, out_len, "%02d:%02d", timeinfo.tm_hour, timeinfo.tm_min);
|
||||
}
|
||||
155
src/web_server.cpp
Normal file
155
src/web_server.cpp
Normal file
@@ -0,0 +1,155 @@
|
||||
#include "web_server.h"
|
||||
#include <WebServer.h>
|
||||
#include "wifi_manager.h"
|
||||
|
||||
static WebServer server(80);
|
||||
static const SenderStatus *g_statuses = nullptr;
|
||||
static uint8_t g_status_count = 0;
|
||||
static WifiMqttConfig g_config;
|
||||
static bool g_is_ap = false;
|
||||
|
||||
static String html_header(const String &title) {
|
||||
String h = "<!DOCTYPE html><html><head><meta charset='utf-8'><meta name='viewport' content='width=device-width,initial-scale=1'>";
|
||||
h += "<title>" + title + "</title></head><body>";
|
||||
h += "<h2>" + title + "</h2>";
|
||||
return h;
|
||||
}
|
||||
|
||||
static String html_footer() {
|
||||
return "</body></html>";
|
||||
}
|
||||
|
||||
static String render_sender_block(const SenderStatus &status) {
|
||||
String s;
|
||||
s += "<div style='margin-bottom:10px;padding:6px;border:1px solid #ccc'>";
|
||||
s += "<strong>" + String(status.last_data.device_id) + "</strong><br>";
|
||||
if (!status.has_data) {
|
||||
s += "No data";
|
||||
} else {
|
||||
s += "Energy: " + String(status.last_data.energy_total_kwh, 3) + " kWh<br>";
|
||||
s += "Power: " + String(status.last_data.total_power_w, 1) + " W<br>";
|
||||
s += "Battery: " + String(status.last_data.battery_voltage_v, 2) + " V (" + String(status.last_data.battery_percent) + ")";
|
||||
}
|
||||
s += "</div>";
|
||||
return s;
|
||||
}
|
||||
|
||||
static void handle_root() {
|
||||
String html = html_header("DD3 Bridge Status");
|
||||
html += g_is_ap ? "<p>Mode: AP</p>" : "<p>Mode: STA</p>";
|
||||
|
||||
if (g_statuses) {
|
||||
for (uint8_t i = 0; i < g_status_count; ++i) {
|
||||
html += render_sender_block(g_statuses[i]);
|
||||
}
|
||||
}
|
||||
|
||||
html += "<p><a href='/wifi'>Configure WiFi/MQTT/NTP</a></p>";
|
||||
html += html_footer();
|
||||
server.send(200, "text/html", html);
|
||||
}
|
||||
|
||||
static void handle_wifi_get() {
|
||||
String html = html_header("WiFi/MQTT Config");
|
||||
html += "<form method='POST' action='/wifi'>";
|
||||
html += "SSID: <input name='ssid' value='" + g_config.ssid + "'><br>";
|
||||
html += "Password: <input name='pass' type='password' value='" + g_config.password + "'><br>";
|
||||
html += "MQTT Host: <input name='mqhost' value='" + g_config.mqtt_host + "'><br>";
|
||||
html += "MQTT Port: <input name='mqport' value='" + String(g_config.mqtt_port) + "'><br>";
|
||||
html += "MQTT User: <input name='mquser' value='" + g_config.mqtt_user + "'><br>";
|
||||
html += "MQTT Pass: <input name='mqpass' type='password' value='" + g_config.mqtt_pass + "'><br>";
|
||||
html += "NTP Server 1: <input name='ntp1' value='" + g_config.ntp_server_1 + "'><br>";
|
||||
html += "NTP Server 2: <input name='ntp2' value='" + g_config.ntp_server_2 + "'><br>";
|
||||
html += "<button type='submit'>Save</button>";
|
||||
html += "</form>";
|
||||
html += html_footer();
|
||||
server.send(200, "text/html", html);
|
||||
}
|
||||
|
||||
static void handle_wifi_post() {
|
||||
WifiMqttConfig cfg;
|
||||
cfg.ntp_server_1 = "pool.ntp.org";
|
||||
cfg.ntp_server_2 = "time.nist.gov";
|
||||
cfg.ssid = server.arg("ssid");
|
||||
cfg.password = server.arg("pass");
|
||||
cfg.mqtt_host = server.arg("mqhost");
|
||||
cfg.mqtt_port = static_cast<uint16_t>(server.arg("mqport").toInt());
|
||||
cfg.mqtt_user = server.arg("mquser");
|
||||
cfg.mqtt_pass = server.arg("mqpass");
|
||||
if (server.arg("ntp1").length() > 0) {
|
||||
cfg.ntp_server_1 = server.arg("ntp1");
|
||||
}
|
||||
if (server.arg("ntp2").length() > 0) {
|
||||
cfg.ntp_server_2 = server.arg("ntp2");
|
||||
}
|
||||
cfg.valid = true;
|
||||
wifi_save_config(cfg);
|
||||
server.send(200, "text/html", "<html><body>Saved. Rebooting...</body></html>");
|
||||
delay(1000);
|
||||
ESP.restart();
|
||||
}
|
||||
|
||||
static void handle_sender() {
|
||||
if (!g_statuses) {
|
||||
server.send(404, "text/plain", "No senders");
|
||||
return;
|
||||
}
|
||||
String uri = server.uri();
|
||||
String device_id = uri.substring(String("/sender/").length());
|
||||
for (uint8_t i = 0; i < g_status_count; ++i) {
|
||||
if (device_id.equalsIgnoreCase(g_statuses[i].last_data.device_id)) {
|
||||
String html = html_header("Sender " + device_id);
|
||||
html += render_sender_block(g_statuses[i]);
|
||||
html += html_footer();
|
||||
server.send(200, "text/html", html);
|
||||
return;
|
||||
}
|
||||
}
|
||||
server.send(404, "text/plain", "Not found");
|
||||
}
|
||||
|
||||
void web_server_set_config(const WifiMqttConfig &config) {
|
||||
g_config = config;
|
||||
}
|
||||
|
||||
void web_server_begin_ap(const SenderStatus *statuses, uint8_t count) {
|
||||
g_statuses = statuses;
|
||||
g_status_count = count;
|
||||
g_is_ap = true;
|
||||
|
||||
server.on("/", handle_root);
|
||||
server.on("/wifi", HTTP_GET, handle_wifi_get);
|
||||
server.on("/wifi", HTTP_POST, handle_wifi_post);
|
||||
server.on("/sender/", handle_sender);
|
||||
server.onNotFound([]() {
|
||||
if (server.uri().startsWith("/sender/")) {
|
||||
handle_sender();
|
||||
return;
|
||||
}
|
||||
server.send(404, "text/plain", "Not found");
|
||||
});
|
||||
server.begin();
|
||||
}
|
||||
|
||||
void web_server_begin_sta(const SenderStatus *statuses, uint8_t count) {
|
||||
g_statuses = statuses;
|
||||
g_status_count = count;
|
||||
g_is_ap = false;
|
||||
|
||||
server.on("/", handle_root);
|
||||
server.on("/sender/", handle_sender);
|
||||
server.on("/wifi", HTTP_GET, handle_wifi_get);
|
||||
server.on("/wifi", HTTP_POST, handle_wifi_post);
|
||||
server.onNotFound([]() {
|
||||
if (server.uri().startsWith("/sender/")) {
|
||||
handle_sender();
|
||||
return;
|
||||
}
|
||||
server.send(404, "text/plain", "Not found");
|
||||
});
|
||||
server.begin();
|
||||
}
|
||||
|
||||
void web_server_loop() {
|
||||
server.handleClient();
|
||||
}
|
||||
60
src/wifi_manager.cpp
Normal file
60
src/wifi_manager.cpp
Normal file
@@ -0,0 +1,60 @@
|
||||
#include "wifi_manager.h"
|
||||
#include <WiFi.h>
|
||||
|
||||
static Preferences prefs;
|
||||
|
||||
void wifi_manager_init() {
|
||||
prefs.begin("dd3cfg", false);
|
||||
}
|
||||
|
||||
bool wifi_load_config(WifiMqttConfig &config) {
|
||||
config.valid = prefs.getBool("valid", false);
|
||||
if (!config.valid) {
|
||||
return false;
|
||||
}
|
||||
config.ssid = prefs.getString("ssid", "");
|
||||
config.password = prefs.getString("pass", "");
|
||||
config.mqtt_host = prefs.getString("mqhost", "");
|
||||
config.mqtt_port = prefs.getUShort("mqport", 1883);
|
||||
config.mqtt_user = prefs.getString("mquser", "");
|
||||
config.mqtt_pass = prefs.getString("mqpass", "");
|
||||
config.ntp_server_1 = prefs.getString("ntp1", "pool.ntp.org");
|
||||
config.ntp_server_2 = prefs.getString("ntp2", "time.nist.gov");
|
||||
return config.ssid.length() > 0 && config.mqtt_host.length() > 0;
|
||||
}
|
||||
|
||||
bool wifi_save_config(const WifiMqttConfig &config) {
|
||||
prefs.putBool("valid", true);
|
||||
prefs.putString("ssid", config.ssid);
|
||||
prefs.putString("pass", config.password);
|
||||
prefs.putString("mqhost", config.mqtt_host);
|
||||
prefs.putUShort("mqport", config.mqtt_port);
|
||||
prefs.putString("mquser", config.mqtt_user);
|
||||
prefs.putString("mqpass", config.mqtt_pass);
|
||||
prefs.putString("ntp1", config.ntp_server_1);
|
||||
prefs.putString("ntp2", config.ntp_server_2);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool wifi_connect_sta(const WifiMqttConfig &config, uint32_t timeout_ms) {
|
||||
WiFi.mode(WIFI_STA);
|
||||
WiFi.begin(config.ssid.c_str(), config.password.c_str());
|
||||
uint32_t start = millis();
|
||||
while (WiFi.status() != WL_CONNECTED && millis() - start < timeout_ms) {
|
||||
delay(200);
|
||||
}
|
||||
return WiFi.status() == WL_CONNECTED;
|
||||
}
|
||||
|
||||
void wifi_start_ap(const char *ap_ssid, const char *ap_pass) {
|
||||
WiFi.mode(WIFI_AP);
|
||||
WiFi.softAP(ap_ssid, ap_pass);
|
||||
}
|
||||
|
||||
bool wifi_is_connected() {
|
||||
return WiFi.status() == WL_CONNECTED;
|
||||
}
|
||||
|
||||
String wifi_get_ssid() {
|
||||
return WiFi.SSID();
|
||||
}
|
||||
Reference in New Issue
Block a user