Arduino v7

This commit is contained in:
Proddy
2024-01-04 23:43:30 +01:00
parent 13a915e1f4
commit af237c4fc0
213 changed files with 3900 additions and 4479 deletions

View File

@@ -462,13 +462,13 @@ void AnalogSensor::publish_values(const bool force) {
}
}
DynamicJsonDocument doc(120 * num_sensors);
JsonDocument doc;
for (auto & sensor : sensors_) {
if (sensor.type() != AnalogType::NOTUSED) {
if (Mqtt::is_nested()) {
char s[10];
JsonObject dataSensor = doc.createNestedObject(Helpers::smallitoa(s, sensor.gpio()));
JsonObject dataSensor = doc[Helpers::smallitoa(s, sensor.gpio())].add<JsonObject>();
dataSensor["name"] = sensor.name();
switch (sensor.type()) {
case AnalogType::COUNTER:
@@ -512,7 +512,7 @@ void AnalogSensor::publish_values(const bool force) {
if (Mqtt::ha_enabled() && (!sensor.ha_registered || force)) {
LOG_DEBUG("Recreating HA config for analog sensor GPIO %02d", sensor.gpio());
StaticJsonDocument<EMSESP_JSON_SIZE_MEDIUM> config;
JsonDocument config;
char stat_t[50];
snprintf(stat_t, sizeof(stat_t), "%s/%s_data", Mqtt::base().c_str(), F_(analogsensor)); // use base path
@@ -615,7 +615,7 @@ void AnalogSensor::publish_values(const bool force) {
config["stat_cla"] = "measurement";
}
Mqtt::add_ha_sections_to_doc("analog", stat_t, config.as<JsonObject>(), true, val_cond);
Mqtt::add_ha_sections_to_doc("analog", stat_t, config, true, val_cond);
sensor.ha_registered = Mqtt::queue_ha(topic, config.as<JsonObject>());
}
@@ -697,7 +697,7 @@ bool AnalogSensor::command_info(const char * value, const int8_t id, JsonObject
for (const auto & sensor : sensors_) {
if (id == -1) { // show number and id for info command
JsonObject dataSensor = output.createNestedObject(sensor.name());
JsonObject dataSensor = output[sensor.name()].add<JsonObject>();
dataSensor["gpio"] = sensor.gpio();
dataSensor["type"] = F_(number);
dataSensor["value"] = sensor.value();

View File

@@ -278,8 +278,8 @@ const char * Command::parse_command_string(const char * command, int8_t & id) {
// calls a command directly
uint8_t Command::call(const uint8_t device_type, const char * cmd, const char * value) {
// create a temporary buffer
StaticJsonDocument<EMSESP_JSON_SIZE_SMALL> output_doc;
JsonObject output = output_doc.to<JsonObject>();
JsonDocument output_doc;
JsonObject output = output_doc.to<JsonObject>();
// authenticated is always true and ID is the default value
return call(device_type, cmd, value, true, -1, output);

View File

@@ -496,11 +496,11 @@ static void setup_commands(std::shared_ptr<Commands> & commands) {
return;
}
DynamicJsonDocument doc(EMSESP_JSON_SIZE_XXXLARGE);
int8_t id = -1;
const char * cmd = Command::parse_command_string(arguments[1].c_str(), id);
uint8_t return_code = CommandRet::OK;
JsonObject json = doc.to<JsonObject>();
JsonDocument doc;
int8_t id = -1;
const char * cmd = Command::parse_command_string(arguments[1].c_str(), id);
uint8_t return_code = CommandRet::OK;
JsonObject json = doc.to<JsonObject>();
if (cmd == nullptr) {
cmd = device_type == EMSdevice::DeviceType::SYSTEM ? F_(info) : F_(values);

View File

@@ -261,7 +261,7 @@ enum {
#else
#define ARDUINO_VERSION_STR(major, minor, patch) "ESP32 Arduino v" STRINGIZE(major) "." STRINGIZE(minor) "." STRINGIZE(patch)
#endif
#define ARDUINO_VERSION ARDUINO_VERSION_STR(ESP_ARDUINO_VERSION_MAJOR, ESP_ARDUINO_VERSION_MINOR, ESP_ARDUINO_VERSION_PATCH)
#define ARDUINO_VERSION ARDUINO_VERSION_STR(ESP_ARDUINO_VERSION_MAJOR, ESP_ARDUINO_VERSION_MINOR, ESP_ARDUINO_VERSION_PATCH)
#endif
#endif

View File

@@ -2905,8 +2905,8 @@ bool Thermostat::set_switchtime(const char * value, const uint16_t type_id, char
uint8_t time = 0x91; // invalid
if (value[0] == '{') {
StaticJsonDocument<EMSESP_JSON_SIZE_SMALL> doc;
DeserializationError error = deserializeJson(doc, value);
JsonDocument doc;
DeserializationError error = deserializeJson(doc, value);
if (error) {
return false;
}

View File

@@ -379,7 +379,7 @@ void EMSdevice::list_device_entries(JsonObject & output) const {
snprintf(key, sizeof(key), "%s", dv.short_name);
}
JsonArray details = output.createNestedArray(key);
JsonArray details = output[key].to<JsonArray>();
// add the full name description
details.add(fullname);
@@ -854,7 +854,7 @@ bool EMSdevice::export_values(uint8_t device_type, JsonObject & output, const in
for (const auto & emsdevice : EMSESP::emsdevices) {
if (emsdevice && (emsdevice->device_type() == device_type)) {
if (!nest_created && emsdevice->has_tags(tag)) {
output_hc = output.createNestedObject(EMSdevice::tag_to_mqtt(tag));
output_hc = output[EMSdevice::tag_to_mqtt(tag)].add<JsonObject>();
nest_created = true;
}
has_value |= emsdevice->generate_values(output_hc, tag, true, output_target); // use nested for id -1 and 0
@@ -871,7 +871,7 @@ bool EMSdevice::export_values(uint8_t device_type, JsonObject & output, const in
void EMSdevice::generate_values_web(JsonObject & output) {
// output["label"] = to_string_short();
// output["label"] = name_;
JsonArray data = output.createNestedArray("data");
JsonArray data = output["data"].to<JsonArray>();
for (auto & dv : devicevalues_) {
auto fullname = dv.get_fullname();
@@ -881,7 +881,7 @@ void EMSdevice::generate_values_web(JsonObject & output) {
// 2. it must have a valid value, if it is not a command like 'reset'
// 3. show favorites first
if (!dv.has_state(DeviceValueState::DV_WEB_EXCLUDE) && !fullname.empty() && (dv.hasValue() || (dv.type == DeviceValueType::CMD))) {
JsonObject obj = data.createNestedObject(); // create the object, we know there is a value
JsonObject obj = data.add<JsonObject>(); // create the object, we know there is a value
uint8_t fahrenheit = 0;
// handle Booleans (true, false), output as strings according to the user settings
@@ -948,7 +948,7 @@ void EMSdevice::generate_values_web(JsonObject & output) {
// add the Command options
if (dv.type == DeviceValueType::ENUM || (dv.type == DeviceValueType::CMD && dv.options_size > 1)) {
JsonArray l = obj.createNestedArray("l");
JsonArray l = obj["l"].to<JsonArray>();
for (uint8_t i = 0; i < dv.options_size; i++) {
auto enum_str = Helpers::translated_word(dv.options[i]);
if (enum_str) {
@@ -956,7 +956,7 @@ void EMSdevice::generate_values_web(JsonObject & output) {
}
}
} else if (dv.type == DeviceValueType::BOOL) {
JsonArray l = obj.createNestedArray("l");
JsonArray l = obj["l"].to<JsonArray>();
char result[12];
l.add(Helpers::render_boolean(result, false, true));
l.add(Helpers::render_boolean(result, true, true));
@@ -990,7 +990,7 @@ void EMSdevice::generate_values_web(JsonObject & output) {
void EMSdevice::generate_values_web_customization(JsonArray & output) {
for (auto & dv : devicevalues_) {
// also show commands and entities that have an empty full name
JsonObject obj = output.createNestedObject();
JsonObject obj = output.add<JsonObject>();
uint8_t fahrenheit = !EMSESP::system_.fahrenheit() ? 0 : (dv.uom == DeviceValueUOM::DEGREES) ? 2 : (dv.uom == DeviceValueUOM::DEGREES_R) ? 1 : 0;
// create the value
@@ -1082,7 +1082,7 @@ void EMSdevice::generate_values_web_customization(JsonArray & output) {
for (std::string entity_id : entityCustomization.entity_ids) {
uint8_t mask = Helpers::hextoint(entity_id.substr(0, 2).c_str());
if (mask & 0x80) {
JsonObject obj = output.createNestedObject();
JsonObject obj = output.add<JsonObject>();
obj["id"] = DeviceValue::get_name(entity_id);
obj["m"] = mask;
obj["w"] = false;
@@ -1419,7 +1419,7 @@ bool EMSdevice::get_value_info(JsonObject & output, const char * cmd, const int8
}
}
json[type] = F_(enum);
JsonArray enum_ = json.createNestedArray(F_(enum));
JsonArray enum_ = json[F_(enum)].to<JsonArray>();
for (uint8_t i = 0; i < dv.options_size; i++) {
enum_.add(Helpers::translated_word(dv.options[i]));
}
@@ -1493,7 +1493,7 @@ bool EMSdevice::get_value_info(JsonObject & output, const char * cmd, const int8
case DeviceValueType::CMD:
json[type] = F_(command);
if (dv.options_size > 1) {
JsonArray enum_ = json.createNestedArray(F_(enum));
JsonArray enum_ = json[F_(enum)].to<JsonArray>();
for (uint8_t i = 0; i < dv.options_size; i++) {
enum_.add(Helpers::translated_word(dv.options[i]));
}
@@ -1614,7 +1614,7 @@ bool EMSdevice::generate_values(JsonObject & output, const uint8_t tag_filter, c
if (dv.tag != old_tag) {
old_tag = dv.tag;
if (nested && have_tag && dv.tag >= DeviceValueTAG::TAG_HC1) {
json = output.createNestedObject(tag_to_mqtt(dv.tag));
json = output[tag_to_mqtt(dv.tag)].add<JsonObject>();
}
}
}

View File

@@ -380,8 +380,8 @@ void EMSESP::show_device_values(uuid::console::Shell & shell) {
// print header, with device type translated
shell.printfln("%s: %s (%d)", emsdevice->device_type_2_device_name_translated(), emsdevice->to_string().c_str(), emsdevice->count_entities());
DynamicJsonDocument doc(EMSESP_JSON_SIZE_XXXLARGE); // use max size
JsonObject json = doc.to<JsonObject>();
JsonDocument doc;
JsonObject json = doc.to<JsonObject>();
emsdevice->generate_values(json, DeviceValueTAG::TAG_NONE, true, EMSdevice::OUTPUT_TARGET::CONSOLE);
@@ -405,8 +405,8 @@ void EMSESP::show_device_values(uuid::console::Shell & shell) {
// show any custom entities
if (webCustomEntityService.count_entities() > 0) {
shell.printfln("Custom entities:");
StaticJsonDocument<EMSESP_JSON_SIZE_MEDIUM> custom_doc; // use max size
JsonObject custom_output = custom_doc.to<JsonObject>();
JsonDocument custom_doc; // use max size
JsonObject custom_output = custom_doc.to<JsonObject>();
webCustomEntityService.show_values(custom_output);
for (JsonPair p : custom_output) {
shell.printfln(" %s: %s%s%s", p.key().c_str(), COLOR_BRIGHT_GREEN, p.value().as<std::string>().c_str(), COLOR_RESET);
@@ -553,10 +553,10 @@ void EMSESP::reset_mqtt_ha() {
// this will also create the HA /config topic for each device value
// generate_values_json is called to build the device value (dv) object array
void EMSESP::publish_device_values(uint8_t device_type) {
DynamicJsonDocument doc(EMSESP_JSON_SIZE_XXLARGE);
JsonObject json = doc.to<JsonObject>();
bool need_publish = false;
bool nested = (Mqtt::is_nested());
JsonDocument doc;
JsonObject json = doc.to<JsonObject>();
bool need_publish = false;
bool nested = (Mqtt::is_nested());
// group by device type
for (uint8_t tag = DeviceValueTAG::TAG_BOILER_DATA_WW; tag <= DeviceValueTAG::TAG_HS16; tag++) {
@@ -565,7 +565,7 @@ void EMSESP::publish_device_values(uint8_t device_type) {
for (const auto & emsdevice : emsdevices) {
if (emsdevice && (emsdevice->device_type() == device_type)) {
if (nested && !nest_created && emsdevice->has_tags(tag)) {
json_hc = doc.createNestedObject(EMSdevice::tag_to_mqtt(tag));
json_hc = doc[EMSdevice::tag_to_mqtt(tag)].add<JsonObject>();
nest_created = true;
}
need_publish |= emsdevice->generate_values(json_hc, tag, false, EMSdevice::OUTPUT_TARGET::MQTT);
@@ -640,8 +640,8 @@ void EMSESP::publish_response(std::shared_ptr<const Telegram> telegram) {
strlcat(buffer, " ", 768);
return;
}
DynamicJsonDocument doc(EMSESP_JSON_SIZE_LARGE);
char s[10];
JsonDocument doc;
char s[10];
doc["src"] = Helpers::hextoa(s, telegram->src);
doc["dest"] = Helpers::hextoa(s, telegram->dest);
doc["type"] = Helpers::hextoa(s, telegram->type_id);

View File

@@ -66,17 +66,6 @@
#define WATCH_ID_NONE 0 // no watch id set
// uses StaticJsonDocument
#define EMSESP_JSON_SIZE_SMALL 256
#define EMSESP_JSON_SIZE_MEDIUM 768
#define EMSESP_JSON_SIZE_LARGE 1024 // used in forming HA config payloads, also in *AsyncJsonResponse
// used in larger buffers like DynamicJsonDocument
#define EMSESP_JSON_SIZE_XLARGE 2048
#define EMSESP_JSON_SIZE_XXLARGE 4096
#define EMSESP_JSON_SIZE_XXXLARGE 16384
#define EMSESP_JSON_SIZE_XXXXLARGE 20480 // web output
// helpers for callback functions
#define MAKE_PF_CB(__f) [&](std::shared_ptr<const Telegram> t) { __f(t); } // for Process Function callbacks to EMSDevice::process_function_p
#define MAKE_CF_CB(__f) [&](const char * value, const int8_t id) { return __f(value, id); } // for Command Function callbacks Command::cmd_function_p

View File

@@ -257,9 +257,9 @@ void Mqtt::on_message(const char * topic, const uint8_t * payload, size_t len) {
}
}
StaticJsonDocument<EMSESP_JSON_SIZE_SMALL> input_doc;
DynamicJsonDocument output_doc(EMSESP_JSON_SIZE_XLARGE);
JsonObject input, output;
JsonDocument input_doc;
JsonDocument output_doc;
JsonObject input, output;
// convert payload into a json doc
// if the payload doesn't not contain the key 'value' or 'data', treat the whole payload as the 'value'
@@ -516,7 +516,7 @@ void Mqtt::on_connect() {
// e.g. homeassistant/sensor/ems-esp/status/config
// all the values from the heartbeat payload will be added as attributes to the entity state
void Mqtt::ha_status() {
StaticJsonDocument<EMSESP_JSON_SIZE_LARGE> doc;
JsonDocument doc;
char uniq[70];
if (Mqtt::entity_format() == entityFormat::MULTI_SHORT) {
@@ -539,7 +539,7 @@ void Mqtt::ha_status() {
// doc["avty_t"] = "~/status"; // commented out, as it causes errors in HA sometimes
// doc["json_attr_t"] = "~/heartbeat"; // store also as HA attributes
JsonObject dev = doc.createNestedObject("dev");
JsonObject dev = doc.add<JsonObject>();
dev["name"] = Mqtt::basename();
dev["sw"] = "v" + std::string(EMSESP_APP_VERSION);
dev["mf"] = "EMS-ESP";
@@ -547,7 +547,7 @@ void Mqtt::ha_status() {
#ifndef EMSESP_STANDALONE
dev["cu"] = "http://" + (EMSESP::system_.ethernet_connected() ? ETH.localIP().toString() : WiFi.localIP().toString());
#endif
JsonArray ids = dev.createNestedArray("ids");
JsonArray ids = dev["ids"].to<JsonArray>();
ids.add(Mqtt::basename());
char topic[MQTT_TOPIC_MAX_SIZE];
@@ -723,12 +723,12 @@ bool Mqtt::queue_ha(const char * topic, const JsonObject & payload) {
// create's a ha sensor config topic from a device value object
// and also takes a flag (create_device_config) used to also create the main HA device config. This is only needed for one entity
bool Mqtt::publish_ha_sensor_config(DeviceValue & dv, const char * model, const char * brand, const bool remove, const bool create_device_config) {
StaticJsonDocument<EMSESP_JSON_SIZE_LARGE> dev_json;
JsonDocument dev_json;
// always create the ids (discovery indentifiers)
// with the name always
// and the manufacturer and model if we're creating the device config for the first entity
JsonArray ids = dev_json.createNestedArray("ids");
JsonArray ids = dev_json["ids"].to<JsonArray>();
char ha_device[40];
auto device_type_name = EMSdevice::device_type_2_device_name(dv.device_type);
snprintf(ha_device, sizeof(ha_device), "%s-%s", Mqtt::basename().c_str(), device_type_name);
@@ -775,11 +775,11 @@ bool Mqtt::publish_ha_sensor_config(DeviceValue & dv, const char * model, const
// publish HA sensor for System using the heartbeat tag
bool Mqtt::publish_system_ha_sensor_config(uint8_t type, const char * name, const char * entity, const uint8_t uom) {
StaticJsonDocument<EMSESP_JSON_SIZE_LARGE> doc;
JsonObject dev_json = doc.createNestedObject("dev");
JsonDocument doc;
JsonObject dev_json = doc["dev"].add<JsonObject>();
dev_json["name"] = Mqtt::basename();
JsonArray ids = dev_json.createNestedArray("ids");
JsonArray ids = dev_json["ids"].to<JsonArray>();
ids.add(Mqtt::basename());
return publish_ha_sensor_config(
@@ -906,7 +906,7 @@ bool Mqtt::publish_ha_sensor_config(uint8_t type, // EMSdev
}
// build the payload
StaticJsonDocument<EMSESP_JSON_SIZE_LARGE> doc;
JsonDocument doc;
doc["uniq_id"] = uniq_id;
doc["obj_id"] = uniq_id; // same as unique_id
@@ -931,7 +931,7 @@ bool Mqtt::publish_ha_sensor_config(uint8_t type, // EMSdev
// extend for enums, add options
if (type == DeviceValueType::ENUM) {
JsonArray option_list = doc.createNestedArray("ops"); // options
JsonArray option_list = doc["ops"].to<JsonArray>();
if (EMSESP::system_.enum_format() == ENUM_FORMAT_INDEX) {
// use index numbers
for (uint8_t i = 0; i < options_size; i++) {
@@ -1137,8 +1137,8 @@ bool Mqtt::publish_ha_sensor_config(uint8_t type, // EMSdev
}
}
doc["dev"] = dev_json; // add the dev json object to the end
add_ha_sections_to_doc("", stat_t, doc.as<JsonObject>(), false, val_cond); // no name, since the "dev" has already been added
doc["dev"] = dev_json; // add the dev json object to the end
add_ha_sections_to_doc("", stat_t, doc, false, val_cond); // no name, since the "dev" has already been added
return queue_ha(topic, doc.as<JsonObject>());
}
@@ -1217,7 +1217,7 @@ bool Mqtt::publish_ha_climate_config(const uint8_t tag, const bool has_roomtemp,
snprintf(temp_cmd_s, sizeof(temp_cmd_s), "~/thermostat/hc%d/seltemp", hc_num);
snprintf(mode_cmd_s, sizeof(mode_cmd_s), "~/thermostat/hc%d/mode", hc_num);
StaticJsonDocument<EMSESP_JSON_SIZE_XLARGE> doc; // 1024 is not enough
JsonDocument doc; // 1024 is not enough
doc["~"] = Mqtt::base();
doc["uniq_id"] = uniq_id_s;
@@ -1240,14 +1240,14 @@ bool Mqtt::publish_ha_climate_config(const uint8_t tag, const bool has_roomtemp,
doc["mode_cmd_t"] = mode_cmd_s;
// the HA climate component only responds to auto, heat and off
JsonArray modes = doc.createNestedArray("modes");
JsonArray modes = doc["modes"].to<JsonArray>();
modes.add("auto");
modes.add("heat");
modes.add("off");
// device name must be different to the entity name, take the ids value we just created
add_ha_sections_to_doc("thermostat", topic_t, doc.as<JsonObject>(), false, seltemp_cond, has_roomtemp ? currtemp_cond : nullptr, hc_mode_cond);
add_ha_sections_to_doc("thermostat", topic_t, doc, false, seltemp_cond, has_roomtemp ? currtemp_cond : nullptr, hc_mode_cond);
return queue_ha(topic, doc.as<JsonObject>()); // publish the config payload with retain flag
}
@@ -1274,14 +1274,14 @@ std::string Mqtt::tag_to_topic(uint8_t device_type, uint8_t tag) {
// adds availability, dev, ids to the config section to HA Discovery config
void Mqtt::add_ha_sections_to_doc(const std::string & name,
const char * state_t,
const JsonObject & config,
JsonDocument & config,
const bool is_first,
const char * cond1,
const char * cond2,
const char * negcond) {
// adds dev section to HA Discovery config
if (!name.empty()) {
JsonObject dev = config.createNestedObject("dev");
JsonObject dev = config.add<JsonObject>();
auto cap_name = name;
cap_name[0] = toupper(name[0]); // capitalize first letter
dev["name"] = Mqtt::basename() + " " + cap_name;
@@ -1291,13 +1291,13 @@ void Mqtt::add_ha_sections_to_doc(const std::string & name,
dev["mdl"] = cap_name;
dev["via_device"] = Mqtt::basename();
}
JsonArray ids = dev.createNestedArray("ids");
JsonArray ids = dev["ids"].to<JsonArray>();
ids.add(Mqtt::basename() + "-" + Helpers::toLower(name));
}
// adds "availability" section to HA Discovery config
JsonArray avty = config.createNestedArray("avty");
StaticJsonDocument<EMSESP_JSON_SIZE_SMALL> avty_json;
JsonArray avty = config["avty"].to<JsonArray>();
JsonDocument avty_json;
const char * tpl_draft = "{{'online' if %s else 'offline'}}";

View File

@@ -219,7 +219,7 @@ class Mqtt {
static void add_ha_sections_to_doc(const std::string & name,
const char * state_t,
const JsonObject & config,
JsonDocument & config,
const bool is_first = false,
const char * cond1 = nullptr,
const char * cond2 = nullptr,

View File

@@ -99,7 +99,7 @@ void Shower::loop() {
if ((timer_pause_ - timer_start_) > SHOWER_OFFSET_TIME) {
duration_ = (timer_pause_ - timer_start_ - SHOWER_OFFSET_TIME);
if (duration_ > SHOWER_MIN_DURATION) {
StaticJsonDocument<EMSESP_JSON_SIZE_SMALL> doc;
JsonDocument doc;
// duration in seconds
doc["duration"] = (duration_ / 1000UL); // seconds
@@ -177,10 +177,10 @@ void Shower::set_shower_state(bool state, bool force) {
// send out HA MQTT Discovery config topic
if ((Mqtt::ha_enabled()) && (!ha_configdone_ || force)) {
StaticJsonDocument<EMSESP_JSON_SIZE_LARGE> doc;
char topic[Mqtt::MQTT_TOPIC_MAX_SIZE];
char str[70];
char stat_t[50];
JsonDocument doc;
char topic[Mqtt::MQTT_TOPIC_MAX_SIZE];
char str[70];
char stat_t[50];
//
// shower active
@@ -210,7 +210,7 @@ void Shower::set_shower_state(bool state, bool force) {
doc["pl_off"] = Helpers::render_boolean(result, false);
}
Mqtt::add_ha_sections_to_doc("shower", stat_t, doc.as<JsonObject>(), true); // create first dev & ids
Mqtt::add_ha_sections_to_doc("shower", stat_t, doc, true); // create first dev & ids
snprintf(topic, sizeof(topic), "binary_sensor/%s/shower_active/config", Mqtt::basename().c_str());
ha_configdone_ = Mqtt::queue_ha(topic, doc.as<JsonObject>()); // publish the config payload with retain flag
@@ -235,7 +235,7 @@ void Shower::set_shower_state(bool state, bool force) {
doc["dev_cla"] = "duration";
// doc["ent_cat"] = "diagnostic";
Mqtt::add_ha_sections_to_doc("shower", stat_t, doc.as<JsonObject>(), false, "value_json.duration is defined");
Mqtt::add_ha_sections_to_doc("shower", stat_t, doc, false, "value_json.duration is defined");
snprintf(topic, sizeof(topic), "sensor/%s/shower_duration/config", Mqtt::basename().c_str());
Mqtt::queue_ha(topic, doc.as<JsonObject>()); // publish the config payload with retain flag
@@ -257,7 +257,7 @@ void Shower::set_shower_state(bool state, bool force) {
doc["val_tpl"] = "{{value_json.timestamp if value_json.timestamp is defined else 0}}";
// doc["ent_cat"] = "diagnostic";
Mqtt::add_ha_sections_to_doc("shower", stat_t, doc.as<JsonObject>(), false, "value_json.timestamp is defined");
Mqtt::add_ha_sections_to_doc("shower", stat_t, doc, false, "value_json.timestamp is defined");
snprintf(topic, sizeof(topic), "sensor/%s/shower_timestamp/config", Mqtt::basename().c_str());
Mqtt::queue_ha(topic, doc.as<JsonObject>()); // publish the config payload with retain flag

View File

@@ -96,7 +96,7 @@ bool System::command_send(const char * value, const int8_t id) {
}
bool System::command_response(const char * value, const int8_t id, JsonObject & output) {
DynamicJsonDocument doc(EMSESP_JSON_SIZE_LARGE);
JsonDocument doc;
if (DeserializationError::Ok == deserializeJson(doc, Mqtt::get_response())) {
for (JsonPair p : doc.as<JsonObject>()) {
output[p.key()] = p.value();
@@ -110,23 +110,23 @@ bool System::command_response(const char * value, const int8_t id, JsonObject &
// output all the EMS devices and their values, plus the sensors and any custom entities
// not scheduler as these are records with no output data
bool System::command_allvalues(const char * value, const int8_t id, JsonObject & output) {
DynamicJsonDocument doc(EMSESP_JSON_SIZE_XXXLARGE);
JsonObject device_output;
JsonDocument doc;
JsonObject device_output;
for (const auto & emsdevice : EMSESP::emsdevices) {
std::string title = emsdevice->device_type_2_device_name_translated() + std::string(" ") + emsdevice->to_string();
device_output = output.createNestedObject(title);
device_output = output[title].add<JsonObject>();
emsdevice->generate_values(device_output, DeviceValueTAG::TAG_NONE, true, EMSdevice::OUTPUT_TARGET::API_VERBOSE); // use nested for id -1 and 0
}
// Custom entities
device_output = output.createNestedObject("Custom Entities");
device_output = output["Custom Entities"].add<JsonObject>();
EMSESP::webCustomEntityService.get_value_info(device_output, "");
// Sensors
device_output = output.createNestedObject("Analog Sensors");
device_output = output["Analog Sensors"].add<JsonObject>();
EMSESP::analogsensor_.command_info(nullptr, 0, device_output);
device_output = output.createNestedObject("Temperature Sensors");
device_output = output["Temperature Sensors"].add<JsonObject>();
EMSESP::temperaturesensor_.command_info(nullptr, 0, device_output);
return true;
@@ -583,7 +583,7 @@ void System::send_info_mqtt() {
return;
}
_connection = connection;
StaticJsonDocument<EMSESP_JSON_SIZE_MEDIUM> doc;
JsonDocument doc;
doc["event"] = "connected";
doc["version"] = EMSESP_APP_VERSION;
@@ -694,8 +694,8 @@ void System::send_heartbeat() {
refreshHeapMem(); // refresh free heap and max alloc heap
StaticJsonDocument<EMSESP_JSON_SIZE_MEDIUM> doc;
JsonObject json = doc.to<JsonObject>();
JsonDocument doc;
JsonObject json = doc.to<JsonObject>();
if (heartbeat_json(json)) {
Mqtt::queue_publish(F_(heartbeat), json); // send to MQTT with retain off. This will add to MQTT queue.
@@ -1048,8 +1048,8 @@ bool System::check_restore() {
// see if we have a temp file, if so try and read it
File new_file = LittleFS.open(TEMP_FILENAME_PATH);
if (new_file) {
DynamicJsonDocument jsonDocument = DynamicJsonDocument(FS_BUFFER_SIZE);
DeserializationError error = deserializeJson(jsonDocument, new_file);
JsonDocument jsonDocument;
DeserializationError error = deserializeJson(jsonDocument, new_file);
if (error == DeserializationError::Ok && jsonDocument.is<JsonObject>()) {
JsonObject input = jsonDocument.as<JsonObject>();
// see what type of file it is, either settings or customization. anything else is ignored
@@ -1174,11 +1174,11 @@ void System::extractSettings(const char * filename, const char * section, JsonOb
#ifndef EMSESP_STANDALONE
File settingsFile = LittleFS.open(filename);
if (settingsFile) {
DynamicJsonDocument jsonDocument = DynamicJsonDocument(FS_BUFFER_SIZE);
DeserializationError error = deserializeJson(jsonDocument, settingsFile);
JsonDocument jsonDocument;
DeserializationError error = deserializeJson(jsonDocument, settingsFile);
if (error == DeserializationError::Ok && jsonDocument.is<JsonObject>()) {
JsonObject jsonObject = jsonDocument.as<JsonObject>();
JsonObject node = output.createNestedObject(section);
JsonObject node = output[section].add<JsonObject>();
for (JsonPair kvp : jsonObject) {
node[kvp.key()] = kvp.value();
}
@@ -1211,7 +1211,7 @@ bool System::command_info(const char * value, const int8_t id, JsonObject & outp
JsonObject node;
// System
node = output.createNestedObject("System Info");
node = output["System Info"].add<JsonObject>();
node["version"] = EMSESP_APP_VERSION;
node["uptime"] = uuid::log::format_timestamp_ms(uuid::get_uptime_ms(), 3);
node["uptime (seconds)"] = uuid::get_uptime_sec();
@@ -1228,7 +1228,7 @@ bool System::command_info(const char * value, const int8_t id, JsonObject & outp
#ifndef EMSESP_STANDALONE
// Network Status
node = output.createNestedObject("Network Info");
node = output["Network Info"].add<JsonObject>();
if (EMSESP::system_.ethernet_connected()) {
node["network"] = "Ethernet";
node["hostname"] = ETH.getHostname();
@@ -1276,7 +1276,7 @@ bool System::command_info(const char * value, const int8_t id, JsonObject & outp
#endif
// NTP status
node = output.createNestedObject("NTP Info");
node = output["NTP Info"].add<JsonObject>();
#ifndef EMSESP_STANDALONE
node["NTP status"] = EMSESP::system_.ntp_connected() ? "connected" : "disconnected";
EMSESP::esp8266React.getNTPSettingsService()->read([&](NTPSettings & settings) {
@@ -1287,7 +1287,7 @@ bool System::command_info(const char * value, const int8_t id, JsonObject & outp
});
// OTA status
node = output.createNestedObject("OTA Info");
node = output["OTA Info"].add<JsonObject>();
EMSESP::esp8266React.getOTASettingsService()->read([&](OTASettings & settings) {
node["enabled"] = settings.enabled;
node["port"] = settings.port;
@@ -1295,7 +1295,7 @@ bool System::command_info(const char * value, const int8_t id, JsonObject & outp
#endif
// MQTT Status
node = output.createNestedObject("MQTT Info");
node = output["MQTT Info"].add<JsonObject>();
node["MQTT status"] = Mqtt::connected() ? F_(connected) : F_(disconnected);
if (Mqtt::enabled()) {
node["MQTT publishes"] = Mqtt::publish_count();
@@ -1329,7 +1329,7 @@ bool System::command_info(const char * value, const int8_t id, JsonObject & outp
});
// Syslog Status
node = output.createNestedObject("Syslog Info");
node = output["Syslog Info"].add<JsonObject>();
node["enabled"] = EMSESP::system_.syslog_enabled_;
#ifndef EMSESP_STANDALONE
if (EMSESP::system_.syslog_enabled_) {
@@ -1341,7 +1341,7 @@ bool System::command_info(const char * value, const int8_t id, JsonObject & outp
#endif
// Sensor Status
node = output.createNestedObject("Sensor Info");
node = output["Sensor Info"].add<JsonObject>();
if (EMSESP::sensor_enabled()) {
node["temperature sensors"] = EMSESP::temperaturesensor_.no_sensors();
node["temperature sensor reads"] = EMSESP::temperaturesensor_.reads();
@@ -1354,12 +1354,12 @@ bool System::command_info(const char * value, const int8_t id, JsonObject & outp
}
// API Status
node = output.createNestedObject("API Info");
node = output["API Info"].add<JsonObject>();
node["API calls"] = WebAPIService::api_count();
node["API fails"] = WebAPIService::api_fails();
// EMS Bus Status
node = output.createNestedObject("Bus Info");
node = output["Bus Info"].add<JsonObject>();
switch (EMSESP::bus_status()) {
case EMSESP::BUS_STATUS_OFFLINE:
node["bus status"] = "disconnected";
@@ -1387,7 +1387,7 @@ bool System::command_info(const char * value, const int8_t id, JsonObject & outp
}
// Settings
node = output.createNestedObject("Settings");
node = output["Settings"].add<JsonObject>();
EMSESP::webSettingsService.read([&](WebSettings & settings) {
node["board profile"] = settings.board_profile;
node["locale"] = settings.locale;
@@ -1428,11 +1428,11 @@ bool System::command_info(const char * value, const int8_t id, JsonObject & outp
// Devices - show EMS devices if we have any
if (!EMSESP::emsdevices.empty()) {
JsonArray devices = output.createNestedArray("Devices");
JsonArray devices = output["Devices"].to<JsonArray>();
for (const auto & device_class : EMSFactory::device_handlers()) {
for (const auto & emsdevice : EMSESP::emsdevices) {
if (emsdevice && (emsdevice->device_type() == device_class.first)) {
JsonObject obj = devices.createNestedObject();
JsonObject obj = devices.add<JsonObject>();
obj["type"] = emsdevice->device_type_name(); // non translated name
obj["name"] = emsdevice->name();
obj["device id"] = Helpers::hextoa(emsdevice->device_id());

View File

@@ -376,7 +376,7 @@ bool TemperatureSensor::command_info(const char * value, const int8_t id, JsonOb
for (const auto & sensor : sensors_) {
char val[10];
if (id == -1) { // show number and id, info command
JsonObject dataSensor = output.createNestedObject(sensor.name());
JsonObject dataSensor = output[sensor.name()].add<JsonObject>();
dataSensor["id"] = sensor.id();
dataSensor["uom"] = EMSdevice::uom_to_string(DeviceValueUOM::DEGREES);
dataSensor["type"] = F_(number);
@@ -490,7 +490,7 @@ void TemperatureSensor::publish_values(const bool force) {
}
}
DynamicJsonDocument doc(150 * num_sensors);
JsonDocument doc;
// used to see if we need to create the [devs] discovery section, as this needs only to be done once for all sensors
bool is_first_ha = true;
@@ -508,7 +508,7 @@ void TemperatureSensor::publish_values(const bool force) {
if (has_value) {
char val[10];
if (Mqtt::is_nested()) {
JsonObject dataSensor = doc.createNestedObject(sensor.id());
JsonObject dataSensor = doc[sensor.id()].add<JsonObject>();
dataSensor["name"] = sensor.name();
dataSensor["temp"] = serialized(Helpers::render_value(val, sensor.temperature_c, 10, EMSESP::system_.fahrenheit() ? 2 : 0));
} else {
@@ -525,7 +525,7 @@ void TemperatureSensor::publish_values(const bool force) {
} else if (!sensor.ha_registered || force) {
LOG_DEBUG("Recreating HA config for sensor ID %s", sensor.id().c_str());
StaticJsonDocument<EMSESP_JSON_SIZE_LARGE> config; // this needs to be large because of all the copying in add_ha_sections_to_doc()
JsonDocument config; // this needs to be large because of all the copying in add_ha_sections_to_doc()
config["dev_cla"] = "temperature";
char stat_t[50];
@@ -566,7 +566,7 @@ void TemperatureSensor::publish_values(const bool force) {
snprintf(name, sizeof(name), "%s", sensor.name().c_str());
config["name"] = name;
Mqtt::add_ha_sections_to_doc("temperature", stat_t, config.as<JsonObject>(), is_first_ha, val_cond);
Mqtt::add_ha_sections_to_doc("temperature", stat_t, config, is_first_ha, val_cond);
char topic[Mqtt::MQTT_TOPIC_MAX_SIZE];
// use '_' as HA doesn't like '-' in the topic name

View File

@@ -545,7 +545,7 @@ void Test::run_test(uuid::console::Shell & shell, const std::string & cmd, const
run_test("boiler");
run_test("thermostat");
DynamicJsonDocument doc(8000); // some absurd high number
JsonDocument doc; // some absurd high number
for (const auto & emsdevice : EMSESP::emsdevices) {
if (emsdevice) {
doc.clear();
@@ -570,8 +570,6 @@ void Test::run_test(uuid::console::Shell & shell, const std::string & cmd, const
serializeJson(doc, Serial);
Serial.print(COLOR_RESET);
Serial.println();
Serial.print("** memoryUsage=");
Serial.print(doc.memoryUsage());
Serial.print(" measureMsgPack=");
Serial.print(measureMsgPack(doc));
Serial.print(" measureJson=");
@@ -848,7 +846,7 @@ void Test::run_test(uuid::console::Shell & shell, const std::string & cmd, const
run_test("thermostat");
AsyncWebServerRequest request;
DynamicJsonDocument doc(2000);
JsonDocument doc;
JsonVariant json;
request.method(HTTP_GET);
@@ -893,8 +891,8 @@ void Test::run_test(uuid::console::Shell & shell, const std::string & cmd, const
AsyncWebServerRequest request;
request.method(HTTP_POST);
DynamicJsonDocument doc(2000);
JsonVariant json;
JsonDocument doc;
JsonVariant json;
char data[] = "{\"value\":\"off\"}";
deserializeJson(doc, data);
@@ -917,7 +915,7 @@ void Test::run_test(uuid::console::Shell & shell, const std::string & cmd, const
run_test("thermostat");
AsyncWebServerRequest requestX;
DynamicJsonDocument docX(2000);
JsonDocument docX;
JsonVariant jsonX;
requestX.method(HTTP_GET);
@@ -1108,8 +1106,8 @@ void Test::run_test(uuid::console::Shell & shell, const std::string & cmd, const
// POST tests
request.method(HTTP_POST);
DynamicJsonDocument doc(2000);
JsonVariant json;
JsonDocument doc;
JsonVariant json;
// 1
char data1[] = "{\"entity\":\"seltemp\",\"value\":11}";
@@ -1536,7 +1534,7 @@ void Test::run_test(uuid::console::Shell & shell, const std::string & cmd, const
if (command == "mqtt2") {
shell.printfln("Testing MQTT large payloads...");
DynamicJsonDocument doc(EMSESP_JSON_SIZE_XXXLARGE);
JsonDocument doc;
char key[8];
char value[8];
@@ -1549,7 +1547,6 @@ void Test::run_test(uuid::console::Shell & shell, const std::string & cmd, const
}
doc.shrinkToFit();
JsonObject jo = doc.as<JsonObject>();
shell.printfln("Size of JSON payload = %d", jo.memoryUsage());
shell.printfln("Length of JSON payload = %d", measureJson(jo));
Mqtt::queue_publish("test", jo);

View File

@@ -27,8 +27,8 @@ uint16_t WebAPIService::api_fails_ = 0;
WebAPIService::WebAPIService(AsyncWebServer * server, SecurityManager * securityManager)
: _securityManager(securityManager)
, _apiHandler("/api", std::bind(&WebAPIService::webAPIService_post, this, _1, _2), 256) { // for POSTS, must use 'Content-Type: application/json' in header
server->on("/api", HTTP_GET, std::bind(&WebAPIService::webAPIService_get, this, _1)); // for GETS
, _apiHandler("/api", std::bind(&WebAPIService::webAPIService_post, this, _1, _2)) { // for POSTS, must use 'Content-Type: application/json' in header
server->on("/api", HTTP_GET, std::bind(&WebAPIService::webAPIService_get, this, _1)); // for GETS
server->addHandler(&_apiHandler);
// for settings
@@ -45,8 +45,8 @@ WebAPIService::WebAPIService(AsyncWebServer * server, SecurityManager * security
// GET /{device}/{entity}
void WebAPIService::webAPIService_get(AsyncWebServerRequest * request) {
// has no body JSON so create dummy as empty input object
StaticJsonDocument<EMSESP_JSON_SIZE_SMALL> input_doc;
JsonObject input = input_doc.to<JsonObject>();
JsonDocument input_doc;
JsonObject input = input_doc.to<JsonObject>();
parse(request, input);
}
@@ -106,15 +106,14 @@ void WebAPIService::parse(AsyncWebServerRequest * request, JsonObject & input) {
emsesp::EMSESP::system_.refreshHeapMem();
// output json buffer
size_t buffer = EMSESP_JSON_SIZE_XXXLARGE;
AsyncJsonResponse * response = new AsyncJsonResponse(false, buffer);
AsyncJsonResponse * response = new AsyncJsonResponse(false);
// add more mem if needed - won't be needed in ArduinoJson 7
while (!response->getSize()) {
delete response;
buffer -= 1024;
response = new AsyncJsonResponse(false, buffer);
}
// while (!response->getSize()) {
// delete response;
// buffer -= 1024;
// response = new AsyncJsonResponse(false, buffer);
// }
JsonObject output = response->getRoot();
@@ -164,12 +163,12 @@ void WebAPIService::parse(AsyncWebServerRequest * request, JsonObject & input) {
}
void WebAPIService::getSettings(AsyncWebServerRequest * request) {
auto * response = new AsyncJsonResponse(false, FS_BUFFER_SIZE);
auto * response = new AsyncJsonResponse(false);
JsonObject root = response->getRoot();
root["type"] = "settings";
JsonObject node = root.createNestedObject("System");
JsonObject node = root["System"].add<JsonObject>();
node["version"] = EMSESP_APP_VERSION;
System::extractSettings(NETWORK_SETTINGS_FILE, "Network", root);
@@ -185,7 +184,7 @@ void WebAPIService::getSettings(AsyncWebServerRequest * request) {
}
void WebAPIService::getCustomizations(AsyncWebServerRequest * request) {
auto * response = new AsyncJsonResponse(false, FS_BUFFER_SIZE);
auto * response = new AsyncJsonResponse(false);
JsonObject root = response->getRoot();
root["type"] = "customizations";
@@ -197,7 +196,7 @@ void WebAPIService::getCustomizations(AsyncWebServerRequest * request) {
}
void WebAPIService::getSchedule(AsyncWebServerRequest * request) {
auto * response = new AsyncJsonResponse(false, FS_BUFFER_SIZE);
auto * response = new AsyncJsonResponse(false);
JsonObject root = response->getRoot();
root["type"] = "schedule";
@@ -209,7 +208,7 @@ void WebAPIService::getSchedule(AsyncWebServerRequest * request) {
}
void WebAPIService::getEntities(AsyncWebServerRequest * request) {
auto * response = new AsyncJsonResponse(false, FS_BUFFER_SIZE);
auto * response = new AsyncJsonResponse(false);
JsonObject root = response->getRoot();
root["type"] = "entities";

View File

@@ -30,7 +30,7 @@ WebCustomEntityService::WebCustomEntityService(AsyncWebServer * server, FS * fs,
EMSESP_CUSTOMENTITY_SERVICE_PATH,
securityManager,
AuthenticationPredicates::IS_AUTHENTICATED)
, _fsPersistence(WebCustomEntity::read, WebCustomEntity::update, this, fs, EMSESP_CUSTOMENTITY_FILE, FS_BUFFER_SIZE) {
, _fsPersistence(WebCustomEntity::read, WebCustomEntity::update, this, fs, EMSESP_CUSTOMENTITY_FILE) {
}
// load the settings when the service starts
@@ -43,10 +43,10 @@ void WebCustomEntityService::begin() {
// this creates the entity file, saving it to the FS
// and also calls when the Entity web page is refreshed
void WebCustomEntity::read(WebCustomEntity & webEntity, JsonObject & root) {
JsonArray entity = root.createNestedArray("entities");
JsonArray entity = root["entities"].to<JsonArray>();
uint8_t counter = 0;
for (const CustomEntityItem & entityItem : webEntity.customEntityItems) {
JsonObject ei = entity.createNestedObject();
JsonObject ei = entity.add<JsonObject>();
ei["id"] = counter++; // id is only used to render the table and must be unique
ei["device_id"] = entityItem.device_id;
ei["type_id"] = entityItem.type_id;
@@ -70,7 +70,7 @@ StateUpdateResult WebCustomEntity::update(JsonObject & root, WebCustomEntity & w
const char * json =
"{\"entities\": [{\"id\":0,\"device_id\":8,\"type_id\":24,\"offset\":0,\"factor\":1,\"name\":\"boiler_flowtemp\",\"uom\":1,\"value_type\":1,\"writeable\":true}]}";
// clang-format on
StaticJsonDocument<500> doc;
JsonDocument doc;
deserializeJson(doc, json);
root = doc.as<JsonObject>();
Serial.println(COLOR_BRIGHT_MAGENTA);
@@ -342,8 +342,8 @@ void WebCustomEntityService::publish_single(const CustomEntityItem & entity) {
} else {
snprintf(topic, sizeof(topic), "%s/%s", "custom_data", entity.name.c_str());
}
StaticJsonDocument<EMSESP_JSON_SIZE_SMALL> doc;
JsonObject output = doc.to<JsonObject>();
JsonDocument doc;
JsonObject output = doc.to<JsonObject>();
render_value(output, entity, true);
Mqtt::queue_publish(topic, output["value"].as<std::string>());
}
@@ -366,15 +366,15 @@ void WebCustomEntityService::publish(const bool force) {
}
}
DynamicJsonDocument doc(EMSESP_JSON_SIZE_XLARGE);
JsonObject output = doc.to<JsonObject>();
bool ha_created = ha_registered_;
JsonDocument doc;
JsonObject output = doc.to<JsonObject>();
bool ha_created = ha_registered_;
for (const CustomEntityItem & entityItem : *customEntityItems) {
render_value(output, entityItem);
// create HA config
if (Mqtt::ha_enabled() && !ha_registered_) {
StaticJsonDocument<EMSESP_JSON_SIZE_MEDIUM> config;
char stat_t[50];
JsonDocument config;
char stat_t[50];
snprintf(stat_t, sizeof(stat_t), "%s/custom_data", Mqtt::base().c_str());
config["stat_t"] = stat_t;
@@ -426,7 +426,7 @@ void WebCustomEntityService::publish(const bool force) {
config["pl_off"] = Helpers::render_boolean(result, false);
}
}
Mqtt::add_ha_sections_to_doc("custom", stat_t, config.as<JsonObject>(), true, val_cond);
Mqtt::add_ha_sections_to_doc("custom", stat_t, config, true, val_cond);
ha_created |= Mqtt::queue_ha(topic, config.as<JsonObject>());
}
@@ -445,9 +445,9 @@ uint8_t WebCustomEntityService::count_entities() {
return 0;
}
DynamicJsonDocument doc(EMSESP_JSON_SIZE_XLARGE);
JsonObject output = doc.to<JsonObject>();
uint8_t count = 0;
JsonDocument doc;
JsonObject output = doc.to<JsonObject>();
uint8_t count = 0;
for (const CustomEntityItem & entity : *customEntityItems) {
render_value(output, entity);
count += (output.containsKey(entity.name) || entity.writeable) ? 1 : 0;
@@ -469,10 +469,10 @@ void WebCustomEntityService::generate_value_web(JsonObject & output) {
EMSESP::webCustomEntityService.read([&](WebCustomEntity & webEntity) { customEntityItems = &webEntity.customEntityItems; });
output["label"] = (std::string) "Custom Entities";
JsonArray data = output.createNestedArray("data");
JsonArray data = output["data"].to<JsonArray>();
uint8_t index = 0;
for (const CustomEntityItem & entity : *customEntityItems) {
JsonObject obj = data.createNestedObject(); // create the object, we know there is a value
JsonObject obj = data.add<JsonObject>(); // create the object, we know there is a value
obj["id"] = "00" + entity.name;
obj["u"] = entity.uom;
if (entity.writeable) {
@@ -487,7 +487,7 @@ void WebCustomEntityService::generate_value_web(JsonObject & output) {
case DeviceValueType::BOOL: {
char s[12];
obj["v"] = Helpers::render_boolean(s, (uint8_t)entity.value, true);
JsonArray l = obj.createNestedArray("l");
JsonArray l = obj["l"].to<JsonArray>();
l.add(Helpers::render_boolean(s, false, true));
l.add(Helpers::render_boolean(s, true, true));
break;

View File

@@ -51,25 +51,24 @@ WebCustomizationService::WebCustomizationService(AsyncWebServer * server, FS * f
_masked_entities_handler.setMethod(HTTP_POST);
_masked_entities_handler.setMaxContentLength(2048);
_masked_entities_handler.setMaxJsonBufferSize(2048);
server->addHandler(&_masked_entities_handler);
}
// this creates the customization file, saving it to the FS
void WebCustomization::read(WebCustomization & customizations, JsonObject & root) {
// Temperature Sensor customization
JsonArray sensorsJson = root.createNestedArray("ts");
JsonArray sensorsJson = root["ts"].to<JsonArray>();
for (const SensorCustomization & sensor : customizations.sensorCustomizations) {
JsonObject sensorJson = sensorsJson.createNestedObject();
JsonObject sensorJson = sensorsJson.add<JsonObject>();
sensorJson["id"] = sensor.id; // ID of chip
sensorJson["name"] = sensor.name; // n
sensorJson["offset"] = sensor.offset; // o
}
// Analog Sensor customization
JsonArray analogJson = root.createNestedArray("as");
JsonArray analogJson = root["as"].to<JsonArray>();
for (const AnalogCustomization & sensor : customizations.analogCustomizations) {
JsonObject sensorJson = analogJson.createNestedObject();
JsonObject sensorJson = analogJson.add<JsonObject>();
sensorJson["gpio"] = sensor.gpio; // g
sensorJson["name"] = sensor.name; // n
sensorJson["offset"] = sensor.offset; // o
@@ -79,14 +78,14 @@ void WebCustomization::read(WebCustomization & customizations, JsonObject & root
}
// Masked entities customization
JsonArray masked_entitiesJson = root.createNestedArray("masked_entities");
JsonArray masked_entitiesJson = root["masked_entities"].to<JsonArray>();
for (const EntityCustomization & entityCustomization : customizations.entityCustomizations) {
JsonObject entityJson = masked_entitiesJson.createNestedObject();
JsonObject entityJson = masked_entitiesJson.add<JsonObject>();
entityJson["product_id"] = entityCustomization.product_id;
entityJson["device_id"] = entityCustomization.device_id;
// entries are in the form <XX><shortname>[|optional customname] e.g "08heatingactive|heating is on"
JsonArray masked_entityJson = entityJson.createNestedArray("entity_ids");
JsonArray masked_entityJson = entityJson["entity_ids"].to<JsonArray>();
for (std::string entity_id : entityCustomization.entity_ids) {
masked_entityJson.add(entity_id);
}
@@ -98,9 +97,9 @@ void WebCustomization::read(WebCustomization & customizations, JsonObject & root
StateUpdateResult WebCustomization::update(JsonObject & root, WebCustomization & customizations) {
#ifdef EMSESP_STANDALONE
// invoke some fake data for testing
const char * json = "{\"ts\":[],\"as\":[],\"masked_entities\":[{\"product_id\":123,\"device_id\":8,\"entity_ids\":[\"08heatingactive|my custom "
"name for heating active (HS1)\",\"08tapwateractive\"]}]}";
StaticJsonDocument<500> doc;
const char * json = "{\"ts\":[],\"as\":[],\"masked_entities\":[{\"product_id\":123,\"device_id\":8,\"entity_ids\":[\"08heatingactive|my custom "
"name for heating active (HS1)\",\"08tapwateractive\"]}]}";
JsonDocument doc;
deserializeJson(doc, json);
root = doc.as<JsonObject>();
Serial.println(COLOR_BRIGHT_MAGENTA);
@@ -179,15 +178,15 @@ void WebCustomizationService::reset_customization(AsyncWebServerRequest * reques
// send back a list of devices used in the customization web page
void WebCustomizationService::devices(AsyncWebServerRequest * request) {
auto * response = new AsyncJsonResponse(false, EMSESP_JSON_SIZE_XLARGE);
auto * response = new AsyncJsonResponse(false);
JsonObject root = response->getRoot();
// list is already sorted by device type
// controller is ignored since it doesn't have any associated entities
JsonArray devices = root.createNestedArray("devices");
JsonArray devices = root["devices"].to<JsonArray>();
for (const auto & emsdevice : EMSESP::emsdevices) {
if (emsdevice->has_entities()) {
JsonObject obj = devices.createNestedObject();
JsonObject obj = devices.add<JsonObject>();
obj["i"] = emsdevice->unique_id(); // its unique id
obj["s"] = std::string(emsdevice->device_type_2_device_name_translated()) + " (" + emsdevice->name() + ")"; // shortname, is device type translated
obj["tn"] = emsdevice->device_type_name(); // non-translated, lower-case
@@ -205,14 +204,14 @@ void WebCustomizationService::device_entities(AsyncWebServerRequest * request) {
if (request->hasParam(F_(id))) {
id = Helpers::atoint(request->getParam(F_(id))->value().c_str()); // get id from url
size_t buffer = EMSESP_JSON_SIZE_XXXXLARGE;
auto * response = new MsgpackAsyncJsonResponse(true, buffer);
auto * response = new MsgpackAsyncJsonResponse(true);
// while (!response) {
// delete response;
// buffer -= 1024;
// response = new MsgpackAsyncJsonResponse(true, buffer);
// }
while (!response) {
delete response;
buffer -= 1024;
response = new MsgpackAsyncJsonResponse(true, buffer);
}
for (const auto & emsdevice : EMSESP::emsdevices) {
if (emsdevice->unique_id() == id) {
#ifndef EMSESP_STANDALONE

View File

@@ -71,15 +71,15 @@ void WebDataService::scan_devices(AsyncWebServerRequest * request) {
// this is used in the dashboard and contains all ems device information
// /coreData endpoint
void WebDataService::core_data(AsyncWebServerRequest * request) {
auto * response = new AsyncJsonResponse(false, EMSESP_JSON_SIZE_XXLARGE);
auto * response = new AsyncJsonResponse(false);
JsonObject root = response->getRoot();
// list is already sorted by device type
JsonArray devices = root.createNestedArray("devices");
JsonArray devices = root["devices"].to<JsonArray>();
for (const auto & emsdevice : EMSESP::emsdevices) {
// ignore controller
if (emsdevice && (emsdevice->device_type() != EMSdevice::DeviceType::CONTROLLER || emsdevice->count_entities() > 0)) {
JsonObject obj = devices.createNestedObject();
JsonObject obj = devices.add<JsonObject>();
obj["id"] = emsdevice->unique_id(); // a unique id
obj["tn"] = emsdevice->device_type_2_device_name_translated(); // translated device type name
obj["t"] = emsdevice->device_type(); // device type number
@@ -95,7 +95,7 @@ void WebDataService::core_data(AsyncWebServerRequest * request) {
// add any custom entities
uint8_t customEntities = EMSESP::webCustomEntityService.count_entities();
if (customEntities) {
JsonObject obj = devices.createNestedObject();
JsonObject obj = devices.add<JsonObject>();
obj["id"] = 99; // the last unique id
obj["tn"] = Helpers::translated_word(FL_(custom_device)); // translated device type name
obj["t"] = EMSdevice::DeviceType::CUSTOM; // device type number
@@ -116,14 +116,14 @@ void WebDataService::core_data(AsyncWebServerRequest * request) {
// sensor data - sends back to web
// /sensorData endpoint
void WebDataService::sensor_data(AsyncWebServerRequest * request) {
auto * response = new AsyncJsonResponse(false, EMSESP_JSON_SIZE_XXLARGE);
auto * response = new AsyncJsonResponse(false);
JsonObject root = response->getRoot();
// temperature sensors
JsonArray sensors = root.createNestedArray("ts");
JsonArray sensors = root["ts"].to<JsonArray>();
if (EMSESP::temperaturesensor_.have_sensors()) {
for (const auto & sensor : EMSESP::temperaturesensor_.sensors()) {
JsonObject obj = sensors.createNestedObject();
JsonObject obj = sensors.add<JsonObject>();
obj["id"] = sensor.id(); // id as string
obj["n"] = sensor.name(); // name
if (EMSESP::system_.fahrenheit()) {
@@ -143,11 +143,11 @@ void WebDataService::sensor_data(AsyncWebServerRequest * request) {
}
// analog sensors
JsonArray analogs = root.createNestedArray("as");
JsonArray analogs = root["as"].to<JsonArray>();
if (EMSESP::analog_enabled() && EMSESP::analogsensor_.have_sensors()) {
uint8_t count = 0;
for (const auto & sensor : EMSESP::analogsensor_.sensors()) {
JsonObject obj = analogs.createNestedObject();
JsonObject obj = analogs.add<JsonObject>();
obj["id"] = ++count; // needed for sorting table
obj["g"] = sensor.gpio();
obj["n"] = sensor.name();
@@ -178,15 +178,14 @@ void WebDataService::device_data(AsyncWebServerRequest * request) {
if (request->hasParam(F_(id))) {
id = Helpers::atoint(request->getParam(F_(id))->value().c_str()); // get id from url
size_t buffer = EMSESP_JSON_SIZE_XXXXLARGE;
auto * response = new MsgpackAsyncJsonResponse(false, buffer);
auto * response = new MsgpackAsyncJsonResponse(false);
// check size
while (!response) {
delete response;
buffer -= 1024;
response = new MsgpackAsyncJsonResponse(false, buffer);
}
// while (!response) {
// delete response;
// buffer -= 1024;
// response = new MsgpackAsyncJsonResponse(false, buffer);
// }
for (const auto & emsdevice : EMSESP::emsdevices) {
if (emsdevice->unique_id() == id) {
@@ -249,7 +248,7 @@ void WebDataService::write_device_value(AsyncWebServerRequest * request, JsonVar
cmd = Command::parse_command_string(cmd, id); // extract hc or wwc
// create JSON for output
auto * response = new AsyncJsonResponse(false, EMSESP_JSON_SIZE_SMALL);
auto * response = new AsyncJsonResponse(false);
JsonObject output = response->getRoot();
// the data could be in any format, but we need string
@@ -289,7 +288,7 @@ void WebDataService::write_device_value(AsyncWebServerRequest * request, JsonVar
// parse the command as it could have a hc or wwc prefixed, e.g. hc2/seltemp
int8_t id = -1;
cmd = Command::parse_command_string(cmd, id);
auto * response = new AsyncJsonResponse(false, EMSESP_JSON_SIZE_SMALL);
auto * response = new AsyncJsonResponse(false);
JsonObject output = response->getRoot();
uint8_t return_code = CommandRet::NOT_FOUND;
uint8_t device_type = EMSdevice::DeviceType::CUSTOM;

View File

@@ -24,7 +24,7 @@ namespace emsesp {
WebLogService::WebLogService(AsyncWebServer * server, SecurityManager * securityManager)
: events_(EVENT_SOURCE_LOG_PATH)
, setValues_(LOG_SETTINGS_PATH, std::bind(&WebLogService::setValues, this, _1, _2), 256) {
, setValues_(LOG_SETTINGS_PATH, std::bind(&WebLogService::setValues, this, _1, _2)) {
events_.setFilter(securityManager->filterRequest(AuthenticationPredicates::IS_ADMIN));
server->on(LOG_SETTINGS_PATH, HTTP_GET, std::bind(&WebLogService::getValues, this, _1)); // get settings
@@ -183,10 +183,8 @@ char * WebLogService::messagetime(char * out, const uint64_t t, const size_t buf
// send to web eventsource
void WebLogService::transmit(const QueuedLogMessage & message) {
DynamicJsonDocument jsonDocument(EMSESP_JSON_SIZE_LARGE);
if (jsonDocument.capacity() == 0) {
return;
}
JsonDocument jsonDocument;
JsonObject logEvent = jsonDocument.to<JsonObject>();
char time_string[25];
@@ -234,7 +232,7 @@ void WebLogService::setValues(AsyncWebServerRequest * request, JsonVariant & jso
// return the current value settings after a GET
void WebLogService::getValues(AsyncWebServerRequest * request) {
auto * response = new AsyncJsonResponse(false, EMSESP_JSON_SIZE_SMALL);
auto * response = new AsyncJsonResponse(false);
JsonObject root = response->getRoot();
root["level"] = log_level();
root["max_messages"] = maximum_log_messages();

View File

@@ -37,10 +37,10 @@ void WebSchedulerService::begin() {
// this creates the scheduler file, saving it to the FS
// and also calls when the Scheduler web page is refreshed
void WebScheduler::read(WebScheduler & webScheduler, JsonObject & root) {
JsonArray schedule = root.createNestedArray("schedule");
JsonArray schedule = root["schedule"].to<JsonArray>();
uint8_t counter = 0;
for (const ScheduleItem & scheduleItem : webScheduler.scheduleItems) {
JsonObject si = schedule.createNestedObject();
JsonObject si = schedule.add<JsonObject>();
si["id"] = counter++; // id is only used to render the table and must be unique
si["active"] = scheduleItem.active;
si["flags"] = scheduleItem.flags;
@@ -59,7 +59,7 @@ StateUpdateResult WebScheduler::update(JsonObject & root, WebScheduler & webSche
const char * json =
"{\"schedule\": [{\"id\":1,\"active\":true,\"flags\":31,\"time\": \"07:30\",\"cmd\": \"hc1mode\",\"value\": \"day\",\"name\": \"turn on "
"central heating\"}]}";
StaticJsonDocument<500> doc;
JsonDocument doc;
deserializeJson(doc, json);
root = doc.as<JsonObject>();
Serial.println(COLOR_BRIGHT_MAGENTA);
@@ -237,8 +237,8 @@ void WebSchedulerService::publish(const bool force) {
}
}
DynamicJsonDocument doc(EMSESP_JSON_SIZE_XLARGE);
bool ha_created = ha_registered_;
JsonDocument doc;
bool ha_created = ha_registered_;
for (const ScheduleItem & scheduleItem : *scheduleItems) {
if (!scheduleItem.name.empty() && !doc.containsKey(scheduleItem.name)) {
if (EMSESP::system_.bool_format() == BOOL_FORMAT_TRUEFALSE) {
@@ -252,8 +252,8 @@ void WebSchedulerService::publish(const bool force) {
// create HA config
if (Mqtt::ha_enabled() && !ha_registered_) {
StaticJsonDocument<EMSESP_JSON_SIZE_MEDIUM> config;
char stat_t[50];
JsonDocument config;
char stat_t[50];
snprintf(stat_t, sizeof(stat_t), "%s/scheduler_data", Mqtt::base().c_str());
config["stat_t"] = stat_t;
@@ -287,7 +287,7 @@ void WebSchedulerService::publish(const bool force) {
config["pl_off"] = Helpers::render_boolean(result, false);
}
Mqtt::add_ha_sections_to_doc("scheduler", stat_t, config.as<JsonObject>(), true, val_cond);
Mqtt::add_ha_sections_to_doc("scheduler", stat_t, config, true, val_cond);
ha_created |= Mqtt::queue_ha(topic, config.as<JsonObject>());
}
@@ -314,14 +314,14 @@ bool WebSchedulerService::has_commands() {
// execute scheduled command
bool WebSchedulerService::command(const char * cmd, const char * data) {
StaticJsonDocument<EMSESP_JSON_SIZE_SMALL> doc_input;
JsonObject input = doc_input.to<JsonObject>();
JsonDocument doc_input;
JsonObject input = doc_input.to<JsonObject>();
if (strlen(data)) { // empty data queries a value
input["data"] = data;
}
StaticJsonDocument<EMSESP_JSON_SIZE_SMALL> doc_output; // only for commands without output
JsonObject output = doc_output.to<JsonObject>();
JsonDocument doc_output; // only for commands without output
JsonObject output = doc_output.to<JsonObject>();
// prefix "api/" to command string
char command_str[100];

View File

@@ -364,7 +364,7 @@ void WebSettingsService::board_profile(AsyncWebServerRequest * request) {
if (request->hasParam("boardProfile")) {
std::string board_profile = request->getParam("boardProfile")->value().c_str();
auto * response = new AsyncJsonResponse(false, EMSESP_JSON_SIZE_MEDIUM);
auto * response = new AsyncJsonResponse(false);
JsonObject root = response->getRoot();
std::vector<int8_t> data; // led, dallas, rx, tx, button, phy_type, eth_power, eth_phy_addr, eth_clock_mode

View File

@@ -115,7 +115,7 @@ void WebStatusService::WiFiEvent(WiFiEvent_t event, WiFiEventInfo_t info) {
}
void WebStatusService::webStatusService(AsyncWebServerRequest * request) {
auto * response = new AsyncJsonResponse(false, EMSESP_JSON_SIZE_LARGE);
auto * response = new AsyncJsonResponse(false);
JsonObject root = response->getRoot();
root["status"] = EMSESP::bus_status(); // 0, 1 or 2
@@ -125,29 +125,29 @@ void WebStatusService::webStatusService(AsyncWebServerRequest * request) {
root["num_sensors"] = EMSESP::temperaturesensor_.no_sensors();
root["num_analogs"] = EMSESP::analogsensor_.no_sensors();
JsonArray statsJson = root.createNestedArray("stats");
JsonArray statsJson = root["stats"].to<JsonArray>();
JsonObject statJson;
statJson = statsJson.createNestedObject();
statJson = statsJson.add<JsonObject>();
statJson["id"] = 0;
statJson["s"] = EMSESP::rxservice_.telegram_count();
statJson["f"] = EMSESP::rxservice_.telegram_error_count();
statJson["q"] = EMSESP::rxservice_.quality();
statJson = statsJson.createNestedObject();
statJson = statsJson.add<JsonObject>();
statJson["id"] = 1;
statJson["s"] = EMSESP::txservice_.telegram_read_count();
statJson["f"] = EMSESP::txservice_.telegram_read_fail_count();
statJson["q"] = EMSESP::txservice_.read_quality();
statJson = statsJson.createNestedObject();
statJson = statsJson.add<JsonObject>();
statJson["id"] = 2;
statJson["s"] = EMSESP::txservice_.telegram_write_count();
statJson["f"] = EMSESP::txservice_.telegram_write_fail_count();
statJson["q"] = EMSESP::txservice_.write_quality();
if (EMSESP::sensor_enabled()) {
statJson = statsJson.createNestedObject();
statJson = statsJson.add<JsonObject>();
statJson["id"] = 3;
statJson["s"] = EMSESP::temperaturesensor_.reads() - EMSESP::temperaturesensor_.fails();
statJson["f"] = EMSESP::temperaturesensor_.fails();
@@ -155,21 +155,21 @@ void WebStatusService::webStatusService(AsyncWebServerRequest * request) {
EMSESP::temperaturesensor_.reads() == 0 ? 100 : 100 - (uint8_t)((100 * EMSESP::temperaturesensor_.fails()) / EMSESP::temperaturesensor_.reads());
}
if (EMSESP::analog_enabled()) {
statJson = statsJson.createNestedObject();
statJson = statsJson.add<JsonObject>();
statJson["id"] = 4;
statJson["s"] = EMSESP::analogsensor_.reads() - EMSESP::analogsensor_.fails();
statJson["f"] = EMSESP::analogsensor_.fails();
statJson["q"] = EMSESP::analogsensor_.reads() == 0 ? 100 : 100 - (uint8_t)((100 * EMSESP::analogsensor_.fails()) / EMSESP::analogsensor_.reads());
}
if (Mqtt::enabled()) {
statJson = statsJson.createNestedObject();
statJson = statsJson.add<JsonObject>();
statJson["id"] = 5;
statJson["s"] = Mqtt::publish_count() - Mqtt::publish_fails();
statJson["f"] = Mqtt::publish_fails();
statJson["q"] = Mqtt::publish_count() == 0 ? 100 : 100 - (uint8_t)((100 * Mqtt::publish_fails()) / Mqtt::publish_count());
}
statJson = statsJson.createNestedObject();
statJson = statsJson.add<JsonObject>();
statJson["id"] = 6;
statJson["s"] = WebAPIService::api_count(); // + WebAPIService::api_fails();
statJson["f"] = WebAPIService::api_fails();
@@ -179,7 +179,7 @@ void WebStatusService::webStatusService(AsyncWebServerRequest * request) {
#ifndef EMSESP_STANDALONE
if (EMSESP::system_.syslog_enabled()) {
statJson = statsJson.createNestedObject();
statJson = statsJson.add<JsonObject>();
statJson["id"] = 7;
statJson["s"] = EMSESP::system_.syslog_count();
statJson["f"] = EMSESP::system_.syslog_fails();