Skip to main content
PSUT / IoTEngineering learning studio
WORKSPACE
Offline-first portalDr. Mohammad Alja’afreh
Intelligent Edge StudioMachine Learning and Edge AIExperimentsWorkspaces
ENGINEERING WORKSPACE
Home/WSL Laboratories/Lab 40 · IoT gateway · JSON lines and fan commands
IoTPSUT IoT Engineering StudioPrincess Sumaya University for Technology · Dr. Mohammad Alja’afreh
Python & IoT / P40
IoT Programming and Applications

Lab 40 · IoT gateway · JSON lines and fan commands

Ask Dr. Mohammad · P40 →

The gateway and nodes use real TCP; the fan relay on GPIO27 is a fake pin.

Open TCP packet analyzer →

Design experiment & verify evidence →
P40 · Laboratory mentorAsk about the current experiment, its algorithms or Python notebook.
Ask Dr. MohammadAdaptive practice
Learning workflow · Core IoT & programmingP40 · IoT gateway · JSON lines and fan commands
Readiness checksRevision deckEngineering workspaceRecord evidence

Related course access: Machine Learning and Edge AI — same laboratory, notebook and completion record.

P40 · Academic orientation

Scope and objectives

Scope of the experiment

Replay the source gateway’s strict temp > LIMIT decision for each valid JSON line; optionally compare a hysteresis extension.

The focus of this experiment is to trace newline-delimited JSON sensor messages and fan commands. Students then evaluate threshold logic, types and hysteresis at boundary readings, and verify command decisions and malformed-message handling. 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 newline-delimited JSON sensor messages and fan commands.
  • Evaluate threshold logic, types and hysteresis at boundary readings.
  • Verify command decisions and malformed-message handling.
  • 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 newline-delimited JSON sensor messages and fan commands, evaluate threshold logic, types and hysteresis at boundary readings, and verify command decisions and malformed-message handling.

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 command decisions and malformed-message handling. Separate predicted values from observations.

Prerequisite knowledge and related learning

Review the following catalogue prerequisites before starting. After completion, continue to Lab 41 · LED control class with a mock GPIO.

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.

P40 / 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

Keep gateway in Terminal 1. Run sensor node in Terminal 2; after it exits, run the fan variant in the same activated directory. Expect OFF, ON, OFF; stop gateway after recording its CSV.

CONCEPTS / ACTIVE RECALL

Understand the experiment

Temperature gateway · strict threshold

Parse telemetry then issue a deterministic fan command
Parse telemetry then issue a deterministic fan command

Scientific architecture · JSON-lines gateway and fan replies

JSON-line gateway and fan — Read complete JSON line / sensor temperature; Validate field / numeric temperature; Threshold comparison / configured limit; Fan ON or OFF / emit command; Actuator reply / confirm state independently
Scientific concept map: Sensor node — TEMP message; Serial gateway — Parse temperature; Threshold decision — Strict > threshold; Fan command — FAN_ON / FAN_OFF; Actuator — Apply returned command.

Scientific foundations and analytical reasoning

A JSON-line gateway parses complete records and compares temperature against a strict threshold. Hysteresis requires a separate state-dependent rule.

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 · Gateway parsing and feedback

A gateway converts a byte stream into validated application records and applies a control policy. JSON lines use a newline delimiter; decoding JSON is not enough to establish the expected fields or acceptable ranges. A strict threshold maps temperature to a fan command. Hysteresis, if implemented separately, prevents rapid switching near the threshold.

Worked example and engineering interpretation

For a teaching rule fan ON only when T>30 °C, 30.0 gives OFF and 30.1 gives ON. An invalid temperature must not be interpreted as zero. Compare received samples, issued commands and actual actuator feedback; a command is not evidence of execution.

Engineering principles · additional worked teaching example

JSON Lines frames one object per newline. A strict fan threshold T>limit differs from T≥limit. For limit 28, readings 27,28,29 produce OFF,OFF,ON. Validate type and units before comparison; hysteresis can reduce rapid cycling near the boundary.

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 40 · IoT gateway · JSON lines and fan commands

