Skip to main content
PSUT / IoTEngineering learning studio
WORKSPACE
Offline-first portalDr. Mohammad Alja’afreh
Embedded Systems StudioIoT Programming and ApplicationsExperimentsWorkspaces
ENGINEERING WORKSPACE
Home/WSL Laboratories/Lab 39 · Internet services · HTTP and NTP
IoTPSUT IoT Engineering StudioPrincess Sumaya University for Technology · Dr. Mohammad Alja’afreh
Python & IoT / P39
Networking and Communication

Lab 39 · Internet services · HTTP and NTP

Ask Dr. Mohammad · P39 →

Secure raw HTTP request over a TLS socket, plus NTP time service.

Open TLS packet analyzer →

Design experiment & verify evidence →
P39 · Laboratory mentorAsk about the current experiment, its algorithms or Python notebook.
Ask Dr. MohammadAdaptive practice
Learning workflow · Core IoT & programmingP39 · Internet services · HTTP and NTP
Readiness checksRevision deckEngineering workspaceRecord evidence

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

P39 · Academic orientation

Scope and objectives

Scope of the experiment

Separate HTTP request outcome from four-timestamp NTP offset and round-trip delay.

The focus of this experiment is to distinguish HTTP request/response from NTP time synchronization. Students then interpret status, timestamps and delay assumptions, and verify service responses and diagnose DNS or connectivity failures. 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

  • Distinguish HTTP request/response from NTP time synchronization.
  • Interpret status, timestamps and delay assumptions.
  • Verify service responses and diagnose DNS or connectivity failures.
  • Identify the configured inputs (HTTP response; Client send t1 (ms); Server receive t2 (ms); Server send t3 (ms); Client receive t4 (ms)) 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 distinguish HTTP request/response from NTP time synchronization, interpret status, timestamps and delay assumptions, and verify service responses and diagnose DNS or connectivity failures.

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 service responses and diagnose DNS or connectivity failures. Separate predicted values from observations.

Prerequisite knowledge and related learning

Review the following catalogue prerequisites before starting. After completion, continue to Lab 7 · Bluetooth board & phone pairing.

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.

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

Internet access and DNS are required. A three-second NTP timeout is inconclusive; do not disable firewalls or certificate verification. ThingSpeak needs a private channel and write key from P34.

CONCEPTS / ACTIVE RECALL

Understand the experiment

NTP · Four timestamps and path delay

Classroom clock-offset fixture · timestamp equations, not a live NTP exchange
Classroom clock-offset fixture · timestamp equations, not a live NTP exchange

Scientific architecture · HTTP response and NTP clock calculation

HTTP and NTP are separate exchanges — Client; HTTP service; NTP service; HTTP request / 0>1; HTTP response / 1>0; NTP request t1,t2 / 0>2; NTP response t3,t4 / 2>0
Scientific concept map: HTTP client — Request URI; Server response — Status and body; NTP request — Clock timestamps; Offset calculation — Compare local and server; Application — Service and time evidence.

Scientific foundations and analytical reasoning

HTTP response codes describe the application exchange. NTP estimates offset and round-trip delay using four timestamps; asymmetry limits accuracy.

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 · HTTP exchanges and network time

An HTTP response has a status code, headers and optionally a body; transport connectivity does not guarantee application success. NTP compares four timestamps t1–t4 from client and server. Estimated offset is [(t2−t1)+(t3−t4)]/2, and delay is (t4−t1)−(t3−t2). The offset assumes approximately symmetric paths.

Worked example and engineering interpretation

For timestamps 0,70,90,100 ms the estimated offset is 30 ms and round-trip network delay is 80 ms. The time on the server is not equal to round-trip latency. Compare timeout, HTTP error and successful response as different observations.

Engineering principles · additional worked teaching example

HTTP status describes the application response; NTP estimates clock offset and network delay using four timestamps. For t1=0,t2=40,t3=50,t4=80 ms, offset=(40−30)/2=5 ms, delay=80−10=70 ms under the symmetric-delay approximation.

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 39 · Internet services · HTTP and NTP

