Skip to main content
PSUT / IoTEngineering learning studio
WORKSPACE
Offline-first portalDr. Mohammad Alja’afreh
Embedded Systems StudioIoT Programming and ApplicationsExperimentsWorkspaces
ENGINEERING WORKSPACE
Home/WSL Laboratories/Lab 5 · DHT22 environmental data logger
IoTPSUT IoT Engineering StudioPrincess Sumaya University for Technology · Dr. Mohammad Alja’afreh
Pi practical / X5
IoT Programming and Applications

Lab 5 · DHT22 environmental data logger

Ask Dr. Mohammad · X5 →

HDF5 logging is real (h5py); the sensor is the fake DHT22 or the lab’s --mock data.

Design experiment & verify evidence →
X5 · Laboratory mentorAsk about the current experiment, its algorithms or Python notebook.
Ask Dr. MohammadAdaptive practice
Learning workflow · Core IoT & programmingX5 · DHT22 environmental data logger
Readiness checksRevision deckEngineering workspaceRecord evidence

Related course access: Machine Learning and Edge AI — same laboratory, notebook and completion record.

X5 · Academic orientation

Scope and objectives

Scope of the experiment

Reproduce the common.py mock sensor sequence and the four output structures used by exp05.log_data.

The focus of this experiment is to acquire DHT22 samples with valid timing and units. Students then trace the acquisition and timestamped logging logic, and verify recorded samples and handle invalid reads explicitly. 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

  • Acquire DHT22 samples with valid timing and units.
  • Trace the acquisition and timestamped logging logic.
  • Verify recorded samples and handle invalid reads explicitly.
  • Identify the configured inputs (Number of readings; Sample interval (s); Fictional sensor ID; Preview output) and record the corresponding observed outputs with units where applicable.
  • Compare the reference calculation or decision with an independent implementation or authorized observation; state any discrepancy and the applicable model boundary.

Expected learning outcomes

On completion, students can acquire DHT22 samples with valid timing and units, trace the acquisition and timestamped logging logic, and verify recorded samples and handle invalid reads explicitly.

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 recorded samples and handle invalid reads explicitly. Separate predicted values from observations.

Prerequisite knowledge and related learning

Review the following catalogue prerequisites before starting. After completion, continue to Lab 6 · DHT22 + SSD1306 OLED.

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.

X5 / PREPARE

Before starting

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

Ubuntu WSL setup →
Before you run / verification gate

Use separate output directories; inspect generated readings.json, readings.csv, readings.h5 and tree.json, including source fields. The logger replaces these files on a new run, rather than appending to previous runs. Expect three entries per completed run; save a copy before repeating if required.

CONCEPTS / ACTIVE RECALL

Understand the experiment

Scientific architecture · DHT22 environmental data logger — CSV, JSON, HDF5 and tree

One sample, four persistence formats — Timestamped sample / T=25, RH=55; CSV / flat row; JSON / key–value object; HDF5 / dataset; Tree / hierarchical records
Scientific concept map: DHT22 acquisition — Temperature and RH; Timestamp — Sample identity; Serialization — CSV / JSON / HDF5; Persistent file — Rows / objects / datasets; Readback — Compare values.

Scientific foundations and analytical reasoning

CSV stores rows, JSON stores named records, HDF5 stores structured datasets. All may represent the same observations with different serialization overhead.

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 · Structured environmental records

CSV represents tabular records, JSON named values and HDF5 hierarchical datasets. All can encode the same sample identities, timestamps, temperature and humidity. Their storage overhead and query abilities differ. Define consistent missing-data conventions and preserve data types.

Worked example and engineering interpretation

Three samples with one missing humidity reading yield three records but only two valid humidity values. Do not convert a missing value to 0%. Compare decoded values and units across formats rather than comparing file sizes alone.

Engineering principles · additional worked teaching example

CSV stores rows; JSON can preserve nested attributes; HDF5 stores typed arrays with metadata. For 4 records and two numeric channels, a simple HDF5 matrix has shape (4,2), eight values. Keep timestamps and units as explicit fields/attributes.

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 5 · DHT22 environmental data logger

