Skip to main content
PSUT / IoTEngineering learning studio
WORKSPACE
Offline-first portalDr. Mohammad Alja’afreh
Embedded Systems StudioIoT Programming and ApplicationsExperimentsWorkspaces
ENGINEERING WORKSPACE
Home/WSL Laboratories/Lab 12 · MQTT publisher
IoTPSUT IoT Engineering StudioPrincess Sumaya University for Technology · Dr. Mohammad Alja’afreh
Pi practical / X12
IoT Programming and Applications

Lab 12 · MQTT publisher

Ask Dr. Mohammad · X12 →

Mosquitto runs in WSL; MQTT Explorer on Windows can connect to localhost:1884 .

Open MQTT packet analyzer →

Design experiment & verify evidence →
X12 · Laboratory mentorAsk about the current experiment, its algorithms or Python notebook.
Ask Dr. MohammadAdaptive practice
Learning workflow · Core IoT & programmingX12 · MQTT publisher
Readiness checksRevision deckEngineering workspaceRecord evidence

Related course access: IoT Security and Privacy · Networking and Communication — same laboratory, notebook and completion record.

X12 · Academic orientation

Scope and objectives

Scope of the experiment

Trace publisher-side connection and completion conditions independently of subscriber receipt.

The focus of this experiment is to trace an MQTT publisher from connection to a topic and payload. Students then distinguish QoS, acknowledgement and reconnect behavior, and verify publication on a matching authorized subscription. The Concepts view explains the operation before the practical work; the Simulation view is used to examine reference and changed inputs, not to substitute for actual measurements.

Learning objectives

  • Trace an MQTT publisher from connection to a topic and payload.
  • Distinguish QoS, acknowledgement and reconnect behavior.
  • Verify publication on a matching authorized subscription.
  • Record the relevant inputs, intermediate states and final verification result before changing the reference configuration.
  • Compare the reference calculation or decision with an independent implementation or authorized observation; state any discrepancy and the applicable model boundary.

Expected learning outcomes

On completion, students can trace an MQTT publisher from connection to a topic and payload, distinguish QoS, acknowledgement and reconnect behavior, and verify publication on a matching authorized subscription.

Required deliverables

Submit the derivation or state trace for the named operation, the exact reference and changed configurations, the associated simulator or practical evidence, and a short validation statement addressing verify publication on a matching authorized subscription. Separate predicted values from observations.

Prerequisite knowledge and related learning

Review the following catalogue prerequisites before starting. After completion, continue to Lab 13 · MQTT subscriber.

Environment and experimental methodology

Browser teaching model, the named WSL or Python environment, and the physical board/components only for the hardware activity described in the practical instructions.

Begin with a manual prediction, record the baseline, change one independent condition at a time, and compare the resulting trace or measurements with the original prediction. Record observations and uncertainty separately from reference values. Follow the experiment’s specific procedure, safety limits, and acceptance checks.

X12 / PREPARE

Before starting

Follow the setup guide and use the named terminal or editor. A browser model is not a real GPIO measurement or a running service.

Ubuntu WSL setup →
Before you run / verification gate

Use one profile in both terminals, ensure subscriber is ready, send five mock messages, check topic and payload, then stop subscriber. Dashboard is a separate check.

CONCEPTS / ACTIVE RECALL

Understand the experiment

MQTT QoS 1 · lost acknowledgment

At-least-once delivery permits duplicates after retransmission
At-least-once delivery permits duplicates after retransmission

Scientific architecture · MQTT publisher topic, QoS and acknowledgement

MQTT QoS 1 publisher — Publisher; Broker; Subscriber; CONNECT / 0>1; CONNACK / 1>0; PUBLISH QoS1 / 0>1; PUBACK / 1>0; Route message / 1>2
Scientific concept map: Publisher — Payload and topic; MQTT CONNECT — Session; PUBLISH — QoS selection; Broker — Route or reject; Acknowledgment — QoS-dependent.

Scientific foundations and analytical reasoning

MQTT QoS 0 is at-most-once; QoS 1 is at-least-once and permits duplicates. Delivery acknowledgment is not subscriber processing acknowledgment.

Before operating the equipment or executing the program, derive the expected outcome using the required theoretical work in Experiment. Use the diagram to identify the variables and system boundaries.

Scientific theory · MQTT publication and delivery levels

MQTT is a broker-mediated protocol. QoS 0 sends without the QoS 1 acknowledgment exchange; QoS 1 uses packet identifiers and PUBACK, permitting redelivery and duplicates. Broker acknowledgment is not proof the subscriber stored the data. Application IDs enable idempotent processing.

Worked example and engineering interpretation

If one of five logical publications is delivered twice, the subscriber may observe six deliveries but only five unique sample IDs. Record publish attempts, acknowledgments and unique records. Use local or approved broker credentials and distinct topics.