HTTP request/response and NTP clock synchronization are different application services. HTTP returns a status and body; NTP estimates offset and round-trip delay from four timestamps. This exercise uses fictional HTTP responses and timestamps.

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: Inspect internet time and HTTPS connectivity observations.

  1. Compute offset ((t2−t1)+(t3−t4))/2 and delay (t4−t1)−(t3−t2).
  2. Set t4=160; compare estimated offset and RTT.
  3. Change HTTP status to 404; NTP calculation remains independent.
  4. Run the actual HTTP/NTP practical and compare status, local timestamps and synchronization outputs.

Reference check:

Model boundary:

Independent task and submission evidence

Hold server processing time fixed and increase t4 by 10 ms. Record offset and delay before/after; explain the symmetric-path assumption and why these are fixture values.

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: HTTP response = 200; Client send t1 (ms) = 0; Server receive t2 (ms) = 70; Server send t3 (ms) = 90; Client receive t4 (ms) = 100. In the classroom model, Clock offset = 30 ms; Round-trip delay = 80 ms; HTTP success = Yes. Timestamp calculation only; no actual clock synchronization. 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 · message sequence

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 39 · Internet services · HTTP and NTP: message sequenceClientServert1=0, t2=70t3=90, t4=100

Step 1 of 2 · t1=0, t2=70

t1=0, t2=70

1. Client → Server
t1=0, t2=70

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

Recall the concept before revealing its explanation.

0 / 3 revealed
P39 · 01 / 08What does NTP provide?Reveal explanation
Engineering explanation

A timestamp from a time server; the teaching client uses UDP 123.

P39 · 02 / 08Why use TLS for HTTP?Reveal explanation
Engineering explanation

It protects transport and verifies the service identity when correctly configured.

P39 · 03 / 08What time and transport observations must be verified before interpreting the NTP/HTTPS result?Reveal explanation
Engineering explanation

Internet access and DNS are required. A three-second NTP timeout is inconclusive; do not disable firewalls or certificate verification. ThingSpeak needs a private channel and write key from P34.

P39 · 04 / 08Why verify HTTP status and content separately?Reveal explanation
Engineering reasoning

A transport connection can succeed while the server returns an application error or unexpected representation.

P39 · 05 / 08Why compare an NTP response to a local clock carefully?Reveal explanation
Engineering reasoning

Network and processing delays affect clock estimates; a response is not proof of perfect clock synchronization.

P39 · 06 / 08A client checks HTTPS and NTP. Select every technically valid statement. A. Time synchronization and HTTP application responses are different checks. B. HTTPS endpoint identity requires certificate validation. C. An NTP response establishes HTTPS endpoint identity. D. A TCP connection alone proves a valid HTTPS certificate.Reveal explanation
Applied scenario

Correct: A. Time synchronization and HTTP application responses are different checks.; B. HTTPS endpoint identity requires certificate validation.

P39 · 07 / 08In Internet services · HTTP and NTP, which command or code executes Send an HTTP request over TLS?Reveal explanation
Implementation recall

read -rsp "ThingSpeak Write key: " THINGSPEAK_WRITE_KEY; echo export THINGSPEAK_WRITE_KEY python thingspeak_tcp.py

P39 · 08 / 08For Internet services · HTTP and NTP, which actual output or state confirms the prescribed practical run succeeded, and what does it not establish?Reveal explanation
Evidence & acceptance

NTP uses UDP 123 and needs DNS/network access. Expect a UTC time only after a valid response; timeout is inconclusive, not proof of NTP failure globally. HTTPS upload is a separate test; use a private channel and write key in the same terminal, wait between writes, require HTTP 200 and positive entry ID. Unset the key.

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.

ThingSpeak integration center

Use the dedicated setup, upload, readback and Node-RED walkthrough.

Open ThingSpeak Cloud Studio →
Independent conceptual protocol trace

