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 15 · UDP humidity server & client
IoTPSUT IoT Engineering StudioPrincess Sumaya University for Technology · Dr. Mohammad Alja’afreh
Pi practical / X15
Networking and Communication

Lab 15 · UDP humidity server & client

Ask Dr. Mohammad · X15 →

Real UDP on 127.0.0.1.

Open UDP packet analyzer →

Design experiment & verify evidence →
X15 · Laboratory mentorAsk about the current experiment, its algorithms or Python notebook.
Ask Dr. MohammadAdaptive practice
Learning workflow · Core IoT & programmingX15 · UDP humidity server & client
Readiness checksRevision deckEngineering workspaceRecord evidence

Related course access: IoT Programming and Applications — same laboratory, notebook and completion record.

X15 · Academic orientation

Scope and objectives

Scope of the experiment

Observe complete UDP message boundaries, deliberate loss and out-of-order delivery.

The focus of this experiment is to trace UDP humidity datagrams and address/port selection. Students then distinguish datagram delivery from acknowledgement guarantees, and verify received values and count missing or duplicate messages. 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 UDP humidity datagrams and address/port selection.
  • Distinguish datagram delivery from acknowledgement guarantees.
  • Verify received values and count missing or duplicate messages.
  • Identify the configured inputs (Datagram count; Drop every N (0=none); Reverse arrival order; Receive buffer bytes) and record the corresponding observed outputs with units where applicable.
  • 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 UDP humidity datagrams and address/port selection, distinguish datagram delivery from acknowledgement guarantees, and verify received values and count missing or duplicate messages.

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 received values and count missing or duplicate messages. Separate predicted values from observations.

Prerequisite knowledge and related learning

Review the following catalogue prerequisites before starting. After completion, continue to Packet encapsulation & MTU.

Environment and experimental methodology

The browser instrument and the specified local software or network environment. Use the experiment’s documented topology and distinguish modeled values from actual packet observations.

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.

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

Start receiver/server before client on port 25001. Confirm response, then stop your own server; do not kill unrelated services.

CONCEPTS / ACTIVE RECALL

Understand the experiment

Scientific architecture · UDP humidity datagram sequence

Humidity UDP sequence — Datagram sender; Network; Receiver; Send seq 1 / 0>1; Deliver seq 1 / 1>2; Send seq 2 / 0>1; No receipt for loss / 1>1; Inspect sequence gap / 2>2
Scientific concept map: Humidity sender — UDP payload and sequence; Datagram network — Loss / reorder; Receiver — One packet per read; Sequence check — Gaps and duplicates; Result — Received values.

Scientific foundations and analytical reasoning

UDP humidity datagrams retain record boundaries but loss and reordering affect the observed sequence.

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 · Humidity telemetry over UDP

UDP preserves each datagram's boundary but does not guarantee delivery or order. Sequence identifiers and timestamps support loss analysis; repeated datagrams must be distinguished from distinct samples. A server may receive from multiple clients, so identify the sender when interpreting records.

Worked example and engineering interpretation

If five datagrams are sent and only sequences 1,2,4,5 are received, four unique samples arrived and one is missing. The packet delivery ratio is 4/5=80%. Reordering does not necessarily mean loss if the delayed sequence arrives later.

Engineering principles · additional worked teaching example

UDP humidity telemetry can carry sequence and timestamp with each reading. If sequence 2 arrives after 3, sorting by acquisition sequence restores presentation order but does not erase network reordering. Lost samples must not be interpolated without a declared policy.

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 15 · UDP humidity server & client

UDP humidity request/response using a real loopback socket and fictional sensor value. UDP preserves datagram boundaries but does not guarantee delivery.

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 mock humidity measurements over UDP.

  1. Send eight numbered datagrams and inspect sequence/payload.
  2. Drop every second datagram and compute delivery ratio.
  3. Set receive buffer to 2 bytes and inspect truncation without merging datagrams.
  4. Reverse arrival order; compare the actual UDP source and its sequence handling.

Reference check:

Model boundary:

Independent task and submission evidence

