Skip to content

Commit

Permalink
Restructuring code to remove duplicates and reduce flash size
Browse files Browse the repository at this point in the history
  • Loading branch information
No-Signal committed Jan 9, 2025
1 parent 6f8c77f commit 1f780e3
Showing 1 changed file with 89 additions and 133 deletions.
222 changes: 89 additions & 133 deletions Software/src/devboard/mqtt/mqtt.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -43,48 +43,44 @@ struct SensorConfig {
const char* device_class;
};

SensorConfig sensorConfigs[] = {
{"SOC", "SOC (scaled)", "{{ value_json.SOC }}", "%", "battery"},
{"SOC_real", "SOC (real)", "{{ value_json.SOC_real }}", "%", "battery"},
{"state_of_health", "State Of Health", "{{ value_json.state_of_health }}", "%", "battery"},
{"temperature_min", "Temperature Min", "{{ value_json.temperature_min }}", "°C", "temperature"},
{"temperature_max", "Temperature Max", "{{ value_json.temperature_max }}", "°C", "temperature"},
{"stat_batt_power", "Stat Batt Power", "{{ value_json.stat_batt_power }}", "W", "power"},
{"battery_current", "Battery Current", "{{ value_json.battery_current }}", "A", "current"},
{"cell_max_voltage", "Cell Max Voltage", "{{ value_json.cell_max_voltage }}", "V", "voltage"},
{"cell_min_voltage", "Cell Min Voltage", "{{ value_json.cell_min_voltage }}", "V", "voltage"},
{"battery_voltage", "Battery Voltage", "{{ value_json.battery_voltage }}", "V", "voltage"},
{"total_capacity", "Battery Total Capacity", "{{ value_json.total_capacity }}", "Wh", "energy"},
{"remaining_capacity", "Battery Remaining Capacity (scaled)", "{{ value_json.remaining_capacity }}", "Wh",
"energy"},
{"remaining_capacity_real", "Battery Remaining Capacity (real)", "{{ value_json.remaining_capacity_real }}", "Wh",
"energy"},
{"max_discharge_power", "Battery Max Discharge Power", "{{ value_json.max_discharge_power }}", "W", "power"},
{"max_charge_power", "Battery Max Charge Power", "{{ value_json.max_charge_power }}", "W", "power"},
{"bms_status", "BMS Status", "{{ value_json.bms_status }}", "", ""},
{"pause_status", "Pause Status", "{{ value_json.pause_status }}", "", ""},
SensorConfig sensorConfigTemplate[] = {
{"SOC", "SOC (Scaled)", "", "%", "battery"},
{"SOC_real", "SOC (real)", "", "%", "battery"},
{"state_of_health", "State Of Health", "", "%", "battery"},
{"temperature_min", "Temperature Min", "", "°C", "temperature"},
{"temperature_max", "Temperature Max", "", "°C", "temperature"},
{"stat_batt_power", "Stat Batt Power", "", "W", "power"},
{"battery_current", "Battery Current", "", "A", "current"},
{"cell_max_voltage", "Cell Max Voltage", "", "V", "voltage"},
{"cell_min_voltage", "Cell Min Voltage", "", "V", "voltage"},
{"battery_voltage", "Battery Voltage", "", "V", "voltage"},
{"total_capacity", "Battery Total Capacity", "", "Wh", "energy"},
{"remaining_capacity", "Battery Remaining Capacity (scaled)", "", "Wh", "energy"},
{"remaining_capacity_real", "Battery Remaining Capacity (real)", "", "Wh", "energy"},
{"max_discharge_power", "Battery Max Discharge Power", "", "W", "power"},
{"max_charge_power", "Battery Max Charge Power", "", "W", "power"},
{"bms_status", "BMS Status", "", "", ""},
{"pause_status", "Pause Status", "", "", ""}};

#ifdef DOUBLE_BATTERY
{"SOC_2", "SOC 2 (scaled)", "{{ value_json.SOC_2 }}", "%", "battery"},
{"SOC_real_2", "SOC 2 (real)", "{{ value_json.SOC_real_2 }}", "%", "battery"},
{"state_of_health_2", "State Of Health 2", "{{ value_json.state_of_health_2 }}", "%", "battery"},
{"temperature_min_2", "Temperature Min 2", "{{ value_json.temperature_min_2 }}", "°C", "temperature"},
{"temperature_max_2", "Temperature Max 2", "{{ value_json.temperature_max_2 }}", "°C", "temperature"},
{"stat_batt_power_2", "Stat Batt Power 2", "{{ value_json.stat_batt_power_2 }}", "W", "power"},
{"battery_current_2", "Battery 2 Current", "{{ value_json.battery_current_2 }}", "A", "current"},
{"cell_max_voltage_2", "Cell Max Voltage 2", "{{ value_json.cell_max_voltage_2 }}", "V", "voltage"},
{"cell_min_voltage_2", "Cell Min Voltage 2", "{{ value_json.cell_min_voltage_2 }}", "V", "voltage"},
{"battery_voltage_2", "Battery 2 Voltage", "{{ value_json.battery_voltage_2 }}", "V", "voltage"},
{"total_capacity_2", "Battery 2 Total Capacity", "{{ value_json.total_capacity_2 }}", "Wh", "energy"},
{"remaining_capacity_2", "Battery 2 Remaining Capacity (scaled)", "{{ value_json.remaining_capacity_2 }}", "Wh",
"energy"},
{"remaining_capacity_real_2", "Battery 2 Remaining Capacity (real)", "{{ value_json.remaining_capacity_real_2 }}",
"Wh", "energy"},
{"max_discharge_power_2", "Battery 2 Max Discharge Power", "{{ value_json.max_discharge_power_2 }}", "W", "power"},
{"max_charge_power_2", "Battery 2 Max Charge Power", "{{ value_json.max_charge_power_2 }}", "W", "power"},
{"bms_status_2", "BMS 2 Status", "{{ value_json.bms_status_2 }}", "", ""},
{"pause_status_2", "Pause Status 2", "{{ value_json.pause_status_2 }}", "", ""},
SensorConfig sensorConfigs[34];
#else
SensorConfig sensorConfigs[17];
#endif // DOUBLE_BATTERY
};