Verify environmental data outputs in CSV, JSON and HDF5.

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: Verify environmental data outputs in CSV, JSON and HDF5.

  1. Run three readings. The mock source uses temperature=round(23+3 sin(i/5),1) and RH=round(55+8 cos(i/5),1). Compare the sensor_data field names.
  2. Select CSV, JSON and Tree JSON; all represent the same readings. CSV includes one header; the JSON document is an array, and the tree is keyed by sensor ID.
  3. Select HDF5 schema. Inspect numeric float64 and UTF-8 datasets and row count; actual HDF5 byte size is not predicted by this browser.
  4. Run python -m labs.exp05.log_data --mock --interval 0.2 --count 3 --out data/mock05, then inspect readings.csv, readings.json, readings.h5 and tree.json. Compare row counts and units.

Reference check:

Model boundary:

Independent task and submission evidence

2. Select CSV, JSON and Tree JSON; all represent the same readings. CSV includes one header; the JSON document is an array, and the tree is keyed by sensor ID. Record the named input, prediction, actual output and one limitation; restore the original condition and repeat.

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: Number of readings = 3; Sample interval (s) = 1; Fictional sensor ID = dht22-01; Preview output = CSV. In the classroom model, Valid samples = 3; CSV data rows = 3; JSON records = 3; HDF5 datasets = 5. CSV quoting and fixed timestamps are teaching serialization choices; actual binary HDF5 is produced by the Python code. 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 5 · DHT22 environmental data logger: independent state notebook123Calculated state 1sensor_iddht22-01timestamp2026-01-01T00:00:00.000Ztemperature23humidity63sourcemock

Step 1 of 3 · Calculated state 1

Calculated state 1

sensor_id
dht22-01
timestamp
2026-01-01T00:00:00.000Z
temperature
23
humidity
63
source
mock

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

Recall the concept before revealing its explanation.

0 / 3 revealed
X5 · 01 / 08What is HDF5?Reveal explanation
Engineering explanation

A structured binary data format suitable for arrays and metadata.

X5 · 02 / 08Why separate mock and fakepi?Reveal explanation
Engineering explanation

Both are simulated data, but their acquisition paths differ.

X5 · 03 / 08What prerequisites distinguish the storage formats and virtual sensor paths?Reveal explanation
Engineering explanation

Use separate output directories; inspect generated readings.json, readings.csv, readings.h5 and tree.json, including source fields. The logger replaces these files on a new run, rather than appending to previous runs. Expect three entries per completed run; save a copy before repeating if required.

X5 · 04 / 08Why compare CSV and JSON representations?Reveal explanation
Engineering reasoning

Both should encode consistent values and timestamps; serialization format changes structure, not the underlying observation.

X5 · 05 / 08Why inspect the HDF5 dataset shape and fields?Reveal explanation
Engineering reasoning

It verifies the expected sample count and representation instead of relying on the file's existence alone.

X5 · 06 / 08Environmental records are exported to several formats. Select every technically valid statement. A. Compare field names and values across exports. B. Preserve sample provenance and missingness. C. Changing CSV to HDF5 automatically improves sensor accuracy. D. A missing humidity reading is necessarily 0%.Reveal explanation
Applied scenario

Correct: A. Compare field names and values across exports.; B. Preserve sample provenance and missingness.

X5 · 07 / 08In DHT22 environmental data logger, which command or code executes Inspect files?Reveal explanation
Implementation recall

find data/mock05 data/fake05 -type f

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

Run from pi-practical. Choose distinct output directories for mock and fakepi. --mock --count 3 creates three deterministic rows; fakepi mode uses the simulated driver. Output files are replaced when reusing a directory, not appended. Verify JSON length, CSV header plus three rows and HDF5/tree file presence; archive before rerunning.

Execution boundary · Simulated (fake Pi). 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.
Environmental data logging. Independent readings and storage.
Environmental data logging. Independent readings and storage.
Shared research workbenches · network designer & advanced studies
Concurrent-device simulation & Monte Carlo research
Distributed digital twin · topology, protocol & battery research
Loading experiment-specific apparatus…
Previous model / additional reference tools
Simulation task

