Skip to main content
PSUT / IoTEngineering learning studio
WORKSPACE
Offline-first portalDr. Mohammad Alja’afreh
Connected Networks StudioNetworking and CommunicationExperimentsWorkspaces
ENGINEERING WORKSPACE
Home/WSL Laboratories/Lab 13 · MQTT subscriber
IoTPSUT IoT Engineering StudioPrincess Sumaya University for Technology · Dr. Mohammad Alja’afreh
Pi practical / X13
IoT Programming and Applications

Lab 13 · MQTT subscriber

Ask Dr. Mohammad · X13 →

Run the subscriber, then Lab 12’s publisher in a second terminal.

Open MQTT packet analyzer →

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

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

X13 · Academic orientation

Scope and objectives

Scope of the experiment

Evaluate topic-level wildcard matching and retained initial delivery.

The focus of this experiment is to trace subscription filters and received MQTT payloads. Students then evaluate wildcard and topic-matching behavior, and verify reception and distinguish broker connection from message delivery. 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 subscription filters and received MQTT payloads.
  • Evaluate wildcard and topic-matching behavior.
  • Verify reception and distinguish broker connection from message delivery.
  • 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 subscription filters and received MQTT payloads, evaluate wildcard and topic-matching behavior, and verify reception and distinguish broker connection from message delivery.

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 reception and distinguish broker connection from message delivery. Separate predicted values from observations.

Prerequisite knowledge and related learning

Review the following catalogue prerequisites before starting.

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.

X13 / 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 the same broker and topic in both terminals and Node-RED. Confirm subscriber output before troubleshooting visualization; Ctrl+C stops the subscriber.

CONCEPTS / ACTIVE RECALL

Understand the experiment

MQTT retained publication and subscription

Retained message is stored per topic; new subscription can receive it immediately
Retained message is stored per topic; new subscription can receive it immediately

Scientific architecture · MQTT subscription filters and retained messages

MQTT retained subscription — Publisher; Broker; Subscriber; Publish retained value / 0>1; SUBSCRIBE topic filter / 2>1; SUBACK / 1>2; Deliver retained value / 1>2; Publish new value / 0>1; Forward matching value / 1>2
Scientific concept map: Subscriber — Topic filter; Broker — Match + / # levels; Retained store — Latest retained publication; Delivery — Matching messages; Subscriber log — Topic and payload.

Scientific foundations and analytical reasoning

MQTT + matches one topic level, # matches remaining levels at the end of a filter. A retained message is a broker snapshot, not an entire history.

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 · Subscription filters and retained state

Topic names are slash-separated levels. The + filter matches exactly one level; # matches the remaining hierarchy when placed at the end as a complete level. The broker forwards matching publications. A retained value represents the latest retained message for a topic, not all historical values.

Worked example and engineering interpretation

The filter lab/+/temp matches lab/a/temp and lab/b/temp but not lab/a/hum or lab/a/room/temp. A late subscriber may receive a retained snapshot before fresh data. Compare message ID and time to distinguish retained and live observations.

Engineering principles · additional worked teaching example

Topic levels are separated by /. + matches exactly one level; # matches remaining levels and must be final. site/+/status matches site/a/status, not site/a/temp/status. A subscriber receives only matching published topics subject to broker authorization.

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 13 · MQTT subscriber

An MQTT subscriber registers a topic with the broker and receives matching publications. This real loopback peer supports exact topics and QoS 1 only; wildcard and retained behavior belong to the separate portal model and actual broker exercise.

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: Receive MQTT telemetry and verify Node-RED behavior independently.

  1. Subscribe to lab/+/temp; publish lab/a/temp, lab/b/temp and lab/a/hum. Record matches.
  2. Reset, publish retained reading before subscribing, then subscribe. Try lab/# and reconnect to apply filter.
  3. In independent Node-RED instrument send valid samples and change temperature; observe gauge and history. Disable valid JSON or broker connection; verify no sample added.
  4. Use existing subscriber and flow: configure matching broker/topic, import once, deploy and open configured dashboard URL.

Reference check:

Model boundary:

Independent task and submission evidence

