Prototyping · Study deck

Reference: IoT Code Pattern Library

Picture a learner copying a sensor example that works once on a desk.

Voltage Vera is your guide for this deck.

codepatternlibrary
iotclass.org

After studying this chapter

Learning objectives

You will be able to:

  • Implement common IoT code patterns for sensor reading, MQTT messaging, and HTTP communication on ESP32
  • Use JSON serialization and ring buffers for efficient IoT data handling
  • Configure BLE beacons and LoRa point-to-point communication for wireless IoT projects
  • Implement common ESP32/Arduino patterns for sensor reading, MQTT messaging, and HTTP communication
iotclass.org

Major section

Start With the Behavior to Prove

In the project, the pin differs, the reply arrives late, and a missing field causes a restart.

  • Code that runs is not yet code that fits the new boundary.
  • A protocol is an agreed set of message and timing rules.
  • Bluetooth Low Energy (BLE) is a short-range radio system.
  • Hardware, libraries, and field conditions differ.
iotclass.org

Major section

Start With the Behavior to Prove (continued)

Hypertext Transfer Protocol (HTTP) carries web requests and replies.

  • JavaScript Object Notation (JSON) is a text shape for named data.
  • Message Queuing Telemetry Transport (MQTT) carries named messages through a service.
  • This process does not make a snippet production-ready.
  • A snippet should prove one behavior before it becomes project code.
iotclass.org

Major section

Snippets Are Starting Points

A snippet is not a finished design record.

  • Even a short DHT22 example carries assumptions about sampling interval and invalid reads.
  • A PubSubClient example carries assumptions about broker reachability, keepalive timing, topic policy, client identity, and payload length.
  • The library is therefore organized for transfer, not blind copying.

Key terms

When that proof
When that proof is missing, the snippet is still a learning aid, but it has not yet become project code.
Safe snippet reuse keeps the example inside a route of boundaries, retries, tests, and evidence rather than treating pasted code as proof.
Safe snippet reuse keeps the example inside a route of boundaries, retries, tests, and evidence rather than treating pasted code as proof.
iotclass.org

Major section

Adapt One Boundary at a Time

Logic-analyzer traces can prove an I2C or SPI transaction is actually leaving the board.

  • The safest way to reuse snippets is to change one boundary, run it, and inspect the result before moving to the next boundary.
  • For I2C scanner code, confirm pullups, SDA/SCL pins, bus speed, address conflicts, and whether Wi-Fi is using ESP32 ADC or bus resources.
  • ArduinoJson Assistant can size JSON documents before heap pressure appears on the board.

Key terms

Measured current traces
Measured current traces are the only reliable way to check whether a sleep snippet saves the power it claims to save.
iotclass.org

Major section

Adapt One Boundary at a Time (continued)

For MQTT or HTTP snippets, confirm client ID, topic policy, QoS choice, timeout, retry delay, TLS need, and payload size.

  • If several of those change at once, a failure no longer tells you where the real mismatch lives.
  • PlatformIO or Arduino IDE can pin board and library versions, which keeps a working example reproducible after the next library update.
  • PubSubClient buffer settings should be checked before a payload is blamed on the broker.
iotclass.org

Major section

Adapt One Boundary at a Time (continued)

Broker logs and Wireshark captures show whether MQTT, HTTP, DNS, TCP, and TLS are failing in the firmware, the network, or the server.

  • Measured current traces are the only reliable way to check whether a sleep snippet saves the power it claims to save.
  • As the snippet grows, move magic values out of the example body and into a visible configuration boundary: pins, topics, endpoints, thresholds, retry limits, and sleep intervals should be easy to review.
  • ESP32 deep-sleep wake reasons should be logged before a wakeup path is trusted.
iotclass.org

Major section

Snippets Hide State Boundaries

Small snippets look linear, but IoT behavior is stateful.

  • Each boundary can succeed in isolation while the whole device still fails under timing, network, or power pressure.
  • The hidden boundary is ownership.
  • The learner owns hardware limits, credentials, timing, error handling, security, logging, and maintainability.
  • The state-machine view helps explain why.
iotclass.org

Major section

Snippets Hide State Boundaries (continued)

A production path must replace placeholder credentials, public brokers, blocking loops, unbounded retries, and demo delays with project-specific configuration, timeouts, observability, and failure handling.

  • A reliable device is usually not "read sensor, publish, delay" forever.
  • Interrupts, timers, queues, and network callbacks may enter that state machine at awkward times.
  • Without bounded retries, a radio outage can turn into a battery drain.
  • Without input validation, one malformed payload can poison downstream logic.
iotclass.org

Deck summary

Key takeaways

In the project, the pin differs, the reply arrives late, and a missing field causes a restart.

  • Hypertext Transfer Protocol (HTTP) carries web requests and replies.
  • A snippet is not a finished design record.
  • Logic-analyzer traces can prove an I2C or SPI transaction is actually leaving the board.
  • For MQTT or HTTP snippets, confirm client ID, topic policy, QoS choice, timeout, retry delay, TLS need, and payload size.
iotclass.org

Retrieval practice

Recall check 1 of 3

Voltage Vera says: answer from memory, then check your reasoning.

Q1A learner finds a code snippet that almost matches their project. What should they do?

AMatch board and library names, then reuse without hardware tests.
BSkip testing because the borrowed snippet appears simple.
CDelete its comments so assumptions cannot slow implementation.
DTest on project hardware and record the snippet's reuse assumptions.
Show answer

Answer: D Code snippets should be adapted, tested, and documented before they become project code.

Q2Complete the robust sensor reading with retry pattern:

Aif is_valid(value):
Bif value is not None:
Cif value > 0:
Dif value:
Show answer

Answer: A Robust sensor reading combines validation (is_valid checks physical plausibility) with specific exception handling (SensorError) and progressive backoff between retries.

iotclass.org

Retrieval practice

Recall check 2 of 3

Voltage Vera says: answer from memory, then check your reasoning.

Q3You find an MQTT code snippet that publishes hospital heart-rate alerts using QoS 0. Which change first addresses the risk that a publish is silently lost on an MQTT delivery hop?

AChange the broker URL from localhost to a cloud MQTT broker
BAdd TLS encryption to protect patient health data in transit
CUse QoS 1 or 2 so heart-rate alerts are acknowledged
DIncrease the publishing frequency from every 30 seconds to every 5 seconds
Show answer

Answer: C QoS 1 or 2 adds MQTT delivery acknowledgements on each sender-to-receiver hop.

iotclass.org

Retrieval practice

Recall check 3 of 3

Voltage Vera says: answer from memory, then check your reasoning.

Q4Complete the MQTT broker message routing function:

Atopic_parts = msg.topic.split('/')
Btopic_parts = msg.topic.split('.')
Ctopic_parts = msg.topic
Dtopic_parts = msg.split('/')
Show answer

Answer: A MQTT message routing parses the topic hierarchy with split('/'), decodes the binary payload to JSON, extracts the device ID from the topic path, and republishes to a processed topic.

iotclass.org

Print reference

Answers

Answer key.

  1. D · Code snippets should be adapted, tested, and documented before they become project code.
  2. A · Robust sensor reading combines validation (is_valid checks physical plausibility) with specific exception handling (SensorError) and progressive backoff between retries.
  3. C · QoS 1 or 2 adds MQTT delivery acknowledgements on each sender-to-receiver hop.
  4. A · MQTT message routing parses the topic hierarchy with split('/'), decodes the binary payload to JSON, extracts the device ID from the topic path, and republishes to a processed topic.
iotclass.org