A TCP byte stream does not preserve application message boundaries. JSON Lines uses newline delimiters; the gateway parses sensor records and chooses fan commands using its threshold. This is a real local loopback exchange with fictional readings.

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: Exchange JSON lines with an IoT gateway and verify the fan threshold.

  1. Set temperature 29 °C and threshold 30 °C. Send JSON-line sample.
  2. Repeat for exactly 30 °C and 31 °C. Compare FAN_OFF and FAN_ON; the source uses strict >.
  3. Disconnect, send, and confirm no new command. Restore.
  4. Run the existing loopback gateway and client instructions and record JSON lines and replies.

Reference check:

Model boundary:

Independent task and submission evidence

Keep the framing rule fixed; inspect the supplied threshold and fragmented input in gateway_trial. Change a valid reading around the threshold and record commands; explain why one recv call is not necessarily one message.

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

Engineering reference configuration: Temperatures separated by comma = 24,31,29,27,32; Source LIMIT / ON threshold (°C) = 30; Control law = source: > LIMIT; Extension OFF threshold (°C) = 28; Initial fan = OFF. In the classroom model, Replies = 5; State changes = 3; Final fan = ON. The source sends one reply per well-formed sensor message; hysteresis is an optional comparison, not the original algorithm. A closed, deterministic browser model. The existing practical instructions and source files provide independent execution; browser results are not hardware measurements.

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 · independent state notebook

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 40 · IoT gateway · JSON lines and fan commands: independent state notebook12345Calculated state 1Sample1Temperature °C24Gateway replyFAN_OFF\nFanOFFState changeUnchanged

Step 1 of 5 · Calculated state 1

Calculated state 1

Sample
1
Temperature °C
24
Gateway reply
FAN_OFF\n
Fan
OFF
State change
Unchanged

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

Recall the concept before revealing its explanation.

0 / 3 revealed
P40 · 01 / 08Why newline-delimited JSON?Reveal explanation
Engineering explanation

TCP is a stream; newline framing identifies each application message.

P40 · 02 / 08When is the fan ON?Reveal explanation
Engineering explanation

Only when temperature is strictly greater than 30 C.

P40 · 03 / 08What must be checked in the newline-delimited telemetry and fan-control route?Reveal explanation
Engineering explanation

Keep gateway in Terminal 1. Run sensor node in Terminal 2; after it exits, run the fan variant in the same activated directory. Expect OFF, ON, OFF; stop gateway after recording its CSV.

P40 · 04 / 08Why use a JSON line delimiter?Reveal explanation
Engineering reasoning

It establishes application record boundaries in a byte stream; parse complete lines rather than assume one read equals one record.

P40 · 05 / 08Why validate commands before changing the fan state?Reveal explanation
Engineering reasoning

Malformed or unauthorized inputs must not become actuator actions; verify allowed commands and a known safe default in the model.

P40 · 06 / 08A gateway receives JSON lines and controls a fan. Select every technically valid statement. A. Parse a complete line before interpreting the fields. B. Test values on both sides of the threshold. C. TCP guarantees one JSON object per recv call. D. An invalid sensor record should always activate the fan.Reveal explanation
Applied scenario

Correct: A. Parse a complete line before interpreting the fields.; B. Test values on both sides of the threshold.

P40 · 07 / 08In IoT gateway · JSON lines and fan commands, which command or code executes Terminal B — fan relay variant?Reveal explanation
Implementation recall

python sensor_node_fan.py

P40 · 08 / 08For IoT gateway · JSON lines and fan commands, which actual output or state confirms the prescribed practical run succeeded, and what does it not establish?Reveal explanation
Evidence & acceptance

Start gateway_server.py in A, keep it listening on 6000. B runs sensor_node.py, then sensor_node_fan.py only after the first exits. Expected decisions for 24.5,31.2,28.0 are FAN_OFF,FAN_ON,FAN_OFF; exactly 30 is OFF. CSV is in the gateway working directory. The source is a loopback teaching gateway, not authenticated or production safe. Stop A after both clients.

Execution boundary · Real TCP + simulated fan relay. 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

Exchange JSON lines with an IoT gateway and verify the fan threshold.

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

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

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
Fan relayBCM GPIO27 · physical 13Use a suitable relay/driver; not a motor directly on GPIOlab40/sensor_node_fan.py
P40 · 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

