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 34 · DHT22 to ThingSpeak
IoTPSUT IoT Engineering StudioPrincess Sumaya University for Technology · Dr. Mohammad Alja’afreh
Python & IoT / P34
IoT Programming and Applications

Lab 34 · DHT22 to ThingSpeak

Ask Dr. Mohammad · P34 →

The upload to ThingSpeak is real (WSL has Internet); only the sensor is simulated.

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

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

P34 · Academic orientation

Scope and objectives

Scope of the experiment

Sample temperature and humidity, reject invalid sensor data, and inspect the HTTP response and stored feed.

The focus of this experiment is to trace validated DHT22 readings into an authorized ThingSpeak channel. Students then distinguish channel fields, write credentials and publishing intervals, and interpret server response and compare stored measurements with sent values. The Concepts view explains the operation before the practical work; the Simulation view is used to examine reference and changed inputs, not to substitute for actual measurements.

Learning objectives

  • Trace validated DHT22 readings into an authorized ThingSpeak channel.
  • Distinguish channel fields, write credentials and publishing intervals.
  • Interpret server response and compare stored measurements with sent values.
  • Record the relevant inputs, intermediate states and final verification result before changing the reference configuration.
  • Compare the reference calculation or decision with an independent implementation or authorized observation; state any discrepancy and the applicable model boundary.

Expected learning outcomes

On completion, students can trace validated DHT22 readings into an authorized ThingSpeak channel, distinguish channel fields, write credentials and publishing intervals, and interpret server response and compare stored measurements with sent values.

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 interpret server response and compare stored measurements with sent values. Separate predicted values from observations.

Prerequisite knowledge and related learning

Review the following catalogue prerequisites before starting. After completion, continue to Lab 35 · Pi ↔ Arduino · USB serial LED control.

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.

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

Use the updated WSL toolkit. Run the local test first; use the explicit live mode only for a channel you own. Enable Field 1 Temperature and Field 2 Humidity. A real key is never required by the browser simulation. Hidden terminal entry does not echo characters.

CONCEPTS / ACTIVE RECALL

Understand the experiment

DHT22 to ThingSpeak · write acceptance

Sensor acquisition and cloud insertion are independent outcomes
Sensor acquisition and cloud insertion are independent outcomes

Scientific architecture · DHT22 → HTTPS → ThingSpeak channel

DHT22 to ThingSpeak — DHT22/Pi; HTTPS endpoint; Channel feed; Acquire T and RH / 0>0; Authenticated write / 0>1; Entry ID or rejection / 1>0; Retrieve accepted fields / 2>1; Feed response / 1>2
Scientific concept map: DHT22 sensor — Temperature + humidity; Raspberry Pi — Validate measurement; HTTPS request — Write key + field1/field2; ThingSpeak — Entry ID or rejection; Channel feed — Accepted points only.

Scientific foundations and analytical reasoning

Sensor validity, HTTPS reachability and application acceptance are separate gates. A positive ThingSpeak entry identifier indicates an accepted write; HTTP success alone is insufficient.

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 upload acceptance

ThingSpeak channels store named measurement fields and time-stamped entries. A Write API Key authorizes a write, while HTTPS provides encrypted transport with certificate validation. Application-level acceptance and transport success are different. Rate limits depend on the configured service tier; a local simulation is not a guarantee of live acceptance.

Worked example and engineering interpretation

At a nominal 15-second interval, 4 scheduled uploads per minute are possible if the reference plan permits them; retry or processing delays change the observed rate. Inspect the returned entry identifier, not merely HTTP 200. Keep keys private and do not send them to a public mentor.

Engineering principles · additional worked teaching example

A ThingSpeak write involves acquisition, serialization, HTTPS request and application response; HTTP success alone need not imply a new entry. With a configured minimum spacing of 20 s and attempts at 0,10,20,30,40, accepted times are 0,20,40 if other gates pass. Service limits may vary; use lab configuration.

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 34 · DHT22 to ThingSpeak

