Master the fundamental concepts of protocol implementation through this focused micro-challenge.
You have read the whole brief, and the concepts above stay free on every task. Writing and running the code needs a plan.
Three hints are available for this task, revealed one at a time inside the code workspace so you can struggle productively before seeing them.
Every task includes starter code, theory, and hidden tests so you can implement and verify locally in the browser.
How it worksMQTT runs over TCP port 1883 (or 8883 with TLS). Every packet starts with a fixed header of 2-5 bytes. For example, a CONNECT packet has type nibble 1 in the high bits of byte 0, plus a variable-length "remaining length" field encoding how many bytes follow.
Common control packet types:
1): client requests connection, carries protocol name "MQTT" and level 4 for v3.1.12): server acknowledges3): message to a topic like sensors/temp8): client requests topic filters with QoS levelsThe variable header adds fields like packet identifier, connect flags, and keep-alive interval (e.g. 60 seconds). The payload carries client ID, credentials, topic names, and message data.
Each byte uses 7 data bits plus a continuation bit. Value 321 encodes as two bytes: 0xC1 0x02.
This task requires you to build MQTT CONNECT and PUBLISH packets. Mosquitto and AWS IoT Core parse this exact fixed-header format from millions of battery-powered sensors where minimal framing overhead matters on cellular links.
QoS levels add delivery guarantees: 0 is fire-and-forget, 1 is at-least-once with PUBACK, 2 is exactly-once with a four-step handshake.
Write a C program that encodes an MQTT 3.1.1 PUBLISH packet (spec section 3.3) from parameters read on stdin.
Input (whitespace/newline separated):
Output:
fixed_header= the fixed header byte(s) in hex: PUBLISH type 3 in the high nibble, then DUP/QoS/RETAIN flags in the low nibble (bit3=DUP, bits2-1=QoS, bit0=RETAIN), followed by the remaining-length varint bytes in hex. MQTT's variable-length encoding: 7 data bits per byte, least-significant-group first, continuation bit 0x80 set on every byte except the last (e.g. 321 encodes as C1 02)remaining_length=N bytes=K where N is the remaining length in bytes, 2-byte big-endian topic length + topic + (2-byte packet identifier only when QoS > 0) + payload, and K is how many varint bytes encode N (1 to 4)topic_len=N: topic length in bytesNo sockets needed: this is pure packet-encoding arithmetic. MQTT 3.1.1 spec section 2.2.3 defines the remaining-length encoding.