Skip to content

Commit

Permalink
Rework reading & writing settings; add more commands for setting control
Browse files Browse the repository at this point in the history
  • Loading branch information
hg committed Nov 21, 2020
1 parent d596258 commit d637cb0
Show file tree
Hide file tree
Showing 12 changed files with 168 additions and 110 deletions.
19 changes: 15 additions & 4 deletions firmware/main/commands.cc
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,21 @@ static bool handleReadSettings(mqtt::Client &client, const mqtt::Message &msg) {
return true;
}

static bool handleWriteSetting(mqtt::Client &client, const mqtt::Message &msg,
const CommandArgs &args) {
static bool handleWriteSettings(mqtt::Client &client,
const mqtt::Message &msg) {
const esp_err_t err = appSettings.write();
const char *const resp =
err == ESP_OK ? "settings saved" : "could not write settings";
return client.send(msg.respTopic, resp);
}

static bool handleSetSetting(mqtt::Client &client, const mqtt::Message &msg,
const CommandArgs &args) {
if (args.size() != 3) {
client.send(msg.respTopic, "usage: setting/set name_no_spaces value_also");
return false;
}
const esp_err_t err = appSettings.write(args[1], args[2]);
const esp_err_t err = appSettings.set(args[1], args[2]);
if (err == ESP_OK) {
client.send(msg.respTopic, "setting set");
} else {
Expand Down Expand Up @@ -106,11 +114,14 @@ static bool handleMessage(mqtt::Client &client, const mqtt::Message &msg) {
return handleRestart(client, msg);
}
if (command == "setting/set") {
return handleWriteSetting(client, msg, tokens);
return handleSetSetting(client, msg, tokens);
}
if (command == "setting/get") {
return handleReadSettings(client, msg);
}
if (command == "setting/write") {
return handleWriteSettings(client, msg);
}
return handleUnknown(client, msg);
}

Expand Down
2 changes: 1 addition & 1 deletion firmware/main/dallas.hh
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
namespace ds {

struct TempSensor {
const char *name;
const char *const name;
const gpio_num_t pin;
const rmt_channel_t rxChan;
const rmt_channel_t txChan;
Expand Down
8 changes: 4 additions & 4 deletions firmware/main/measurement.cc
Original file line number Diff line number Diff line change
Expand Up @@ -63,16 +63,16 @@ bool Measurement::formatMsg(char *const buf, const size_t size) const {
switch (type) {
case MeasurementType::TEMPERATURE: {
constexpr auto tpl = R"({"dev":"%s","time":%ld,"sens":"%s","temp":%f})";
snprintf(buf, size, tpl, appSettings.devName, time, sensor, temp);
snprintf(buf, size, tpl, appSettings.devName.c_str(), time, sensor, temp);
return true;
}

case MeasurementType::PARTICULATES: {
constexpr auto tpl =
R"({"dev":"%s","time":%ld,"sens":"%s","std":{"pm1":%u,"pm2.5":%u,"pm10":%u},"atm":{"pm1":%u,"pm2.5":%u,"pm10":%u},"cnt":{"pm0.3":%u,"pm0.5":%u,"pm1":%u,"pm2.5":%u,"pm5":%u,"pm10":%u}})";
snprintf(buf, size, tpl, appSettings.devName, time, sensor, pm.std.pm1Mcg,
pm.std.pm2Mcg, pm.std.pm10Mcg, pm.atm.pm1Mcg, pm.atm.pm2Mcg,
pm.atm.pm10Mcg, pm.cnt.pm03Count, pm.cnt.pm05Count,
snprintf(buf, size, tpl, appSettings.devName.c_str(), time, sensor,
pm.std.pm1Mcg, pm.std.pm2Mcg, pm.std.pm10Mcg, pm.atm.pm1Mcg,
pm.atm.pm2Mcg, pm.atm.pm10Mcg, pm.cnt.pm03Count, pm.cnt.pm05Count,
pm.cnt.pm1Count, pm.cnt.pm2Count, pm.cnt.pm5Count,
pm.cnt.pm10Count);
return true;
Expand Down
30 changes: 16 additions & 14 deletions firmware/main/mqtt.cc
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,14 @@ esp_err_t Client::handleEvent(esp_mqtt_event_handle_t evt) {

case MQTT_EVENT_DATA: {
ESP_LOGI(logTag, "mqtt message received (id %d)", evt->msg_id);
auto *const msg = new Message{
std::string topic{evt->topic, static_cast<unsigned>(evt->topic_len)};
Message *const msg = new Message{
.id = evt->msg_id,
.topic = std::string{evt->topic, static_cast<unsigned>(evt->topic_len)},
.data = std::string{evt->data, static_cast<unsigned>(evt->data_len)}};
msg->respTopic = msg->isBroadcast() ? "response/*" : client.respTopic;
.topic = std::move(topic),
.respTopic = topic == "cmd/*" ? "response/*" : client.respTopic,
.data = std::string{evt->data, static_cast<unsigned>(evt->data_len)},
};

client.msgQueue.put(msg);
break;
}
Expand All @@ -52,21 +55,20 @@ esp_err_t Client::handleEvent(esp_mqtt_event_handle_t evt) {
return ESP_OK;
}

Client::Client(const char *const brokerUri, const char *const caCert,
const char *const username, const char *const password) {
cmdTopic = std::string{"cmd/"} + username;
respTopic = std::string{"response/"} + username;
cert = caCert;
event = xEventGroupCreate();
Client::Client(std::string_view brokerUri, std::string_view caCert,
std::string_view username, std::string_view password)
: cmdTopic{std::string{"cmd/"}.append(username)},
respTopic{std::string{"response/"}.append(username)}, cert{caCert},
event{xEventGroupCreate()} {

const esp_mqtt_client_config_t conf{
.event_handle = handleEvent,
.uri = brokerUri,
.username = username,
.password = password,
.uri = brokerUri.data(),
.username = username.data(),
.password = password.data(),
.keepalive = 30,
.user_context = this,
.cert_pem = caCert,
.cert_pem = caCert.data(),
};
handle = esp_mqtt_client_init(&conf);
configASSERT(handle);
Expand Down
22 changes: 10 additions & 12 deletions firmware/main/mqtt.hh
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,16 @@ enum class MqttState : EventBits_t {
};

struct Message {
int id;
std::string topic;
std::string respTopic;
std::string data;

[[nodiscard]] bool isBroadcast() const { return topic == "cmd/*"; }
const int id;
const std::string topic;
const std::string respTopic;
const std::string data;
};

class Client {
public:
Client(const char *brokerUri, const char *caCert, const char *username,
const char *password);
Client(std::string_view brokerUri, std::string_view caCert,
std::string_view username, std::string_view password);

Client(const Client &) = delete;

Expand All @@ -51,10 +49,10 @@ private:

Queue<Message *> msgQueue{10};
esp_mqtt_client_handle_t handle;
EventGroupHandle_t event;
const char *cert;
std::string cmdTopic;
std::string respTopic;
const std::string cmdTopic;
const std::string respTopic;
const std::string_view cert;
const EventGroupHandle_t event;
};

} // namespace mqtt
22 changes: 12 additions & 10 deletions firmware/main/net.cc
Original file line number Diff line number Diff line change
Expand Up @@ -81,24 +81,26 @@ void initWifi() {
ESP_ERROR_CHECK(esp_event_handler_instance_register(
IP_EVENT, ESP_EVENT_ANY_ID, handleIpEvent, nullptr, nullptr));

wifi_scan_threshold_t threshold{
.authmode = WIFI_AUTH_WPA2_PSK,
};

// connect to station
wifi_config_t wf_conf{
.sta{
.threshold = threshold,
.pmf_cfg{.capable = true, .required = false},
.threshold =
wifi_scan_threshold_t{
.authmode = WIFI_AUTH_WPA2_PSK,
},
.pmf_cfg{
.capable = true,
.required = false,
},
},
};

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstringop-truncation"
strncpy(reinterpret_cast<char *>(wf_conf.sta.ssid), appSettings.wifi.ssid,
sizeof(wf_conf.sta.ssid));
strncpy(reinterpret_cast<char *>(wf_conf.sta.password), appSettings.wifi.pass,
sizeof(wf_conf.sta.password));
strncpy(reinterpret_cast<char *>(wf_conf.sta.ssid),
appSettings.wifi.ssid.c_str(), sizeof(wf_conf.sta.ssid));
strncpy(reinterpret_cast<char *>(wf_conf.sta.password),
appSettings.wifi.pass.c_str(), sizeof(wf_conf.sta.password));
#pragma GCC diagnostic pop

ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
Expand Down
36 changes: 20 additions & 16 deletions firmware/main/pms.cc
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#include "pms.hh"
#include "common.hh"
#include "measurement.hh"
#include "settings.hh"
#include "state.hh"
#include "time.hh"
#include "timer.hh"
Expand All @@ -9,9 +10,6 @@
#include <cstring>
#include <numeric>

// delay between two particulate matter measurements
static const int delayPm = secToTicks(CONFIG_PARTICULATE_PERIOD_SECONDS);

namespace pms {

namespace cmd {
Expand All @@ -27,11 +25,11 @@ static constexpr Command initCmd(uint8_t cmd, uint8_t hi, uint8_t lo) {
};
}

static const Command cmdRead = initCmd(0xe2, 0x00, 0x00);
static const Command cmdModePassive = initCmd(0xe1, 0x00, 0x00);
static const Command cmdModeActive = initCmd(0xe1, 0x00, 0x01);
static const Command cmdSleep = initCmd(0xe4, 0x00, 0x00);
static const Command cmdWakeup = initCmd(0xe4, 0x00, 0x01);
static constexpr Command cmdRead = initCmd(0xe2, 0x00, 0x00);
static constexpr Command cmdModePassive = initCmd(0xe1, 0x00, 0x00);
static constexpr Command cmdModeActive = initCmd(0xe1, 0x00, 0x01);
static constexpr Command cmdSleep = initCmd(0xe4, 0x00, 0x00);
static constexpr Command cmdWakeup = initCmd(0xe4, 0x00, 0x01);

} // namespace cmd

Expand All @@ -41,15 +39,14 @@ uint16_t Response::calcChecksum() const {
}

void Response::swapBytes() {
std::transform(&frameLen, (&checksum) + 1, &frameLen,
[](uint16_t num) -> uint16_t { return ntohs(num); });
std::transform(&frameLen, (&checksum) + 1, &frameLen, &lwip_htons);
}

[[noreturn]] void Station::collectionTask(void *const arg) {
Station &station{*reinterpret_cast<Station *>(arg)};

Response res;
ResponseSum sum;
Response res{};
ResponseSum sum{};
Measurement ms{.type = MeasurementType::PARTICULATES, .sensor = station.name};

TickType_t lastWake = xTaskGetTickCount();
Expand All @@ -58,6 +55,7 @@ void Response::swapBytes() {
int sent = station.writeCommand(cmd::cmdWakeup);
if (sent != sizeof(cmd::cmdWakeup)) {
ESP_LOGE(logTag, "could not send wakeup command");
station.flushOutput(portMAX_DELAY);
vTaskDelay(secToTicks(1));
continue;
}
Expand Down Expand Up @@ -160,7 +158,7 @@ void Response::swapBytes() {
}
}

vTaskDelayUntil(&lastWake, delayPm);
vTaskDelayUntil(&lastWake, secToTicks(appSettings.period.pm));
}
}

Expand All @@ -174,8 +172,14 @@ int Station::writeCommand(const cmd::Command &cmd) {

esp_err_t Station::flushInput() { return uart_flush_input(port); }

esp_err_t Station::flushOutput(const TickType_t wait) {
return uart_wait_tx_done(port, wait);
}

void Station::start(Queue<Measurement> &msQueue) {
const uart_config_t conf{
queue = &msQueue;

constexpr uart_config_t conf{
.baud_rate = 9600,
.data_bits = UART_DATA_8_BITS,
.parity = UART_PARITY_DISABLE,
Expand All @@ -184,8 +188,8 @@ void Station::start(Queue<Measurement> &msQueue) {
.source_clk = UART_SCLK_APB,
};

const size_t rxBuf = sizeof(Response) * 10;
queue = &msQueue;
constexpr size_t rxBuf = sizeof(Response) * 10;
static_assert(rxBuf >= UART_FIFO_LEN);

ESP_ERROR_CHECK(uart_driver_install(port, rxBuf, 0, 0, nullptr, 0));
ESP_ERROR_CHECK(uart_param_config(port, &conf));
Expand Down
2 changes: 2 additions & 0 deletions firmware/main/pms.hh
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@ struct Station {

esp_err_t flushInput();

esp_err_t flushOutput(const TickType_t wait);

void start(Queue<Measurement> &msQueue);

private:
Expand Down
Loading

0 comments on commit d637cb0

Please sign in to comment.