DHT22-to-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: Publish environmental measurements to ThingSpeak and verify the upload result.

  1. Use the existing DHT22 instrument for sensor acquisition. In the new channel instrument, set 25 °C, 55% RH and a 20 s interval; step twice.
  2. Change humidity to 75%; step and compare stored samples with earlier history.
  3. Reduce the interval below the configured minimum and observe rejected writes.
  4. Disable the credential and network conditions independently; verify no new entry. Restore both.

Reference check:

Model boundary:

Independent task and submission evidence

Use fictional DHT22 temperature/humidity values as field1/field2. Keep authorization fixed and compare 5 s and 15 s intervals; then test rejected authorization. Record returned entry IDs and distinguish modeled behavior from an actual authorized HTTPS write.

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) = 25; Relative humidity (%) = 55; Sensor failure every N attempts (0 = none) = 0; Channel fields 1 and 2 configured = true. In the classroom model, Stored entries = 6; Rejected attempts = 0; Valid sensor samples = 6; HTTP requests = 6. Virtual DHT22 readings and modeled channel decisions. Real service responses may differ; a zero body alone does not identify the cause. 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.

Mathematical representation and interpretation

Sampling and sensor summary

Delta t is the sampling interval in seconds, f_s is in hertz, and x_i are valid observations in a consistent unit. Missing readings are not automatically zero.

\[f_s=\frac1{\Delta t},\qquad \bar x=\frac1N\sum_{i=1}^{N}x_i\]

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 34 · DHT22 to ThingSpeak: progressive data plot24.632.4540.348.1556Attempted tempera…Stored temperatur…Stored humidity %0750

Step 1 of 6 · Observation 0

Observation 0

Attempted temperature °C
24.6
Stored temperature °C
24.6
Stored humidity %
54

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

Recall the concept before revealing its explanation.

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

A credential authorizing updates to the selected private channel.

P34 · 02 / 08What proves a successful upload?Reveal explanation
Engineering explanation

A positive entry ID plus the matching entry in the channel, not merely HTTP connectivity.

P34 · 03 / 08What channel settings and credential-handling precautions precede a ThingSpeak write?Reveal explanation
Engineering explanation

Create the private channel with temperature and humidity fields first. Enter the write key without echo; wait at least 20 seconds between repeat uploads and unset the key when finished.

P34 · 04 / 08Why check the ThingSpeak response and channel readback?Reveal explanation
Engineering reasoning

A request alone does not establish a successful stored entry; verify the service response and the intended channel's records.

P34 · 05 / 08Why keep write keys private?Reveal explanation
Engineering reasoning

They authorize channel changes; do not place them in shared screenshots, source repositories or evidence files.

P34 · 06 / 08A ThingSpeak upload is attempted. Select every technically valid statement. A. Inspect the service response for acceptance. B. Keep write credentials private. C. A network connection guarantees that the record was stored. D. Use the public channel number as a universal write credential.Reveal explanation
Applied scenario

Correct: A. Inspect the service response for acceptance.; B. Keep write credentials private.

P34 · 07 / 08In DHT22 to ThingSpeak, which command or code executes Upload one simulated reading?Reveal explanation
Implementation recall

python dht22_thingspeak.py

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

Create a private ThingSpeak channel with Field 1 temperature and Field 2 humidity, save it, copy its Write API Key, and wait at least the configured update interval (20 s is a safe teaching setting for a 15 s minimum). Read the key silently in the same terminal. Expect Accepted entry: followed by a positive integer; a 0 or HTTP/network failure exits nonzero. Verify that ID and fields in the private channel. Unset THINGSPEAK_WRITE_KEY after use. Never upload private or real personal data.

Execution boundary · Real HTTPS + simulated sensor. 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 →
DHT22 acquisition and cloud upload pipeline.
DHT22 acquisition and cloud upload pipeline.
P34 engineering diagram
Engineering diagram · P34. Use the interactive workstation to investigate the calculated state.
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

Publish environmental measurements to ThingSpeak and verify the upload 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 workbenchP34 · 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 GPIO23 · physical 163.3 V power, GND, pull-up on bare sensor datalab34/dht22_thingspeak.py
P34 · 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

P34 · 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 34 · DHT22 to ThingSpeak

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