Change the subscribed topic and matching publication together; leave a nonmatching publication in the trial. Record the delivered topic and payload. In the separate simulator compare lab/+/temp with lab/#.

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

A subscriber receives messages matching topic filters, subject to subscription and delivery conditions. + matches one whole level; # matches remaining levels and must be last. A retained message may arrive after subscribing. Example site/+/temp matches site/a/temp but not site/a/b/temp.

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 13 · MQTT subscriber: operation pathwayTopicsite/a/tempFiltersite/+/tempMatchone level aDelivermatchingsubscription; checkQoSRead the active operation, then inspect the accumulated state.

Step 1 of 4 · Topic

Topic

Topic
site/a/temp

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

Recall the concept before revealing its explanation.

0 / 3 revealed
X13 · 01 / 08What does a subscriber do?Reveal explanation
Engineering explanation

Registers interest in topics and receives matching published data.

X13 · 02 / 08Why validate JSON?Reveal explanation
Engineering explanation

A received message may still contain invalid fields or values.

X13 · 03 / 08What broker/topic/dashboard conditions must be checked before interpreting telemetry?Reveal explanation
Engineering explanation

Use the same broker and topic in both terminals and Node-RED. Confirm subscriber output before troubleshooting visualization; Ctrl+C stops the subscriber.

X13 · 04 / 08Why subscribe before publishing a non-retained test message?Reveal explanation
Engineering reasoning

A new subscriber normally receives future matching messages; it may miss messages published before subscription.

X13 · 05 / 08Why inspect the message topic as well as JSON?Reveal explanation
Engineering reasoning

A valid payload from the wrong topic may be unrelated to the intended student or device.

X13 · 06 / 08An MQTT subscriber displays telemetry. Select every technically valid statement. A. Verify its topic filter and broker connection. B. Check Node-RED processing separately. C. Subscription to a different broker always receives the same message. D. A dashboard display proves the publisher's sensor is calibrated.Reveal explanation
Applied scenario

Correct: A. Verify its topic filter and broker connection.; B. Check Node-RED processing separately.

X13 · 07 / 08In MQTT subscriber, 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

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

Complete X12 first. Import only the matching local or HiveMQ flow from generated toolkit configuration and deploy; avoid duplicate dashboard paths. Start publisher again, verify MQTT input debug and the matching dashboard (local /psut-local/live, HiveMQ /psut-hive/live). Inspect actual timestamps and source, not stale charts. Stop publisher/subscriber when done.

WOKWI / WSL INTEGRATION

Connect to actual MQTT telemetry

Run the supplied ESP32 greenhouse firmware and inspect received messages, live sensor readings and per-device history. No browser-generated readings are inserted into the live view.

Open Live Telemetry Studio →
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

Receive MQTT telemetry and verify Node-RED behavior independently.

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 workbenchX13 · Existing model

Explore the interactive 3D electronics laboratory ↗ · 3D system simulation ↗

01 / Explore

Interactive lab simulation

Browser model
X13 · 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

X13 · 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 13 · MQTT subscriber

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 Node-RED flow and telemetry validation passed; live dashboard pending.

Complete X12 first. Import only the matching local or HiveMQ flow from generated toolkit configuration and deploy; avoid duplicate dashboard paths. Start publisher again, verify MQTT input debug and the matching dashboard (local /psut-local/live, HiveMQ /psut-hive/live). Inspect actual timestamps and source, not stale charts. Stop publisher/subscriber when done.

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

Apply lab/+/temp, lab/# and lab/a/+ to lab/a/temp;lab/b/temp;lab/a/hum;other/a/temp. List matches for each.

02 · Compare or justify using evidence

Explain how a newly subscribing client can receive a retained value before a new publication and why a Node-RED chart needs timestamps.

03 · Topic tracing

Topic tracing · Independent work

For topics site/a/temp, site/a/hum, site/b/temp, site/a/room/temp, evaluate filters site/+/temp and site/a/#.

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 · X13-01

For psut/lab1/temp, psut/lab1/rh, psut/lab2/temp, psut/lab2/led, determine matches for psut/+/temp.

Intermediate · Calculate or trace

Independent theoretical exercise · X13-02