void create_sensor_configs() {
for (int i = 0; i < sizeof(sensorConfigTemplate) / sizeof(sensorConfigTemplate[0]); i++) {
SensorConfig& config = sensorConfigTemplate[i];
config.value_template = ("{{ value_json." + String(config.object_id) + " }}").c_str();
sensorConfigs[i] = config;
#ifdef DOUBLE_BATTERY
sensorConfigs[i + 17] = config;
sensorConfigs[i + 17].object_id = String(config.object_id + String("_2")).c_str();
String temp_value_template = "{{ value_json." + String(sensorConfigs[i + 17].object_id) + " }}";
sensorConfigs[i + 17].value_template = temp_value_template.c_str();
#endif // DOUBLE_BATTERY
}
}

SensorConfig buttonConfigs[] = {{"BMSRESET", "Reset BMS", "", "", ""}};

Expand All @@ -108,6 +104,49 @@ static String generateButtonAutoConfigTopic(const char* subtype) {
return generateButtonTopic(subtype) + "/config";
}

void set_common_discovery_attributes(JsonDocument& doc) {
doc["device"]["identifiers"][0] = ha_device_id;
doc["device"]["manufacturer"] = "DalaTech";
doc["device"]["model"] = "BatteryEmulator";
doc["origin"]["name"] = "BatteryEmulator";
doc["origin"]["sw"] = String(version_number) + "-mqtt";
doc["origin"]["url"] = "https://github.com/dalathegreat/Battery-Emulator";
}

