Simvik

Build an MQTT PUBLISH packet

Encode a PUBLISH with its fixed header, variable-length size, topic and payload. A medium embedded C problem (MQTT), run and graded in the browser.

medium · MQTT · mqtt · packets · encoding

An MQTT PUBLISH packet (QoS 0) is:

  1. a fixed-header byte: 0x30, plus 0x01 if retain is set,
  2. the remaining length (the size of everything after it) as a variable-length integer: 7 bits per byte, least significant group first, with bit 7 set on every byte except the last (1 to 4 bytes),
  3. the topic: a 2-byte big-endian length, then its characters,
  4. the payload bytes (no length: it is whatever remains).

Write mqtt_publish(topic, payload, plen, retain, out), returning the packet size.

Starter code

int mqtt_publish(const char *topic, const uint8_t *payload, int plen, int retain, uint8_t *out) {
  int tlen = (int)strlen(topic);
  int n = 0;
  out[n++] = 0x30;
  out[n++] = (uint8_t)(tlen + plen);
  out[n++] = (uint8_t)tlen;
  memcpy(out + n, topic, (size_t)tlen); n += tlen;
  memcpy(out + n, payload, (size_t)plen); n += plen;
  (void)retain;
  return n;
}

Example tests

A small reading

show("t/1", "21.5", 0);

Expected output:

11 bytes: 30 09 00 03 74 2F 31 32 31 2E 35

Retained

show("status", "online", 1);

Expected output:

16 bytes: 31 0E 00 06 73 74 61 74 75 73 6F 6E ...

Learn it first

  • MQTT · Publish/subscribe, topics, wildcards, QoS, retained messages and wills.

More MQTT problems