P40 · 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 40 · IoT gateway · JSON lines and fan commands

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: Actual gateway and sensor-node loopback exchange passed.

Start gateway_server.py in A, keep it listening on 6000. B runs sensor_node.py, then sensor_node_fan.py only after the first exits. Expected decisions for 24.5,31.2,28.0 are FAN_OFF,FAN_ON,FAN_OFF; exactly 30 is OFF. CSV is in the gateway working directory. The source is a loopback teaching gateway, not authenticated or production safe. Stop A after both clients.

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 24,31,29,27,32 °C and LIMIT=30, derive the five fan commands using temperature>LIMIT. Include a reading of exactly 30.

02 · Compare or justify using evidence

Compare with an alternative ON>30, OFF<28 hysteresis controller starting OFF. Explain why that extension is not the original source behavior.

03 · Boundary/design

Boundary/design · Independent work

With limit 26 and hysteresis policy ON at ≥28, OFF at ≤24, otherwise retain state, starting OFF trace 25,28,27,26,24,25. Compare with simple >26 control.

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.

Intermediate · Explain a changed-input result

Independent theoretical exercise · P40-01

Use the reference configuration (Temperatures separated by comma = 24,31,29,27,32; Source LIMIT / ON threshold (°C) = 30; Control law = source: > LIMIT; Extension OFF threshold (°C) = 28; Initial fan = OFF), but change Source LIMIT / ON threshold (°C) = 32. The model reports State changes = 0. Explain the governing rule and assumptions that make this output plausible; identify an independent verification method.

Intermediate · Quantitative comparison

Independent theoretical exercise · P40-02

Two model observations of State changes are 3 (reference) and 0 (changed condition). Compute signed change and, when the reference is nonzero, percentage change. Explain why units matter.

Intermediate · Interpret a technical trace

Independent theoretical exercise · P40-03

For Initial fan = ON, the model supplies this excerpt from Gateway trace: Sample · Temperature °C · Gateway reply · Fan · State change 1 · 24 · FAN_OFF\n · OFF · Changed 2 · 31 · FAN_ON\n · ON · Changed 3 · 29 · FAN_OFF\n · OFF · Changed 4 · 27 · FAN_OFF\n · OFF · Unchanged 5 · 32 · FAN_ON\n · ON · Changed Compute the range (maximum minus minimum) of the Temperature °C column in these rows. Identify the maximum observation. Do not extrapolate beyond these rows.

Advanced · Reverse reasoning

Independent theoretical exercise · P40-04

An observation is State changes = 4. Candidate A uses Temperatures separated by comma = 24,31,29,27,32; Source LIMIT / ON threshold (°C) = 30; Control law = source: > LIMIT; Extension OFF threshold (°C) = 28; Initial fan = OFF. Candidate B changes the listed settings (Initial fan = ON) and keeps the remaining settings fixed. Which is consistent with the observation? If both can explain it, say what additional evidence is required.

Advanced · Diagnose a reported mismatch

Independent theoretical exercise · P40-05

A student configures Source LIMIT / ON threshold (°C) = 40 while preserving all other reference settings, but copies the reference report of State changes = 3. Evaluate whether the report is justified. Identify the first configuration/output check to perform.

Challenging · Design a controlled verification

Independent theoretical exercise · P40-06

Design a controlled comparison for Lab 40 · IoT gateway · JSON lines and fan commands using reference Temperatures separated by comma = 24,31,29,27,32; Source LIMIT / ON threshold (°C) = 30; Control law = source: > LIMIT; Extension OFF threshold (°C) = 28; Initial fan = OFF and test Source LIMIT / ON threshold (°C) = 32. Specify the changed setting(s), measured metric State changes, controls, repetitions, an acceptance check and what evidence can distinguish an actual implementation from the model.

Live simulation · Gateway fan control

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

  1. Set temperature 29 °C and threshold 30 °C. Send JSON-line sample.
  2. Repeat for exactly 30 °C and 31 °C. Compare FAN_OFF and FAN_ON; the source uses strict >.
  3. Disconnect, send, and confirm no new command. Restore.
  4. Run the existing loopback gateway and client instructions and record JSON lines and replies.

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

Replay the source gateway’s strict temp > LIMIT decision for each valid JSON line; optionally compare a hysteresis extension.

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.