Engineering principles · additional worked teaching example

MQTT QoS 0 has no delivery acknowledgment; QoS 1 provides at-least-once delivery, so retransmission can cause duplicates. If 3 distinct QoS1 publications each need one attempt and one is retransmitted, four transmissions may yield four deliveries but only three distinct messages.

From theory to experiment

Predict the reference result before operating the workbench; check the actual intermediate state, units and constraints. The existing simulation, implementation and procedure below are distinct sources of evidence.

How to investigate Lab 12 · MQTT publisher

An MQTT publisher establishes a session, publishes bytes on an exact topic and receives PUBACK for QoS 1. PUBACK confirms broker acceptance, not necessarily subscriber processing.

Analytical investigation means collecting an observation, identifying the mechanism, using a calculation or state trace to explain it, and checking your conclusion against evidence. Controlled comparison means changing one independent variable, holding the remaining relevant conditions constant, and measuring a dependent variable against a baseline. Experimental validation means comparing a predicted result to a reproducible observation or assertion; agreement inside a model does not certify hardware. Evidence-based reasoning connects a specific observation to a theoretical rule and states uncertainty, not merely an opinion. Performance characterization records a named metric and its units across conditions; sensitivity analysis changes one parameter across several values. A threat assessment links an asset, threat, consequence and evidence to a mitigation.

Experiment-specific guided practice

Objective: Publish MQTT telemetry using a consistent broker and topic.

  1. With QoS 0 select data loss and send. Compare application and delivered counts.
  2. Select QoS 1 and repeat; compare bounded retry and PUBACK.
  3. Select ACK loss and send. Compare deliveries and distinct sequence IDs.
  4. Disconnect, send, restore; then execute original QoS 1 publisher and check publish completion.

Reference check:

Model boundary:

Independent task and submission evidence

Change the message count from 3 to 5, keeping the exact topic fixed. Record sequence IDs and confirmed publishes. Explain why PUBACK does not prove a dashboard received data.

Before execution write the independent variable and its levels, dependent observation with units where applicable, baseline, controlled variables, measurement method and expected result. For a state machine use state/event/output rather than inventing a numeric metric. Record failures and repeat the baseline. A weak conclusion is “it works”; a supported conclusion names the changed setting, observed value/state, corresponding rule and one limitation.

TrialChanged settingFixed settingsPredicted resultActual observation / unitsEvidence / uncertainty
A: baselineReferenceRecordPredictRecordRecord
B: one changeRecordSame as APredictRecordRecord
A: repeatRestoreSame as APredictRecordRecord

Completion: submit the filled table, relevant simulator screenshot or terminal/notebook output, reasoning with units/assumptions, and one limitation. Preserve the independent assessment questions; this guide does not fill their answers.

Worked engineering reasoning and boundary conditions

MQTT publisher sends a topic and payload to broker; QoS 0 has no protocol ACK, QoS 1 uses PUBACK and can duplicate, QoS 2 has four-stage delivery handshake. QoS describes each protocol leg, not sensor accuracy. Example 10 intended publications and 8 observed completions means 80% completion in that model.

Use the diagram to follow the calculation or state progression. Keep the teaching configuration separate from the independent exercise values; compare observations with the actual model and implementation.

Concept animation · operation pathway

Explore the teaching example independently of the simulator. Each step reveals an operation, data relationship or calculated state. The Simulation view has separate editable inputs.

Lab 12 · MQTT publisher: operation pathwayPublisher10 intended QoS 1publishesBrokerreceive PUBLISHAcknowledge8 observed PUBACKcompletionsMetric8/10=80%; notunique deliveryproofRead the active operation, then inspect the accumulated state.

Step 1 of 4 · Publisher

Publisher

Publisher
10 intended QoS 1 publishes

Teaching example only; inspect live calculations or real practical evidence separately.

Recall the concept before revealing its explanation.

0 / 3 revealed
X12 · 01 / 08What is a topic?Reveal explanation
Engineering explanation

A hierarchical MQTT message routing label.

X12 · 02 / 08Why start the subscriber first?Reveal explanation
Engineering explanation

Non-retained messages published before subscription may be missed.

X12 · 03 / 08What subscriber/broker prerequisites precede MQTT publication?Reveal explanation
Engineering explanation

Use one profile in both terminals, ensure subscriber is ready, send five mock messages, check topic and payload, then stop subscriber. Dashboard is a separate check.

X12 · 04 / 08What must match between publisher and subscriber?Reveal explanation
Engineering reasoning

The broker endpoint and topic/filter must be compatible; the payload must meet the consumer's expected schema.

X12 · 05 / 08Why inspect the publish outcome and subscriber output?Reveal explanation
Engineering reasoning

A publish call alone is not end-to-end evidence; check delivery at the intended consumer.