Which of psut/#/temp, psut/lab1/# and psut/lab+ is valid filter syntax?

Intermediate · Interpret the result

Independent theoretical exercise · X13-03

For filter psut/lab1/#, does psut/lab1 itself match?

Advanced · Analyze a condition

Independent theoretical exercise · X13-04

A subscriber sees sequence [1,2,2,4]. Calculate unique receive count and missing sequence assuming 1..4 sent.

Advanced · Diagnose or compare

Independent theoretical exercise · X13-05

Explain why subscribe QoS1 cannot upgrade a QoS0 published message to QoS1.

Challenging · Engineering verification

Independent theoretical exercise · X13-06

Design a test distinguishing retained from fresh live data.

Live simulation · Subscription and Node-RED

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

  1. Subscribe to lab/+/temp; publish lab/a/temp, lab/b/temp and lab/a/hum. Record matches.
  2. Reset, publish retained reading before subscribing, then subscribe. Try lab/# and reconnect to apply filter.
  3. In independent Node-RED instrument send valid samples and change temperature; observe gauge and history. Disable valid JSON or broker connection; verify no sample added.
  4. Use existing subscriber and flow: configure matching broker/topic, import once, deploy and open configured dashboard URL.

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

Evaluate topic-level wildcard matching and retained initial delivery.

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.

Topic filterlab/+/temp
Publication setlab/a/temp;lab/b/temp;lab/a/hum;other/a/temp
Matching retained value availableYes
Subscriber connectedYes

2 · Perform the investigation in order

  1. Subscribe to lab/+/temp and inspect matching topics; + consumes exactly one level.
  2. Use lab/# and compare the additional humidity match.
  3. Change to exact topic lab/a/temp and toggle retained initial delivery.
  4. Use the actual MQTT subscriber practical and compare callbacks, topic names and retained flag.

3 · Compare controlled trials

TrialIndependent changeExpected checkObservation
Single-level wildcardUse reference inputs aboveLive matches: 2Record actual result
Multi-level wildcardTopic filter = lab/#Live matches: 3Record actual result
DisconnectedSubscriber connected = NoLive matches: 0Record actual result

4 · Analyze and report

The fixture implements ordinary topic levels, not all broker-specific $ topics or shared subscriptions.

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 the same broker and topic in both terminals and Node-RED. Confirm subscriber output before troubleshooting visualization; Ctrl+C stops the subscriber.

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/exp13/subscriber.pyDownload source
PY · source file
# ------------------------------------------------------------
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform
# ------------------------------------------------------------
# ====================================================================
# LAB PURPOSE / SUBSCRIBER
# ====================================================================
"""Experiment 13: subscribe to the exact publisher topic and decode JSON."""

# ====================================================================
# 01 / IMPORT REQUIRED LIBRARIES
# ====================================================================
import json
from labs.mqtt_common import config, client

# ====================================================================
# 02 / CONFIGURE THE MQTT SUBSCRIBER
# ====================================================================
def main():
    # Use the same broker and exact topic as the publisher.
    host,port,topic=config(); c=client()
    # ====================================================================
    # 03 / SUBSCRIBE AFTER CONNECT OR RECONNECT
    # ====================================================================
    def on_connect(client,userdata,flags,reason_code,properties):
        if not reason_code.is_failure:
            # Request QoS 1 on the configured topic after a successful connection.
            client.subscribe(topic,qos=1); print('Subscribed:',topic,flush=True)
        else: print('Broker refused:',reason_code)
    # ====================================================================
    # 04 / DECODE INCOMING TELEMETRY
    # ====================================================================
    def on_message(client,userdata,msg):
        try:
            # Decode the UTF-8 MQTT byte payload into a Python dictionary.
            r=json.loads(msg.payload.decode('utf-8'))
            # Print temperature, humidity and provenance from the received JSON.
            print(f"{msg.topic}: {float(r['temperature']):.1f} C; humidity={float(r['humidity']):.1f}%; source={r['source']}",flush=True)
        # Ignore malformed or incomplete telemetry instead of crashing.
        except (ValueError,KeyError,TypeError,UnicodeError): print('Invalid telemetry ignored',flush=True)
    # ====================================================================
    # 05 / REGISTER CALLBACKS AND RUN THE NETWORK LOOP
    # ====================================================================
    c.on_connect=on_connect;c.on_message=on_message;c.connect(host,port,60)
    # Process incoming MQTT packets continuously until stopped.
    try: c.loop_forever()
    # Disconnect when the application exits.
    finally: c.disconnect()