Local HTTP positive/negative test, followed by optional live HTTPS with a hidden channel Write API Key. Only a positive entry ID and matching channel fields confirm a real write. Never expose the key. Use a 20-second interval between live writes. WSL mock and physical Pi modes are distinct.

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 t=0,5,10,15,20,25 s with a 15 s minimum accepted-write interval, predict accepted times assuming all other gates pass and a rejected attempt does not reset the interval.

02 · Compare or justify using evidence

Draw the sensor-to-cloud path. Explain how an invalid Write API Key, a network timeout and a missing field differ; never include your key in evidence.

03 · Boundary analysis

Boundary analysis · Independent work

An accepted write occurs at 4 s; attempts at 14,19,20,34 s. Model minimum interval 15 s; rejected attempts do not reset it. List accepted times and specify how to verify storage.

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 · P34-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) = 25; Relative humidity (%) = 55; Sensor failure every N attempts (0 = none) = 0; Channel fields 1 and 2 configured = true), 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 · P34-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 · P34-03

For Configured service minimum interval (s) = 17, the model supplies this excerpt from DHT22 / HTTP trace: Time (s) · Temp °C · RH % · HTTP status · Entry ID/body · Result 0 · 24.6 · 54 · 200 · 1 · Stored 15 · 24.8 · 55 · 200 · 0 · Rate limited 30 · 25 · 56 · 200 · 2 · Stored 45 · 25.2 · 54 · 200 · 0 · Rate limited 60 · 25.4 · 55 · 200 · 3 · Stored Compute the range (maximum minus minimum) of the Temp °C column in these rows. Identify the maximum observation. Do not extrapolate beyond these rows.

Advanced · Reverse reasoning

Independent theoretical exercise · P34-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) = 25; Relative humidity (%) = 55; Sensor failure every N attempts (0 = none) = 0; Channel fields 1 and 2 configured = true. 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 · P34-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 · P34-06

Design a controlled comparison for Lab 34 · DHT22 to ThingSpeak 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) = 25; Relative humidity (%) = 55; Sensor failure every N attempts (0 = none) = 0; Channel fields 1 and 2 configured = true 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 · Live channel upload

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

  1. Use the existing DHT22 instrument for sensor acquisition. In the new channel instrument, set 25 °C, 55% RH and a 20 s interval; step twice.
  2. Change humidity to 75%; step and compare stored samples with earlier history.
  3. Reduce the interval below the configured minimum and observe rejected writes.
  4. Disable the credential and network conditions independently; verify no new entry. Restore both.
  5. Run the existing local HTTP test, then the live Python mode using your own Write API Key.

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

Sample temperature and humidity, reject invalid sensor data, and inspect the HTTP response and stored feed.

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)25
Relative humidity (%)55
Sensor failure every N attempts (0 = none)0
Channel fields 1 and 2 configuredYes

2 · Perform the investigation in order

  1. Create a private channel with field 1 Temperature and field 2 Humidity. For this browser experiment no real API key is needed.
  2. Set 25 °C, 55% RH, six samples and a 15 s modeled service limit; inspect each sample, HTTP status and entry ID. Play the calculated sensor/feed series.
  3. Set upload interval to 5 s; identify which samples are rejected and why. Restore 15 s and set sensor failure every second sample; confirm invalid sensor data never reaches HTTPS.
  4. Toggle key acceptance, transport and field configuration separately. Inspect the trace; a zero response does not establish its specific cause on the real service.
  5. For a real write use the updated Python program in Method & source: run --local first, then --live --sensor mock. Enter the channel Write API Key at the hidden prompt. Enable fields 1 and 2, wait at least 20 s between writes, verify the entry in your channel. Use --sensor hardware only on a physical Raspberry Pi.

3 · Compare controlled trials

TrialIndependent changeExpected checkObservation
ReferenceUse reference inputs aboveStored entries: 6Record actual result
Rate pressureUpload interval (s) = 5Stored entries: 2Record actual result
Wrong keyDemonstration write key accepted = NoStored entries: 0Record actual result
Sensor failureSensor failure every N attempts (0 = none) = 2Stored entries: 3Record actual result
HTTPS unavailableHTTPS connection succeeds = NoStored entries: 0Record actual result
Fields not configuredChannel fields 1 and 2 configured = NoStored entries: 0Record actual result