X12 · 06 / 08An MQTT publisher sends sensor telemetry. Select every technically valid statement. A. Select the intended broker and topic. B. A published message and a received message are different observations. C. Every topic is automatically authorized. D. MQTT QoS 0 guarantees application delivery.Reveal explanation
Applied scenario

Correct: A. Select the intended broker and topic.; B. A published message and a received message are different observations.

X12 · 07 / 08In MQTT publisher, which command or code executes the final documented practical action?Reveal explanation
Implementation recall

source ~/psut-wsl/activate.sh source ~/.config/psut-wsl/mqtt-hive.env cd ~/psut-wsl/labs/pi-practical python -m labs.exp12.publisher --mock --count 5 --interval 2

X12 · 08 / 08For MQTT publisher, which actual output or state confirms the prescribed practical run succeeded, and what does it not establish?Reveal explanation
Evidence & acceptance

Choose exactly one profile for both terminals. Start exp13 subscriber before exp12 publisher, wait for subscription readiness. Publisher sends five mock readings; check all five actual messages with correct topic/source. A publish print alone is insufficient. Stop subscriber after verification. Public HiveMQ uses generated session ID, fictional data only.

Execution boundary · Real Mosquitto. Browser simulation below is a teaching model, not execution of Python or firmware. The real commands run in VS Code/WSL; Wokwi is used for Arduino/ESP32 where indicated.
Shared research workbenches · network designer & advanced studies
Concurrent-device simulation & Monte Carlo research
Distributed digital twin · topology, protocol & battery research

Live experimental workstations

Loading experiment-specific apparatus…
Previous model / additional reference tools
Simulation task

Publish MQTT telemetry using a consistent broker and topic.

Explore the model using its own controls. Record a prediction before changing a condition. Compare the reference with a changed condition, then use the Experiment tab for the procedure, acceptance criteria and notebook. Model outputs and physical observations must remain separate.

Interactive engineering workbenchX12 · Existing model
01 / Explore

Interactive lab simulation

Browser model

Pin and connection reference

WSL uses simulated GPIO. These are source-derived signal mappings; physical connection notes are guidance, not a claim of physical testing.

ComponentSignal / pinConnection notesSource
DHT22 DATABCM GPIO17 · physical 113.3 V, GND; pull-up on bare sensorlabs/pi-practical/labs/common.py
X12 · Model-linked instrumentation

Visual observation lens

Back to controls ↑

Original virtual instrument; model signals and execution trace.

Loading instrument…

Awaiting model display.

Experimental instrumentation · A/B

Compare two model conditions

Capture a baseline, change one experimental condition, run the model if required and capture the comparison. Snapshots contain visible controls and display text, not physical sensor readings. Review before exporting.

Open simulation view
Baseline A
Not captured
Comparison B
Not captured

Capture a baseline to begin.

Evidence portfolio →
V19.0 · Contextual AI workspace

Ask your engineering assistants

X12 · current context

Ask Dr. Mohammad locally, or prepare an experiment-aware prompt for ChatGPT, Gemini or Claude. The external providers open in their own tabs; nothing is automatically submitted.

Dr. Mohammad · offline
Dr. Mohammad

Offline curriculum-grounded assistance.

Open local tutor
Lab 12 · MQTT publisher

Public course objective, displayed commands, source excerpts and procedure. Private assessment content is not collected.

Prepare a contextual AI prompt

0 characters

Common secret and email patterns are redacted on preparation; this is not a comprehensive privacy filter. Review the entire editable prompt, including student work and unpublished research, before sharing. The providers apply their own accounts, privacy settings and limits.

Prepare → review → copy & open your selected provider → paste and submit there.

Run & verify — acceptance checklist

Build verification: Static MQTT profiles and telemetry validation passed; broker pending.

Choose exactly one profile for both terminals. Start exp13 subscriber before exp12 publisher, wait for subscription readiness. Publisher sends five mock readings; check all five actual messages with correct topic/source. A publish print alone is insufficient. Stop subscriber after verification. Public HiveMQ uses generated session ID, fictional data only.

Record the actual output, source (mock/model or physical), and any error. A missing tool, timeout or untested external service is not a pass.

Complete lab-by-lab verification report →Open automated verification center → Ask Engineering Copilot →

Independent theoretical exercises

Before the simulation or practical, solve both experiment-specific tasks. List the given inputs, show the intermediate calculation or state trace, identify the expected observation, and state a limitation. Show formulas and intermediate calculations where relevant, or draw the requested state/sequence diagram. These are independent classroom fixtures; where they differ from the reference configuration below, do not treat them as measured values. Compare your predictions with the corresponding experiment afterwards.

01 · Predict and derive using the given inputs

For six QoS 1 messages where acknowledgments 3 and 6 are lost and each is retried once, count transmission attempts and possible duplicate deliveries.

