Skip to content

Commit

Permalink
Enhancements/opmemoizations and optimizations (#526)
Browse files Browse the repository at this point in the history
  • Loading branch information
Zer0-bit authored Aug 2, 2023
2 parents fc7cfa5 + f0684a4 commit 6fac866
Show file tree
Hide file tree
Showing 26 changed files with 202 additions and 153 deletions.
2 changes: 1 addition & 1 deletion lib/Common/mcu_comms.h
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ enum class McuCommsMessageType : uint8_t {

// Commands
MCUC_CMD_REMOTE_SCALES_TARE = 16,
MCUC_CMD_UPDATE_OPERATION_MODE = 17,
MCUC_CMD_UPDATE_SYSTEM_STATE = 17,
};

struct McuCommsRequestData {
Expand Down
10 changes: 7 additions & 3 deletions lib/Common/proto/message_converters.h
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ class SystemStateConverter : public NanoPb::Converter::MessageConverter<SystemSt
.operationMode = OperationModeConverter::encode(local.operationMode),
.timeAlive = local.timeAlive,
.descaleProgress = local.descaleProgress,
.tarePending = local.tarePending,
};
};

Expand All @@ -70,24 +71,27 @@ class SystemStateConverter : public NanoPb::Converter::MessageConverter<SystemSt
local.operationMode = OperationModeConverter::decode(proto.operationMode);
local.timeAlive = proto.timeAlive;
local.descaleProgress = proto.descaleProgress;
local.tarePending = proto.tarePending;
return true;
};
};