4 · Analyze and report

Compare accepted feed values with attempted sensor readings. Differentiate absent HTTP responses, zero bodies, and actual positive entry IDs. Never paste real keys into the browser model or report.

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. Create a ThingSpeak channel
  2. Enter the key without echo
  3. Upload one simulated reading
02 / Implement

Step-by-step instructions

Before you run

Use the updated WSL toolkit. Run the local test first; use the explicit live mode only for a channel you own. Enable Field 1 Temperature and Field 2 Humidity. A real key is never required by the browser simulation. Hidden terminal entry does not echo characters.

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

Create a ThingSpeak channel

In Windows browser open ThingSpeak, sign in, Channels → My Channels → New Channel. Name it PSUT Lab, enable Field 1 Temperature and Field 2 Humidity, save. API Keys → copy Write API Key. Keep channel private.

Checkpoint Complete the action before continuing.
02

Run the local HTTP and DHT22 test

No ThingSpeak account, GPIO library or API key is required. In WSL use the updated toolkit. A real loopback HTTP server accepts one virtual reading and rejects a second request with the wrong credential.

WSL · Bash
cd ~/psut-wsl/labs/python/lab34
python3 dht22_thingspeak.py --local
Expected: LOCAL HTTP TEST PASS and LOCAL NEGATIVE TEST PASS. No cloud write.
Checkpoint Both messages appear; no credentials requested.
03

Perform one real ThingSpeak HTTPS write

The local test is complete. Open your private channel API Keys tab and copy the Write API Key only. The command clears any stale environment key and securely prompts for a new one. Type/paste the key and press Enter even though nothing is displayed. WSL uses mock readings, not real GPIO.

WSL · Bash
unset THINGSPEAK_WRITE_KEY
python3 dht22_thingspeak.py --live --sensor mock --temperature 24.5 --humidity 55
Expected: HTTP 200 with a positive entry ID confirms a write. HTTP 200 with 0, HTTP 401/403/429 or connection failure is not a successful write.
Checkpoint Verify Field 1 and Field 2 in your channel. Wait at least 20 s before repeating. Physical Pi only: --live --sensor hardware.

Experimental notebook

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

03 / Inspect

Source code and method

labs/python/lab34/dht22_thingspeak.pyDownload source
PY · source file
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform — P34
"""Explicit virtual/physical DHT22 sensor and local/live HTTP experiment."""
import argparse
import getpass
import math
import os
import re
import sys
import time
import warnings
from urllib.error import HTTPError, URLError
from urllib.parse import urlencode
from urllib.request import Request, urlopen
ENDPOINT = 'https://api.thingspeak.com/update'
def validate_key(value):
    key = (value or '').strip()
    # Channel keys are 16 alphanumeric characters. Do not accept URLs or channel IDs.
if not re.fullmatch(r'[A-Za-z0-9]{16}', key):
        raise ValueError('Enter only the 16-character channel Write API Key from Channels > API Keys (not the Read key, URL or channel ID).')
    return key
def response_entry(status, body):
    if status != 200:
        raise RuntimeError(f'HTTP {status}: update not accepted.')
    body = body.strip()
    if body == '0':
        raise RuntimeError('HTTP 200, entry 0: ThingSpeak rejected the update. Check the channel Write API Key, enabled fields, and wait at least 20 seconds before another attempt. The response alone cannot identify the cause.')
    if not re.fullmatch(r'[0-9]+', body) or int(body) <= 0:
        raise RuntimeError('Unexpected response body; no confirmed entry ID.')
    return int(body)


def upload(t, h, key, source, endpoint=ENDPOINT, opener=urlopen):
    if not (math.isfinite(t) and math.isfinite(h) and -40 <= t <= 80 and 0 <= h <= 100):
        raise ValueError('Invalid DHT22 reading; no upload attempted.')
    payload = urlencode({'api_key': key, 'field1': round(t, 1), 'field2': round(h, 1), 'status': source}).encode('ascii')
    req = Request(endpoint, data=payload, method='POST', headers={'Content-Type': 'application/x-www-form-urlencoded'})
    try:
        with opener(req, timeout=15) as response:
            return response_entry(response.status, response.read(128).decode('ascii', errors='replace'))
    except HTTPError as e:
        hint = {401:'Check the channel Write API Key.',403:'Check channel permissions and Write API Key.',429:'Wait at least 20 seconds and check channel rate limits.'}.get(e.code,'Check channel settings and service availability.')
        raise RuntimeError(f'HTTP {e.code}: {hint}') from None