# ====================================================================
# PROGRAM ENTRY POINT / RUN THE EXPERIMENT
# ====================================================================
if __name__ == '__main__':
    try: main()
    except KeyboardInterrupt: pass
labs/pi-practical/labs/exp13/flow.jsonDownload source
JSON · source file
[
  {
    "id": "psutv2localtab",
    "type": "tab",
    "label": "PSUT Studio \u00b7 local",
    "disabled": false,
    "info": "Generated by mqtt_profile.py; only import once per profile."
  },
  {
    "id": "psutv2localbroker",
    "type": "mqtt-broker",
    "name": "local MQTT",
    "broker": "127.0.0.1",
    "port": "1884",
    "clientid": "",
    "autoConnect": true,
    "usetls": false,
    "protocolVersion": "4",
    "keepalive": "60",
    "cleansession": true
  },
  {
    "id": "psutv2localbase",
    "type": "ui-base",
    "name": "IoT Studio \u00b7 local",
    "path": "/psut-local",
    "includeClientData": true,
    "acceptsClientConfig": [],
    "showPathInSidebar": false,
    "showPageTitle": true,
    "navigationStyle": "default",
    "titleBarStyle": "default"
  },
  {
    "id": "psutv2localtheme",
    "type": "ui-theme",
    "name": "PSUT Studio",
    "colors": {
      "surface": "#ffffff",
      "primary": "#087e79",
      "bgPage": "#f2f6fa",
      "groupBg": "#ffffff",
      "groupOutline": "#dce5ed"
    },
    "sizes": {
      "density": "default",
      "pagePadding": "16px",
      "groupGap": "16px",
      "groupBorderRadius": "12px",
      "widgetGap": "12px"
    }
  },
  {
    "id": "psutv2localpage",
    "type": "ui-page",
    "name": "Live telemetry",
    "ui": "psutv2localbase",
    "path": "/live",
    "icon": "dashboard",
    "layout": "grid",
    "theme": "psutv2localtheme",
    "order": 1,
    "visible": true,
    "disabled": false,
    "breakpoints": [
      {
        "name": "Default",
        "px": "0",
        "cols": "3"
      },
      {
        "name": "Tablet",
        "px": "576",
        "cols": "6"
      },
      {
        "name": "Desktop",
        "px": "1024",
        "cols": "12"
      }
    ]
  },
  {
    "id": "psutv2localgroup",
    "type": "ui-group",
    "name": "Environmental monitoring",
    "page": "psutv2localpage",
    "width": "12",
    "height": "1",
    "order": 1,
    "showTitle": true,
    "visible": true,
    "disabled": false
  },
  {
    "id": "psutv2localpractical",
    "type": "mqtt in",
    "z": "psutv2localtab",
    "name": "practical",
    "topic": "iotstudio/iot/group01/temperature",
    "qos": "1",
    "datatype": "utf8",
    "broker": "psutv2localbroker",
    "nl": false,
    "rap": true,
    "rh": 0,
    "inputs": 0,
    "x": 150,
    "y": 100,
    "wires": [
      [
        "psutv2localvalidate"
      ]
    ]
  },
  {
    "id": "psutv2localgreenhouse",
    "type": "mqtt in",
    "z": "psutv2localtab",
    "name": "greenhouse",
    "topic": "psut/iot/lab-local/greenhouse/+/telemetry",
    "qos": "1",
    "datatype": "utf8",
    "broker": "psutv2localbroker",
    "nl": false,
    "rap": true,
    "rh": 0,
    "inputs": 0,
    "x": 150,
    "y": 160,
    "wires": [
      [
        "psutv2localvalidate"
      ]
    ]
  },
  {
    "id": "psutv2localvalidate",
    "type": "function",
    "z": "psutv2localtab",
    "name": "Validate JSON + update bounded per-device history",
    "func": "// Node-RED function body. Only valid numeric JSON telemetry reaches dashboard.\ntry {\n  const p = typeof msg.payload === 'string' ? JSON.parse(msg.payload) : msg.payload;\n  if (!p || typeof p !== 'object' || Array.isArray(p)) throw Error('Expected JSON object');\n  const valid=(v,min,max)=>typeof v==='number' && Number.isFinite(v) && v>=min && v<=max;\n  if(!valid(p.temperature,-40,80)||!valid(p.humidity,0,100)) throw Error('Invalid DHT22 values');\n  if(p.soil_moisture!==undefined&&!valid(p.soil_moisture,0,100)) throw Error('Invalid soil moisture');\n  if(!['mock','fakepi','wokwi','hardware'].includes(p.source)) throw Error('Missing/unknown source');\n  if(false && !['mock','wokwi'].includes(p.source)) throw Error('Public broker: demo sources only (self-reported)');\n  const topic=String(msg.topic||'');\n  const label=String(p.sensor_id || topic.split('/').at(-2) || 'device').slice(0,48);\n  const key=topic.slice(0,180)+' | '+label;\n  const latest={temperature:p.temperature,humidity:p.humidity,soil:p.soil_moisture??null,source:p.source,device:label,topic:topic.slice(0,180),received:Date.now()};\n  let records=context.get('records')||[];\n  // Global history bounded to 180 accepted messages; device histories filtered in UI.\n  records=[...records,{...latest,key}].slice(-180);\n  context.set('records',records);\n  msg.payload={latest:{...latest,key},records,total:(context.get('total')||0)+1};\n  context.set('total',msg.payload.total);\n  return [msg,null];\n} catch(e){return [null,{payload:'Rejected telemetry: '+e.message,topic:msg.topic}];}\n",
    "outputs": 2,
    "noerr": 0,
    "initialize": "",
    "finalize": "",
    "libs": [],
    "x": 440,
    "y": 140,
    "wires": [
      [
        "psutv2localdisplay",
        "psutv2localdebug"
      ],
      [
        "psutv2localreject"
      ]
    ]
  },
  {
    "id": "psutv2localdebug",
    "type": "debug",
    "z": "psutv2localtab",
    "name": "Accepted telemetry",
    "active": true,
    "tosidebar": true,
    "complete": "payload.latest",
    "targetType": "msg",
    "x": 760,
    "y": 80,
    "wires": []
  },
  {
    "id": "psutv2localreject",
    "type": "debug",
    "z": "psutv2localtab",
    "name": "Rejected telemetry",
    "active": true,
    "tosidebar": true,
    "complete": "payload",
    "targetType": "msg",
    "x": 760,
    "y": 220,
    "wires": []
  },
  {
    "id": "psutv2localdisplay",
    "type": "ui-template",
    "z": "psutv2localtab",
    "group": "psutv2localgroup",
    "page": "",
    "ui": "",
    "name": "Live tiles \u00b7 trend \u00b7 history",
    "order": 1,
    "width": "12",
    "height": "11",
    "head": "",
    "format": "<template>\n  <div class=\"psut-dashboard\">\n    <div v-if=\"!msg || !msg.payload || !msg.payload.latest\" class=\"psut-wait\">Waiting for actual MQTT messages. Start the Python or Wokwi publisher.</div>\n    <div v-else>\n      <div class=\"psut-top\"><div><small>MQTT LIVE \u00b7 {{msg.payload.total}} accepted messages</small><h2>Environment telemetry</h2></div><select v-model=\"selected\"><option value=\"\">Latest device</option><option v-for=\"d in devices\" :key=\"d\" :value=\"d\">{{d}}</option></select></div>\n      <div class=\"psut-meta\">{{latest.device}} \u00b7 {{latest.source}} (self-reported) \u00b7 Received {{new Date(latest.received).toLocaleTimeString()}}</div>\n      <div class=\"psut-cards\"><div v-for=\"k in metrics\" :key=\"k.key\" class=\"psut-metric\"><small>{{k.label}}</small><strong>{{latest[k.key]===null?'\u2014':latest[k.key].toFixed(1)}} <span>{{k.unit}}</span></strong><div class=\"psut-bar\"><i :style=\"{width: percent(k)+'%',background:k.color}\"></i></div></div></div>\n      <div class=\"psut-plot\"><h3>Recent samples \u00b7 selected device</h3><svg viewBox=\"0 0 600 175\" role=\"img\" aria-label=\"Temperature, humidity and soil history\"><g stroke=\"#d6e1eb\"><path d=\"M40 15V145H580 M40 15H580 M40 47.5H580 M40 80H580 M40 112.5H580\" fill=\"none\"/></g><g font-size=\"11\" fill=\"#63758a\"><text x=\"4\" y=\"20\">100</text><text x=\"10\" y=\"85\">50</text><text x=\"18\" y=\"149\">0</text><text x=\"40\" y=\"166\">Oldest</text><text x=\"548\" y=\"166\">Latest</text></g><polyline v-for=\"k in metrics\" :key=\"k.key\" :points=\"points(k.key)\" :stroke=\"k.color\" stroke-width=\"3\" fill=\"none\" stroke-linejoin=\"round\"/></svg><small>Humidity / soil 0\u2013100%; temperature chart normalized from \u221240 to 80\u00b0C. Exact values below.</small><div class=\"psut-legend\"><span v-for=\"k in metrics\" :key=\"k.key\" :style=\"{color:k.color}\">\u25cf {{k.label}}</span></div></div>\n      <div class=\"psut-table\"><table><thead><tr><th>Received</th><th>Temperature \u00b0C</th><th>Humidity %</th><th>Soil %</th><th>Source</th></tr></thead><tbody><tr v-for=\"(r,i) in history.slice(-10).reverse()\" :key=\"i\"><td>{{new Date(r.received).toLocaleTimeString()}}</td><td>{{r.temperature}}</td><td>{{r.humidity}}</td><td>{{r.soil===null?'\u2014':r.soil}}</td><td>{{r.source}}</td></tr></tbody></table></div><small>In-memory history (last 180 messages across devices); not persistent storage. Public MQTT data is untrusted.</small>\n    </div>\n  </div>\n</template>\n<script>\nexport default {data(){return {selected:'',metrics:[{key:'temperature',label:'Temperature',unit:'\u00b0C',color:'#e8793a'},{key:'humidity',label:'Humidity',unit:'%',color:'#3388dd'},{key:'soil',label:'Soil moisture',unit:'%',color:'#0b9c81'}]}},computed:{records(){return this.msg?.payload?.records||[]},devices(){return [...new Set(this.records.map(r=>r.key))]},history(){const key=this.devices.includes(this.selected)?this.selected:this.msg?.payload?.latest?.key;return this.records.filter(r=>r.key===key)},latest(){return this.history.at(-1)||this.msg.payload.latest}},methods:{norm(k,v){return k==='temperature'?(v+40)/120*100:v},percent(k){return this.latest[k.key]===null?0:Math.max(0,Math.min(100,this.norm(k.key,this.latest[k.key])))},points(key){return this.history.map((r,i)=>r[key]===null?'':`${40+540*i/Math.max(1,this.history.length-1)},${145-1.3*this.norm(key,r[key])}`).filter(Boolean).join(' ')}}}\n</script>\n<style>\n.psut-dashboard{font-family:system-ui,sans-serif;color:#18334b}.psut-top,.psut-legend{display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px}.psut-top h2{margin:4px 0 12px}.psut-top select{max-width:100%;background:#eaf3f7;padding:8px;border-radius:8px}.psut-meta{font-size:12px;overflow-wrap:anywhere;margin:8px 0}.psut-cards{display:grid;grid-template-columns:repeat(auto-fit,minmax(130px,1fr));gap:12px}.psut-metric{background:#f2f7fb;border:1px solid #dbe6ed;border-radius:12px;padding:14px}.psut-metric strong{display:block;font-size:28px;margin:8px 0}.psut-metric strong span{font-size:14px}.psut-bar{height:8px;background:#dae5ee;border-radius:10px;overflow:hidden}.psut-bar i{display:block;height:100%;transition:width .4s}.psut-plot{margin:15px 0;padding:12px;border:1px solid #dbe6ed;border-radius:12px}.psut-plot svg{width:100%;max-height:230px}.psut-table{overflow:auto}.psut-table table{width:100%;border-collapse:collapse;font-size:13px}.psut-table td,.psut-table th{padding:8px;border-bottom:1px solid #dce7ee;text-align:left}.psut-wait{padding:30px;background:#f1f7fb;border-radius:12px}\n</style>\n",
    "storeOutMessages": false,
    "passthru": false,
    "resendOnRefresh": true,
    "templateScope": "local",
    "className": "",
    "x": 760,
    "y": 140,
    "wires": [
      []
    ]
  }
]
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

