Skip to main content
PSUT / IoTEngineering learning studio
WORKSPACE
Offline-first portalDr. Mohammad Alja’afreh
Cyber Defense StudioIoT Security and PrivacyExperimentsWorkspaces
ENGINEERING WORKSPACE
Home/WSL Laboratories/Lab 9 · ThingSpeak HTTPS upload
IoTPSUT IoT Engineering StudioPrincess Sumaya University for Technology · Dr. Mohammad Alja’afreh
Pi practical / X9
IoT Programming and Applications

Lab 9 · ThingSpeak HTTPS upload

Ask Dr. Mohammad · X9 →

Real HTTPS upload from WSL; use --mock so the channel shows labelled demo data.

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

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

X9 · Academic orientation

Scope and objectives

Scope of the experiment

Model the supplied exp09 upload loop, explicit mock provenance and response interpretation; do not assume an ESP32 Wi-Fi sketch.

The focus of this experiment is to construct an authorized ThingSpeak HTTPS upload with correct fields. Students then distinguish successful transport from application acceptance and rate constraints, and verify the channel update without exposing credentials. 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

  • Construct an authorized ThingSpeak HTTPS upload with correct fields.
  • Distinguish successful transport from application acceptance and rate constraints.
  • Verify the channel update without exposing credentials.
  • 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 construct an authorized ThingSpeak HTTPS upload with correct fields, distinguish successful transport from application acceptance and rate constraints, and verify the channel update without exposing credentials.

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 the channel update without exposing credentials. Separate predicted values from observations.

Prerequisite knowledge and related learning

Review the following catalogue prerequisites before starting. After completion, continue to Lab 10 · ThingSpeak HTTPS retrieval.

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.

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

Finish P34 channel setup first. Wait for all three submissions (may take 40 seconds or more); confirm actual entries and unset the write key.

CONCEPTS / ACTIVE RECALL

Understand the experiment

Scientific architecture · Raspberry Pi DHT22 → ThingSpeak HTTPS uploads

HTTPS sensor uploads — Pi client; TLS endpoint; ThingSpeak store; Acquire sensor sample / 0>0; TLS verification / 0>1; Submit write / 0>1; Accepted entry / 1>2; Response / 1>0
Scientific concept map: DHT22 — Sensor values; Pi HTTPS client — Channel write request; TLS transport — Server trust; ThingSpeak — Entry ID; Feed — Accepted sample history.

Scientific foundations and analytical reasoning

HTTPS adds authenticated transport to ThingSpeak writes; certificate validation, Write API Key and sensor validity remain distinct conditions.

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 · HTTPS and channel write permissions

HTTPS authenticates the server through its certificate and protects data in transit. The channel Write API Key authorizes the application operation; it is not the TLS key. A correct key does not cure an invalid sensor payload, rate limit or server-identity failure.

Worked example and engineering interpretation

An HTTP response and a positive entry ID provide different evidence. Compare the lab's valid write, rejected key and premature write in separate trials. Never paste a real key into a shared screenshot or exported report; use a placeholder in documentation.

Engineering principles · additional worked teaching example

An HTTPS upload has transport authentication, request authorization, rate-limit policy and storage acceptance. A 25 s interval gives four attempts at 0,25,50,75 s; time span is 75 s, not 100. Validate the actual channel response.

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 9 · ThingSpeak HTTPS upload

ThingSpeak HTTPS upload maps temperature and humidity to channel fields; a successful write returns an entry ID. The local fixture models credential rejection and the minimum interval chosen for this classroom trial; it is not a live cloud response. The later cell performs an actual local HTTP exchange and optionally a real HTTPS write/readback on your own channel.

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: Upload a measurement to ThingSpeak and inspect the result.

  1. Set 23 °C and 63% RH; submit an accepted write.
  2. In the independent HTTPS gate disable certificate trust and send; restore trust and test the credential condition separately.
  3. Compare the results. Execute the original Python upload procedure using your authorized channel.
  4. Use mock source, key accepted and TLS trusted. Inspect field1, field2, status and each positive entry ID.