except (URLError, TimeoutError, OSError) as e:
        # Never print exception URLs or credentials.
raise RuntimeError(f'HTTPS/HTTP connection failed ({type(e).__name__}); check DNS, internet, system clock and trusted certificates. Do not disable TLS verification.') from None
def local_trial(t, h):
    from http.server import BaseHTTPRequestHandler, HTTPServer
from threading import Thread
from urllib.parse import parse_qs
rows = []
    class Handler(BaseHTTPRequestHandler):
        def log_message(self, *_): pass
def do_POST(self):
            data = parse_qs(self.rfile.read(int(self.headers['Content-Length'])).decode())
            if data.get('api_key') == ['LOCALDEMO1234567']:
                rows.append(data); body = str(len(rows)).encode()
            else: body = b'0'
self.send_response(200); self.end_headers(); self.wfile.write(body)
    server = HTTPServer(('127.0.0.1',0), Handler)
    worker = Thread(target=server.serve_forever, daemon=True); worker.start()
    try:
        endpoint = f'http://127.0.0.1:{server.server_port}/update'
entry = upload(t,h,'LOCALDEMO1234567','mock',endpoint)
        assert entry == 1 and float(rows[0]['field1'][0]) == round(t,1) and float(rows[0]['field2'][0]) == round(h,1)
        print(f'LOCAL HTTP TEST PASS: entry {entry}; temperature {t:.1f} °C; humidity {h:.1f}%. No cloud write.')
        try: upload(t,h,'wrong','mock',endpoint)
        except RuntimeError: print('LOCAL NEGATIVE TEST PASS: wrong credential rejected (entry 0).')
        else: raise AssertionError('Invalid key accepted by local fixture')
    finally:
        server.shutdown();server.server_close();worker.join()


def sample(args):
    if args.sensor == 'mock':
        return args.temperature, args.humidity
# Only import physical hardware dependencies when explicitly requested.
try:
        import board
import adafruit_dht
if 'fakepi' in str(getattr(board, '__file__', '')):
            raise RuntimeError('Fake GPIO module detected. Use --sensor mock or deactivate the WSL fakepi environment.')
        device = adafruit_dht.DHT22(board.D23)
    except (ImportError, AttributeError, OSError, RuntimeError) as e:
        raise RuntimeError('Physical DHT22 unavailable. Use --sensor mock in WSL; on a Raspberry Pi install Blinka and Adafruit DHT and verify BCM23 wiring.') from None
try:
        for i in range(5):
            try:
                t,h=device.temperature,device.humidity
if t is not None and h is not None and -40 <= t <= 80 and 0 <= h <= 100:
                    return t,h
except RuntimeError: pass
if i<4:time.sleep(2.1)
        raise RuntimeError('DHT22 failed after five attempts. No upload performed.')
    finally: device.exit()


def main():
    p=argparse.ArgumentParser(description=__doc__)
    mode=p.add_mutually_exclusive_group();mode.add_argument('--local',action='store_true',help='Loopback HTTP test (default; no real key)');mode.add_argument('--live',action='store_true',help='One real HTTPS update to your own private channel')
    p.add_argument('--sensor',choices=['mock','hardware'],default='mock');p.add_argument('--temperature',type=float,default=24.5);p.add_argument('--humidity',type=float,default=55.0)
    args=p.parse_args()
    try:
        t,h=sample(args)
        if not args.live:
            local_trial(t,h);return 0
raw=os.getenv('THINGSPEAK_WRITE_KEY','').strip()
        if not raw:
            if not sys.stdin.isatty():raise ValueError('Use an interactive terminal for hidden key entry, or set THINGSPEAK_WRITE_KEY in the current terminal.')
            with warnings.catch_warnings():
                warnings.simplefilter('error',getpass.GetPassWarning)
                raw=getpass.getpass('ThingSpeak channel Write API Key (hidden): ')
        key=validate_key(raw)
        print('Key format accepted locally; only the server can confirm authorization.')
        entry=upload(t,h,key,'mock' if args.sensor=='mock' else 'hardware')
        print(f'HTTP 200; accepted entry ID: {entry}; temperature {t:.1f} °C; humidity {h:.1f}%. Verify your private channel. Wait at least 20 seconds before another write.')
        return 0