void set_battery_attributes(JsonDocument& doc, const DATALAYER_BATTERY_TYPE& battery, const String& suffix) {
doc["SOC" + suffix] = ((float)battery.status.reported_soc) / 100.0;
doc["SOC_real" + suffix] = ((float)battery.status.real_soc) / 100.0;
doc["state_of_health" + suffix] = ((float)battery.status.soh_pptt) / 100.0;
doc["temperature_min" + suffix] = ((float)((int16_t)battery.status.temperature_min_dC)) / 10.0;
doc["temperature_max" + suffix] = ((float)((int16_t)battery.status.temperature_max_dC)) / 10.0;
doc["stat_batt_power" + suffix] = ((float)((int32_t)battery.status.active_power_W));
doc["battery_current" + suffix] = ((float)((int16_t)battery.status.current_dA)) / 10.0;
doc["battery_voltage" + suffix] = ((float)battery.status.voltage_dV) / 10.0;
if (battery.info.number_of_cells != 0u && battery.status.cell_voltages_mV[battery.info.number_of_cells - 1] != 0u) {
doc["cell_max_voltage" + suffix] = ((float)battery.status.cell_max_voltage_mV) / 1000.0;
doc["cell_min_voltage" + suffix] = ((float)battery.status.cell_min_voltage_mV) / 1000.0;
}
doc["total_capacity" + suffix] = ((float)battery.info.total_capacity_Wh);
doc["remaining_capacity_real" + suffix] = ((float)battery.status.remaining_capacity_Wh);
doc["remaining_capacity" + suffix] = ((float)battery.status.reported_remaining_capacity_Wh);
doc["max_discharge_power" + suffix] = ((float)battery.status.max_discharge_power_W);
doc["max_charge_power" + suffix] = ((float)battery.status.max_charge_power_W);
}

void set_battery_voltage_attributes(JsonDocument& doc, int i, int cellNumber, const String& state_topic,
const String& object_id_prefix) {
doc["name"] = "Battery Cell Voltage " + String(cellNumber);
doc["object_id"] = object_id_prefix + "battery_voltage_cell" + String(cellNumber);
doc["unique_id"] = topic_name + "_battery_voltage_cell" + String(cellNumber);
doc["device_class"] = "voltage";
doc["state_class"] = "measurement";
doc["state_topic"] = state_topic;
doc["unit_of_measurement"] = "V";
doc["enabled_by_default"] = true;
doc["expire_after"] = 240;
doc["value_template"] = "{{ value_json.cell_voltages[" + String(i) + "] }}";
}

#endif // HA_AUTODISCOVERY