02 · Compare or justify using evidence

Compare QoS 0 and a disconnected client; explain why an application should use a message ID if duplicate processing matters.

03 · Protocol analysis

Protocol analysis · Independent work

Ten QoS1 publications; two PUBACKs are lost after receipt and each is retried once. Count wire PUBLISH attempts and possible extra deliveries. What field should application use for deduplication?

Work is saved locally when browser storage is available. Export it for submission; no remote upload or automatic grade is assigned.

Expanded independent theoretical exercise bank

Progress from calculation and interpretation to diagnosis and controlled engineering design. Complete the questions without opening the simulation first; show intermediate steps.

Foundational · Apply the principle

Independent theoretical exercise · X12-01

A publisher sends 12 QoS1 messages and receives 9 PUBACKs before timeout. Compute observed completion rate.

Intermediate · Calculate or trace

Independent theoretical exercise · X12-02

Topic psut/lab2/temperature is published. Does filter psut/+/temperature match? Does psut/lab1/# match?

Intermediate · Interpret the result

Independent theoretical exercise · X12-03

Why does QoS0 not return PUBACK?

Advanced · Analyze a condition

Independent theoretical exercise · X12-04

A retry causes sequence 14 to reach a gateway twice. Give application-level handling.

Advanced · Diagnose or compare

Independent theoretical exercise · X12-05

A retained status is published and a new subscriber connects. What can arrive immediately?

Challenging · Engineering verification

Independent theoretical exercise · X12-06

Design a controlled QoS1 test.

Live simulation · MQTT acknowledgements

Perform these controlled trials before the existing practical experiment. Independent workstations have separate state.

  1. With QoS 0 select data loss and send. Compare application and delivered counts.
  2. Select QoS 1 and repeat; compare bounded retry and PUBACK.
  3. Select ACK loss and send. Compare deliveries and distinct sequence IDs.
  4. Disconnect, send, restore; then execute original QoS 1 publisher and check publish completion.

Evidence

Record initial settings, actual observations, one failure and a restored condition. Compare calculated values with the practical run; distinguish virtual and physical/cloud evidence.

Step-by-step experimental procedure

Trace publisher-side connection and completion conditions independently of subscriber receipt.

1 · Reference workbench configuration

Use the named reference workbench and its reference inputs. Additional live instruments may have different controls; use the matching instrument. Record virtual and practical results separately.

Publications6
QoS1
Connection establishedYes
Drop every N acknowledgement (0=none)0
Wait for publish completionYes

2 · Perform the investigation in order

  1. Publish six messages at QoS 1 with connection ready. Inspect packet identifier and acknowledgements.
  2. Drop every second acknowledgement; distinguish sent messages from confirmed completion.
  3. Switch to QoS 0: no broker acknowledgment is required; local completion is not broker delivery.
  4. Compare with actual MQTT publisher notebook and inspect on_connect/wait_for_publish behavior.

3 · Compare controlled trials

TrialIndependent changeExpected checkObservation
QoS1 referenceUse reference inputs aboveCompleted publishes: 6Record actual result
Missing acknowledgementsDrop every N acknowledgement (0=none) = 2Completed publishes: 3Record actual result
DisconnectedConnection established = NoCompleted publishes: 0Record actual result

4 · Analyze and report

QoS does not prove downstream processing or subscriber storage.

Required evidence: Record the named metrics and trace for the reference and changed cases, then attach the corresponding practical command output or device evidence if available.

Model boundary: A closed, deterministic browser model. The existing practical instructions and source files provide independent execution; browser results are not hardware measurements.

Loading laboratory-specific procedure…

Python / Google Colab notebook

Actual TCP MQTT 3.1.1 exchange with a restricted loopback peer and opt-in real HiveMQ TLS; actual SQLite readback, virtual telemetry. External broker not validated locally. Default profile executed in an isolated local Python kernel. Live services and physical hardware are separate acceptance tasks.

Download NotebookOpen Google ColabAll Python notebooks

Independent implementation sequence

  1. Prepare broker and dashboard
  2. Terminal A — subscribe first
  3. Terminal B — send five readings
  4. Verify the live dashboard
02 / Implement

Step-by-step instructions

Before you run / verification gate

Use one profile in both terminals, ensure subscriber is ready, send five mock messages, check topic and payload, then stop subscriber. Dashboard is a separate check.

Run only the selected broker branch. Each terminal needs activation and profile sourcing.

Choose ONE broker for a run. Local Mosquitto = 127.0.0.1:1884 in WSL, host.wokwi.internal:1884 in Wokwi. HiveMQ public = broker.hivemq.com:1883; simulated data only, no student IDs or secrets. Open the broker & Node-RED setup first. Use the same profile in every terminal.
01

Prepare broker and dashboard

Generate the chosen profile and import its flow using the dashboard guide. Keep the dashboard open.