Temperatures separated by comma24,31,29,27,32
Source LIMIT / ON threshold (°C)30
Control lawsource: > LIMIT
Extension OFF threshold (°C)28
Initial fanOFF

2 · Perform the investigation in order

  1. Run temperatures 24,31,29,27,32 with LIMIT=30. gateway_server.py sends FAN_ON only when temp > 30; each valid line receives a reply, not only changed states.
  2. Use 30,30.1,30 to test strict inequality. Verify FAN_OFF at exactly 30.
  3. Compare the optional hysteresis extension (ON at upper, OFF at lower) and distinguish it from the supplied source. Count replies and actual actuator state changes separately.
  4. Start gateway_server.py in one WSL terminal and sensor_node_fan.py in another. Read CSV and compare the newline-terminated FAN_ON/FAN_OFF strings. Invalid numeric samples are rejected by this teaching fixture; the original server expects well-formed JSON.

3 · Compare controlled trials

TrialIndependent changeExpected checkObservation
Source referenceUse reference inputs aboveReplies: 5; State changes: 3; Final fan: ONRecord actual result
Higher limitSource LIMIT / ON threshold (°C) = 40State changes: 0Record actual result
Equality at limitTemperatures separated by comma = 30,30.1,30Final fan: OFF; Replies: 3Record actual result
Hysteresis comparisonControl law = hysteresis extensionState changes: 3Record actual result

4 · Analyze and report

The original source uses a single strict threshold, not hysteresis. Repeated commands can occur without a state change.

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 loopback TCP stream with fragmented JSON lines, virtual GPIO fan and verified command responses. 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. Terminal 1: gateway
  2. Terminal 2: sensor node
  3. Terminal B — fan relay variant
  4. Stop background processes
02 / Implement

Step-by-step instructions

Before you run / verification gate

Keep gateway in Terminal 1. Run sensor node in Terminal 2; after it exits, run the fan variant in the same activated directory. Expect OFF, ON, OFF; stop gateway after recording its CSV.

Complete one-time setup first. Copy one command block at a time into the indicated environment. Do not copy prompt characters. Open new terminals where named; variables are terminal-specific. Ctrl+C stops a running foreground command.

01

Terminal 1: gateway

WSL · Bash
source ~/psut-wsl/activate.sh
cd ~/psut-wsl/labs/python/lab40 && python gateway_server.py
✓ Expected: Normally no output. pwd should show the requested directory. A missing path produces an error; do not continue until corrected. If successful, Gateway listening on port 6000
Expected result for each action (2)
  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. cd ~/psut-wsl/labs/python/lab40 && python gateway_server.pyNormally no output. pwd should show the requested directory. A missing path produces an error; do not continue until corrected. If successful, Gateway listening on port 6000
Checkpoint Gateway listening on port 6000
02

Terminal 2: sensor node

WSL · Bash
source ~/psut-wsl/activate.sh
cd ~/psut-wsl/labs/python/lab40 && python sensor_node.py
✓ Expected: Normally no output. pwd should show the requested directory. A missing path produces an error; do not continue until corrected. If successful, sent 24.5 -> gateway says FAN_OFF , 31.2 -> FAN_ON , 28.0 -> FAN_OFF ; the gateway prints the three JSON readings.
Expected result for each action (2)
  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. cd ~/psut-wsl/labs/python/lab40 && python sensor_node.pyNormally no output. pwd should show the requested directory. A missing path produces an error; do not continue until corrected. If successful, sent 24.5 -> gateway says FAN_OFF , 31.2 -> FAN_ON , 28.0 -> FAN_OFF ; the gateway prints the three JSON readings.
Checkpoint sent 24.5 -> gateway says FAN_OFF , 31.2 -> FAN_ON , 28.0 -> FAN_OFF ; the gateway prints the three JSON readings.
03

Reuse Terminal 2 after sensor_node.py has exited. Ensure the gateway is still running in Terminal 1 and your current directory is ~/psut-wsl/labs/python/lab40.

Terminal B — fan relay variant

Stop the previous sensor node with Ctrl+C if it is still running; leave gateway Terminal A open.

