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 10 · ThingSpeak HTTPS retrieval
IoTPSUT IoT Engineering StudioPrincess Sumaya University for Technology · Dr. Mohammad Alja’afreh
Pi practical / X10
IoT Programming and Applications

Lab 10 · ThingSpeak HTTPS retrieval

Ask Dr. Mohammad · X10 →

Reading the channel back is ordinary HTTPS.

Design experiment & verify evidence →
X10 · Laboratory mentorAsk about the current experiment, its algorithms or Python notebook.
Ask Dr. MohammadAdaptive practice
Learning workflow · Core IoT & programmingX10 · ThingSpeak HTTPS retrieval
Readiness checksRevision deckEngineering workspaceRecord evidence

Related course access: Networking and Communication — same laboratory, notebook and completion record.

X10 · Academic orientation

Scope and objectives

Scope of the experiment

Read the most recent N fixture entries and distinguish empty fields, access denial and valid numerical records.

The focus of this experiment is to retrieve authorized ThingSpeak records over HTTPS. Students then interpret HTTP status, field values and missing data, and compare returned records with the channel and handle failed retrieval. 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

  • Retrieve authorized ThingSpeak records over HTTPS.
  • Interpret HTTP status, field values and missing data.
  • Compare returned records with the channel and handle failed retrieval.
  • 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 retrieve authorized ThingSpeak records over HTTPS, interpret HTTP status, field values and missing data, and compare returned records with the channel and handle failed retrieval.

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 compare returned records with the channel and handle failed retrieval. Separate predicted values from observations.

Prerequisite knowledge and related learning

Review the following catalogue prerequisites before starting. After completion, continue to Lab 11 · MySQL / MariaDB sensor database.

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.

X10 / PREPARE

Before starting

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

Ubuntu WSL setup →
Before you run / verification gate

Use the numeric ID and read key from the same channel. Complete X9 if empty. Unset the read key after verification.

CONCEPTS / ACTIVE RECALL

Understand the experiment

Scientific architecture · ThingSpeak readback and missing field handling

Channel feed readback — Feed / entry_id and timestamp; Field1 / temperature; Field2 / humidity; Missing field / preserve null; Sort and display / chronological order
Scientific concept map: Channel identifier — Read request; ThingSpeak feed — JSON entries; Field parser — Missing or invalid values; Time ordering — Entry timestamps; Display — Valid series and gaps.

Scientific foundations and analytical reasoning

A read API retrieves stored channel entries; missing fields do not imply a sensor measurement of zero. Entry count and valid-value count can differ.

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 · Cloud retrieval and completeness

A channel read returns stored entries, potentially with missing fields. Public and private channels have different access requirements. A time range or result limit can change the returned population. A valid entry identifier does not guarantee every field is present or numeric.

Worked example and engineering interpretation

If five entries contain four numeric humidity values and one null, entry count=5 and valid humidity count=4. Compute the average using the four valid values and report the missing field. Verify the selected channel, field and ordering before comparing against local samples.

Engineering principles · additional worked teaching example

Channel retrieval reads stored data, not necessarily the latest live sensor value. An HTTP response can contain a blank field or an empty feed; validate JSON shape and timestamps before calculating statistics. Latest 3 of IDs 8–12 are 10,11,12.

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 10 · ThingSpeak HTTPS retrieval

ThingSpeak retrieval reads existing channel entries and may require a read key for private channels. This offline fixture models JSON readback, field conversion and missing values; no account or cloud request is made.

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: Retrieve channel measurements using the correct read credentials.

  1. Set last N to 5 and authorize read. Step and count entries.
  2. Set missing humidity every 2 entries; repeat and count missing values. Explain why absent is not zero.
  3. Disable authorization, step, then restore and request 10 entries.
  4. Use the original readback script for an actual authorized channel; keep its results separate.

Reference check:

Model boundary:

Independent task and submission evidence

Compare limits 1 and 2; record returned entry IDs and missing field2. Test authorized=False using try/except and explain why missing data is not zero.

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: Stored entries = 10; Requested latest entries = 5; Empty field every N (0=none) = 0; Read access granted = true. In the classroom model, Returned entries = 5; Numeric readings = 5; Mean = 25.7. Local fictional feed data; no actual channel is read. 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 10 · ThingSpeak HTTPS retrieval: progressive data plot25.525.625.725.825.9field16106

Step 1 of 5 · Observation 6

Observation 6

field1
25.5

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

Recall the concept before revealing its explanation.

0 / 3 revealed
X10 · 01 / 08What is a read API key?Reveal explanation
Engineering explanation