Checkpoint Correct dashboard route and MQTT subscription show connected.
02

Terminal A — subscribe first

Keep this terminal running. The profile sets the exact host, port and topic.

WSL · Bash
source ~/psut-wsl/activate.sh
source ~/.config/psut-wsl/mqtt-local.env
cd ~/psut-wsl/labs/pi-practical
python -m labs.exp13.subscriber
✓ Expected: The subscriber remains running and waits for the matching topic; received JSON prints when the publisher runs.
Expected result for each action (4)
  1. source ~/psut-wsl/activate.shThe toolkit virtual environment is selected in this terminal, usually with (.venv) in the prompt. Verify which python points into ~/psut-wsl/.venv.
  2. source ~/.config/psut-wsl/mqtt-local.envThe local MQTT profile is loaded silently. Verify host 127.0.0.1, port 1884 and the matching topic in this shell.
  3. cd ~/psut-wsl/labs/pi-practicalNormally no output. pwd should show the requested directory. A missing path produces an error; do not continue until corrected.
  4. python -m labs.exp13.subscriberThe subscriber remains running and waits for the matching topic; received JSON prints when the publisher runs.
Checkpoint Subscriber prints the exact topic.
03

Terminal B — send five readings

Open a second WSL terminal. Mock sensor data works for both choices.

WSL · Bash
source ~/psut-wsl/activate.sh
source ~/.config/psut-wsl/mqtt-local.env
cd ~/psut-wsl/labs/pi-practical
python -m labs.exp12.publisher --mock --count 5 --interval 2
✓ Expected: Five acknowledged publications are expected with --count 5; verify unique received records separately.
Expected result for each action (4)
  1. source ~/psut-wsl/activate.shThe toolkit virtual environment is selected in this terminal, usually with (.venv) in the prompt. Verify which python points into ~/psut-wsl/.venv.
  2. source ~/.config/psut-wsl/mqtt-local.envThe local MQTT profile is loaded silently. Verify host 127.0.0.1, port 1884 and the matching topic in this shell.
  3. cd ~/psut-wsl/labs/pi-practicalNormally no output. pwd should show the requested directory. A missing path produces an error; do not continue until corrected.
  4. python -m labs.exp12.publisher --mock --count 5 --interval 2Five acknowledged publications are expected with --count 5; verify unique received records separately.
Checkpoint Five acknowledged publishes; readings appear in Terminal A and Node-RED.
04

Verify the live dashboard

Open Local dashboard or HiveMQ dashboard. Select the device, inspect temperature and humidity tiles and the trend/history. Soil is intentionally absent for practical DHT22 telemetry. Stop A with Ctrl+C.

Checkpoint Source mock; 5 additional received messages. MQTT QoS 1 can duplicate deliveries.

Experimental notebook

Record your own results. Values are not prefilled or independently verified.

03 / Inspect

Source code and method

labs/pi-practical/labs/exp12/publisher.pyDownload source
PY · source file
# ------------------------------------------------------------
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform
# ------------------------------------------------------------
# ====================================================================
# LAB PURPOSE / PUBLISHER
# ====================================================================
"""Experiment 12: publish DHT22 temperature as JSON (with humidity as context)."""

# ====================================================================
# 01 / IMPORT REQUIRED LIBRARIES
# ====================================================================
import threading
import re
from labs.common import parser, sensor, samples
from labs.mqtt_common import config, client

# ====================================================================
# 02 / CONFIGURE THE MQTT PUBLISHER
# ====================================================================
def main():
    p = parser(__doc__)
    a = p.parse_args()
    # Read a common broker address, port and topic from configuration.
    host, port, topic = config()
    # Apply additional restrictions when using a public demo broker.
    if host.lower() in ('broker.hivemq.com','test.mosquitto.org'):
        if not a.mock: p.error('Use --mock on public brokers; do not expose actual sensor measurements.')
        if not re.fullmatch(r'iotstudio/iot/demo-[0-9a-f]{16}/temperature', topic): p.error('Set a unique random demo MQTT_TOPIC (not private) first.')
    # Create the configured MQTT client and a connection-ready event.
    c = client(); ready = threading.Event()
    # ====================================================================
    # 03 / HANDLE CONNECTION CALLBACKS
    # ====================================================================
    def on_connect(client, userdata, flags, reason_code, properties):
        # Signal readiness only when the broker accepts the connection.
        if not reason_code.is_failure: ready.set()
        else: print('Broker refused connection:', reason_code)
    # Clear the readiness event when the broker connection is lost.
    def on_disconnect(client, userdata, disconnect_flags, reason_code, properties): ready.clear()
    c.on_connect=on_connect; c.on_disconnect=on_disconnect
    # Connect and keep MQTT network processing active in the background.
    # ====================================================================
    # 04 / START MQTT NETWORK PROCESSING
    # ====================================================================
    c.connect(host,port,60); c.loop_start()
    try:
        # Wait for the CONNACK callback before sending telemetry.
        if not ready.wait(10): raise RuntimeError('MQTT connection timed out')
        # ====================================================================
        # 05 / PUBLISH SENSOR DATA WITH QOS 1
        # ====================================================================
        with sensor(a.mock) as dev:
            # Acquire one reading at each configured sampling interval.
            for r in samples(dev,a.interval,a.count):
                # Wait for the CONNACK callback before sending telemetry.
                if not ready.wait(10): print('Broker unavailable; sample skipped'); continue
                # Send the JSON reading without retaining it; QoS 1 permits duplicates.
                result=c.publish(topic,r.json(),qos=1,retain=False)
                # Wait for the broker acknowledgment, with a bounded timeout.
                result.wait_for_publish(timeout=10)
                # Detect failure to complete the publish operation.
                if not result.is_published(): raise RuntimeError('MQTT publish not acknowledged')
                print(topic,r.json(),flush=True)
    # ====================================================================
    # 06 / DISCONNECT AND STOP THE NETWORK LOOP
    # ====================================================================
    finally:
        c.disconnect(); c.loop_stop()

