fix: accept form posts for manual sensor values

Accept form submissions alongside the existing JSON sensor value endpoint
for compatibility with the manual sensor use case discussed in PR #270.
Support named value and unnamed body parameters with strict numeric parsing
and bounded input lengths. Preserve authentication, unit conversion, MQTT
publication and noresponse handling.

Share payload trimming and numeric parsing between HTTP and MQTT instead
of maintaining separate parser implementations.

Refs #270
This commit is contained in:
Yurii committed 2026-11-29 05:43:51 +03:00
1 parent cc6131eac9
commit 8fba88636e
3 files changed
+148 -54

No files matched your search

-42
View File
@@ -6,10 +6,8 @@
#include <algorithm>
#include <atomic>
#include <bitset>
#include <cerrno>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <initializer_list>
#include <list>
@@ -308,46 +306,6 @@ static void publishState() {
publishMasterState();
}
static std::string_view trimPayload(std::string_view payload) {
const auto first = payload.find_first_not_of(" \t\r\n");
if (first == std::string_view::npos) {
return {};
}
return payload.substr(first, payload.find_last_not_of(" \t\r\n") - first + 1);
}
static std::optional<float> parseNumber(std::string_view payload, uint8_t bufferSize = 17) {
if (payload.empty() || bufferSize < 2) {
return std::nullopt;
}
// Long input is intentionally truncated to leave room for the terminating NUL.
payload = payload.substr(0, bufferSize - 1);
// strtof also accepts leading whitespace, '+' and hexadecimal numbers.
const char first = payload.front();
if ((first < '0' || first > '9') && first != '-' && first != '.') {
return std::nullopt;
}
if (payload.find_first_of("xX") != std::string_view::npos) {
return std::nullopt;
}
char buffer[bufferSize];
memcpy(buffer, payload.data(), payload.size());
buffer[payload.size()] = '\0';
char* end;
errno = 0;
const float parsed = std::strtof(buffer, &end);
if (end != buffer + payload.size() || !std::isfinite(parsed) || (errno == ERANGE && parsed == 0.0f)) {
return std::nullopt;
}
return parsed;
}
static bool isCommandValid(const std::string& topic, std::string_view payload) {
if (payload.empty()) {
return false;
+92 -12
View File
@@ -817,57 +817,137 @@ static void restApi() {
request->send(response);
}).addMiddleware(&authMiddleware);
// Set sensor value (JSON)
auto& sensorValueHandler = webServer->on(AsyncURIMatcher::exact("/api/sensor/value"), HTTP_POST, [](AsyncWebServerRequest *request, JsonVariant &requestDoc) {
if (upgrading || restartTask.scheduled() || restartTask.active()) {
return request->send(503);
}
if (!requestDoc.is<JsonObjectConst>() || !requestDoc.size()) {
} else if (!requestDoc.is<JsonObjectConst>() || !requestDoc.size()) {
return request->send(400);
} else if (!request->hasParam("id") || !requestDoc[S_VALUE].is<float>()) {
return request->send(400);
}
if (!request->hasParam("id")) {
return request->send(400);
}
// Read sensor value
const auto value = requestDoc[S_VALUE].as<float>();
requestDoc.clear();
// Parse sensor ID
const auto& id = request->getParam("id")->value();
const auto sensorId = Sensors::parseId(id.c_str());
if (!sensorId) {
return request->send(404);
}
if (!requestDoc[S_VALUE].is<float>()) {
return request->send(400);
}
const auto value = requestDoc[S_VALUE].as<float>();
requestDoc.clear();
// Try to set sensor value
if (!Sensors::setManualValueById(*sensorId, value, settings.system.unitSystem)) {
return request->send(400);
}
// Request MQTT publication
requestPublishMqttSensor(*sensorId);
// If the noresponse parameter is provided,
// simply return HTTP 201 with an empty body.
if (request->hasParam("noresponse")) {
return request->send(201);
}
// Get sensor snapshot for response
const auto sensor = Sensors::getSnapshot(*sensorId);
if (!sensor) {
return request->send(404);
}
// Prepare response
auto *response = new AsyncJsonResponse();
auto& responseDoc = response->getRoot();
toJson(sensor->settings, sensor->result, responseDoc);
// Send response
response->setLength();
response->setCode(201);
request->send(response);
});
sensorValueHandler.setMaxContentLength(1024);
sensorValueHandler.setMaxContentLength(64);
sensorValueHandler.addMiddleware(&authMiddleware);
// Set sensor value (form)
webServer->on(AsyncURIMatcher::exact("/api/sensor/value"), HTTP_POST, [](AsyncWebServerRequest *request) {
if (upgrading || restartTask.scheduled() || restartTask.active()) {
return request->send(503);
} else if (request->contentLength() > 64) {
return request->send(413);
} else if (!request->hasParam("id")) {
return request->send(400);
}
// Parse sensor ID
const auto& id = request->getParam("id")->value();
const auto sensorId = Sensors::parseId(id.c_str());
if (!sensorId) {
return request->send(404);
}
// Read POST payload
const auto* parameter = request->getParam(S_VALUE, true);
if (parameter == nullptr) {
parameter = request->getParam("body", true);
}
if (parameter == nullptr) {
return request->send(400);
}
// Validate payload length
const auto& text = parameter->value();
const auto payload = trimPayload(std::string_view(text.c_str(), text.length()));
if (payload.size() >= 17) {
return request->send(400);
}
// Parse numeric value
const auto value = parseNumber(payload.data(), payload.size());
if (!value) {
return request->send(400);
}
// Try to set sensor value
if (!Sensors::setManualValueById(*sensorId, *value, settings.system.unitSystem)) {
return request->send(400);
}
// Request MQTT publication
requestPublishMqttSensor(*sensorId);
// If the noresponse parameter is provided,
// simply return HTTP 201 with an empty body.
if (request->hasParam("noresponse")) {
return request->send(201);
}
// Get sensor snapshot for response
const auto sensor = Sensors::getSnapshot(*sensorId);
if (!sensor) {
return request->send(404);
}
// Prepare response
auto *response = new AsyncJsonResponse();
auto& responseDoc = response->getRoot();
toJson(sensor->settings, sensor->result, responseDoc);
// Send response
response->setLength();
response->setCode(201);
request->send(response);
}).addMiddleware(&authMiddleware);
// vars
webServer->on("/api/vars", HTTP_GET, [](AsyncWebServerRequest *request) {
// make response