WSL · Bash
python sensor_node_fan.py
✓ Expected: Gateway returns FAN_ON above 30 °C, otherwise FAN_OFF.
Checkpoint Gateway returns FAN_ON above 30 °C, otherwise FAN_OFF.
04

Stop background processes

After the client finishes, press Ctrl+C in each server/receiver terminal. If a port is busy, inspect it with ss -ltnp or ss -lunp; stop your own earlier terminal, not an unrelated service.

Checkpoint Complete the action before continuing.

Experimental notebook

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

03 / Inspect

Source code and method

labs/python/lab40/gateway_server.pyDownload source
PY · source file
# ------------------------------------------------------------
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform
# ------------------------------------------------------------
import socket, threading, json, csv
from datetime import datetime
 
HOST, PORT = '127.0.0.1', 6000        # gateway listens on loopback for lab safety
LIMIT = 30.0                        # fan switches on above 30 °C
lock = threading.Lock()             # one thread writes the CSV at a time
 
# ---- One thread per node: read JSON lines, log them, reply with a command
def handle_node(conn, addr):
    """Serve one sensor node until it disconnects."""
    # makefile('r') lets us read the TCP stream one line at a time.
    with conn, conn.makefile('r') as rx:
        for line in rx:                          # one JSON message per line
            msg = json.loads(line)               # text -> dict
            # Log the reading with a timestamp (lock = safe file access).
            with lock, open('readings.csv', 'a', newline='') as f:
                csv.writer(f).writerow([datetime.now().isoformat(),
                                        msg['id'], msg['temp']])
            # Decide the command and send it back to the same node.
            cmd = 'FAN_ON' if msg['temp'] > LIMIT else 'FAN_OFF'
            conn.sendall((cmd + '\n').encode())
            print(addr[0], msg, '->', cmd)
 
# ---- Main program: create, bind and listen on the gateway socket.
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as srv:
    srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    srv.bind((HOST, PORT))
    srv.listen()
    print('Gateway listening on port', PORT)
    while True:                                  # serve nodes forever
        conn, addr = srv.accept()                # wait for a new node
        # One thread per node, so many rooms can connect at once.
        threading.Thread(target=handle_node, args=(conn, addr),
                         daemon=True).start()
labs/python/lab40/sensor_node.pyDownload source
PY · source file
# ------------------------------------------------------------
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform
# ------------------------------------------------------------
import socket, json, time
 
GATEWAY = '127.0.0.1'               # IP of the Pi gateway (e.g. 192.168.1.20)
PORT, NODE_ID = 6000, 'room-101'    # gateway port and this node's name
 
# ---- Connect once and keep the TCP connection open for all readings.
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect((GATEWAY, PORT))
    rx = s.makefile('r')                         # read replies line by line
    for temp in [24.5, 31.2, 28.0]:              # demo values (or a DHT22)
        msg = {'id': NODE_ID, 'temp': temp}      # build the message
        # dict -> JSON text + newline (framing) -> bytes -> send
        s.sendall((json.dumps(msg) + '\n').encode())
        cmd = rx.readline().strip()              # wait for FAN_ON / FAN_OFF
        print('sent', temp, '-> gateway says', cmd)
        time.sleep(1)                            # next reading in 1 s
labs/python/lab40/sensor_node_fan.pyDownload source
PY · source file
# ------------------------------------------------------------
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform
# ------------------------------------------------------------
# ---- Sensor node with a fan relay: send readings, switch the relay on each command
import socket, json, time

try:
    from gpiozero import OutputDevice        # real Raspberry Pi: drives the relay pin
except ImportError:                          # Colab / laptop: no gpiozero → print instead
    class OutputDevice:
        """Stand-in relay that prints what the real one would do."""
        def __init__(self, pin): self.pin = pin
        def on(self): print(f'   relay GPIO{self.pin}: fan ON')
        def off(self): print(f'   relay GPIO{self.pin}: fan OFF')

GATEWAY = '127.0.0.1'               # IP of the Pi gateway (e.g. 192.168.1.20)
PORT, NODE_ID = 6000, 'room-101'    # gateway port and this node's name
fan = OutputDevice(27)              # fan relay on BCM GPIO27