Animated Lab 39 · Internet services · HTTP and NTP

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

    Inspect internet time and HTTPS connectivity observations.

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

    Interactive lab simulation

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

    P39 · 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 39 · Internet services · HTTP and NTP

    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: Source reviewed; external NTP and ThingSpeak execution pending.

    NTP uses UDP 123 and needs DNS/network access. Expect a UTC time only after a valid response; timeout is inconclusive, not proof of NTP failure globally. HTTPS upload is a separate test; use a private channel and write key in the same terminal, wait between writes, require HTTP 200 and positive entry ID. Unset the key.

    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

    Using t1=0,t2=70,t3=90,t4=100 ms, calculate offset ((t2−t1)+(t3−t4))/2 and delay (t4−t1)−(t3−t2).

    02 · Compare or justify using evidence

    Compare HTTP 200, 404 and timeout; explain why neither an HTTP response nor a single NTP exchange proves exact time synchronization.

    03 · Calculation

    Calculation · Independent work

    Given t1=10,t2=65,t3=75,t4=110 ms, derive offset and round-trip network delay. Explain why asymmetry matters.

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

    Use the reference configuration (HTTP response = 200; Client send t1 (ms) = 0; Server receive t2 (ms) = 70; Server send t3 (ms) = 90; Client receive t4 (ms) = 100), but change HTTP response = 500. The model reports HTTP success = No. Explain the governing rule and assumptions that make this output plausible; identify an independent verification method.

    Intermediate · Interpret a state transition

    Independent theoretical exercise · P39-02

    The reference model reports HTTP success: Yes. Under HTTP response = 500 it reports No. Explain which configured condition changed and what the two outputs establish, and what they do not establish.

    Intermediate · Interpret a technical trace

    Independent theoretical exercise · P39-03

    For Client send t1 (ms) = 2, the model supplies this excerpt from Execution observations: Event / item · Observed result HTTP · 200 t1 · 2 t2 · 70 t3 · 90 t4 · 100 Count rows whose Observed result value is exactly “200”, and identify the displayed row numbers. Explain what the count describes.

    Advanced · Reverse reasoning

    Independent theoretical exercise · P39-04

    An observation is Clock offset = 29 ms. Candidate A uses HTTP response = 200; Client send t1 (ms) = 0; Server receive t2 (ms) = 70; Server send t3 (ms) = 90; Client receive t4 (ms) = 100. Candidate B changes the listed settings (Client send t1 (ms) = 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 · P39-05

    A student configures Server receive t2 (ms) = 72 while preserving all other reference settings, but copies the reference report of Clock offset = 30 ms. Evaluate whether the report is justified. Identify the first configuration/output check to perform.

    Challenging · Design a controlled verification

    Independent theoretical exercise · P39-06

    Design a controlled comparison for Lab 39 · Internet services · HTTP and NTP using reference HTTP response = 200; Client send t1 (ms) = 0; Server receive t2 (ms) = 70; Server send t3 (ms) = 90; Client receive t4 (ms) = 100 and test HTTP response = 500. Specify the changed setting(s), measured metric HTTP success, controls, repetitions, an acceptance check and what evidence can distinguish an actual implementation from the model.

    Step-by-step experimental procedure

    Separate HTTP request outcome from four-timestamp NTP offset and round-trip delay.

    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.

    HTTP response200
    Client send t1 (ms)0
    Server receive t2 (ms)70
    Server send t3 (ms)90
    Client receive t4 (ms)100

    2 · Perform the investigation in order

    1. Compute offset ((t2−t1)+(t3−t4))/2 and delay (t4−t1)−(t3−t2).
    2. Set t4=160; compare estimated offset and RTT.
    3. Change HTTP status to 404; NTP calculation remains independent.
    4. Run the actual HTTP/NTP practical and compare status, local timestamps and synchronization outputs.

    3 · Compare controlled trials

    TrialIndependent changeExpected checkObservation
    ReferenceUse reference inputs aboveClock offset: 30; Round-trip delay: 80Record actual result
    HTTP failureHTTP response = 404HTTP success: NoRecord actual result
    Longer returnClient receive t4 (ms) = 160Clock offset: 0; Round-trip delay: 140Record actual result

    4 · Analyze and report

    Asymmetric delay biases an NTP offset estimate.

    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
    HTTP failureHTTP response = 404Record actual outcome and units
    Longer returnClient receive t4 (ms) = 160Record 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

    Bounded notebook reference exercise; original device/service commands are reference-only. Validated locally in a fresh Jupyter kernel. Download, then upload to Google Colab.

    Download NotebookOpen Google ColabAll Python notebooks

    Independent implementation sequence

    1. Open lab and query NTP
    2. Send an HTTP request over TLS
    ThingSpeak credential and response checks

    Use the channel Write API Key for writes; a private readback needs the channel Read API Key and numeric channel ID. Hidden input displays no characters. A positive entry ID confirms acceptance; zero or an HTTP error does not. Wait 20 seconds between writes; do not share keys or disable TLS verification.

    02 / Implement

    Step-by-step instructions

    Before you run / verification gate

    Internet access and DNS are required. A three-second NTP timeout is inconclusive; do not disable firewalls or certificate verification. ThingSpeak needs a private channel and write key from P34.

    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

    Open lab and query NTP

    The external NTP server requires Internet access and UDP/123.

    WSL · Bash
    source ~/psut-wsl/activate.sh
    cd ~/psut-wsl/labs/python/lab39
    python ntp_client.py
    ✓ Expected: UTC time or a timeout if blocked.
    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/python/lab39Normally no output. pwd should show the requested directory. A missing path produces an error; do not continue until corrected.
    3. python ntp_client.pyUTC time or a timeout if blocked.
    Checkpoint UTC time or a timeout if blocked.
    02

    Send an HTTP request over TLS

    Create a ThingSpeak channel in Lab 34. The corrected program uses TLS on TCP/443 and the environment key.

    WSL · Bash
    unset THINGSPEAK_WRITE_KEY
    python thingspeak_tcp.py
    ✓ Expected: Successful service submission reports a positive entry ID; verify the private ThingSpeak channel. A zero or HTTP error is not success.
    Checkpoint HTTP status: 200 and positive Entry ID. Do not send real keys over port 80.

    Experimental notebook

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

    03 / Inspect

    Source code and method

    labs/python/lab39/ntp_client.pyDownload source
    PY · source file
    # ------------------------------------------------------------
    # Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
    # PSUT IoT Engineering Learning Platform
    # ------------------------------------------------------------
    import socket, struct, time
     
    # ---- Real public time servers: NTP uses UDP port 123.
    NTP_SERVER = ('pool.ntp.org', 123)
    # 48-byte request; first byte 0x1b = version 3, client mode.
    packet = b'\x1b' + 47 * b'\0'
     
    with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
        s.settimeout(3)                  # give up after 3 s (UDP may lose it)
        s.sendto(packet, NTP_SERVER)     # one datagram out ...
        data, addr = s.recvfrom(48)      # ... one datagram back
     
    # Bytes 40-43 hold the server time in seconds since 1900.
    secs_1900 = struct.unpack('!I', data[40:44])[0]
    # Subtract 70 years of seconds to get Unix time (since 1970).
    unix_time = secs_1900 - 2208988800
    print('Answer from', addr)
    utc = time.gmtime(unix_time)
    print('UTC time:', time.strftime('%Y-%m-%d %H:%M:%S', utc))
    
    labs/python/lab39/thingspeak_tcp.pyDownload source
    PY · source file
    # Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
    # PSUT IoT Engineering Learning Platform — P39 HTTPS over TCP
    import os, socket, ssl, http.client, urllib.parse, sys
    from pathlib import Path
    from getpass import getpass, GetPassWarning
    import warnings
    warnings.filterwarnings("error",category=GetPassWarning)
    sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'lab34'))
    from dht22_thingspeak import validate_key, response_entry
    HOST='api.thingspeak.com'
    def main():
        try:
            key=validate_key(os.getenv('THINGSPEAK_WRITE_KEY','').strip() or getpass('ThingSpeak channel Write API Key (hidden): '))
            body=urllib.parse.urlencode({'api_key':key,'field1':24.5,'status':'tcp-demo'}).encode('ascii')
            headers=(f'POST /update HTTP/1.1\r\nHost: {HOST}\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: {len(body)}\r\nConnection: close\r\n\r\n').encode('ascii')
            with socket.create_connection((HOST,443),timeout=15) as raw:
                with ssl.create_default_context().wrap_socket(raw,server_hostname=HOST) as conn:
                    conn.sendall(headers+body)
                    reply=http.client.HTTPResponse(conn);reply.begin()
                    status=reply.status;data=reply.read(128).decode('ascii',errors='replace')
                    print('HTTP status:',status)
                    entry=response_entry(status,data)
                    print('Accepted entry ID:',entry,'— verify your private channel; wait 20 seconds before repeating.')
            return 0
    except (ValueError,RuntimeError,EOFError,GetPassWarning) as e:print('P39:',str(e),file=sys.stderr);return 1
    except (OSError,http.client.HTTPException) as e:print('P39: HTTPS exchange failed ('+type(e).__name__+'); check DNS, connectivity, clock and trust.',file=sys.stderr);return 1
    if __name__=='__main__':
        try:sys.exit(main())
        except KeyboardInterrupt:sys.exit(130)
    
    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

    P39 · 6 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
    # P39 · Lab 39 · Internet services · HTTP and NTP **PSUT IoT Engineering Studio — Dr. Mohammad Alja’afreh** ## Theory and purpose HTTP request/response and NTP clock synchronization are different application services. HTTP returns a status and body; NTP estimates offset and round-trip delay from four timestamps. This exercise uses fictional HTTP responses and timestamps. **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
    # =====================================================================
    # P39 | Code cell 01 | Lab 39 · Internet services · HTTP and NTP
    # 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.
    # =====================================================================
    # Define the reusable operation http request; keep its logic separate from the trial.
    def http_request(path):
        return (200,'sensor=25') if path=='/reading' else (404,'Not found')
    # Define the reusable operation ntp; keep its logic separate from the trial.
    def ntp(t1,t2,t3,t4):
        return ((t2-t1)+(t3-t4))/2,(t4-t1)-(t3-t2)
    
    Ask Dr. Mohammad about this cell
    04Instructions · Markdown
    ## 2. Execute the reference and inspect observations
    05Python · executable cell
    PYTHON · Code cell
    # =====================================================================
    # P39 | Code cell 02 | Lab 39 · Internet services · HTTP and NTP
    # 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.
    # =====================================================================
    # Repeat the same operation for each configured input so observations are comparable.
    for path in ('/reading','/missing'): print(path,http_request(path))
    # Repeat the same operation for each configured input so observations are comparable.
    for timestamps in [(0,12,13,21),(0,12,13,31)]: print(timestamps,ntp(*timestamps))
    # Check the expected invariant so a mismatch fails visibly instead of appearing successful.
    assert http_request('/missing')[0]==404
    # Check the expected invariant so a mismatch fails visibly instead of appearing successful.
    assert ntp(0,12,13,21)==(2,20)
    
    Ask Dr. Mohammad about this cell
    06Instructions · Markdown
    ## Independent investigation and submission Hold server processing time fixed and increase t4 by 10 ms. Record offset and delay before/after; explain the symmetric-path assumption and why these are fixture values. | Trial | Changed input | Fixed settings | Predicted output | Observed output | Explanation | |---|---|---|---|---|---| | A | baseline | | | | | | B | one change | | | | | | A repeat | baseline | | | | | Save outputs and state one limitation.