Reference check:

Model boundary:

Independent task and submission evidence

Keep the payload fixed; compare valid versus invalid authorization and a 5 s versus 15 s interval in the fixture. Record entry IDs. Real channel limits depend on the account; verify using the authorized live procedure.

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: Upload interval (s) = 15; Configured service minimum interval (s) = 15; Upload attempts = 6; Demonstration write key accepted = true; HTTPS connection succeeds = true; Temperature (°C) = 23; Humidity (%) = 63; Trusted HTTPS certificate = true; Sensor source = mock. In the classroom model, Stored entries = 6; TLS channel = Yes; Rejected attempts = 0. No credentials or network requests in this model; source values are fictional even when hardware provenance is selected for comparison. A closed, deterministic browser model. The existing practical instructions and source files provide independent execution; browser results are not hardware measurements.

Use the diagram to follow the calculation or state progression. Keep the teaching configuration separate from the independent exercise values; compare observations with the actual model and implementation.

Concept animation · independent state notebook

Explore the teaching example independently of the simulator. Each step reveals an operation, data relationship or calculated state. The Simulation view has separate editable inputs.

Lab 9 · ThingSpeak HTTPS upload: independent state notebook123456Calculated state 1Time s0Field1 °C23Field2 %63Status provenancemockHTTP200Entry/body1

Step 1 of 6 · Calculated state 1

Calculated state 1

Time s
0
Field1 °C
23
Field2 %
63
Status provenance
mock
HTTP
200
Entry/body
1
Outcome
Stored

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

Recall the concept before revealing its explanation.

0 / 3 revealed
X9 · 01 / 08Why respect upload intervals?Reveal explanation
Engineering explanation

Cloud APIs may reject updates sent too quickly.

X9 · 02 / 08What proves cloud storage?Reveal explanation
Engineering explanation

Positive entry IDs and matching private channel records.

X9 · 03 / 08What must be verified before repeat HTTPS cloud writes?Reveal explanation
Engineering explanation

Finish P34 channel setup first. Wait for all three submissions (may take 40 seconds or more); confirm actual entries and unset the write key.

X9 · 04 / 08Why use HTTPS for a ThingSpeak upload?Reveal explanation
Engineering reasoning

TLS protects data in transit and authenticates the endpoint when certificate verification is enabled.

X9 · 05 / 08Why verify the entry identifier or stored fields?Reveal explanation
Engineering reasoning

A request sent by the client does not by itself prove the service accepted and stored the data.

X9 · 06 / 08A ThingSpeak HTTPS write is configured. Select every technically valid statement. A. Protect the write key. B. Check the returned result and stored entry. C. The channel ID alone always authorizes writes. D. Disabling certificate validation establishes the server identity.Reveal explanation
Applied scenario

Correct: A. Protect the write key.; B. Check the returned result and stored entry.

X9 · 07 / 08In ThingSpeak HTTPS upload, which command or code executes Upload three samples?Reveal explanation
Implementation recall

source ~/psut-wsl/activate.sh cd ~/psut-wsl/labs/pi-practical read -rsp "ThingSpeak Write key: " THINGSPEAK_WRITE_KEY; echo export THINGSPEAK_WRITE_KEY python -m labs.exp09.upload --mock --count 3

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

Create private channel with Field 1 temperature, Field 2 humidity and optional status field. Set only Write API Key in current terminal. --count 3 defaults to 20 s between samples. Each accepted entry must be positive; count the three accepted IDs, not just process exit. Any Upload failed line means incomplete experiment. Verify in channel and unset key.

Execution boundary · Real HTTPS + mock data. 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

Upload a measurement to ThingSpeak and inspect the result.

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 workbenchX9 · 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
X9 · 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

X9 · 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 9 · ThingSpeak HTTPS upload

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