# ====================================================================
# PROGRAM ENTRY POINT / RUN THE EXPERIMENT
# ====================================================================
if __name__ == '__main__':
    try: main()
    except KeyboardInterrupt: pass
04 / Verify

Evidence of completion

Save the actual terminal output from the checkpoints above. For simulated inputs explicitly record browser model, fakepi, mock or Wokwi. Never present those data as physical measurements. If a checkpoint fails, see the troubleshooting guide.

Integrated IoT System Studio

Follow the complete telemetry pipeline, compare live and stored evidence, and investigate controlled failures.

Open integrated system workbench →

Python / Google Colab laboratory

X12 · 7 notebook cells · 2 executable Python cells

Complete the theoretical investigation first. Run the cells in order, record actual outputs and compare against your prediction.

How to execute

  1. Download this notebook and open Google Colab. Select File → Upload notebook and choose the downloaded .ipynb.
  2. Read the Markdown instructions before each executable cell. Use a Python runtime, run cells from top to bottom, and resolve imports if necessary.
  3. Perform the baseline and controlled changes. Save the notebook with actual outputs and your written interpretation.

Execution scope: Default computational cells passed isolated local Python execution; physical equipment and live services require separate verification.

01Instructions · Markdown
# X12 · Lab 12 · MQTT publisher **PSUT IoT Engineering Studio — Dr. Mohammad Alja’afreh** ## Theory and purpose An MQTT publisher establishes a session, publishes bytes on an exact topic and receives PUBACK for QoS 1. PUBACK confirms broker acceptance, not necessarily subscriber processing. **Execution boundary:** local computational model or loopback as explicitly described; not physical measurements or external service certification. Run cells in order.
02Instructions · Markdown
## 1. Define the experiment mechanism and inputs
03Python · executable cell
PYTHON · Code cell
# =====================================================================
# X12 | Code cell 01 | Lab 12 · MQTT publisher
# Purpose: 1. Define the experiment mechanism and inputs
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
import contextlib, json, socket, socketserver, ssl, struct, threading, uuid

# Define the reusable operation check; keep its logic separate from the trial.
def check(condition, message):
    if not condition: raise RuntimeError(message)

# Define the reusable operation u16; keep its logic separate from the trial.
def u16(n): return struct.pack('!H', n)

# Define the reusable operation string; keep its logic separate from the trial.
def string(s):
    b=s.encode('utf-8');return u16(len(b))+b

# Define the reusable operation exact; keep its logic separate from the trial.
def exact(s,n):
    b=bytearray()
    while len(b)<n:
        c=s.recv(n-len(b))
        if not c: raise EOFError('peer closed')
        b.extend(c)
    return bytes(b)

# Define the reusable operation packet; keep its logic separate from the trial.
def packet(s,head,body=b''):
    n=len(body);out=bytearray([head])
    while True:
        digit=n%128;n//=128;out.append(digit|(128 if n else 0))
        if not n: break
    s.sendall(out+body)

# Define the reusable operation read packet; keep its logic separate from the trial.
def read_packet(s):
    h=exact(s,1)[0];n=0;mul=1
    for _ in range(4):
        b=exact(s,1)[0];n+=(b&127)*mul
        if not b&128:break
        mul*=128
    else:raise ValueError('invalid MQTT length')
    check(n<=65536,'packet too large for lab');return h,exact(s,n)

# Define the reusable operation split string; keep its logic separate from the trial.
def split_string(b):
    check(len(b)>=2,'truncated MQTT field');n=int.from_bytes(b[:2],'big');check(len(b)>=2+n,'truncated MQTT string');return b[2:2+n].decode(),b[2+n:]