Replace GET_HUMIDITY with BAD and update the expected assertion to check the error response. Record the response and explain the UDP message boundary and timeout.

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: Datagram count = 8; Drop every N (0=none) = 0; Reverse arrival order = false; Receive buffer bytes = 64. In the classroom model, Delivered datagrams = 8; Lost datagrams = 0; Truncated datagrams = 0; PDR = 100 %. No datagrams are transmitted by this browser model. 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 · progressive data plot

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 15 · UDP humidity server & client: progressive data plot12.754.56.258Sequence received181

Step 1 of 7 · Observation 1

Observation 1

Sequence received
1

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

Recall the concept before revealing its explanation.

0 / 3 revealed
X15 · 01 / 08What does UDP provide?Reveal explanation
Engineering explanation

Individual datagrams without a delivery guarantee.

X15 · 02 / 08What does a timeout mean?Reveal explanation
Engineering explanation

No matching response arrived within the wait; it is not proof of a security control.

X15 · 03 / 08What UDP sender and receiver conditions must be checked before sending?Reveal explanation
Engineering explanation

Start receiver/server before client on port 25001. Confirm response, then stop your own server; do not kill unrelated services.

X15 · 04 / 08Why use a receive timeout in a UDP request/reply lab?Reveal explanation
Engineering reasoning

A reply is application-defined and may never arrive; a timeout prevents indefinite blocking.

X15 · 05 / 08What establishes successful delivery in this lab?Reveal explanation
Engineering reasoning

Observe the expected datagram or response at the intended endpoint, not merely the return from sendto.

X15 · 06 / 08A UDP humidity message is sent. Select every technically valid statement. A. Use sequence IDs to identify missing records. B. A receive observation is needed to establish delivery. C. UDP guarantees ordered delivery. D. Sender success alone proves remote application receipt.Reveal explanation
Applied scenario

Correct: A. Use sequence IDs to identify missing records.; B. A receive observation is needed to establish delivery.

X15 · 07 / 08In UDP humidity server & client, which command or code executes Terminal 2: client?Reveal explanation
Implementation recall

source ~/psut-wsl/activate.sh cd ~/psut-wsl/labs/pi-practical python -m labs.exp15.client

X15 · 08 / 08For UDP humidity server & client, which actual output or state confirms the prescribed practical run succeeded, and what does it not establish?Reveal explanation
Evidence & acceptance

Run server A before client B; port 25001 is loopback. Expected JSON as X14 with source mock. If client times out, check server and port; restart as recovery rather than accepting a missing reply. Use --once for a single controlled exchange or Ctrl+C to stop A.

Execution boundary · Real on WSL. 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.
Independent conceptual protocol trace

Animated Lab 15 · UDP humidity server & client

Use the scenario selector to explore reference, failure and recovery. The animation is explanatory, separate from the actual terminal exercise. Animation timing is for learning, not measured protocol latency.