Create private channel with Field 1 temperature, Field 2 humidity and optional status field. Set only Write API Key in current terminal. --count 3 defaults to 20 s between samples. Each accepted entry must be positive; count the three accepted IDs, not just process exit. Any Upload failed line means incomplete experiment. Verify in channel and unset 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

At 15 s intervals for six attempts, calculate the time span and upper bound on accepted records if all gates pass and minimum interval is 15 s.

02 · Compare or justify using evidence

Construct a truth table for valid certificate, accepted key and valid sample. Explain which actual evidence distinguishes transport failure from rejected cloud write.

03 · Investigation design

Investigation design · Independent work

With 10 s attempted intervals over 61 s (t=0 through 60) and teaching minimum accepted interval 15 s, count attempts and accepted writes when other gates pass.

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

Use the reference configuration (Upload interval (s) = 15; Configured service minimum interval (s) = 15; Upload attempts = 6; Demonstration write key accepted = true; HTTPS connection succeeds = true; Temperature (°C) = 23; Humidity (%) = 63; Trusted HTTPS certificate = true; Sensor source = mock), but change Upload interval (s) = 13. The model reports Stored entries = 3. Explain the governing rule and assumptions that make this output plausible; identify an independent verification method.

Intermediate · Quantitative comparison

Independent theoretical exercise · X9-02