A credential for retrieving a private channel's data.

X10 · 02 / 08Why may results be empty?Reveal explanation
Engineering explanation

The channel may not yet contain accepted uploads.

X10 · 03 / 08What channel access and retrieval prerequisites must be established?Reveal explanation
Engineering explanation

Use the numeric ID and read key from the same channel. Complete X9 if empty. Unset the read key after verification.

X10 · 04 / 08Why use the read permission rather than a write key for retrieval?Reveal explanation
Engineering reasoning

It limits credentials to the intended operation and reduces unintended modification privileges.

X10 · 05 / 08Why might a valid query return an empty feed?Reveal explanation
Engineering reasoning

The channel may have no entries in the selected range; distinguish empty results from transport, auth and parsing errors.

X10 · 06 / 08A private ThingSpeak channel is read. Select every technically valid statement. A. Use the appropriate read credentials. B. Check returned fields and timestamps. C. A write key is required for every public read. D. A successful response guarantees the data is current.Reveal explanation
Applied scenario

Correct: A. Use the appropriate read credentials.; B. Check returned fields and timestamps.

X10 · 07 / 08In ThingSpeak HTTPS retrieval, which command or code executes Retrieve readings?Reveal explanation
Implementation recall

source ~/psut-wsl/activate.sh cd ~/psut-wsl/labs/pi-practical read -rp "Numeric channel ID: " THINGSPEAK_CHANNEL export THINGSPEAK_CHANNEL read -rsp "ThingSpeak Read key: " THINGSPEAK_READ_KEY; echo export THINGSPEAK_READ_KEY python -m labs.exp10.download

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

Finish X9 first. Use numeric channel ID and its Read API Key (not Write key). Run in pi-practical from activated terminal. Compare entry ID, timestamp, field1/field2 and provenance status with X9. An older entry is not evidence of a new upload. Unset Read key and channel variables.

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 →
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

Retrieve channel measurements using the correct read credentials.

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

Interactive lab simulation

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

X10 · 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 10 · ThingSpeak HTTPS retrieval

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 REST read helper tested on local HTTP fixture; ThingSpeak pending.

Finish X9 first. Use numeric channel ID and its Read API Key (not Write key). Run in pi-practical from activated terminal. Compare entry ID, timestamp, field1/field2 and provenance status with X9. An older entry is not evidence of a new upload. Unset Read key and channel variables.

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

From ten records request latest five. Number records 1–10 and list selected IDs. If every third record has a blank field, count valid values.

02 · Compare or justify using evidence

Explain the effect of a denied read request; distinguish no data, blank value and actual zero when calculating mean.

03 · Data analysis

Data analysis · Independent work

Latest four feed entries have values 18, blank, 22, 20. Calculate valid count and mean; state what to report alongside the result.

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

Use the reference configuration (Stored entries = 10; Requested latest entries = 5; Empty field every N (0=none) = 0; Read access granted = true), but change Stored entries = 12. The model reports Mean = 25.9. Explain the governing rule and assumptions that make this output plausible; identify an independent verification method.

Intermediate · Quantitative comparison

Independent theoretical exercise · X10-02