Recent trace events
    Shared research workbenches · network designer & advanced studies
    Concurrent-device simulation & Monte Carlo research
    Distributed digital twin · topology, protocol & battery research
    Loading experiment-specific apparatus…
    Previous model / additional reference tools
    Simulation task

    Exchange mock humidity measurements over UDP.

    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 workbenchX15 · Existing model
    01 / Explore

    Interactive lab simulation

    Browser model

    Pin and connection reference

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

    ComponentSignal / pinConnection notesSource
    DHT22 DATABCM GPIO17 · physical 113.3 V, GND; pull-up on bare sensorlabs/pi-practical/labs/common.py
    X15 · 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

    X15 · 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 15 · UDP humidity server & client

    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 loopback UDP mock humidity request/response passed.

    Run server A before client B; port 25001 is loopback. Expected JSON as X14 with source mock. If client times out, check server and port; restart as recovery rather than accepting a missing reply. Use --once for a single controlled exchange or Ctrl+C to stop A.

    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 eight numbered humidity datagrams with every fourth dropped, calculate delivery ratio and list IDs in reverse arrival order.

    02 · Compare or justify using evidence

    Explain how sequence and timestamp fields help identify gaps and why a mean of received readings may be biased.

    03 · Measurement

    Measurement · Independent work

    Eight packets sent; arrivals 1,3,4,3,6,8. Compute unique delivery, duplicates and missing IDs.

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

    Use the reference configuration (Datagram count = 8; Drop every N (0=none) = 0; Reverse arrival order = false; Receive buffer bytes = 64), but change Datagram count = 10. The model reports Delivered datagrams = 10. Explain the governing rule and assumptions that make this output plausible; identify an independent verification method.

    Intermediate · Quantitative comparison

    Independent theoretical exercise · X15-02

    Two model observations of Delivered datagrams are 8 (reference) and 10 (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 · X15-03

    For Drop every N (0=none) = 2, the model supplies this excerpt from Datagram arrivals: Sequence · Payload read · Status 1 · 1,55 · Complete 3 · 3,55.2 · Complete 5 · 5,55.4 · Complete 7 · 7,55.6 · Complete Count rows whose Payload read value is exactly “1,55”, and identify the displayed row numbers. Explain what the count describes.

    Advanced · Reverse reasoning

    Independent theoretical exercise · X15-04

    An observation is Delivered datagrams = 4. Candidate A uses Datagram count = 8; Drop every N (0=none) = 0; Reverse arrival order = false; Receive buffer bytes = 64. Candidate B changes the listed settings (Drop every N (0=none) = 2) 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 · X15-05

    A student configures Receive buffer bytes = 2 while preserving all other reference settings, but copies the reference report of Truncated datagrams = 0. Evaluate whether the report is justified. Identify the first configuration/output check to perform.

    Challenging · Design a controlled verification

    Independent theoretical exercise · X15-06

    Design a controlled comparison for Lab 15 · UDP humidity server & client using reference Datagram count = 8; Drop every N (0=none) = 0; Reverse arrival order = false; Receive buffer bytes = 64 and test Datagram count = 10. Specify the changed setting(s), measured metric Delivered datagrams, controls, repetitions, an acceptance check and what evidence can distinguish an actual implementation from the model.

    Step-by-step experimental procedure

    Observe complete UDP message boundaries, deliberate loss and out-of-order 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.

    Datagram count8
    Drop every N (0=none)0
    Reverse arrival orderNo
    Receive buffer bytes64

    2 · Perform the investigation in order

    1. Send eight numbered datagrams and inspect sequence/payload.
    2. Drop every second datagram and compute delivery ratio.
    3. Set receive buffer to 2 bytes and inspect truncation without merging datagrams.
    4. Reverse arrival order; compare the actual UDP source and its sequence handling.

    3 · Compare controlled trials

    TrialIndependent changeExpected checkObservation
    ReferenceUse reference inputs aboveDelivered datagrams: 8Record actual result
    Drop every 2Drop every N (0=none) = 2Delivered datagrams: 4Record actual result
    Tiny receive bufferReceive buffer bytes = 2Truncated datagrams: 8Record actual result

    4 · Analyze and report

    UDP does not provide reliable delivery or ordering; one receive generally returns one datagram.

    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.

    Controlled investigation · reproducible evidence

    Method. Use the existing reference workbench configuration and the named controlled changes below. A controlled variable stays fixed while the independent variable is intentionally changed; the dependent variable is the resulting observed output. First predict each trial from the Concepts page. Run the baseline, then change only the specified setting and record the outcome. For deterministic traces one execution per case and a repeated verification are sufficient; for timing or stochastic measurements repeat at least five times, recording each run, median and range. Reset to the reference state between independent comparisons.

    TrialIndependent changeDependent observation
    ReferenceUse reference inputs aboveRecord actual outcome and units
    Drop every 2Drop every N (0=none) = 2Record actual outcome and units
    Tiny receive bufferReceive buffer bytes = 2Record actual outcome and units

    Evidence: attach the completed comparison table, one trace or screenshot per condition, and actual practical terminal/hardware evidence where applicable. Explain any prediction mismatch and distinguish modeled behavior from measured results.

    Loading laboratory-specific procedure…

    Python / Google Colab notebook

    Original shared humidity protocol and mock acquisition; network transport separately verified by portal tests. Validated locally in a fresh Jupyter kernel. Download, then upload to Google Colab.

    Download NotebookOpen Google ColabAll Python notebooks

    Independent implementation sequence

    1. Terminal 1: server
    2. Terminal 2: client
    3. Stop background processes
    02 / Implement

    Step-by-step instructions

    Before you run / verification gate

    Start receiver/server before client on port 25001. Confirm response, then stop your own server; do not kill unrelated services.

    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: server

    WSL · Bash
    source ~/psut-wsl/activate.sh
    cd ~/psut-wsl/labs/pi-practical
    python -m labs.exp15.server --mock
    ✓ Expected: UDP listening on 127.0.0.1:25001; keep the server running.
    Expected result for each action (3)
    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/pi-practicalNormally no output. pwd should show the requested directory. A missing path produces an error; do not continue until corrected.
    3. python -m labs.exp15.server --mockUDP listening on 127.0.0.1:25001; keep the server running.
    Checkpoint UDP listening ('127.0.0.1', 25001)
    02

    Terminal 2: client

    WSL · Bash
    source ~/psut-wsl/activate.sh
    cd ~/psut-wsl/labs/pi-practical
    python -m labs.exp15.client
    ✓ Expected: A JSON reading containing temperature, humidity and source is received if the matching server is available.
    Expected result for each action (3)
    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/pi-practicalNormally no output. pwd should show the requested directory. A missing path produces an error; do not continue until corrected.
    3. python -m labs.exp15.clientA JSON reading containing temperature, humidity and source is received if the matching server is available.
    Checkpoint the same JSON reading as Lab 14, over UDP.
    03

    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/pi-practical/labs/exp15/client.pyDownload source
    PY · source file
    # ------------------------------------------------------------
    # Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
    # PSUT IoT Engineering Learning Platform
    # ------------------------------------------------------------
    # ====================================================================
    # LAB PURPOSE / CLIENT
    # ====================================================================
    """Experiment 15: UDP client; bounded retries because delivery is not guaranteed."""
    
    # ====================================================================
    # 01 / IMPORT REQUIRED LIBRARIES
    # ====================================================================
    import argparse
    import json
    import socket
    from labs.socket_protocol import REQUEST,MAX
    
    # ====================================================================
    # 02 / CONFIGURE A UDP DATAGRAM SOCKET
    # ====================================================================
    def request(host,port,timeout=15,retries=3):
        # Create an IPv4 UDP socket without a connection handshake.
        with socket.socket(socket.AF_INET,socket.SOCK_DGRAM) as sock:
            # connect() on UDP selects the peer; it does not perform a TCP handshake.
            # Select the peer and set the response timeout.
            sock.connect((host,port));sock.settimeout(timeout)
            # ====================================================================
            # 03 / SEND AND RETRY THE REQUEST
            # ====================================================================
            for _ in range(retries):
                # Transmit the command as one datagram.
                sock.send(REQUEST)
                try:
                    # Receive at most MAX+1 bytes to detect oversized datagrams.
                    data=sock.recv(MAX+1)
                    # Reject an oversized reply.
                    if len(data)>MAX: raise RuntimeError('Oversized datagram')
                    # Decode a successful response from JSON.
                    return json.loads(data)
                # Retry on timeout because UDP does not guarantee delivery.
                except socket.timeout: continue
        # Report failure after the bounded number of attempts.
        raise TimeoutError('UDP response not received after retries')
    
    # ====================================================================
    # 04 / CONFIGURE DESTINATION AND PRINT RESULT
    # ====================================================================
    def main():
        p=argparse.ArgumentParser(description=__doc__);p.add_argument('--host',default='127.0.0.1');p.add_argument('--port',type=int,default=25001);a=p.parse_args()
        print(json.dumps(request(a.host,a.port),indent=2))
    
    # ====================================================================
    # PROGRAM ENTRY POINT / RUN THE EXPERIMENT
    # ====================================================================
    if __name__=='__main__': main()
    
    labs/pi-practical/labs/exp15/server.pyDownload source
    PY · source file
    # ------------------------------------------------------------
    # Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
    # PSUT IoT Engineering Learning Platform
    # ------------------------------------------------------------
    # ====================================================================
    # LAB PURPOSE / SERVER
    # ====================================================================
    """Experiment 15: UDP server, return one humidity datagram per request."""
    
    # ====================================================================
    # 01 / IMPORT REQUIRED LIBRARIES
    # ====================================================================
    import argparse
    import socket
    from labs.common import sensor
    from labs.socket_protocol import reply,MAX
    
    # ====================================================================
    # 02 / CONFIGURE THE UDP SERVER
    # ====================================================================
    def main():
        p=argparse.ArgumentParser(description=__doc__);p.add_argument('--host',default='127.0.0.1');p.add_argument('--port',type=int,default=25001);p.add_argument('--mock',action='store_true');p.add_argument('--once',action='store_true');a=p.parse_args()
        # Open the sensor and an IPv4 datagram socket.
        with sensor(a.mock) as dev,socket.socket(socket.AF_INET,socket.SOCK_DGRAM) as server:
            # Bind the local address and port without listening or accepting connections.
            server.bind((a.host,a.port));print('UDP listening',server.getsockname(),flush=True)
            # ====================================================================
            # 03 / RECEIVE AND RESPOND TO DATAGRAMS
            # ====================================================================
            while True:
                # Receive a datagram and its sender address.
                data,addr=server.recvfrom(MAX+1)
                # Validate the message size and send the response to the sender.
                if len(data)<=MAX: server.sendto(reply(data,dev),addr)
                # Exit after one datagram when requested.
                if a.once: break
    
    # ====================================================================
    # PROGRAM ENTRY POINT / RUN THE EXPERIMENT
    # ====================================================================
    if __name__=='__main__':
        try: main()
        except KeyboardInterrupt: pass
    
    04 / Verify

    Evidence of completion

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

    Python / Google Colab laboratory

    X15 · 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
    # X15 · Lab 15 · UDP humidity server & client **PSUT IoT Engineering Studio — Dr. Mohammad Alja’afreh** ## Theory and purpose UDP humidity request/response using a real loopback socket and fictional sensor value. UDP preserves datagram boundaries but does not guarantee delivery. **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
    # =====================================================================
    # X15 | Code cell 01 | Lab 15 · UDP humidity server & client
    # 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 socket, json
    # Set REQUEST for the next computation or reference condition.
    REQUEST=b'GET_HUMIDITY'
    # Define the reusable operation reply; keep its logic separate from the trial.
    def reply(payload):
        return json.dumps({'humidity':45.0,'source':'fixture'} if payload==REQUEST else {'error':'bad request'}).encode()
    
    Ask Dr. Mohammad about this cell
    04Instructions · Markdown
    ## 2. Execute the reference and inspect observations
    05Python · executable cell
    PYTHON · Code cell
    # =====================================================================
    # X15 | Code cell 02 | Lab 15 · UDP humidity server & client
    # 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 socket.socket(socket.AF_INET,socket.SOCK_DGRAM) as server, socket.socket(socket.AF_INET,socket.SOCK_DGRAM) as client:
        server.bind(('127.0.0.1',0));server.settimeout(2);client.settimeout(2)
        client.sendto(REQUEST,server.getsockname());data,peer=server.recvfrom(1024)
        server.sendto(reply(data),peer);observed=json.loads(client.recvfrom(1024)[0])
    # Check the expected invariant so a mismatch fails visibly instead of appearing successful.
    print(observed);assert observed['humidity']==45.0
    
    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/pi-practical python -m labs.exp15.server --mock ``` ```bash source ~/psut-wsl/activate.sh cd ~/psut-wsl/labs/pi-practical python -m labs.exp15.client ``` ```python # ------------------------------------------------------------ # Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved. # PSUT IoT Engineering Learning Platform # ------------------------------------------------------------ # ==================================================================== # LAB PURPOSE / CLIENT # ==================================================================== """Experiment 15: UDP client; bounded retries because delivery is not guaranteed.""" # ==================================================================== # 01 / IMPORT REQUIRED LIBRARIES # ==================================================================== import argparse import json import socket from labs.socket_protocol import REQUEST,MAX # ==================================================================== # 02 / CONFIGURE A UDP DATAGRAM SOCKET # ==================================================================== def request(host,port,timeout=15,retries=3): # Create an IPv4 UDP socket without a connection handshake. with socket.socket(socket.AF_INET,socket.SOCK_DGRAM) as sock: # connect() on UDP selects the peer; it does not perform a TCP handshake. # Select the peer and set the response timeout. sock.connect((host,port));sock.settimeout(timeout) # ==================================================================== # 03 / SEND AND RETRY THE REQUEST # ==================================================================== for _ in range(retries): # Transmit the command as one datagram. sock.send(REQUEST) try: # Receive at most MAX+1 bytes to detect oversized datagrams. data=sock.recv(MAX+1) # Reject an oversized reply. if len(data)>MAX: raise RuntimeError('Oversized datagram') # Decode a successful response from JSON. return json.loads(data) # Retry on timeout because UDP does not guarantee delivery. except socket.timeout: continue # Report failure after the bounded number of attempts. raise TimeoutError('UDP response not received after retries') # ==================================================================== # 04 / CONFIGURE DESTINATION AND PRINT RESULT # ==================================================================== def main(): p=argparse.ArgumentParser(description=__doc__);p.add_argument('--host',default='127.0.0.1');p.add_argument('--port',type=int,default=25001);a=p.parse_args() print(json.dumps(request(a.host,a.port),indent=2)) # ==================================================================== # PROGRAM ENTRY POINT / RUN THE EXPERIMENT # ==================================================================== if __name__=='__main__': main() ``` ```python # ------------------------------------------------------------ # Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved. # PSUT IoT Engineering Learning Platform # ------------------------------------------------------------ # ==================================================================== # LAB PURPOSE / SERVER # ==================================================================== """Experiment 15: UDP server, return one humidity datagram per request.""" # ==================================================================== # 01 / IMPORT REQUIRED LIBRARIES # ==================================================================== import argparse import socket from labs.common import sensor from labs.socket_protocol import reply,MAX # ==================================================================== # 02 / CONFIGURE THE UDP SERVER # ==================================================================== def main(): p=argparse.ArgumentParser(description=__doc__);p.add_argument('--host',default='127.0.0.1');p.add_argument('--port',type=int,default=25001);p.add_argument('--mock',action='store_true');p.add_argument('--once',action='store_true');a=p.parse_args() # Open the sensor and an IPv4 datagram socket. with sensor(a.mock) as dev,socket.socket(socket.AF_INET,socket.SOCK_DGRAM) as server: # Bind the local address and port without listening or accepting connections. server.bind((a.host,a.port));print('UDP listening',server.getsockname(),flush=True) # ==================================================================== # 03 / RECEIVE AND RESPOND TO DATAGRAMS # ==================================================================== while True: # Receive a datagram and its sender address. data,addr=server.recvfrom(MAX+1) # Validate the message size and send the response to the sender. if len(data)<=MAX: server.sendto(reply(data,dev),addr) # Exit after one datagram when requested. if a.once: break # ==================================================================== # PROGRAM ENTRY POINT / RUN THE EXPERIMENT # ==================================================================== if __name__=='__main__': try: main() except KeyboardInterrupt: pass ```
    07Instructions · Markdown
    ## Independent investigation and submission Replace GET_HUMIDITY with BAD and update the expected assertion to check the error response. Record the response and explain the UDP message boundary and timeout. | Trial | Changed input | Fixed settings | Predicted output | Observed output | Explanation | |---|---|---|---|---|---| | A | baseline | | | | | | B | one change | | | | | | A repeat | baseline | | | | | Save outputs and state one limitation.