Smart thermostat: publish its state
Build the MQTT topic and JSON payload for the thermostat's state, refusing anything that would not fit. A medium embedded C problem (MQTT), run and graded in…
medium · MQTT · mqtt · snprintf · json · product
Product: Smart thermostat (Smart home)
Requirement. The thermostat publishes its state for the home hub. A truncated topic or payload would be published to the wrong place or fail to parse, so it must never be sent: report it instead.
Write the topic home/<room>/thermostat/state into topic and the payload, for example {"temp":21.5,"target":22.0,"heating":true}, into payload. Temperatures are given in tenths of a degree and printed with one decimal, including below zero (-0.5).
Return the payload's length, or -1 if either string does not fit its buffer (tsize and psize bytes, including the terminating zero).
Starter code
int build_state(char *topic, size_t tsize, char *payload, size_t psize,
const char *room, int16_t temp_c10, int16_t target_c10, bool heating) {
sprintf(topic, "home/%s/thermostat/state", room);
return sprintf(payload, "{\"temp\":%d.%d,\"target\":%d.%d,\"heating\":%s}", temp_c10 / 10, temp_c10 % 10,
target_c10 / 10, target_c10 % 10, heating ? "true" : "false");
}Example tests
A warm kitchen
char topic[64], payload[64];
int n = build_state(topic, sizeof topic, payload, sizeof payload, "kitchen", 215, 220, true);
printf("%s\n%s\n%d\n", topic, payload, n);Expected output:
home/kitchen/thermostat/state
{"temp":21.5,"target":22.0,"heating":true}
42A frosty garage
char topic[64], payload[64];
build_state(topic, sizeof topic, payload, sizeof payload, "garage", -5, 50, false);
printf("%s\n", payload);Expected output:
{"temp":-0.5,"target":5.0,"heating":false}Learn it first
- MQTT · Publish/subscribe, topics, wildcards, QoS, retained messages and wills.
More MQTT problems
- Build an MQTT PUBLISH packet · Encode a PUBLISH with its fixed header, variable-length size, topic and payload.