X13 · 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
# X13 · Lab 13 · MQTT subscriber **PSUT IoT Engineering Studio — Dr. Mohammad Alja’afreh** ## Theory and purpose An MQTT subscriber registers a topic with the broker and receives matching publications. This real loopback peer supports exact topics and QoS 1 only; wildcard and retained behavior belong to the separate portal model and actual broker exercise. **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
# =====================================================================
# X13 | Code cell 01 | Lab 13 · MQTT subscriber
# 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
# =====================================================================
# X13 | Code cell 02 | Lab 13 · MQTT subscriber
# 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 subscriber, MQTT(*addr) as publisher:
    subscriber.subscribe('lab/a/temp')
    publisher.publish('lab/b/temp',b'not subscribed')
    publisher.publish('lab/a/temp',b'25.4')
    topic,payload=subscriber.receive()
    print(topic,payload)
    assert (topic,payload)==('lab/a/temp',b'25.4')
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 / SUBSCRIBER # ==================================================================== """Experiment 13: subscribe to the exact publisher topic and decode JSON.""" # ==================================================================== # 01 / IMPORT REQUIRED LIBRARIES # ==================================================================== import json from labs.mqtt_common import config, client # ==================================================================== # 02 / CONFIGURE THE MQTT SUBSCRIBER # ==================================================================== def main(): # Use the same broker and exact topic as the publisher. host,port,topic=config(); c=client() # ==================================================================== # 03 / SUBSCRIBE AFTER CONNECT OR RECONNECT # ==================================================================== def on_connect(client,userdata,flags,reason_code,properties): if not reason_code.is_failure: # Request QoS 1 on the configured topic after a successful connection. client.subscribe(topic,qos=1); print('Subscribed:',topic,flush=True) else: print('Broker refused:',reason_code) # ==================================================================== # 04 / DECODE INCOMING TELEMETRY # ==================================================================== def on_message(client,userdata,msg): try: # Decode the UTF-8 MQTT byte payload into a Python dictionary. r=json.loads(msg.payload.decode('utf-8')) # Print temperature, humidity and provenance from the received JSON. print(f"{msg.topic}: {float(r['temperature']):.1f} C; humidity={float(r['humidity']):.1f}%; source={r['source']}",flush=True) # Ignore malformed or incomplete telemetry instead of crashing. except (ValueError,KeyError,TypeError,UnicodeError): print('Invalid telemetry ignored',flush=True) # ==================================================================== # 05 / REGISTER CALLBACKS AND RUN THE NETWORK LOOP # ==================================================================== c.on_connect=on_connect;c.on_message=on_message;c.connect(host,port,60) # Process incoming MQTT packets continuously until stopped. try: c.loop_forever() # Disconnect when the application exits. finally: c.disconnect() # ==================================================================== # PROGRAM ENTRY POINT / RUN THE EXPERIMENT # ==================================================================== if __name__ == '__main__': try: main() except KeyboardInterrupt: pass ```
07Instructions · Markdown
## Independent investigation and submission Change the subscribed topic and matching publication together; leave a nonmatching publication in the trial. Record the delivered topic and payload. In the separate simulator compare lab/+/temp with lab/#. | Trial | Changed input | Fixed settings | Predicted output | Observed output | Explanation | |---|---|---|---|---|---| | A | baseline | | | | | | B | one change | | | | | | A repeat | baseline | | | | | Save outputs and state one limitation.