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 cell10Instructions · 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)
```