static std::vector<EventData> order_events;
Expand Down Expand Up @@ -136,13 +175,7 @@ static void publish_common_info(void) {
}
doc["enabled_by_default"] = true;
doc["expire_after"] = 240;
doc["device"]["identifiers"][0] = ha_device_id;
doc["device"]["manufacturer"] = "DalaTech";
doc["device"]["model"] = "BatteryEmulator";
doc["device"]["name"] = device_name;
doc["origin"]["name"] = "BatteryEmulator";
doc["origin"]["sw"] = String(version_number) + "-mqtt";
doc["origin"]["url"] = "https://github.com/dalathegreat/Battery-Emulator";
set_common_discovery_attributes(doc);
serializeJson(doc, mqtt_msg);
mqtt_publish(generateCommonInfoAutoConfigTopic(config.object_id).c_str(), mqtt_msg, true);
doc.clear();
Expand All @@ -155,48 +188,12 @@ static void publish_common_info(void) {

//only publish these values if BMS is active and we are comunication with the battery (can send CAN messages to the battery)
if (datalayer.battery.status.CAN_battery_still_alive && allowed_to_send_CAN && millis() > BOOTUP_TIME) {
doc["SOC"] = ((float)datalayer.battery.status.reported_soc) / 100.0;
doc["SOC_real"] = ((float)datalayer.battery.status.real_soc) / 100.0;
doc["state_of_health"] = ((float)datalayer.battery.status.soh_pptt) / 100.0;
doc["temperature_min"] = ((float)((int16_t)datalayer.battery.status.temperature_min_dC)) / 10.0;
doc["temperature_max"] = ((float)((int16_t)datalayer.battery.status.temperature_max_dC)) / 10.0;
doc["stat_batt_power"] = ((float)((int32_t)datalayer.battery.status.active_power_W));
doc["battery_current"] = ((float)((int16_t)datalayer.battery.status.current_dA)) / 10.0;
doc["battery_voltage"] = ((float)datalayer.battery.status.voltage_dV) / 10.0;
// publish only if cell voltages have been populated...
if (datalayer.battery.info.number_of_cells != 0u &&
datalayer.battery.status.cell_voltages_mV[datalayer.battery.info.number_of_cells - 1] != 0u) {
doc["cell_max_voltage"] = ((float)datalayer.battery.status.cell_max_voltage_mV) / 1000.0;
doc["cell_min_voltage"] = ((float)datalayer.battery.status.cell_min_voltage_mV) / 1000.0;
}
doc["total_capacity"] = ((float)datalayer.battery.info.total_capacity_Wh);
doc["remaining_capacity_real"] = ((float)datalayer.battery.status.remaining_capacity_Wh);
doc["remaining_capacity"] = ((float)datalayer.battery.status.reported_remaining_capacity_Wh);
doc["max_discharge_power"] = ((float)datalayer.battery.status.max_discharge_power_W);
doc["max_charge_power"] = ((float)datalayer.battery.status.max_charge_power_W);
set_battery_attributes(doc, datalayer.battery, "");
}
#ifdef DOUBLE_BATTERY
//only publish these values if BMS is active and we are comunication with the battery (can send CAN messages to the battery)
if (datalayer.battery2.status.CAN_battery_still_alive && allowed_to_send_CAN && millis() > BOOTUP_TIME) {
doc["SOC_2"] = ((float)datalayer.battery2.status.reported_soc) / 100.0;
doc["SOC_real_2"] = ((float)datalayer.battery2.status.real_soc) / 100.0;
doc["state_of_health_2"] = ((float)datalayer.battery2.status.soh_pptt) / 100.0;
doc["temperature_min_2"] = ((float)((int16_t)datalayer.battery2.status.temperature_min_dC)) / 10.0;
doc["temperature_max_2"] = ((float)((int16_t)datalayer.battery2.status.temperature_max_dC)) / 10.0;
doc["stat_batt_power_2"] = ((float)((int32_t)datalayer.battery2.status.active_power_W));
doc["battery_current_2"] = ((float)((int16_t)datalayer.battery2.status.current_dA)) / 10.0;
doc["battery_voltage_2"] = ((float)datalayer.battery2.status.voltage_dV) / 10.0;
// publish only if cell voltages have been populated...
if (datalayer.battery2.info.number_of_cells != 0u &&
datalayer.battery2.status.cell_voltages_mV[datalayer.battery2.info.number_of_cells - 1] != 0u) {
doc["cell_max_voltage_2"] = ((float)datalayer.battery2.status.cell_max_voltage_mV) / 1000.0;
doc["cell_min_voltage_2"] = ((float)datalayer.battery2.status.cell_min_voltage_mV) / 1000.0;
}
doc["total_capacity_2"] = ((float)datalayer.battery2.info.total_capacity_Wh);
doc["remaining_capacity_real_2"] = ((float)datalayer.battery2.status.remaining_capacity_Wh);
doc["remaining_capacity_2"] = ((float)datalayer.battery2.status.reported_remaining_capacity_Wh);
doc["max_discharge_power_2"] = ((float)datalayer.battery2.status.max_discharge_power_W);
doc["max_charge_power_2"] = ((float)datalayer.battery2.status.max_charge_power_W);
set_battery_attributes(doc, datalayer.battery2, "_2");
}
#endif // DOUBLE_BATTERY
serializeJson(doc, mqtt_msg);
Expand Down Expand Up @@ -231,23 +228,8 @@ static void publish_cell_voltages(void) {

for (int i = 0; i < datalayer.battery.info.number_of_cells; i++) {
int cellNumber = i + 1;
doc["name"] = "Battery Cell Voltage " + String(cellNumber);
doc["object_id"] = object_id_prefix + "battery_voltage_cell" + String(cellNumber);
doc["unique_id"] = topic_name + "_battery_voltage_cell" + String(cellNumber);
doc["device_class"] = "voltage";
doc["state_class"] = "measurement";
doc["state_topic"] = state_topic;
doc["unit_of_measurement"] = "V";
doc["enabled_by_default"] = true;
doc["expire_after"] = 240;
doc["value_template"] = "{{ value_json.cell_voltages[" + String(i) + "] }}";
doc["device"]["identifiers"][0] = ha_device_id;
doc["device"]["manufacturer"] = "DalaTech";
doc["device"]["model"] = "BatteryEmulator";
doc["device"]["name"] = device_name;
doc["origin"]["name"] = "BatteryEmulator";
doc["origin"]["sw"] = String(version_number) + "-mqtt";
doc["origin"]["url"] = "https://github.com/dalathegreat/Battery-Emulator";
set_battery_voltage_attributes(doc, i, cellNumber, state_topic, object_id_prefix);
set_common_discovery_attributes(doc);

serializeJson(doc, mqtt_msg, sizeof(mqtt_msg));
mqtt_publish(generateCellVoltageAutoConfigTopic(cellNumber, "").c_str(), mqtt_msg, true);
Expand All @@ -260,23 +242,8 @@ static void publish_cell_voltages(void) {

for (int i = 0; i < datalayer.battery.info.number_of_cells; i++) {
int cellNumber = i + 1;
doc["name"] = "Battery 2 Cell Voltage " + String(cellNumber);
doc["object_id"] = object_id_prefix + "battery_2_voltage_cell" + String(cellNumber);
doc["unique_id"] = topic_name + "_battery_2_voltage_cell" + String(cellNumber);
doc["device_class"] = "voltage";
doc["state_class"] = "measurement";
doc["state_topic"] = state_topic_2;
doc["unit_of_measurement"] = "V";
doc["enabled_by_default"] = true;
doc["expire_after"] = 240;
doc["value_template"] = "{{ value_json.cell_voltages[" + String(i) + "] }}";
doc["device"]["identifiers"][0] = ha_device_id;
doc["device"]["manufacturer"] = "DalaTech";
doc["device"]["model"] = "BatteryEmulator";
doc["device"]["name"] = device_name;
doc["origin"]["name"] = "BatteryEmulator";
doc["origin"]["sw"] = String(version_number) + "-mqtt";
doc["origin"]["url"] = "https://github.com/dalathegreat/Battery-Emulator";
set_battery_voltage_attributes(doc, i, cellNumber, state_topic_2, object_id_prefix + "2_");
set_common_discovery_attributes(doc);

serializeJson(doc, mqtt_msg, sizeof(mqtt_msg));
mqtt_publish(generateCellVoltageAutoConfigTopic(cellNumber, "_2_").c_str(), mqtt_msg, true);
Expand Down Expand Up @@ -349,13 +316,7 @@ void publish_events() {
doc["json_attributes_topic"] = state_topic;
doc["json_attributes_template"] = "{{ value_json | tojson }}";
doc["enabled_by_default"] = true;
doc["device"]["identifiers"][0] = ha_device_id;
doc["device"]["manufacturer"] = "DalaTech";
doc["device"]["model"] = "BatteryEmulator";
doc["device"]["name"] = device_name;
doc["origin"]["name"] = "BatteryEmulator";
doc["origin"]["sw"] = String(version_number) + "-mqtt";
doc["origin"]["url"] = "https://github.com/dalathegreat/Battery-Emulator";
set_common_discovery_attributes(doc);
serializeJson(doc, mqtt_msg);
mqtt_publish(generateEventsAutoConfigTopic("event").c_str(), mqtt_msg, true);

Expand Down Expand Up @@ -424,13 +385,7 @@ static void publish_buttons_discovery(void) {
doc["command_topic"] = generateButtonTopic(config.object_id);
doc["enabled_by_default"] = true;
doc["expire_after"] = 240;
doc["device"]["identifiers"][0] = ha_device_id;
doc["device"]["manufacturer"] = "DalaTech";
doc["device"]["model"] = "BatteryEmulator";
doc["device"]["name"] = device_name;
doc["origin"]["name"] = "BatteryEmulator";
doc["origin"]["sw"] = String(version_number) + "-mqtt";
doc["origin"]["url"] = "https://github.com/dalathegreat/Battery-Emulator";
set_common_discovery_attributes(doc);
serializeJson(doc, mqtt_msg);
mqtt_publish(generateButtonAutoConfigTopic(config.object_id).c_str(), mqtt_msg, true);
doc.clear();
Expand Down Expand Up @@ -494,6 +449,7 @@ static void mqtt_event_handler(void* handler_args, esp_event_base_t base, int32_
void init_mqtt(void) {

#ifdef MQTT
create_sensor_configs();
#ifdef MQTT_MANUAL_TOPIC_OBJECT_NAME
// Use custom topic name, object ID prefix, and device name from user settings
topic_name = mqtt_topic_name;
Expand Down

0 comments on commit 1f780e3

Please sign in to comment.