except (ValueError,RuntimeError,getpass.GetPassWarning,EOFError) as e:
        print('P34:',str(e),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

P34 · 11 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
# P34 · Lab 34 · DHT22 to ThingSpeak **PSUT IoT Engineering Studio — Dr. Mohammad Alja’afreh** ## Theory and purpose DHT22-to-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
# =====================================================================
# P34 | Code cell 01 | Lab 34 · DHT22 to ThingSpeak
# 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
# =====================================================================
# P34 | Code cell 02 | Lab 34 · DHT22 to ThingSpeak
# 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
# =====================================================================
# P34 | Code cell 03 | Lab 34 · DHT22 to ThingSpeak
# 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
# =====================================================================
# P34 | Code cell 04 | Lab 34 · DHT22 to ThingSpeak
# 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
## Updated WSL / physical practical (reference only) Run the loopback test without a key first, then explicitly opt into a live write. The browser never requires a real credential. ```bash python3 dht22_thingspeak.py --local python3 dht22_thingspeak.py --live --sensor mock ``` ```python # Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved. # PSUT IoT Engineering Learning Platform — P34 """Explicit virtual/physical DHT22 sensor and local/live HTTP experiment.""" import argparse import getpass import math import os import re import sys import time import warnings from urllib.error import HTTPError, URLError from urllib.parse import urlencode from urllib.request import Request, urlopen ENDPOINT = 'https://api.thingspeak.com/update' def validate_key(value): key = (value or '').strip() # Channel keys are 16 alphanumeric characters. Do not accept URLs or channel IDs. if not re.fullmatch(r'[A-Za-z0-9]{16}', key): raise ValueError('Enter only the 16-character channel Write API Key from Channels > API Keys (not the Read key, URL or channel ID).') return key def response_entry(status, body): if status != 200: raise RuntimeError(f'HTTP {status}: update not accepted.') body = body.strip() if body == '0': raise RuntimeError('HTTP 200, entry 0: ThingSpeak rejected the update. Check the channel Write API Key, enabled fields, and wait at least 20 seconds before another attempt. The response alone cannot identify the cause.') if not re.fullmatch(r'[0-9]+', body) or int(body) <= 0: raise RuntimeError('Unexpected response body; no confirmed entry ID.') return int(body) def upload(t, h, key, source, endpoint=ENDPOINT, opener=urlopen): if not (math.isfinite(t) and math.isfinite(h) and -40 <= t <= 80 and 0 <= h <= 100): raise ValueError('Invalid DHT22 reading; no upload attempted.') payload = urlencode({'api_key': key, 'field1': round(t, 1), 'field2': round(h, 1), 'status': source}).encode('ascii') req = Request(endpoint, data=payload, method='POST', headers={'Content-Type': 'application/x-www-form-urlencoded'}) try: with opener(req, timeout=15) as response: return response_entry(response.status, response.read(128).decode('ascii', errors='replace')) except HTTPError as e: hint = {401:'Check the channel Write API Key.',403:'Check channel permissions and Write API Key.',429:'Wait at least 20 seconds and check channel rate limits.'}.get(e.code,'Check channel settings and service availability.') raise RuntimeError(f'HTTP {e.code}: {hint}') from None except (URLError, TimeoutError, OSError) as e: # Never print exception URLs or credentials. raise RuntimeError(f'HTTPS/HTTP connection failed ({type(e).__name__}); check DNS, internet, system clock and trusted certificates. Do not disable TLS verification.') from None def local_trial(t, h): from http.server import BaseHTTPRequestHandler, HTTPServer from threading import Thread from urllib.parse import parse_qs rows = [] class Handler(BaseHTTPRequestHandler): def log_message(self, *_): pass def do_POST(self): data = parse_qs(self.rfile.read(int(self.headers['Content-Length'])).decode()) if data.get('api_key') == ['LOCALDEMO1234567']: rows.append(data); body = str(len(rows)).encode() else: body = b'0' self.send_response(200); self.end_headers(); self.wfile.write(body) server = HTTPServer(('127.0.0.1',0), Handler) worker = Thread(target=server.serve_forever, daemon=True); worker.start() try: endpoint = f'http://127.0.0.1:{server.server_port}/update' entry = upload(t,h,'LOCALDEMO1234567','mock',endpoint) assert entry == 1 and float(rows[0]['field1'][0]) == round(t,1) and float(rows[0]['field2'][0]) == round(h,1) print(f'LOCAL HTTP TEST PASS: entry {entry}; temperature {t:.1f} °C; humidity {h:.1f}%. No cloud write.') try: upload(t,h,'wrong','mock',endpoint) except RuntimeError: print('LOCAL NEGATIVE TEST PASS: wrong credential rejected (entry 0).') else: raise AssertionError('Invalid key accepted by local fixture') finally: server.shutdown();server.server_close();worker.join() def sample(args): if args.sensor == 'mock': return args.temperature, args.humidity # Only import physical hardware dependencies when explicitly requested. try: import board import adafruit_dht if 'fakepi' in str(getattr(board, '__file__', '')): raise RuntimeError('Fake GPIO module detected. Use --sensor mock or deactivate the WSL fakepi environment.') device = adafruit_dht.DHT22(board.D23) except (ImportError, AttributeError, OSError, RuntimeError) as e: raise RuntimeError('Physical DHT22 unavailable. Use --sensor mock in WSL; on a Raspberry Pi install Blinka and Adafruit DHT and verify BCM23 wiring.') from None try: for i in range(5): try: t,h=device.temperature,device.humidity if t is not None and h is not None and -40 <= t <= 80 and 0 <= h <= 100: return t,h except RuntimeError: pass if i<4:time.sleep(2.1) raise RuntimeError('DHT22 failed after five attempts. No upload performed.') finally: device.exit() def main(): p=argparse.ArgumentParser(description=__doc__) mode=p.add_mutually_exclusive_group();mode.add_argument('--local',action='store_true',help='Loopback HTTP test (default; no real key)');mode.add_argument('--live',action='store_true',help='One real HTTPS update to your own private channel') p.add_argument('--sensor',choices=['mock','hardware'],default='mock');p.add_argument('--temperature',type=float,default=24.5);p.add_argument('--humidity',type=float,default=55.0) args=p.parse_args() try: t,h=sample(args) if not args.live: local_trial(t,h);return 0 raw=os.getenv('THINGSPEAK_WRITE_KEY','').strip() if not raw: if not sys.stdin.isatty():raise ValueError('Use an interactive terminal for hidden key entry, or set THINGSPEAK_WRITE_KEY in the current terminal.') with warnings.catch_warnings(): warnings.simplefilter('error',getpass.GetPassWarning) raw=getpass.getpass('ThingSpeak channel Write API Key (hidden): ') key=validate_key(raw) print('Key format accepted locally; only the server can confirm authorization.') entry=upload(t,h,key,'mock' if args.sensor=='mock' else 'hardware') print(f'HTTP 200; accepted entry ID: {entry}; temperature {t:.1f} °C; humidity {h:.1f}%. Verify your private channel. Wait at least 20 seconds before another write.') return 0 except (ValueError,RuntimeError,getpass.GetPassWarning,EOFError) as e: print('P34:',str(e),file=sys.stderr);return 1 if __name__=='__main__': try: sys.exit(main()) except KeyboardInterrupt: sys.exit(130) ```
11Instructions · Markdown
## Independent investigation and submission Use fictional DHT22 temperature/humidity values as field1/field2. Keep authorization fixed and compare 5 s and 15 s intervals; then test rejected authorization. Record returned entry IDs and distinguish modeled behavior from an actual authorized HTTPS write. | Trial | Changed input | Fixed settings | Predicted output | Observed output | Explanation | |---|---|---|---|---|---| | A | baseline | | | | | | B | one change | | | | | | A repeat | baseline | | | | | Save outputs and state one limitation.