# Small synchronous teaching client: clean session, exact-topic QoS 1.
class MQTT:
    """Small synchronous teaching client: clean session, exact-topic QoS 1.
    Separate publisher/subscriber sockets; no reconnect, keepalive or wildcard API.
    """
    def __init__(self,host,port,tls=False):
        s=socket.create_connection((host,port),timeout=8);s.settimeout(8)
        try:
            if tls:s=ssl.create_default_context().wrap_socket(s,server_hostname=host)
            self.s=s;self.pid=0
            packet(s,0x10,string('MQTT')+b'\x04\x02'+u16(60)+string('psut-'+uuid.uuid4().hex[:16]))
            h,b=read_packet(s);check(h==0x20 and b==b'\x00\x00','CONNACK failed')
        except BaseException:s.close();raise
    def next_id(self):self.pid=self.pid%65535+1;return u16(self.pid)
    def subscribe(self,topic):
        pid=self.next_id();packet(self.s,0x82,pid+string(topic)+b'\x01');h,b=read_packet(self.s);check(h==0x90 and b==pid+b'\x01','QoS 1 SUBACK not granted')
    def publish(self,topic,payload):
        pid=self.next_id();packet(self.s,0x32,string(topic)+pid+payload);h,b=read_packet(self.s);check(h==0x40 and b==pid,'PUBACK mismatch')
    def receive(self):
        h,b=read_packet(self.s);check(h>>4==3 and ((h>>1)&3)==1,'expected QoS 1 PUBLISH');topic,rest=split_string(b);check(len(rest)>=2,'missing packet ID');packet(self.s,0x40,rest[:2]);return topic,rest[2:]
    def close(self):
        try:packet(self.s,0xe0)
        except OSError:pass
        self.s.close()
    def __enter__(self):return self
    def __exit__(self,*args):self.close()

# Encapsulate state and operations for Peer; keep its logic separate from the trial.
class Peer(socketserver.BaseRequestHandler):
    def handle(self):
        s=self.request;s.settimeout(15);server=self.server
        try:
            h,b=read_packet(s);proto,b=split_string(b);check(h==0x10 and proto=='MQTT' and b[:2]==b'\x04\x02','unsupported CONNECT');packet(s,0x20,b'\x00\x00')
            while True:
                h,b=read_packet(s)
                if h==0x82:
                    topic,tail=split_string(b[2:]);check(tail==b'\x01' and '+' not in topic and '#' not in topic,'exact QoS1 only')
                    with server.lock:server.subs.setdefault(topic,set()).add(s)
                    packet(s,0x90,b[:2]+b'\x01')
                elif h==0x32:
                    topic,tail=split_string(b);check(len(tail)>=2,'missing packet ID')
                    with server.lock:
                        for target in list(server.subs.get(topic,())):
                            server.seq=server.seq%65535+1
                            try:packet(target,0x32,string(topic)+u16(server.seq)+tail[2:])
                            except OSError:server.subs[topic].discard(target)
                    packet(s,0x40,tail[:2])
                elif h==0x40:continue # no retransmission in this restricted fixture
                elif h==0xc0:packet(s,0xd0)
                elif h==0xe0:break
                else:raise ValueError('unsupported packet')
        except (EOFError,OSError,ValueError,RuntimeError):pass
        finally:
            with server.lock:
                for targets in server.subs.values():targets.discard(s)

# Encapsulate state and operations for LoopbackPeer; keep its logic separate from the trial.
class LoopbackPeer(socketserver.ThreadingTCPServer):
    daemon_threads=True
    def __init__(self):
        self.lock=threading.Lock();self.subs={};self.seq=0;super().__init__(('127.0.0.1',0),Peer)

# Define the reusable operation endpoint; keep its logic separate from the trial.
@contextlib.contextmanager
def endpoint(mode):
    if mode=='hivemq':
        yield 'broker.hivemq.com',8883,True
    elif mode=='local':
        with LoopbackPeer() as p:
            t=threading.Thread(target=p.serve_forever,daemon=True);t.start()
            try:yield '127.0.0.1',p.server_address[1],False
            finally:p.shutdown();t.join(3)
    else:raise ValueError('Choose local or hivemq explicitly')
Ask Dr. Mohammad about this cell
04Instructions · Markdown
## 2. Execute the reference and inspect observations
05Python · executable cell
PYTHON · Code cell
# =====================================================================
# X12 | Code cell 02 | Lab 12 · MQTT publisher
# Purpose: 2. Execute the reference and inspect observations
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
# Limit resource lifetime to this block so files, sockets or temporary state are cleaned up.
with endpoint('local') as addr, MQTT(*addr) as publisher:
    for seq in range(3):
        payload=json.dumps({'sequence':seq,'temperature':25+seq}).encode()
        publisher.publish('psut/lab/telemetry',payload)
        print('PUBACK verified for',seq,payload)