Verify environmental data outputs in CSV, JSON and HDF5.

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 workbenchX5 · 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
X5 · 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

X5 · 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 5 · DHT22 environmental data logger

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 JSON/CSV/HDF5/tree creation executed.

Run from pi-practical. Choose distinct output directories for mock and fakepi. --mock --count 3 creates three deterministic rows; fakepi mode uses the simulated driver. Output files are replaced when reusing a directory, not appended. Verify JSON length, CSV header plus three rows and HDF5/tree file presence; archive before rerunning.

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

For three readings with timestamp, sensor ID, temperature and humidity, sketch CSV columns, a JSON array and HDF5 dataset dimensions.

02 · Compare or justify using evidence

Calculate the expected number of temperature and humidity values. Explain why file sizes need not match and how to verify equal logical records.

03 · Data design

Data design · Independent work

Five sensors each produce 12 records with two readings. Give record count and shape for a flattened numeric matrix. Propose identifiers preventing accidental mixing of devices.

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

Use the reference configuration (Number of readings = 3; Sample interval (s) = 1; Fictional sensor ID = dht22-01; Preview output = CSV), but change Number of readings = 5. The model reports Valid samples = 5. Explain the governing rule and assumptions that make this output plausible; identify an independent verification method.

Intermediate · Quantitative comparison

Independent theoretical exercise · X5-02