class UpdateOperationModeConverter : public NanoPb::Converter::MessageConverter<UpdateOperationModeConverter, UpdateOperationMode, UpdateOperationModeDto, UpdateOperationModeDto_fields> {
class UpdateSystemStateComandConverter : public NanoPb::Converter::MessageConverter<UpdateSystemStateComandConverter, UpdateSystemStateComand, UpdateSystemStateComandDto, UpdateSystemStateComandDto_fields> {
public:
static ProtoType encoderInit(const LocalType& local) {
return UpdateOperationModeDto{
return UpdateSystemStateComandDto{
.operationMode = OperationModeConverter::encode(local.operationMode),
.tarePending = local.tarePending,
};
};

static ProtoType decoderInit(LocalType& local) {
return UpdateOperationModeDto{};
return UpdateSystemStateComandDto{};
};

static bool decoderApply(const ProtoType& proto, LocalType& local) {
local.operationMode = OperationModeConverter::decode(proto.operationMode);
local.tarePending = proto.tarePending;
return true;
};
};
Expand Down
4 changes: 3 additions & 1 deletion lib/Common/proto/messages.proto
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@ enum OperationModeDto {
FLUSH_AUTO = 5;
};

message UpdateOperationModeDto {
message UpdateSystemStateComandDto {
OperationModeDto operationMode = 1;
bool tarePending = 2;
}

message RequestDataDto {
Expand All @@ -25,6 +26,7 @@ message SystemStateDto {
OperationModeDto operationMode = 5;
uint32 timeAlive = 6;
uint32 descaleProgress = 7;
bool tarePending = 8;
}

message SensorStateSnapshotDto {
Expand Down
1 change: 0 additions & 1 deletion lib/Common/sensors_state.h
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ struct SensorState {
bool brewSwitchState;
bool steamSwitchState;
bool hotWaterSwitchState;
bool tarePending;
float temperature; // °C
/* calculated water temperature as wanted but not guaranteed
due to boiler having a hard limit of 4ml/s heat capacity */
Expand Down
4 changes: 3 additions & 1 deletion lib/Common/system_state.h
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,12 @@ struct SystemState {
bool scalesPresent = false;
uint32_t timeAlive = 0; // sec
uint8_t descaleProgress = 0; // %
bool tarePending = false;
};

struct UpdateOperationMode {
struct UpdateSystemStateComand {
OperationMode operationMode;
bool tarePending;
};

#endif
2 changes: 0 additions & 2 deletions platformio.ini
Original file line number Diff line number Diff line change
Expand Up @@ -115,8 +115,6 @@ build_flags =
; -DDEBUG_ENABLED
;if using a bigger boilr machine like Silvia set -DDREAM_STEAM_DISABLED in the extra_defines.ini
; Define the tof placeholder and init with 0
-DTOF_START=0
-DTOF_END=0
${extra.build_flags}
-DPIO_FRAMEWORK_ARDUINO_STANDARD_LIB
-DENABLE_HWSERIAL2
Expand Down
10 changes: 8 additions & 2 deletions src/gaggiuino.h
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,14 @@
#define SYS_PRESSURE_IDLE 0.7f // System pressure threshold at idle
#define MIN_WATER_LVL 10u // Min allowable tank water lvl

const uint16_t tofStartValue = TOF_START != 0u ? TOF_START : 15u; // Tof offset when tank is full
const uint16_t tofEndValue = TOF_END != 0u ? TOF_END : 125u; // Tof offset when tank is nearly empty
// If not defined in the extra_defines.ini use default range
#if not defined(TOF_START) || not defined(TOF_END)
#define TOF_START 15u
#define TOF_END 125u
#endif

const uint16_t tofStartValue = TOF_START; // Tof offset when tank is full
const uint16_t tofEndValue = TOF_END; // Tof offset when tank is nearly empty

//Timers
unsigned long systemHealthTimer;
Expand Down
15 changes: 8 additions & 7 deletions src/gaggiuino.ino
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ static void sensorsReadTemperature(void) {
}

static Measurement handleTaringAndReadWeight() {
if (!currentState.tarePending) { // No tare needed just get weight
if (!systemState.tarePending) { // No tare needed just get weight
return scalesGetWeight();
}

Expand All @@ -148,7 +148,7 @@ static Measurement handleTaringAndReadWeight() {
Measurement weight = scalesGetWeight();

if (fabsf(weight.value) < 0.5f) { // Tare was successful. return reading
currentState.tarePending = false;
systemState.tarePending = false;
return weight;
} else { // Tare was unsuccessful. return 0 weight.
return Measurement{ .value=0.f, .millis = millis()};
Expand All @@ -166,7 +166,7 @@ static void sensorsReadWeight(void) {
currentState.weight = weightMeasurements.getLatest().value;

if (brewActive) {
currentState.shotWeight = currentState.tarePending ? 0.f : currentState.weight;
currentState.shotWeight = systemState.tarePending ? 0.f : currentState.weight;

currentState.weightFlow = fmax(0.f, weightMeasurements.getMeasurementChange().speed());
currentState.smoothedWeightFlow = smoothScalesFlow.updateEstimate(currentState.weightFlow);
Expand Down Expand Up @@ -214,7 +214,7 @@ static void calculateWeightAndFlow(void) {

if (brewActive) {
// Marking for tare in case smth has gone wrong and it has exited tare already.
if (currentState.weight < -.3f) currentState.tarePending = true;
if (currentState.weight < -.3f) systemState.tarePending = true;

if (elapsedTime > REFRESH_FLOW_EVERY) {
flowTimer = millis();
Expand Down Expand Up @@ -341,8 +341,9 @@ void onManualBrewPhaseReceived(const Phase& phase) {
manualProfile.phases[0] = phase;
}

void onOperationModeReceived(const OperationMode operationMode) {
systemState.operationMode = operationMode;
void onUpdateSystemStateCommandReceived(const UpdateSystemStateComand& command) {
systemState.operationMode = command.operationMode;
systemState.tarePending = command.tarePending;
}

void onBoilerSettingsReceived(const BoilerSettings& boilerSettings) {
Expand Down Expand Up @@ -426,7 +427,7 @@ static void brewDetect(void) {
}

static void brewParamsReset(void) {
currentState.tarePending = true;
systemState.tarePending = true;
currentState.shotWeight = 0.f;
currentState.pumpFlow = 0.f;
currentState.weight = 0.f;
Expand Down
14 changes: 4 additions & 10 deletions src/peripherals/esp_comms.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -170,12 +170,6 @@ void handleMessageReceived(McuCommsMessageType messageType, std::vector<uint8_t>
onManualBrewPhaseReceived(phase);
break;
}
case McuCommsMessageType::MCUC_DATA_SYSTEM_STATE: {
UpdateOperationMode updateOperationMode = { OperationMode::BREW_AUTO };
ProtoSerializer::deserialize<UpdateOperationModeConverter>(data, updateOperationMode);
onOperationModeReceived(updateOperationMode.operationMode);
break;
}
case McuCommsMessageType::MCUC_DATA_BOILER_SETTINGS: {
BoilerSettings boilerSettings;
ProtoSerializer::deserialize<BoilerSettingsConverter>(data, boilerSettings);
Expand All @@ -200,10 +194,10 @@ void handleMessageReceived(McuCommsMessageType messageType, std::vector<uint8_t>
onBrewSettingsReceived(brewSettings);
break;
}
case McuCommsMessageType::MCUC_CMD_UPDATE_OPERATION_MODE: {
UpdateOperationMode command{ .operationMode = OperationMode::BREW_AUTO }; // init default
ProtoSerializer::deserialize<UpdateOperationModeConverter>(data, command);
onOperationModeReceived(command.operationMode);
case McuCommsMessageType::MCUC_CMD_UPDATE_SYSTEM_STATE: {
UpdateSystemStateComand command;
ProtoSerializer::deserialize<UpdateSystemStateComandConverter>(data, command);
onUpdateSystemStateCommandReceived(command);
break;
}
default: // Ignore message in all other cases
Expand Down
2 changes: 1 addition & 1 deletion src/peripherals/esp_comms.h
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ void onSystemSettingsReceived(const SystemSettings& systemSettings);
void onBrewSettingsReceived(const BrewSettings& brewSettings);

// System state updates
void onOperationModeReceived(const OperationMode operationMode);
void onUpdateSystemStateCommandReceived(const UpdateSystemStateComand& command);

// Profiling
void onProfileReceived(const Profile& profile);
Expand Down
9 changes: 6 additions & 3 deletions webserver/src/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ void onShotSnapshotReceived(const ShotSnapshot& shotData) {
wsSendShotSnapshotToClients(shotData);
}
void onSystemStateReceived(const SystemState& systemState) {
wsSendSystemStateToClients(systemState);
state::updateSystemState(systemState);
}
void onScalesTareReceived() {
LOG_INFO("STM sent tare command");
Expand Down Expand Up @@ -78,6 +78,9 @@ void state::onLedSettingsUpdated(const LedSettings& settings) {
void state::onSystemSettingsUpdated(const SystemSettings& settings) {
stmCommsSendSystemSettings(settings);
}
void state::onOperationModeUpdated(const OperationMode operationMode) {
stmCommsSendUpdateOperationMode(operationMode);
void state::onSystemStateUpdated(const SystemState& systemState) {
wsSendSystemStateToClients(systemState);
}
void state::onUpdateSystemStateCommandSubmitted(const UpdateSystemStateComand& command) {
stmCommsSendUpdateSystemState(command);
}
49 changes: 31 additions & 18 deletions webserver/src/server/api/api_system_state.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,39 +9,52 @@
#include "../../log/log.h"

// Gets and updates part of the settings object in memory.
void handleGetOperationMode(AsyncWebServerRequest* request);
void handleUpdateOperationMode(AsyncWebServerRequest* request, JsonVariant& json);
void handleGetSystemState(AsyncWebServerRequest* request);
void handleUpdateSystemStateOperationMode(AsyncWebServerRequest* request, JsonVariant& json);
void handleUpdateSystemStateTarePending(AsyncWebServerRequest* request, JsonVariant& json);

void setupSystemStateApi(AsyncWebServer& server) {
server.on("/api/system-state/operation-mode", HTTP_GET, handleGetOperationMode);
server.on("/api/system-state/operation-mode", HTTP_PUT, withJson(handleUpdateOperationMode), NULL, onJsonBody);
server.on("/api/system-state", HTTP_GET, handleGetSystemState);
server.on("/api/system-state/operation-mode", HTTP_PUT, withJson(handleUpdateSystemStateOperationMode), NULL, onJsonBody);
server.on("/api/system-state/tare-pending", HTTP_PUT, withJson(handleUpdateSystemStateTarePending), NULL, onJsonBody);
}

// ------------------------------------------------------------------------------------------
// ------------------------------------- GET METHODS ----------------------------------------
// ------------------------------------------------------------------------------------------

void handleGetOperationMode(AsyncWebServerRequest* request) {
void systemStateResponse(AsyncWebServerRequest* request, JsonObject json, int code = 200) {
AsyncResponseStream* response = request->beginResponseStream("application/json");
response->setCode(code);

json::mapSystemStateToJson(state::getSystemState(), json);
serializeJson(json, *response);

request->send(response);
}

void handleGetSystemState(AsyncWebServerRequest* request) {
LOG_INFO("Got request get operation mode");

AsyncResponseStream* response = request->beginResponseStream("application/json");
DynamicJsonDocument json(100);
DynamicJsonDocument json(512);
JsonObject jsonObj = json.to<JsonObject>();
jsonObj["operationMode"] = json::mapOperationModeToJsonValue(state::getOperationMode());
systemStateResponse(request, jsonObj, 200);
}

response->setCode(200);
serializeJson(jsonObj, *response);
request->send(response);
void handleUpdateSystemStateTarePending(AsyncWebServerRequest* request, JsonVariant& body) {
LOG_INFO("Got request to update operation mode");

state::updateTarePending(body["tarePending"]);

JsonObject responseBody = body.to<JsonObject>();
systemStateResponse(request, responseBody, 200);
}

void handleUpdateOperationMode(AsyncWebServerRequest* request, JsonVariant& body) {
void handleUpdateSystemStateOperationMode(AsyncWebServerRequest* request, JsonVariant& body) {
LOG_INFO("Got request to update operation mode");

AsyncResponseStream* response = request->beginResponseStream("application/json");
UpdateOperationMode command = json::mapJsonToUpdateOperationMode(body);
state::updateOperationMode(command.operationMode);
state::updateOperationMode(json::mapJsonValueToOperationMode(body["operationMode"]));

response->setCode(200);
serializeJson(body, *response);
request->send(response);
JsonObject responseBody = body.to<JsonObject>();
systemStateResponse(request, responseBody, 200);
}
11 changes: 7 additions & 4 deletions webserver/src/server/json/json_system_state_converters.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,9 @@ namespace json {
}
}

void mapUpdateOperationModeToJson(const UpdateOperationMode& updateOperationMode, JsonObject& target) {
target["operationMode"] = mapOperationModeToJsonValue(updateOperationMode.operationMode);
void mapUpdateSystemStateCommmandToJson(const UpdateSystemStateComand& command, JsonObject& target) {
target["operationMode"] = mapOperationModeToJsonValue(command.operationMode);
target["tarePending"] = command.tarePending;
}

void mapSensorStateToJson(const SensorStateSnapshot& sensorState, JsonObject& target) {
Expand Down Expand Up @@ -71,9 +72,10 @@ namespace json {
return OperationMode::BREW_AUTO;
}

UpdateOperationMode mapJsonToUpdateOperationMode(const JsonObject& json) {
return UpdateOperationMode{
UpdateSystemStateComand mapJsonToUpdateSystemStateCommand(const JsonObject& json) {
return UpdateSystemStateComand{
.operationMode = mapJsonValueToOperationMode(json["operationMode"]),
.tarePending = json["tarePending"],
};
}

Expand All @@ -86,6 +88,7 @@ namespace json {
systemState.scalesPresent = json["scalesPresent"];
systemState.timeAlive = json["timeAlive"];
systemState.descaleProgress = json["descaleProgress"];
systemState.tarePending = json["tarePending"];
return systemState;
}
}
4 changes: 2 additions & 2 deletions webserver/src/server/json/json_system_state_converters.h
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ namespace json {
// ------------------------------------------------------------------------------------------
std::string mapOperationModeToJsonValue(const OperationMode& mode);
void mapSystemStateToJson(const SystemState& systemState, JsonObject& target);
void mapUpdateOperationModeToJson(const UpdateOperationMode& updateOperationMode, JsonObject& target);
void mapUpdateSystemStateCommmandToJson(const UpdateSystemStateComand& command, JsonObject& target);
void mapSensorStateToJson(const SensorStateSnapshot& sensorState, JsonObject& target);
void mapShotSnapshotToJson(const ShotSnapshot& shotSnaposhot, JsonObject& target);

Expand All @@ -21,6 +21,6 @@ namespace json {
// ------------------------------------------------------------------------------------------
OperationMode mapJsonValueToOperationMode(const std::string& modeValue);
SystemState mapJsonToSystemState(const JsonObject& json);
UpdateOperationMode mapJsonToUpdateOperationMode(const JsonObject& json);
UpdateSystemStateComand mapJsonToUpdateSystemStateCommand(const JsonObject& json);
}
#endif
25 changes: 19 additions & 6 deletions webserver/src/state/state.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,12 @@ namespace state {
GaggiaSettings currentSettings;
Profile activeProfile;
ProfileId activeProfileId;
OperationMode operationMode;
SystemState systemState;

void init() {
currentSettings = persistence::getSettings();
activeProfileId = persistence::getActiveProfileId();
activeProfile = persistence::getProfile(activeProfileId).second;
operationMode = OperationMode::BREW_AUTO;

LOG_INFO("Initialized state. s.hpwr=%d, apId=%d, ap.name=%s", currentSettings.boiler.hpwr, activeProfileId, activeProfile.name.c_str());
}
Expand Down Expand Up @@ -99,12 +98,26 @@ namespace state {
// ---------------------------------------------------------------------------------
// -------------------------------- SYSTEM_STATE -----------------------------------
// ---------------------------------------------------------------------------------
OperationMode getOperationMode() {
return operationMode;
SystemState getSystemState() {
return systemState;
}

void updateSystemState(const SystemState& newState) {
systemState = newState;
onSystemStateUpdated(systemState);
}

void sumitUpdateSystemStateCommand(const UpdateSystemStateComand& command) {
systemState.tarePending = command.tarePending;
systemState.operationMode = command.operationMode;
onUpdateSystemStateCommandSubmitted(command);
}

void updateTarePending(bool tarePending) {
sumitUpdateSystemStateCommand({ .operationMode = systemState.operationMode, .tarePending = tarePending });
}

void updateOperationMode(OperationMode operationMode) {
state::operationMode = operationMode;
onOperationModeUpdated(state::operationMode);
sumitUpdateSystemStateCommand({ .operationMode = operationMode, .tarePending = systemState.tarePending });
}
}
Loading

0 comments on commit 6fac866

Please sign in to comment.