Free stage 1 of 3: runs on your computer.
This is one piece of the broker that keeps a greenhouse of a thousand sensors talking to its grower.
Stage 1: Accept a connection
Your broker listens on a TCP port, reads a CONNECT packet and answers with a CONNACK.
Why it matters
A greenhouse has a thousand sensors, and none of them talks to the grower's software directly. They all connect to one broker. If that broker cannot accept a connection, nothing else in the system can work: no readings, no alerts, no dashboard. This stage builds that front door.
Your task
- Listen on the port given by the
MQTT_PORTenvironment variable (1883if it is unset). - Accept connections. A client that connects and hangs up without sending a byte must not crash your broker (the tester does exactly that to find out when your port is open).
- Read the first packet.
- If it is not a
CONNECT: close the connection without replying. - If its protocol level is not
4(MQTT 3.1.1): reply with aCONNACKcarrying return code0x01("unacceptable protocol version"), then close the connection. - Otherwise reply with
CONNACKaccepted and keep the connection open.
- If it is not a
A CONNACK is always 4 bytes:
20 packet type 2 (CONNACK), flags 0
02 remaining length: 2 bytes follow
00 session present flag (always 0 for now)
00 return code: 0 = accepted, 1 = unacceptable protocol version
Run the tests
iotbricks test local --stage 1 --run ./iotbricks-mqtt-go
For this stage you may assume one conn.Read / recv returns the whole CONNECT. Stage 2 is
about why that assumption is wrong.
Hints
Hint 1: reading the packet type
The first byte of every MQTT packet holds the packet type in its high 4 bits and flags in its low
4 bits. CONNECT is type 1, so its first byte is 0x10. CONNACK is type 2: 0x20.
Hint 2: finding the protocol level
A CONNECT starts with the protocol name as an MQTT string (2-byte length, then bytes), which is
00 04 4D 51 54 54 for "MQTT". The protocol level is the single byte right after it.
Hint 3: the flow
accept connection
read the first packet
if type != CONNECT -> close
if protocol level != 4 -> write 20 02 00 01, close
write 20 02 00 00
keep reading until the client leaves
1Install the iotbricks CLI
curl -fsSL https://iotbricks.dev/install.sh | sh
2Run the tests on your broker
iotbricks test local --stage 1 --run ./iotbricks-mqtt-go
--run is the command that starts your broker, for example --run "go run .". The broker must listen on the port in the MQTT_PORT environment variable (default 1883).