# ---- Connect once and keep the TCP connection open for all readings.
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect((GATEWAY, PORT))
    rx = s.makefile('r')                         # read replies line by line
    for temp in [24.5, 31.2, 28.0]:              # demo values (or a DHT22)
        msg = {'id': NODE_ID, 'temp': temp}      # build the message
        # dict -> JSON text + newline (framing) -> bytes -> send
        s.sendall((json.dumps(msg) + '\n').encode())
        cmd = rx.readline().strip()              # wait for FAN_ON / FAN_OFF
        print('sent', temp, '-> gateway says', cmd)
        # ---- Act on the command
        fan.on() if cmd == 'FAN_ON' else fan.off()
        time.sleep(1)                            # next reading in 1 s
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

P40 · 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
# P40 · Lab 40 · IoT gateway · JSON lines and fan commands **PSUT IoT Engineering Studio — Dr. Mohammad Alja’afreh** ## Theory and purpose A TCP byte stream does not preserve application message boundaries. JSON Lines uses newline delimiters; the gateway parses sensor records and chooses fan commands using its threshold. This is a real local loopback exchange with fictional readings. **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
# =====================================================================
# P40 | Code cell 01 | Lab 40 · IoT gateway · JSON lines and fan commands
# 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 json, socket

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

# Explicit logical device adapter. Not an electrical or timing emulator.
class VirtualGPIO:
    """Explicit logical device adapter. Not an electrical or timing emulator."""
    def __init__(self):self.pins={};self.trace=[]
    def setup(self,pin,direction,pull=0):
        check(direction in ('in','out') and type(pin)==int and 0<=pin<=27,'invalid pin setup');self.pins[pin]=[direction,float(pull)]
    def _set(self,pin,val,direction):
        check(pin in self.pins and self.pins[pin][0]==direction,'incorrect pin direction');check(0<=val<=1,'invalid logical level');self.pins[pin][1]=float(val);self.trace.append((pin,float(val)))
    def write(self,pin,val):self._set(pin,val,'out')
    def drive_input(self,pin,val):self._set(pin,val,'in')
    def read(self,pin):return self.pins[pin][1]
    def pwm(self,pin,duty):self.write(pin,duty)

# Actual TCP stream framing with fragmented messages and bounded control replies.
def gateway_trial():
    """Actual TCP stream framing with fragmented messages and bounded control replies."""
    import socket
    with socket.socket() as listener:
        listener.bind(('127.0.0.1',0));listener.listen(1);listener.settimeout(3)
        with socket.create_connection(listener.getsockname(),timeout=3) as client:
            server,_=listener.accept()
            with server:
                server.settimeout(3);g=VirtualGPIO();g.setup(17,'out');results=[]
                with server.makefile('rb') as incoming,client.makefile('rb') as replies:
                    for temp in (24.5,35,30,29):
                        raw=(json.dumps({'temp':temp})+'\n').encode();client.sendall(raw[:5]);client.sendall(raw[5:]);v=json.loads(incoming.readline(4096))['temp'];g.write(17,int(v>30));command='FAN_ON' if g.read(17) else 'FAN_OFF';server.sendall((command+'\n').encode());observed=replies.readline(64).decode().strip();results.append(observed)
                check(results==['FAN_OFF','FAN_ON','FAN_OFF','FAN_OFF'],'gateway command mismatch');return results