Ask Dr. Mohammad about this cell
06Instructions · Markdown
## Original portal implementation (reference only) These are the actual laboratory snippets. They are retained for comparison; follow the portal setup for WSL, hardware or services. They are **not** executed by Run all. ```bash source ~/psut-wsl/activate.sh source ~/.config/psut-wsl/mqtt-local.env cd ~/psut-wsl/labs/pi-practical python -m labs.exp13.subscriber ``` ```bash source ~/psut-wsl/activate.sh source ~/.config/psut-wsl/mqtt-hive.env cd ~/psut-wsl/labs/pi-practical python -m labs.exp13.subscriber ``` ```bash source ~/psut-wsl/activate.sh source ~/.config/psut-wsl/mqtt-local.env cd ~/psut-wsl/labs/pi-practical python -m labs.exp12.publisher --mock --count 5 --interval 2 ``` ```bash source ~/psut-wsl/activate.sh source ~/.config/psut-wsl/mqtt-hive.env cd ~/psut-wsl/labs/pi-practical python -m labs.exp12.publisher --mock --count 5 --interval 2 ``` ```python # ------------------------------------------------------------ # Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved. # PSUT IoT Engineering Learning Platform # ------------------------------------------------------------ # ==================================================================== # LAB PURPOSE / PUBLISHER # ==================================================================== """Experiment 12: publish DHT22 temperature as JSON (with humidity as context).""" # ==================================================================== # 01 / IMPORT REQUIRED LIBRARIES # ==================================================================== import threading import re from labs.common import parser, sensor, samples from labs.mqtt_common import config, client # ==================================================================== # 02 / CONFIGURE THE MQTT PUBLISHER # ==================================================================== def main(): p = parser(__doc__) a = p.parse_args() # Read a common broker address, port and topic from configuration. host, port, topic = config() # Apply additional restrictions when using a public demo broker. if host.lower() in ('broker.hivemq.com','test.mosquitto.org'): if not a.mock: p.error('Use --mock on public brokers; do not expose actual sensor measurements.') if not re.fullmatch(r'iotstudio/iot/demo-[0-9a-f]{16}/temperature', topic): p.error('Set a unique random demo MQTT_TOPIC (not private) first.') # Create the configured MQTT client and a connection-ready event. c = client(); ready = threading.Event() # ==================================================================== # 03 / HANDLE CONNECTION CALLBACKS # ==================================================================== def on_connect(client, userdata, flags, reason_code, properties): # Signal readiness only when the broker accepts the connection. if not reason_code.is_failure: ready.set() else: print('Broker refused connection:', reason_code) # Clear the readiness event when the broker connection is lost. def on_disconnect(client, userdata, disconnect_flags, reason_code, properties): ready.clear() c.on_connect=on_connect; c.on_disconnect=on_disconnect # Connect and keep MQTT network processing active in the background. # ==================================================================== # 04 / START MQTT NETWORK PROCESSING # ==================================================================== c.connect(host,port,60); c.loop_start() try: # Wait for the CONNACK callback before sending telemetry. if not ready.wait(10): raise RuntimeError('MQTT connection timed out') # ==================================================================== # 05 / PUBLISH SENSOR DATA WITH QOS 1 # ==================================================================== with sensor(a.mock) as dev: # Acquire one reading at each configured sampling interval. for r in samples(dev,a.interval,a.count): # Wait for the CONNACK callback before sending telemetry. if not ready.wait(10): print('Broker unavailable; sample skipped'); continue # Send the JSON reading without retaining it; QoS 1 permits duplicates. result=c.publish(topic,r.json(),qos=1,retain=False) # Wait for the broker acknowledgment, with a bounded timeout. result.wait_for_publish(timeout=10) # Detect failure to complete the publish operation. if not result.is_published(): raise RuntimeError('MQTT publish not acknowledged') print(topic,r.json(),flush=True) # ==================================================================== # 06 / DISCONNECT AND STOP THE NETWORK LOOP # ==================================================================== finally: c.disconnect(); c.loop_stop() # ==================================================================== # PROGRAM ENTRY POINT / RUN THE EXPERIMENT # ==================================================================== if __name__ == '__main__': try: main() except KeyboardInterrupt: pass ```
07Instructions · Markdown
## Independent investigation and submission Change the message count from 3 to 5, keeping the exact topic fixed. Record sequence IDs and confirmed publishes. Explain why PUBACK does not prove a dashboard received data. | Trial | Changed input | Fixed settings | Predicted output | Observed output | Explanation | |---|---|---|---|---|---| | A | baseline | | | | | | B | one change | | | | | | A repeat | baseline | | | | | Save outputs and state one limitation.