Two model observations of Valid samples are 3 (reference) and 5 (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 · X5-03

For Number of readings = 6, the model supplies this excerpt from Readings: sensor_id · timestamp · temperature · humidity · source dht22-01 · 2026-01-01T00:00:00.000Z · 23 · 63 · mock dht22-01 · 2026-01-01T00:00:01.000Z · 23.6 · 62.8 · mock dht22-01 · 2026-01-01T00:00:02.000Z · 24.2 · 62.4 · mock dht22-01 · 2026-01-01T00:00:03.000Z · 24.7 · 61.6 · mock dht22-01 · 2026-01-01T00:00:04.000Z · 25.2 · 60.6 · mock Count rows whose timestamp value is exactly “2026-01-01T00:00:00.000Z”, and identify the displayed row numbers. Explain what the count describes.

Advanced · Reverse reasoning

Independent theoretical exercise · X5-04

An observation is Valid samples = 6. Candidate A uses Number of readings = 3; Sample interval (s) = 1; Fictional sensor ID = dht22-01; Preview output = CSV. Candidate B changes the listed settings (Number of readings = 6) 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 · X5-05

A student configures Number of readings = 6 while preserving all other reference settings, but copies the reference report of Valid samples = 3. Evaluate whether the report is justified. Identify the first configuration/output check to perform.

Challenging · Design a controlled verification

Independent theoretical exercise · X5-06

Design a controlled comparison for Lab 5 · DHT22 environmental data logger using reference Number of readings = 3; Sample interval (s) = 1; Fictional sensor ID = dht22-01; Preview output = CSV and test Number of readings = 5. Specify the changed setting(s), measured metric Valid samples, controls, repetitions, an acceptance check and what evidence can distinguish an actual implementation from the model.

Step-by-step experimental procedure

Reproduce the common.py mock sensor sequence and the four output structures used by exp05.log_data.

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.

Number of readings3
Sample interval (s)1
Fictional sensor IDdht22-01
Preview outputCSV

2 · Perform the investigation in order

  1. Run three readings. The mock source uses temperature=round(23+3 sin(i/5),1) and RH=round(55+8 cos(i/5),1). Compare the sensor_data field names.
  2. Select CSV, JSON and Tree JSON; all represent the same readings. CSV includes one header; the JSON document is an array, and the tree is keyed by sensor ID.
  3. Select HDF5 schema. Inspect numeric float64 and UTF-8 datasets and row count; actual HDF5 byte size is not predicted by this browser.
  4. Run python -m labs.exp05.log_data --mock --interval 0.2 --count 3 --out data/mock05, then inspect readings.csv, readings.json, readings.h5 and tree.json. Compare row counts and units.

3 · Compare controlled trials

TrialIndependent changeExpected checkObservation
Three recordsUse reference inputs aboveValid samples: 3; CSV data rows: 3Record actual result
Six recordsNumber of readings = 6CSV data rows: 6Record actual result
Second sensorFictional sensor ID = dht22-02; Preview output = Tree JSONValid samples: 3Record actual result

4 · Analyze and report

All four files are rewritten with the accumulated snapshot at each acquisition in the source, not four different sensor runs.

Required evidence: Record the named metrics and trace for the reference and changed cases, then attach the corresponding practical command output or device evidence if available.

Model boundary: A closed, deterministic browser model. The existing practical instructions and source files provide independent execution; browser results are not hardware measurements.

Controlled investigation · reproducible evidence

Method. Use the existing reference workbench configuration and the named controlled changes below. A controlled variable stays fixed while the independent variable is intentionally changed; the dependent variable is the resulting observed output. First predict each trial from the Concepts page. Run the baseline, then change only the specified setting and record the outcome. For deterministic traces one execution per case and a repeated verification are sufficient; for timing or stochastic measurements repeat at least five times, recording each run, median and range. Reset to the reference state between independent comparisons.

TrialIndependent changeDependent observation
Three recordsUse reference inputs aboveRecord actual outcome and units
Six recordsNumber of readings = 6Record actual outcome and units
Second sensorFictional sensor ID = dht22-02; Preview output = Tree JSONRecord actual outcome and units

Evidence: attach the completed comparison table, one trace or screenshot per condition, and actual practical terminal/hardware evidence where applicable. Explain any prediction mismatch and distinguish modeled behavior from measured results.

Loading laboratory-specific procedure…

Python / Google Colab notebook

Original common sensor model; mock samples and in-memory output. Validated locally in a fresh Jupyter kernel. Download, then upload to Google Colab.

Download NotebookOpen Google ColabAll Python notebooks

Independent implementation sequence

  1. Open a terminal in the project root
  2. Mock data (labelled)
  3. Use the fake DHT22 driver
  4. Inspect files
02 / Implement

Step-by-step instructions

Before you run / verification gate

Use separate output directories; inspect generated readings.json, readings.csv, readings.h5 and tree.json, including source fields. The logger replaces these files on a new run, rather than appending to previous runs. Expect three entries per completed run; save a copy before repeating if required.

Complete one-time setup first. Copy one command block at a time into the indicated environment. Do not copy prompt characters. Open new terminals where named; variables are terminal-specific. Ctrl+C stops a running foreground command.

01

Open a terminal in the project root

WSL · Bash
source ~/psut-wsl/activate.sh
cd ~/psut-wsl/labs/pi-practical
✓ Expected: Normally no output. pwd should show the requested directory. A missing path produces an error; do not continue until corrected.
Expected result for each action (2)
  1. source ~/psut-wsl/activate.shThe toolkit virtual environment is selected in this terminal, usually with (.venv) in the prompt. Verify which python points into ~/psut-wsl/.venv.
  2. cd ~/psut-wsl/labs/pi-practicalNormally no output. pwd should show the requested directory. A missing path produces an error; do not continue until corrected.
Checkpoint you are in the folder that contains labs/ ; every command is python -m labs.expNN.… as on the page.
02

Mock data (labelled)

WSL · Bash
python -m labs.exp05.log_data --mock --interval 0.2 --count 3 --out data/mock05
✓ Expected: three JSON lines with "source": "mock" and the HDF5 file in data/.
Checkpoint three JSON lines with "source": "mock" and the HDF5 file in data/.
03

Use the fake DHT22 driver

This path exercises the sensor driver but produces simulated values labelled fakepi.

WSL · Bash
python -m labs.exp05.log_data --interval 5 --count 3 --out data/fake05
✓ Expected: Three fakepi readings stored.
Checkpoint Three fakepi readings stored.
04

Inspect files

Do not confuse mock and fakepi with physical measurements.

WSL · Bash
find data/mock05 data/fake05 -type f
✓ Expected: The generated HDF5 and/or CSV data files are listed.
Checkpoint HDF5 and/or CSV outputs from the logger.

Experimental notebook

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

03 / Inspect

Source code and method

labs/pi-practical/labs/exp05/log_data.pyDownload source
PY · source file
# ------------------------------------------------------------
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform
# ------------------------------------------------------------
# ====================================================================
# LAB PURPOSE / LOG DATA
# ====================================================================
"""Experiment 5: 24 hourly DHT22 readings, JSON, CSV, HDF5 and tree."""

# ====================================================================
# 01 / IMPORT REQUIRED LIBRARIES
# ====================================================================
import csv
import json
from dataclasses import asdict
from pathlib import Path
from labs.common import parser, sensor, samples, Reading

# Derive the storage columns from the shared Reading dataclass.
FIELDS = list(Reading.__dataclass_fields__)

# ====================================================================
# 02 / EXPORT SENSOR DATA IN FOUR FORMATS
# ====================================================================
def save(rows, directory):
    # Recreate the small snapshot atomically for JSON; preserve a valid document.
    # Create the output folder if it does not already exist.
    directory = Path(directory); directory.mkdir(parents=True, exist_ok=True)
    # ====================================================================
    # JSON SNAPSHOT / ATOMIC REPLACEMENT
    # ====================================================================
    tmp = directory / 'readings.json.tmp'
    # Serialize all readings as one valid JSON array.
    tmp.write_text(json.dumps(rows, indent=2, allow_nan=False), encoding='utf-8')
    # Replace the old JSON file only after the new file has been written.
    tmp.replace(directory / 'readings.json')
    # ====================================================================
    # CSV / TABULAR EXPORT
    # ====================================================================
    with (directory / 'readings.csv').open('w', newline='', encoding='utf-8') as f:
        # Write a header followed by one row per reading.
        writer = csv.DictWriter(f, fieldnames=FIELDS); writer.writeheader(); writer.writerows(rows)
    # ====================================================================
    # HDF5 / STRUCTURED BINARY STORAGE
    # ====================================================================
    import h5py
    with h5py.File(directory / 'readings.h5', 'w') as f:
        # Create a group containing one dataset per sensor field.
        group = f.create_group('sensor_data')
        for field in FIELDS:
            # Extract one column from the list of recorded samples.
            values = [r[field] for r in rows]
            # Store physical quantities as floating-point values and other fields as UTF-8.
            if field in ('temperature','humidity'):
                group.create_dataset(field, data=values, dtype='f8')
            else:
                group.create_dataset(field, data=values, dtype=h5py.string_dtype('utf-8'))
    # ====================================================================
    # TREE / HIERARCHICAL JSON
    # ====================================================================
    tree = {}
    for row in rows:
        # Group the records under their sensor identifier.
        tree.setdefault(row['sensor_id'], {}).setdefault('readings', []).append(row)
    (directory / 'tree.json').write_text(json.dumps(tree, indent=2), encoding='utf-8')

# ====================================================================
# 03 / ACQUISITION AND LOGGING LOOP
# ====================================================================
def main():
    # Default to 24 measurements with a one-hour delay between samples.
    p = parser(__doc__, interval=3600, count=24)
    p.add_argument('--out', default='data/exp05')
    a = p.parse_args()
    # Hold the readings accumulated during this run.
    rows = []
    with sensor(a.mock) as device:
        for reading in samples(device, a.interval, a.count):
            # Append the new sample and update all four output formats.
            # Convert each reading into a dictionary and refresh all four output files.
            rows.append(asdict(reading)); save(rows, a.out)
            # Show the current reading immediately in the terminal.
            print(reading.json(), flush=True)

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

X5 · 11 notebook cells · 3 executable Python cells

Complete the theoretical investigation first. Run the cells in order, record actual outputs and compare against your prediction.

How to execute

  1. Download this notebook and open Google Colab. Select File → Upload notebook and choose the downloaded .ipynb.
  2. Read the Markdown instructions before each executable cell. Use a Python runtime, run cells from top to bottom, and resolve imports if necessary.
  3. Perform the baseline and controlled changes. Save the notebook with actual outputs and your written interpretation.

Execution scope: Default computational cells passed isolated local Python execution; physical equipment and live services require separate verification.

01Instructions · Markdown
# x5 · Lab 5 · DHT22 environmental data logger **PSUT IoT Engineering Studio — Dr. Mohammad Alja’afreh** ## Introduction Verify environmental data outputs in CSV, JSON and HDF5. ## How to run 1. Download this notebook from the laboratory page. Open Google Colab → File → Upload notebook. 2. Select a Python CPU runtime. Run cells from top to bottom using Shift+Enter, or Runtime → Run all. 3. Read the printed observations and assertions. Change one parameter at a time and rerun the relevant cell. 4. Save your own outputs and compare them to the portal Experiment tab. **Execution boundary:** Original common sensor model; mock samples and in-memory output. Do not run the hardware or service commands in Colab. No real credentials are needed. The notebook is self-contained.
02Instructions · Markdown
## Experiment-specific preparation Verify environmental data outputs in CSV, JSON and HDF5. **Reference procedure (use the matching simulator/WSL tool where named, not an unrelated service):** 1. Run three readings. The mock source uses temperature=round(23+3 sin(i/5),1) and RH=round(55+8 cos(i/5),1). Compare the sensor_data field names. 2. Select CSV, JSON and Tree JSON; all represent the same readings. CSV includes one header; the JSON document is an array, and the tree is keyed by sensor ID. 3. Select HDF5 schema. Inspect numeric float64 and UTF-8 datasets and row count; actual HDF5 byte size is not predicted by this browser. 4. Run python -m labs.exp05.log_data --mock --interval 0.2 --count 3 --out data/mock05, then inspect readings.csv, readings.json, readings.h5 and tree.json. Compare row counts and units. **Evidence:** **Boundary:**
03Instructions · Markdown
## 1. Objectives and reference condition - Reproduce the specific computational mechanism in this laboratory. - Inspect the output, compare the reference condition with a changed or rejected condition where implemented, and explain any discrepancy. - Distinguish actual local Python execution from mock, physical and external-service observations. ## 2. Environment check
04Python · executable cell
PYTHON · Code cell
# =====================================================================
# X5 | Code cell 01 | Lab 5 · DHT22 environmental data logger
# Purpose: 1. Objectives and reference condition - Reproduce the specific computational mechanism in this laboratory. - Inspect the output, compare the reference condition with a changed or rejected condition where implem
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
import sys
print("Python",sys.version.split()[0])
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert sys.version_info >= (3,10)
Ask Dr. Mohammad about this cell
05Instructions · Markdown
## 3. Implementation Read the comments and variable definitions before execution. Assertions must pass; inspect values, not just completion.
06Python · executable cell
PYTHON · Code cell
# =====================================================================
# X5 | Code cell 02 | Lab 5 · DHT22 environmental data logger
# Purpose: implement only the mechanism named in this laboratory.
# Inputs: the explicit fictional fixture and reference parameters below.
# Output: printed observations and assertions for the controlled trial.
# =====================================================================
import json

import math

import os

import time

from datetime import datetime, timezone

from dataclasses import dataclass, asdict

@dataclass(frozen=True)
# ====================================================================
# 01 / READING DATA MODEL
# ====================================================================
class Reading:
    # Unique identifier distinguishes multiple devices.
    sensor_id: str
    # UTC ISO-8601 time allows consistent comparisons across devices.
    timestamp: str
    temperature: float
    humidity: float
    # Distinguish generated demo readings from physical measurements.
    source: str

    def json(self):
        # Convert the dataclass to JSON; reject NaN values.
        return json.dumps(asdict(self), allow_nan=False)

class Sensor:
    def __init__(self, mock=False):
        self.mock = mock
        self.simulated_driver = False
        self.index = 0
        # Read an optional sensor identifier from the environment.
        self.sensor_id = os.getenv('SENSOR_ID', 'dht22-01')
        self.device = None
        self.last_read = 0.0
        # Load Raspberry Pi hardware libraries only for physical acquisition.
        if not mock:
            import board
            import adafruit_dht
            self.simulated_driver = getattr(adafruit_dht, "SIMULATED", False)
            # GPIO17 is BCM numbering; use the DHT22 single-data-wire protocol.
            self.device = adafruit_dht.DHT22(board.D17, use_pulseio=False)

    # ====================================================================
    # 03 / ACQUIRE AND VALIDATE A SAMPLE
    # ====================================================================
    def read(self):
        # Protect the physical DHT22 against excessively frequent polling.
        # Generate repeatable values for testing without a sensor.
        if self.mock:
            # Produce a slowly varying temperature in degrees Celsius.
            t = round(23 + 3 * math.sin(self.index / 5), 1)
            # Produce a slowly varying relative humidity percentage.
            h = round(55 + 8 * math.cos(self.index / 5), 1)
            self.index += 1
        else:
            # Retry transient DHT timing or checksum failures up to five times.
            for attempt in range(5):
                # Enforce at least 2.1 seconds between real sensor read attempts.
                time.sleep(max(0, 2.1 - (time.monotonic() - self.last_read)))
                self.last_read = time.monotonic()
                try:
                    # Read both quantities from the DHT22 driver.
                    t, h = self.device.temperature, self.device.humidity
                    # Accept only available readings with humidity in its physical range.
                    if t is not None and h is not None and 0 <= h <= 100:
                        break
                except RuntimeError:
                    pass  # DHT checksum/timing error: retry at a safe interval.
            else:
                # Report persistent failures instead of inventing a valid reading.
                raise RuntimeError('DHT22 failed after five attempts; check wiring.')
        # Attach acquisition time, sensor identity and provenance.
        return Reading(self.sensor_id, datetime.now(timezone.utc).isoformat(),
                       float(t), float(h), 'mock' if self.mock else ('fakepi' if self.simulated_driver else 'hardware'))

    # ====================================================================
    # 04 / RELEASE THE SENSOR
    # ====================================================================
    def close(self):
        if self.device is not None:
            # Release the hardware resources allocated by the DHT driver.
            self.device.exit()
Ask Dr. Mohammad about this cell
07Instructions · Markdown
### Step 2 · Run the reference calculation Read the comments and variable definitions before execution. Assertions must pass; inspect values, not just completion.
08Python · executable cell
PYTHON · Code cell
# =====================================================================
# X5 | Code cell 03 | Lab 5 · DHT22 environmental data logger
# Purpose: Step 2 · Run the reference calculation Read the comments and variable definitions before execution. Assertions must pass; inspect values, not just completion.
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
# Set sensor for the next computation or reference condition.
sensor=Sensor(mock=True)
try: readings=[sensor.read() for _ in range(3)]
finally: sensor.close()
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
print([r.json() for r in readings]);assert len(readings)==3 and all(r.source=='mock' and 0<=r.humidity<=100 for r in readings)
import csv,io
# Set f for the next computation or reference condition.
f=io.StringIO();writer=csv.DictWriter(f,fieldnames=list(asdict(readings[0])));writer.writeheader();writer.writerows(asdict(r) for r in readings);assert len(list(csv.DictReader(io.StringIO(f.getvalue()))))==3
print(f.getvalue())
Ask Dr. Mohammad about this cell
09Instructions · Markdown
## Original portal implementation (reference only) These are the actual laboratory snippets. They are retained for comparison; follow the portal setup for WSL, hardware or services. They are **not** executed by Run all. ```bash python -m labs.exp05.log_data --mock --interval 0.2 --count 3 --out data/mock05 ``` ```bash python -m labs.exp05.log_data --interval 5 --count 3 --out data/fake05 ``` ```python # ------------------------------------------------------------ # Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved. # PSUT IoT Engineering Learning Platform # ------------------------------------------------------------ # ==================================================================== # LAB PURPOSE / LOG DATA # ==================================================================== """Experiment 5: 24 hourly DHT22 readings, JSON, CSV, HDF5 and tree.""" # ==================================================================== # 01 / IMPORT REQUIRED LIBRARIES # ==================================================================== import csv import json from dataclasses import asdict from pathlib import Path from labs.common import parser, sensor, samples, Reading # Derive the storage columns from the shared Reading dataclass. FIELDS = list(Reading.__dataclass_fields__) # ==================================================================== # 02 / EXPORT SENSOR DATA IN FOUR FORMATS # ==================================================================== def save(rows, directory): # Recreate the small snapshot atomically for JSON; preserve a valid document. # Create the output folder if it does not already exist. directory = Path(directory); directory.mkdir(parents=True, exist_ok=True) # ==================================================================== # JSON SNAPSHOT / ATOMIC REPLACEMENT # ==================================================================== tmp = directory / 'readings.json.tmp' # Serialize all readings as one valid JSON array. tmp.write_text(json.dumps(rows, indent=2, allow_nan=False), encoding='utf-8') # Replace the old JSON file only after the new file has been written. tmp.replace(directory / 'readings.json') # ==================================================================== # CSV / TABULAR EXPORT # ==================================================================== with (directory / 'readings.csv').open('w', newline='', encoding='utf-8') as f: # Write a header followed by one row per reading. writer = csv.DictWriter(f, fieldnames=FIELDS); writer.writeheader(); writer.writerows(rows) # ==================================================================== # HDF5 / STRUCTURED BINARY STORAGE # ==================================================================== import h5py with h5py.File(directory / 'readings.h5', 'w') as f: # Create a group containing one dataset per sensor field. group = f.create_group('sensor_data') for field in FIELDS: # Extract one column from the list of recorded samples. values = [r[field] for r in rows] # Store physical quantities as floating-point values and other fields as UTF-8. if field in ('temperature','humidity'): group.create_dataset(field, data=values, dtype='f8') else: group.create_dataset(field, data=values, dtype=h5py.string_dtype('utf-8')) # ==================================================================== # TREE / HIERARCHICAL JSON # ==================================================================== tree = {} for row in rows: # Group the records under their sensor identifier. tree.setdefault(row['sensor_id'], {}).setdefault('readings', []).append(row) (directory / 'tree.json').write_text(json.dumps(tree, indent=2), encoding='utf-8') # ==================================================================== # 03 / ACQUISITION AND LOGGING LOOP # ==================================================================== def main(): # Default to 24 measurements with a one-hour delay between samples. p = parser(__doc__, interval=3600, count=24) p.add_argument('--out', default='data/exp05') a = p.parse_args() # Hold the readings accumulated during this run. rows = [] with sensor(a.mock) as device: for reading in samples(device, a.interval, a.count): # Append the new sample and update all four output formats. # Convert each reading into a dictionary and refresh all four output files. rows.append(asdict(reading)); save(rows, a.out) # Show the current reading immediately in the terminal. print(reading.json(), flush=True) # ==================================================================== # PROGRAM ENTRY POINT / RUN THE EXPERIMENT # ==================================================================== if __name__ == '__main__': try: main() except KeyboardInterrupt: pass ```
10Instructions · Markdown
## 4. Results and analysis Record the actual output and whether the assertions pass. Identify a parameter to vary, state your prediction, repeat the reference calculation, then explain the changed result. | Trial | Configuration | Observation | Interpretation | |---|---|---|---| | A | Reference | | | | B | One controlled change | | | | C | Reference repeat | | | **Limitations:** Original common sensor model; mock samples and in-memory output. Notebook success does not certify external equipment or services.
11Instructions · Markdown
## Guided reasoning and evidence A controlled comparison changes one independent input while keeping the other relevant inputs fixed; the dependent variable is the recorded output. Use this lab’s reference condition above. **Independent task:** 2. Select CSV, JSON and Tree JSON; all represent the same readings. CSV includes one header; the JSON document is an array, and the tree is keyed by sensor ID. Record the named input, prediction, actual output and one limitation; restore the original condition and repeat. | Trial | Input/configuration | Prediction | Observation | Evidence / limitation | |---|---|---|---|---| | A | Reference | | | | | B | Changed input | | | | | A repeat | Reference | | | | A conclusion is supported only when it cites the recorded values or observed states and explains them with the experiment theory.