Ask Dr. Mohammad about this cell
04Instructions · Markdown
## 2. Execute the reference and inspect observations
05Python · executable cell
PYTHON · Code cell
# =====================================================================
# P40 | Code cell 02 | Lab 40 · IoT gateway · JSON lines and fan commands
# 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.
# =====================================================================
# Set result for the next computation or reference condition.
result=gateway_trial()
print(result)
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert result==['FAN_OFF','FAN_ON','FAN_OFF','FAN_OFF']
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 cd ~/psut-wsl/labs/python/lab40 && python gateway_server.py ``` ```bash source ~/psut-wsl/activate.sh cd ~/psut-wsl/labs/python/lab40 && python sensor_node.py ``` ```bash python sensor_node_fan.py ``` ```python # ------------------------------------------------------------ # Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved. # PSUT IoT Engineering Learning Platform # ------------------------------------------------------------ import socket, threading, json, csv from datetime import datetime HOST, PORT = '127.0.0.1', 6000 # gateway listens on loopback for lab safety LIMIT = 30.0 # fan switches on above 30 °C lock = threading.Lock() # one thread writes the CSV at a time # ---- One thread per node: read JSON lines, log them, reply with a command def handle_node(conn, addr): """Serve one sensor node until it disconnects.""" # makefile('r') lets us read the TCP stream one line at a time. with conn, conn.makefile('r') as rx: for line in rx: # one JSON message per line msg = json.loads(line) # text -> dict # Log the reading with a timestamp (lock = safe file access). with lock, open('readings.csv', 'a', newline='') as f: csv.writer(f).writerow([datetime.now().isoformat(), msg['id'], msg['temp']]) # Decide the command and send it back to the same node. cmd = 'FAN_ON' if msg['temp'] > LIMIT else 'FAN_OFF' conn.sendall((cmd + '\n').encode()) print(addr[0], msg, '->', cmd) # ---- Main program: create, bind and listen on the gateway socket. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as srv: srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) srv.bind((HOST, PORT)) srv.listen() print('Gateway listening on port', PORT) while True: # serve nodes forever conn, addr = srv.accept() # wait for a new node # One thread per node, so many rooms can connect at once. threading.Thread(target=handle_node, args=(conn, addr), daemon=True).start() ``` ```python # ------------------------------------------------------------ # Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved. # PSUT IoT Engineering Learning Platform # ------------------------------------------------------------ import socket, json, time GATEWAY = '127.0.0.1' # IP of the Pi gateway (e.g. 192.168.1.20) PORT, NODE_ID = 6000, 'room-101' # gateway port and this node's name # ---- Connect once and keep the TCP connection open for all readings. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect((GATEWAY, PORT)) rx = s.makefile('r') # read replies line by line for temp in [24.5, 31.2, 28.0]: # demo values (or a DHT22) msg = {'id': NODE_ID, 'temp': temp} # build the message # dict -> JSON text + newline (framing) -> bytes -> send s.sendall((json.dumps(msg) + '\n').encode()) cmd = rx.readline().strip() # wait for FAN_ON / FAN_OFF print('sent', temp, '-> gateway says', cmd) time.sleep(1) # next reading in 1 s ``` ```python # ------------------------------------------------------------ # Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved. # PSUT IoT Engineering Learning Platform # ------------------------------------------------------------ # ---- Sensor node with a fan relay: send readings, switch the relay on each command import socket, json, time try: from gpiozero import OutputDevice # real Raspberry Pi: drives the relay pin except ImportError: # Colab / laptop: no gpiozero → print instead class OutputDevice: """Stand-in relay that prints what the real one would do.""" def __init__(self, pin): self.pin = pin def on(self): print(f' relay GPIO{self.pin}: fan ON') def off(self): print(f' relay GPIO{self.pin}: fan OFF') GATEWAY = '127.0.0.1' # IP of the Pi gateway (e.g. 192.168.1.20) PORT, NODE_ID = 6000, 'room-101' # gateway port and this node's name fan = OutputDevice(27) # fan relay on BCM GPIO27 # ---- Connect once and keep the TCP connection open for all readings. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect((GATEWAY, PORT)) rx = s.makefile('r') # read replies line by line for temp in [24.5, 31.2, 28.0]: # demo values (or a DHT22) msg = {'id': NODE_ID, 'temp': temp} # build the message # dict -> JSON text + newline (framing) -> bytes -> send s.sendall((json.dumps(msg) + '\n').encode()) cmd = rx.readline().strip() # wait for FAN_ON / FAN_OFF print('sent', temp, '-> gateway says', cmd) # ---- Act on the command fan.on() if cmd == 'FAN_ON' else fan.off() time.sleep(1) # next reading in 1 s ```
07Instructions · Markdown
## Independent investigation and submission Keep the framing rule fixed; inspect the supplied threshold and fragmented input in gateway_trial. Change a valid reading around the threshold and record commands; explain why one recv call is not necessarily one message. | Trial | Changed input | Fixed settings | Predicted output | Observed output | Explanation | |---|---|---|---|---|---| | A | baseline | | | | | | B | one change | | | | | | A repeat | baseline | | | | | Save outputs and state one limitation.