Two model observations of Mean are 25.7 (reference) and 25.9 (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 · X10-03

For Requested latest entries = 7, the model supplies this excerpt from Feed entries: Entry ID · Field value 4 · 25.3 5 · 25.4 6 · 25.5 7 · 25.6 8 · 25.7 Compute the range (maximum minus minimum) of the Field value column in these rows. Identify the maximum observation. Do not extrapolate beyond these rows.

Advanced · Reverse reasoning

Independent theoretical exercise · X10-04

An observation is Returned entries = 7. Candidate A uses Stored entries = 10; Requested latest entries = 5; Empty field every N (0=none) = 0; Read access granted = true. Candidate B changes the listed settings (Requested latest entries = 7) 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 · X10-05

A student configures Empty field every N (0=none) = 10 while preserving all other reference settings, but copies the reference report of Numeric readings = 5. Evaluate whether the report is justified. Identify the first configuration/output check to perform.

Challenging · Design a controlled verification

Independent theoretical exercise · X10-06

Design a controlled comparison for Lab 10 · ThingSpeak HTTPS retrieval using reference Stored entries = 10; Requested latest entries = 5; Empty field every N (0=none) = 0; Read access granted = true and test Stored entries = 12. Specify the changed setting(s), measured metric Mean, controls, repetitions, an acceptance check and what evidence can distinguish an actual implementation from the model.

Live simulation · Feed retrieval

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

  1. Set last N to 5 and authorize read. Step and count entries.
  2. Set missing humidity every 2 entries; repeat and count missing values. Explain why absent is not zero.
  3. Disable authorization, step, then restore and request 10 entries.
  4. Use the original readback script for an actual authorized channel; keep its results separate.

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

Read the most recent N fixture entries and distinguish empty fields, access denial and valid numerical records.

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.

Stored entries10
Requested latest entries5
Empty field every N (0=none)0
Read access grantedYes

2 · Perform the investigation in order

  1. Read latest five of ten entries; inspect IDs and values.
  2. Set empty field every second entry; compare returned records to numeric readings.
  3. Deny read access; do not interpret empty response as a numeric zero.
  4. Run the actual ThingSpeak read API example; parse field values and nulls explicitly.

3 · Compare controlled trials

TrialIndependent changeExpected checkObservation
Five entriesUse reference inputs aboveReturned entries: 5; Numeric readings: 5Record actual result
DeniedRead access granted = NoReturned entries: 0Record actual result
Missing fieldEmpty field every N (0=none) = 2Numeric readings: 2Record actual result

4 · Analyze and report

A channel entry can exist without the requested sensor field.

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 HTTP writes and queries with negative authentication test; optional genuine ThingSpeak HTTPS write/readback using your own channel. 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. Find channel ID and read key
  2. Retrieve readings
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

Use the numeric ID and read key from the same channel. Complete X9 if empty. Unset the read key after verification.

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

Find channel ID and read key

Open your ThingSpeak channel → API Keys. Copy the Read API Key for your private channel and the numeric channel ID.

Checkpoint Complete the action before continuing.
02

Retrieve readings

Enter the number at the first prompt and key at the hidden second prompt.

WSL · Bash
source ~/psut-wsl/activate.sh
cd ~/psut-wsl/labs/pi-practical
read -rp "Numeric channel ID: " THINGSPEAK_CHANNEL
export THINGSPEAK_CHANNEL
read -rsp "ThingSpeak Read key: " THINGSPEAK_READ_KEY; echo
export THINGSPEAK_READ_KEY
python -m labs.exp10.download
✓ Expected: Channel entries are retrieved and printed; an empty channel may contain no records yet.
Expected result for each action (7)
  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. read -rp "Numeric channel ID: " THINGSPEAK_CHANNELThe shell prompts for the requested value and waits for Enter. Use the actual channel ID or path, not an example placeholder.
  4. export THINGSPEAK_CHANNELUsually silent. The variable is inherited by child processes launched from this terminal; never print a secret to verify it.
  5. read -rsp "ThingSpeak Read key: " THINGSPEAK_READ_KEY; echoA secret-entry prompt appears; typing is not echoed. Enter only your local lab credential. Nothing should expose its value.
  6. export THINGSPEAK_READ_KEYUsually silent. The variable is inherited by child processes launched from this terminal; never print a secret to verify it.
  7. python -m labs.exp10.downloadChannel entries are retrieved and printed; an empty channel may contain no records yet.
Checkpoint JSON/parsed entries from the channel. Run Lab 9 if channel is empty.

Experimental notebook

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

03 / Inspect

Source code and method

labs/pi-practical/labs/exp10/download.pyDownload source
PY · source file
# ------------------------------------------------------------
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform
# ------------------------------------------------------------
# ====================================================================
# LAB PURPOSE / DOWNLOAD
# ====================================================================
"""Experiment 10: read most recent ThingSpeak entry over HTTPS."""

# ====================================================================
# 01 / IMPORT REQUIRED LIBRARIES
# ====================================================================
import os
from labs.common import require_env
from labs.thingspeak import read_latest

# ====================================================================
# 02 / RETRIEVE THE LATEST CLOUD RECORD
# ====================================================================
def main():
    try:
        # Use the channel ID and optional read key to fetch one JSON entry.
        row = read_latest(require_env('THINGSPEAK_CHANNEL'), os.getenv('THINGSPEAK_READ_KEY',''))
        # Extract the timestamp, temperature, humidity and source fields.
        print('Entry:', row['entry_id'], 'Time:', row.get('created_at'), 'Temperature:', row.get('field1'), 'Humidity:', row.get('field2'), 'Source:', row.get('status'))
    # Return a clear error if the channel cannot be read.
    except (OSError, ValueError, RuntimeError): raise SystemExit('Read failed: verify channel, permissions, and network.') from None

# ====================================================================
# PROGRAM ENTRY POINT / RUN THE EXPERIMENT
# ====================================================================
if __name__ == '__main__': main()
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

X10 · 9 notebook cells · 3 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
# X10 · Lab 10 · ThingSpeak HTTPS retrieval **PSUT IoT Engineering Studio — Dr. Mohammad Alja’afreh** ## Theory and purpose ThingSpeak retrieval reads existing channel entries and may require a read key for private channels. This offline fixture models JSON readback, field conversion and missing values; no account or cloud request is made. **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
# =====================================================================
# X10 | Code cell 01 | Lab 10 · ThingSpeak HTTPS retrieval
# 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
# Set response for the next computation or reference condition.
response='{"feeds":[{"entry_id":1,"field1":"25.0","field2":"45"},{"entry_id":2,"field1":"26.5","field2":null}]}'
# Define the reusable operation read; keep its logic separate from the trial.
def read(response,limit,authorized=True):
    if not authorized: raise PermissionError('Read not authorized')
    if limit<1: raise ValueError('Positive limit')
    return json.loads(response)['feeds'][-limit:]
Ask Dr. Mohammad about this cell
04Instructions · Markdown
## 2. Execute the reference and inspect observations
05Python · executable cell
PYTHON · Code cell
# =====================================================================
# X10 | Code cell 02 | Lab 10 · ThingSpeak HTTPS retrieval
# 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 limit in (1,2):
    rows=read(response,limit)
    print(limit,[(r['entry_id'],float(r['field1']),r['field2']) for r in rows])
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert read(response,1)[0]['entry_id']==2
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert read(response,1)[0]['field2'] is None
Ask Dr. Mohammad about this cell
06Instructions · Markdown
## 3. Compare the controlled conditions
07Python · executable cell
PYTHON · Code cell
# =====================================================================
# X10 | Code cell 03 | Lab 10 · ThingSpeak HTTPS retrieval
# Purpose: 3. Compare the controlled conditions
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
# Set LIVE for the next computation or reference condition.
LIVE=False  # Set True only for your authorized channel
if LIVE:
    from getpass import getpass
    from urllib.request import urlopen
    from urllib.parse import urlencode
    channel_id=input('Authorized channel ID: ').strip()
    if not channel_id.isdigit(): raise ValueError('Numeric channel ID required')
    read_key=getpass('Read key (blank for public channel): ')
    url=f'https://api.thingspeak.com/channels/{channel_id}/feeds.json?'+urlencode({'results':2,**({'api_key':read_key} if read_key else {})})
    with urlopen(url,timeout=15) as reply: live_data=json.load(reply)
    print([(row['entry_id'],row.get('field1'),row.get('field2')) for row in live_data['feeds']])
    del read_key,url
Ask Dr. Mohammad about this cell
08Instructions · 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 read -rp "Numeric channel ID: " THINGSPEAK_CHANNEL export THINGSPEAK_CHANNEL read -rsp "ThingSpeak Read key: " THINGSPEAK_READ_KEY; echo export THINGSPEAK_READ_KEY python -m labs.exp10.download ``` ```python # ------------------------------------------------------------ # Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved. # PSUT IoT Engineering Learning Platform # ------------------------------------------------------------ # ==================================================================== # LAB PURPOSE / DOWNLOAD # ==================================================================== """Experiment 10: read most recent ThingSpeak entry over HTTPS.""" # ==================================================================== # 01 / IMPORT REQUIRED LIBRARIES # ==================================================================== import os from labs.common import require_env from labs.thingspeak import read_latest # ==================================================================== # 02 / RETRIEVE THE LATEST CLOUD RECORD # ==================================================================== def main(): try: # Use the channel ID and optional read key to fetch one JSON entry. row = read_latest(require_env('THINGSPEAK_CHANNEL'), os.getenv('THINGSPEAK_READ_KEY','')) # Extract the timestamp, temperature, humidity and source fields. print('Entry:', row['entry_id'], 'Time:', row.get('created_at'), 'Temperature:', row.get('field1'), 'Humidity:', row.get('field2'), 'Source:', row.get('status')) # Return a clear error if the channel cannot be read. except (OSError, ValueError, RuntimeError): raise SystemExit('Read failed: verify channel, permissions, and network.') from None # ==================================================================== # PROGRAM ENTRY POINT / RUN THE EXPERIMENT # ==================================================================== if __name__ == '__main__': main() ```
09Instructions · Markdown
## Independent investigation and submission Compare limits 1 and 2; record returned entry IDs and missing field2. Test authorized=False using try/except and explain why missing data is not zero. | Trial | Changed input | Fixed settings | Predicted output | Observed output | Explanation | |---|---|---|---|---|---| | A | baseline | | | | | | B | one change | | | | | | A repeat | baseline | | | | | Save outputs and state one limitation.