Two model observations of Stored entries are 6 (reference) and 3 (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 · X9-03

For Configured service minimum interval (s) = 17, the model supplies this excerpt from Upload trace: Time s · Field1 °C · Field2 % · Status provenance · HTTP · Entry/body · Outcome 0 · 23 · 63 · mock · 200 · 1 · Stored 15 · 23.6 · 62.8 · mock · 200 · 0 · Rate limited 30 · 24.2 · 62.4 · mock · 200 · 2 · Stored 45 · 24.7 · 61.6 · mock · 200 · 0 · Rate limited 60 · 25.2 · 60.6 · mock · 200 · 3 · Stored Compute the range (maximum minus minimum) of the Field1 °C column in these rows. Identify the maximum observation. Do not extrapolate beyond these rows.

Advanced · Reverse reasoning

Independent theoretical exercise · X9-04

An observation is Stored entries = 3. Candidate A uses Upload interval (s) = 15; Configured service minimum interval (s) = 15; Upload attempts = 6; Demonstration write key accepted = true; HTTPS connection succeeds = true; Temperature (°C) = 23; Humidity (%) = 63; Trusted HTTPS certificate = true; Sensor source = mock. Candidate B changes the listed settings (Configured service minimum interval (s) = 17) 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 · X9-05

A student configures Upload attempts = 8 while preserving all other reference settings, but copies the reference report of Stored entries = 6. Evaluate whether the report is justified. Identify the first configuration/output check to perform.

Challenging · Design a controlled verification

Independent theoretical exercise · X9-06

Design a controlled comparison for Lab 9 · ThingSpeak HTTPS upload using reference Upload interval (s) = 15; Configured service minimum interval (s) = 15; Upload attempts = 6; Demonstration write key accepted = true; HTTPS connection succeeds = true; Temperature (°C) = 23; Humidity (%) = 63; Trusted HTTPS certificate = true; Sensor source = mock and test Upload interval (s) = 13. Specify the changed setting(s), measured metric Stored entries, controls, repetitions, an acceptance check and what evidence can distinguish an actual implementation from the model.

Live simulation · HTTPS upload

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

  1. Set 23 °C and 63% RH; submit an accepted write.
  2. In the independent HTTPS gate disable certificate trust and send; restore trust and test the credential condition separately.
  3. Compare the results. Execute the original Python upload procedure using your authorized channel.

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

Model the supplied exp09 upload loop, explicit mock provenance and response interpretation; do not assume an ESP32 Wi-Fi sketch.

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.

Upload interval (s)15
Configured service minimum interval (s)15
Upload attempts6
Demonstration write key acceptedYes
HTTPS connection succeedsYes
Temperature (°C)23
Humidity (%)63
Trusted HTTPS certificateYes
Sensor sourcemock

2 · Perform the investigation in order

  1. Use mock source, key accepted and TLS trusted. Inspect field1, field2, status and each positive entry ID.
  2. Set interval below 15 s; the actual X9 CLI refuses that free-tier interval before running. The browser deliberately explores modeled service-side rejection for teaching.
  3. Disable TLS or HTTPS; compare no response with an HTTP 200 response containing 0. The service does not reveal the cause of every zero response.
  4. Use python -m labs.exp09.upload --mock --count 3 --interval 20 from pi-practical. Enter the Write API Key at the hidden prompt or via a current terminal variable. Check source status and field1/field2 in the private channel.

3 · Compare controlled trials

TrialIndependent changeExpected checkObservation
Accepted updatesUse reference inputs aboveStored entries: 6Record actual result
TLS errorTrusted HTTPS certificate = NoStored entries: 0Record actual result
Wrong keyDemonstration write key accepted = NoStored entries: 0Record actual result
Too frequentUpload interval (s) = 5Stored entries: 2Record actual result

4 · Analyze and report

This practical uses the Python Pi sensor abstraction and an actual HTTPS REST request, not ESP32 firmware.

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. Prepare ThingSpeak
  2. Upload three samples
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

Finish P34 channel setup first. Wait for all three submissions (may take 40 seconds or more); confirm actual entries and unset the write key.

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

Prepare ThingSpeak

Follow channel creation in Python Lab 34. This lab sends mock readings.

Checkpoint Complete the action before continuing.
02

Upload three mock DHT22 samples

First complete P34 local test. The Pi Python upload program prompts for the channel Write API Key if it is unset. It rejects intervals below 15 seconds and the command below uses 20 seconds.

WSL · Bash
source ~/psut-wsl/activate.sh
cd ~/psut-wsl/labs/pi-practical
unset THINGSPEAK_WRITE_KEY
python -m labs.exp09.upload --mock --count 3 --interval 20
Expected: Three positive entry IDs for a healthy channel. Failures are reported with a diagnostic and a nonzero exit status.
Checkpoint Confirm Field 1, Field 2 and mock status in your private channel. No API key is displayed.

Experimental notebook

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

03 / Inspect

Source code and method

labs/pi-practical/labs/exp09/upload.pyDownload source
PY · source file
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform — X9
"""Upload labelled DHT22 readings via HTTPS; any failed sample/write is visible."""
import math
from getpass import GetPassWarning
import sys
from labs.common import parser, sensor, samples
from labs.thingspeak import write, write_key
def main():
    p = parser(__doc__, interval=20, count=3)
    a = p.parse_args()
    if not math.isfinite(a.interval) or a.interval < 15 or a.count<0:
        p.error('Use a finite interval >= 15 seconds and count >= 0; 20 seconds is recommended for a free channel.')
    try:
        key = write_key()
        print('Key format checked locally; authorization is confirmed only by the service.')
    except (ValueError,RuntimeError,EOFError,GetPassWarning) as e:
        print('Credential error:',str(e),file=sys.stderr);return 1
failures=0;accepted=0
try:
        with sensor(a.mock) as device:
            for r in samples(device,a.interval,a.count):
                try:
                    entry=write(r,key);accepted+=1
print('HTTP 200; accepted entry:',entry,r.json(),flush=True)
                except (ValueError,RuntimeError,OSError) as e:
                    failures+=1;print('Upload failed:',str(e),flush=True)
    except (ImportError,OSError,RuntimeError):
        print('Sensor unavailable. In WSL use --mock or activate fakepi; verify physical GPIO on a Pi.',file=sys.stderr);return 1
print(f'Accepted: {accepted}; failed: {failures}. Verify the private channel entries.')
    return 1 if failures or not accepted else 0
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

X9 · 10 notebook cells · 4 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
# X9 · Lab 9 · ThingSpeak HTTPS upload **PSUT IoT Engineering Studio — Dr. Mohammad Alja’afreh** ## Theory and purpose ThingSpeak HTTPS upload maps temperature and humidity to channel fields; a successful write returns an entry ID. The local fixture models credential rejection and the minimum interval chosen for this classroom trial; it is not a live cloud response. The later cell performs an actual local HTTP exchange and optionally a real HTTPS write/readback on your own channel. **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
# =====================================================================
# X9 | Code cell 01 | Lab 9 · ThingSpeak HTTPS upload
# 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.
# =====================================================================
from urllib.parse import urlencode
# Encapsulate state and operations for Channel; keep its logic separate from the trial.
class Channel:
    def __init__(self): self.rows=[]
    def write(self,fields,authorized,seconds):
        if not authorized or (self.rows and seconds-self.rows[-1][0]<15): return 0
        self.rows.append((seconds,fields));return len(self.rows)
Ask Dr. Mohammad about this cell
04Instructions · Markdown
## 2. Execute the reference and inspect observations
05Python · executable cell
PYTHON · Code cell
# =====================================================================
# X9 | Code cell 02 | Lab 9 · ThingSpeak HTTPS upload
# Purpose: 2. Execute the reference and inspect observations
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
# Set channel for the next computation or reference condition.
channel=Channel(); fields={'field1':25.4,'field2':47.0}
print(urlencode(fields))
# Repeat the same operation for each configured input so observations are comparable.
for seconds,authorized in [(0,True),(5,True),(15,False),(15,True)]: print(seconds,channel.write(fields,authorized,seconds))
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert len(channel.rows)==2
Ask Dr. Mohammad about this cell
06Instructions · Markdown
## 3. Compare the controlled conditions
07Python · executable cell
PYTHON · Code cell
# =====================================================================
# X9 | Code cell 03 | Lab 9 · ThingSpeak HTTPS upload
# 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.
# =====================================================================
import json, threading

from urllib.request import Request, urlopen

from urllib.parse import urlencode

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

# Actual HTTP requests, local teaching endpoint (not ThingSpeak cloud).
def http_trial():
    """Actual HTTP requests, local teaching endpoint (not ThingSpeak cloud)."""
    from http.server import BaseHTTPRequestHandler,ThreadingHTTPServer
    from urllib.parse import parse_qs,urlsplit
    rows=[]
    class Handler(BaseHTTPRequestHandler):
        def log_message(self,*a):pass
        def send(self,status,data):
            data=json.dumps(data).encode();self.send_response(status);self.send_header('Content-Type','application/json');self.send_header('Content-Length',str(len(data)));self.end_headers();self.wfile.write(data)
        def do_POST(self):
            if self.path!='/update':return self.send(404,{})
            try:
                length=int(self.headers.get('Content-Length','0'));check(0<length<=4096,'size');p=parse_qs(self.rfile.read(length).decode());check(p['api_key']==['local-demo'],'key');t=float(p['field1'][0]);h=float(p['field2'][0]);check(-40<=t<=80 and 0<=h<=100,'range');rows.append({'field1':t,'field2':h,'entry_id':len(rows)+1});self.send(200,rows[-1]['entry_id'])
            except (KeyError,ValueError,RuntimeError):self.send(400,{'error':'invalid sample'})
        def do_GET(self):
            if urlsplit(self.path).path!='/feeds.json':return self.send(404,{})
            self.send(200,{'feeds':rows})
    with ThreadingHTTPServer(('127.0.0.1',0),Handler) as s:
        t=threading.Thread(target=s.serve_forever,daemon=True);t.start();base=f'http://127.0.0.1:{s.server_port}'
        try:
            for i in range(3):
                req=Request(base+'/update',data=urlencode({'api_key':'local-demo','field1':24+i,'field2':60-i}).encode());check(json.load(urlopen(req,timeout=3))==i+1,'HTTP write ID mismatch')
            from urllib.error import HTTPError
            try:urlopen(Request(base+'/update',data=b'api_key=bad&field1=24&field2=60'),timeout=3)
            except HTTPError as e:check(e.code==400,'unexpected error response')
            else:raise RuntimeError('invalid key accepted')
            observed=json.load(urlopen(base+'/feeds.json',timeout=3))['feeds'];check([x['field1'] for x in observed]==[24,25,26],'readback mismatch');return observed
        finally:s.shutdown();t.join(3)

# One real HTTPS write/readback on a student's own private channel, only if opted in.
def thingspeak_live(channel,write_key,read_key=''):
    """One real HTTPS write/readback on a student's own private channel, only if opted in."""
    import re
    from urllib.error import HTTPError, URLError
    channel=str(channel).strip();write_key=write_key.strip();read_key=read_key.strip()
    check(channel.isdigit() and int(channel)>0,'Enter a positive numeric channel ID')
    check(re.fullmatch(r'[A-Za-z0-9]{16}',write_key),'Enter the channel Write API Key, not the Read key or URL')
    check(not read_key or re.fullmatch(r'[A-Za-z0-9]{16}',read_key),'Enter the private channel Read API Key or leave blank for a public channel')
    req=Request('https://api.thingspeak.com/update.json',data=urlencode({'api_key':write_key,'field1':24.5,'field2':60,'status':'mock'}).encode(),method='POST',headers={'Content-Type':'application/x-www-form-urlencoded'})
    try:
        with urlopen(req,timeout=15) as response: r=json.load(response)
        entry=r.get('entry_id') if isinstance(r,dict) else None
        check(type(entry)==int and entry>0,'No positive entry ID; check the Write API Key, enabled fields and update interval (wait 20 seconds)')
        check(str(r.get('channel_id'))==channel,'The write key belongs to a different channel than the requested readback ID')
        req=Request(f'https://api.thingspeak.com/channels/{channel}/feeds/{entry}.json'+('?'+urlencode({'api_key':read_key}) if read_key else ''))
        with urlopen(req,timeout=15) as response: observed=json.load(response)
        check(float(observed['field1'])==24.5 and float(observed['field2'])==60,'Readback does not match the submitted data')
        return {'entry_id':entry,'temperature':24.5,'humidity':60,'source':'mock'}
    except HTTPError as e: raise RuntimeError(f'ThingSpeak HTTP {e.code}: verify key, channel permissions and pacing') from None
    except (URLError,OSError,ValueError,KeyError,TypeError): raise RuntimeError('ThingSpeak request/readback failed; check network, fields and read permissions. Do not retry immediately.') from None
Ask Dr. Mohammad about this cell
08Instructions · Markdown
## 4. Compare the controlled conditions
09Python · executable cell
PYTHON · Code cell
# =====================================================================
# X9 | Code cell 04 | Lab 9 · ThingSpeak HTTPS upload
# Purpose: 4. 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.
# =====================================================================
# Real loopback HTTP write and readback. No external connection in default mode.
observed=http_trial()
print('Local HTTP readback',observed)
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert len(observed)==3
# Set LIVE for the next computation or reference condition.
LIVE=False  # Explicit opt-in only for a channel you own
if LIVE:
    from getpass import getpass
    channel_id=input('Your authorized channel ID: ').strip()
    print(thingspeak_live(channel_id,getpass('Write key: '),getpass('Read key (blank if public): ')))
Ask Dr. Mohammad about this cell
10Instructions · Markdown
## Independent investigation and submission Keep the payload fixed; compare valid versus invalid authorization and a 5 s versus 15 s interval in the fixture. Record entry IDs. Real channel limits depend on the account; verify using the authorized live procedure. | Trial | Changed input | Fixed settings | Predicted output | Observed output | Explanation | |---|---|---|---|---|---| | A | baseline | | | | | | B | one change | | | | | | A repeat | baseline | | | | | Save outputs and state one limitation.