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 11 · MySQL / MariaDB sensor database
IoTPSUT IoT Engineering StudioPrincess Sumaya University for Technology · Dr. Mohammad Alja’afreh
Pi practical / X11
IoT Programming and Applications

Lab 11 · MySQL / MariaDB sensor database

Ask Dr. Mohammad · X11 →

Create a repeatable local MariaDB account and insert/query sensor readings.

Design experiment & verify evidence →
X11 · Laboratory mentorAsk about the current experiment, its algorithms or Python notebook.
Ask Dr. MohammadAdaptive practice
Learning workflow · Core IoT & programmingX11 · MySQL / MariaDB sensor database
Readiness checksRevision deckEngineering workspaceRecord evidence
X11 · Academic orientation

Scope and objectives

Scope of the experiment

Simulate parameterized insert/query behavior, duplicate IDs and permission failures.

The focus of this experiment is to distinguish database schema, columns, credentials and prepared statements. Students then trace insertion and selection of timestamped sensor records, and verify stored values and diagnose connection or schema errors. 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

  • Distinguish database schema, columns, credentials and prepared statements.
  • Trace insertion and selection of timestamped sensor records.
  • Verify stored values and diagnose connection or schema errors.
  • 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 distinguish database schema, columns, credentials and prepared statements, trace insertion and selection of timestamped sensor records, and verify stored values and diagnose connection or schema errors.

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 stored values and diagnose connection or schema errors. Separate predicted values from observations.

Prerequisite knowledge and related learning

Review the following catalogue prerequisites before starting. After completion, continue to Lab 12 · MQTT publisher.

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.

X11 / 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 setup_db.sh rather than manually inventing a password. Source db.env in each client terminal. Compare newly inserted rows separately from prior records; never display the password.

CONCEPTS / ACTIVE RECALL

Understand the experiment

Database storage · Primary key integrity

Relational state illustration · verify real MariaDB separately from the local SQL model
Relational state illustration · verify real MariaDB separately from the local SQL model

Scientific architecture · MariaDB sensor records and SQL aggregation

Relational sensor data — Sensor table / sensor_id PK; Reading table / reading_id PK, sensor_id FK; INSERT / parameterized values; SELECT / filter interval; AVG / group by sensor
Scientific concept map: DHT22 reading — Temperature + RH; Parameterized INSERT — SQL values; MariaDB table — Timestamped rows; SELECT / AVG — Filter range; Result — Count and aggregate.

Scientific foundations and analytical reasoning

A relational database uses keys, constraints and privileges. An INSERT creates a record only if accepted; SELECT can be separately denied.

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 · Relational constraints and transactions

A relational schema identifies rows with keys and relates tables using constraints. INSERT changes state only if constraints, permissions and transaction outcome permit it. SELECT reads rows according to its own privileges. Grouping and aggregation operate on the selected records, including defined null semantics.

Worked example and engineering interpretation

Two records for the same sensor can have different reading IDs. A duplicate primary key may be rejected even though an earlier row is readable. For temperatures 21,23,25 the mean is 23; confirm the query's sensor and time filters before comparing results.

Engineering principles · additional worked teaching example

A primary key uniquely identifies a row; a duplicate can fail an INSERT unless an explicit upsert policy is used. If four attempts use IDs 1,2,1,3, reject-on-duplicate stores three rows. Parameterized SQL treats values separately from the query structure.

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 11 · MySQL / MariaDB sensor database

Insert or query MariaDB sensor records and verify storage independently.

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: Insert or query MariaDB sensor records and verify storage independently.

  1. Enable INSERT and SELECT, node a and mock source. Step twice; check two rows and one sensor key.
  2. Change node to b and source to hardware; change temperature and insert. Calculate grouped means.
  3. Disable INSERT and send; verify no committed row. Restore; adjust UTC-hour bounds.
  4. Disable SELECT and verify query denial independently. Run actual schema and parameter-bound program using your authorized account.

Reference check:

Model boundary:

Independent task and submission evidence

2. Change node to b and source to hardware; change temperature and insert. Calculate grouped means. 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: Insert attempts = 8; Duplicate existing ID on every N (0=none) = 0; INSERT privilege = true; SELECT privilege = true; Query minimum temperature = 26. In the classroom model, Inserted rows = 8; Selected rows = 3; Query status = Executed. A local in-memory relation, not a MariaDB server. 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 11 · MySQL / MariaDB sensor database: independent state notebook12345678Calculated state 1ID1Temperature25ResultInserted

Step 1 of 8 · Calculated state 1

Calculated state 1

ID
1
Temperature
25
Result
Inserted

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

Recall the concept before revealing its explanation.

0 / 3 revealed
X11 · 01 / 08What is a relational database?Reveal explanation
Engineering explanation

Tables store typed rows that can be queried using SQL.

X11 · 02 / 08Why least privilege?Reveal explanation
Engineering explanation

The lab account needs limited access to sensorDB rather than server administration.

X11 · 03 / 08What database/schema and account conditions must be checked before SQL queries?Reveal explanation
Engineering explanation

Use setup_db.sh rather than manually inventing a password. Source db.env in each client terminal. Compare newly inserted rows separately from prior records; never display the password.

X11 · 04 / 08Why grant a database account limited table privileges?Reveal explanation
Engineering reasoning

It reduces the impact of credential compromise and prevents unrelated administrative operations.

X11 · 05 / 08How do parameterized queries help?Reveal explanation
Engineering reasoning

They separate SQL syntax from data values, reducing injection risks and preserving the intended query structure.

X11 · 06 / 08A MariaDB sensor insert is tested. Select every technically valid statement. A. Use parameterized values in database queries. B. Query the inserted record to verify persistence. C. String concatenation is required for parameterized SQL. D. A connection alone proves an insert committed.Reveal explanation
Applied scenario

Correct: A. Use parameterized values in database queries.; B. Query the inserted record to verify persistence.

X11 · 07 / 08In MySQL / MariaDB sensor database, which command or code executes Verify using SQL?Reveal explanation
Implementation recall

sudo mariadb -e "SELECT reading_id,temperature,humidity,source FROM sensorDB.sensor_readings ORDER BY reading_id DESC LIMIT 3;"

X11 · 08 / 08For MySQL / MariaDB sensor database, which actual output or state confirms the prescribed practical run succeeded, and what does it not establish?Reveal explanation
Evidence & acceptance

Start MariaDB and confirm service active. Run setup_db.sh once to create schema and generated password; source db.env without printing credentials. Record the largest reading_id before insertion. After three successful inserts verify three newer rows with source mock, then query UTC hours 0–23. Aggregates include existing records. Use existing user, not root, for application code.

Execution boundary · Real MariaDB. 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.
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

Insert or query MariaDB sensor records and verify storage independently.

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 workbenchX11 · 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
X11 · 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

X11 · 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 11 · MySQL / MariaDB sensor database

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: SQL/source checked; actual MariaDB pending.

Start MariaDB and confirm service active. Run setup_db.sh once to create schema and generated password; source db.env without printing credentials. Record the largest reading_id before insertion. After three successful inserts verify three newer rows with source mock, then query UTC hours 0–23. Aggregates include existing records. Use existing user, not root, for application code.

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 8 inserts where attempts 3 and 6 reuse an existing primary key, calculate committed rows under reject-on-duplicate behavior.

02 · Compare or justify using evidence

For temperatures 24,26,28,30, calculate count and mean with WHERE temperature>=26. Explain why INSERT success does not imply SELECT permission.

03 · Debugging

Debugging · Independent work

IDs 5,6,5,7,6,8 arrive. With reject-on-duplicate, count commits and rejects. What changes under an explicit update-on-conflict policy?

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

Use the reference configuration (Insert attempts = 8; Duplicate existing ID on every N (0=none) = 0; INSERT privilege = true; SELECT privilege = true; Query minimum temperature = 26), but change Insert attempts = 10. The model reports Inserted rows = 10. Explain the governing rule and assumptions that make this output plausible; identify an independent verification method.

Intermediate · Quantitative comparison

Independent theoretical exercise · X11-02

Two model observations of Inserted rows are 8 (reference) and 10 (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 · X11-03

For Duplicate existing ID on every N (0=none) = 2, the model supplies this excerpt from Insert attempts: ID · Temperature · Result 1 · 25 · Inserted 1 · 25.2 · Duplicate key 3 · 25.4 · Inserted 1 · 25.6 · Duplicate key 5 · 25.8 · Inserted Compute the range (maximum minus minimum) of the Temperature column in these rows. Identify the maximum observation. Do not extrapolate beyond these rows.

Advanced · Reverse reasoning

Independent theoretical exercise · X11-04

An observation is Inserted rows = 4. Candidate A uses Insert attempts = 8; Duplicate existing ID on every N (0=none) = 0; INSERT privilege = true; SELECT privilege = true; Query minimum temperature = 26. Candidate B changes the listed settings (Duplicate existing ID on every N (0=none) = 2) 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 · X11-05

A student configures Query minimum temperature = 26.2 while preserving all other reference settings, but copies the reference report of Selected rows = 3. Evaluate whether the report is justified. Identify the first configuration/output check to perform.

Challenging · Design a controlled verification

Independent theoretical exercise · X11-06

Design a controlled comparison for Lab 11 · MySQL / MariaDB sensor database using reference Insert attempts = 8; Duplicate existing ID on every N (0=none) = 0; INSERT privilege = true; SELECT privilege = true; Query minimum temperature = 26 and test Insert attempts = 10. Specify the changed setting(s), measured metric Inserted rows, controls, repetitions, an acceptance check and what evidence can distinguish an actual implementation from the model.

Live simulation · MariaDB relational transactions

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

  1. Enable INSERT and SELECT, node a and mock source. Step twice; check two rows and one sensor key.
  2. Change node to b and source to hardware; change temperature and insert. Calculate grouped means.
  3. Disable INSERT and send; verify no committed row. Restore; adjust UTC-hour bounds.
  4. Disable SELECT and verify query denial independently. Run actual schema and parameter-bound program using your authorized account.

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

Simulate parameterized insert/query behavior, duplicate IDs and permission failures.

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.

Insert attempts8
Duplicate existing ID on every N (0=none)0
INSERT privilegeYes
SELECT privilegeYes
Query minimum temperature26

2 · Perform the investigation in order

  1. Insert eight generated rows with temperatures 25.0 through 26.4 °C. Select values >=26.0.
  2. Inject duplicate IDs and inspect unique-key errors.
  3. Deny INSERT, then independently deny SELECT; distinguish an empty table from access rejection.
  4. Run the actual sensorDB SQL and Python source with parameterized statements; record row counts and errors.

3 · Compare controlled trials

TrialIndependent changeExpected checkObservation
ReferenceUse reference inputs aboveInserted rows: 8; Selected rows: 3Record actual result
INSERT deniedINSERT privilege = NoInserted rows: 0Record actual result
SELECT deniedSELECT privilege = NoSelected rows: 0Record actual result

4 · Analyze and report

Parameter binding prevents treating a value as SQL code. Permission and uniqueness are distinct.

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

Bounded notebook reference exercise; original device/service commands are reference-only. Validated locally in a fresh Jupyter kernel. Download, then upload to Google Colab.

Download NotebookOpen Google ColabAll Python notebooks

Independent implementation sequence

  1. Initialize database and user
  2. Insert three samples
  3. Query stored rows
  4. Verify using SQL
02 / Implement

Step-by-step instructions

Before you run / verification gate

Use setup_db.sh rather than manually inventing a password. Source db.env in each client terminal. Compare newly inserted rows separately from prior records; never display the password.

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

Initialize database and user

The script generates a password on first run and stores it in a private file. Re-running reuses it and updates only the dedicated iotlab account.

WSL · Bash
source ~/psut-wsl/activate.sh
cd ~/psut-wsl/labs/pi-practical
sudo systemctl start mariadb
bash ~/psut-wsl/tools/setup_db.sh
source ~/.config/psut-wsl/db.env
✓ Expected: Database and limited-privilege user preparation completes. No password should appear in shared output; verify authorized queries.
Expected result for each action (5)
  1. source ~/psut-wsl/activate.shThe toolkit virtual environment is selected in this terminal, usually with (.venv) in the prompt. Verify which python points into ~/psut-wsl/.venv.
  2. cd ~/psut-wsl/labs/pi-practicalNormally no output. pwd should show the requested directory. A missing path produces an error; do not continue until corrected.
  3. sudo systemctl start mariadbNormally no output on success. Run systemctl is-active for the named service and confirm active; inspect logs if it fails.
  4. bash ~/psut-wsl/tools/setup_db.shDatabase and limited-privilege user preparation completes. No password should appear in shared output; verify authorized queries.
  5. source ~/.config/psut-wsl/db.envDatabase environment variables load without displaying credentials. The next authorized database query must succeed.
Checkpoint Database ready. No password is printed.
02

Insert three samples

The program reads DB_PASSWORD from this terminal.

WSL · Bash
python -m labs.exp11.database --mock --count 3 --interval 1
✓ Expected: Three mock JSON records are inserted for --count 3; confirm with the independent query.
Checkpoint Three JSON records labelled mock.
03

Query stored rows

All hours are UTC. Prior rows remain on subsequent runs.

WSL · Bash
python -m labs.exp11.database --query --start-hour 0 --end-hour 23
✓ Expected: Matching stored rows and grouped averages are printed; prior runs can increase the count.
Checkpoint Rows and grouped averages; count may exceed 3 if previously run.
04

Verify using SQL

Inspect the most recent entries without changing the database.

WSL · Bash
sudo mariadb -e "SELECT reading_id,temperature,humidity,source FROM sensorDB.sensor_readings ORDER BY reading_id DESC LIMIT 3;"
✓ Expected: A table of the latest three stored rows appears, including reading_id, temperature, humidity and source.
Checkpoint Three latest rows.

Experimental notebook

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

03 / Inspect

Source code and method

labs/pi-practical/labs/exp11/database.pyDownload source
PY · source file
# ------------------------------------------------------------
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform
# ------------------------------------------------------------
# ====================================================================
# LAB PURPOSE / DATABASE
# ====================================================================
"""Experiment 11: insert and query sensor readings in MariaDB/MySQL."""

# ====================================================================
# 01 / IMPORT REQUIRED LIBRARIES
# ====================================================================
import argparse
import os
from datetime import datetime
from contextlib import closing
from labs.common import parser, sensor, samples, require_env

# ====================================================================
# 02 / ESTABLISH THE DATABASE CONNECTION
# ====================================================================
def connect():
    import mysql.connector
    # Read database settings from the environment; connect to sensorDB.
    return mysql.connector.connect(host=os.getenv('DB_HOST','127.0.0.1'), port=int(os.getenv('DB_PORT','3306')), user=os.getenv('DB_USER','iotlab'), password=require_env('DB_PASSWORD'), database='sensorDB')

# ====================================================================
# 03 / INSERT ONE READING AS A TRANSACTION
# ====================================================================
def insert(conn, reading):
    # Convert the UTC ISO timestamp to the SQL DATETIME representation.
    stamp = datetime.fromisoformat(reading.timestamp).replace(tzinfo=None)  # UTC stored as DATETIME.
    # Ensure the SQL cursor is closed after use.
    with closing(conn.cursor()) as cur:
        try:
            # Create or update the sensor metadata with parameter binding.
            cur.execute('INSERT INTO sensors(sensor_id,sensor_name) VALUES (%s,%s) ON DUPLICATE KEY UPDATE sensor_name=VALUES(sensor_name)', (reading.sensor_id,'DHT22'))
            # Insert the measurement using bound values rather than SQL string concatenation.
            cur.execute('INSERT INTO sensor_readings(sensor_id,recorded_at,temperature,humidity,source) VALUES (%s,%s,%s,%s,%s)', (reading.sensor_id,stamp,reading.temperature,reading.humidity,reading.source))
            # Commit both statements together.
            conn.commit()
        except Exception:
            # Undo the transaction on failure and propagate the error.
            conn.rollback(); raise

# ====================================================================
# 04 / FILTER AND AGGREGATE MEASUREMENTS
# ====================================================================
def query(conn, start_hour=9, end_hour=17):
    # Ensure the SQL cursor is closed after use.
    with closing(conn.cursor()) as cur:
        # Filter readings by UTC hour using parameterized bounds.
        cur.execute('SELECT reading_id,sensor_id,recorded_at,temperature,humidity,source FROM sensor_readings WHERE HOUR(recorded_at) BETWEEN %s AND %s ORDER BY recorded_at', (start_hour,end_hour))
        # Retrieve the selected rows before executing the next query.
        rows = cur.fetchall()
        # Compute count and average measurements separately for each source.
        cur.execute('SELECT source,COUNT(*),AVG(temperature),AVG(humidity) FROM sensor_readings GROUP BY source')
        return rows, cur.fetchall()

# ====================================================================
# 05 / CHOOSE LOGGING OR QUERY MODE
# ====================================================================
def main():
    p = parser(__doc__, count=24)
    p.add_argument('--query', action='store_true')
    p.add_argument('--start-hour', type=int, default=9); p.add_argument('--end-hour', type=int, default=17)
    a = p.parse_args()
    # Validate the requested hour range before querying.
    if not 0 <= a.start_hour <= a.end_hour <= 23: p.error('Hours must be ordered and in 0–23 UTC')
    with closing(connect()) as conn:
        # Read existing measurements and print aggregate statistics.
        if a.query:
            rows, aggregates = query(conn,a.start_hour,a.end_hour)
            for row in rows: print(row)
            print('Source, count, avg temperature, avg humidity:', aggregates)
        else:
            # Otherwise acquire samples and store each in the database.
            with sensor(a.mock) as dev:
                for r in samples(dev,a.interval,a.count): insert(conn,r); print(r.json(), flush=True)

# ====================================================================
# PROGRAM ENTRY POINT / RUN THE EXPERIMENT
# ====================================================================
if __name__ == '__main__':
    try: main()
    except KeyboardInterrupt: pass
labs/pi-practical/labs/exp11/schema.sqlDownload source
SQL · source file
-- ------------------------------------------------------------
-- Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
-- PSUT IoT Engineering Learning Platform
-- ------------------------------------------------------------
-- ====================================================================
-- 01 / CREATE AND SELECT THE DATABASE
-- ====================================================================
CREATE DATABASE IF NOT EXISTS sensorDB CHARACTER SET utf8mb4;
USE sensorDB;
-- ====================================================================
-- 02 / SENSOR METADATA TABLE (PRIMARY KEY IDENTIFIES SENSOR)
-- ====================================================================
CREATE TABLE IF NOT EXISTS sensors (
    sensor_id VARCHAR(64) PRIMARY KEY,
    sensor_name VARCHAR(64) NOT NULL
) ENGINE=InnoDB;
-- ====================================================================
-- 03 / MEASUREMENT TABLE (ONE ROW PER SAMPLE)
-- ====================================================================
CREATE TABLE IF NOT EXISTS sensor_readings (
    -- Auto-incremented primary key identifies each measurement.
    reading_id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    sensor_id VARCHAR(64) NOT NULL,
    -- Store UTC timestamps with microsecond precision.
    recorded_at DATETIME(6) NOT NULL,
    -- Temperature is measured in degrees Celsius.
    temperature DOUBLE NOT NULL,
    -- Relative humidity is measured as a percentage.
    humidity DOUBLE NOT NULL,
    -- Record whether data came from hardware or mock acquisition.
    source VARCHAR(16) NOT NULL,
    -- ====================================================================
    -- 04 / RELATIONAL INTEGRITY AND TIME INDEX
    -- ====================================================================
    FOREIGN KEY (sensor_id) REFERENCES sensors(sensor_id),
    -- Index timestamp-based queries.
    INDEX idx_recorded_at (recorded_at)
) ENGINE=InnoDB;
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

X11 · 9 notebook cells · 2 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
# x11 · Lab 11 · MySQL / MariaDB sensor database **PSUT IoT Engineering Studio — Dr. Mohammad Alja’afreh** ## Introduction Insert or query MariaDB sensor records and verify storage independently. ## 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:** Bounded notebook reference exercise; original device/service commands are reference-only. 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 Insert or query MariaDB sensor records and verify storage independently. **Reference procedure (use the matching simulator/WSL tool where named, not an unrelated service):** 1. Enable INSERT and SELECT, node a and mock source. Step twice; check two rows and one sensor key. 2. Change node to b and source to hardware; change temperature and insert. Calculate grouped means. 3. Disable INSERT and send; verify no committed row. Restore; adjust UTC-hour bounds. 4. Disable SELECT and verify query denial independently. Run actual schema and parameter-bound program using your authorized account. 5. Insert eight generated rows with temperatures 25.0 through 26.4 °C. Select values >=26.0. **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
# =====================================================================
# X11 | Code cell 01 | Lab 11 · MySQL / MariaDB sensor database
# 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
# =====================================================================
# X11 | Code cell 02 | Lab 11 · MySQL / MariaDB sensor database
# Purpose: 3. Implementation 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.
# =====================================================================
import sqlite3
# Actual local SQL with SQLite, not MariaDB protocol or schema compatibility.
with sqlite3.connect(':memory:') as c:
    c.execute('CREATE TABLE readings(hour INTEGER, temperature REAL)')
    c.executemany('INSERT INTO readings VALUES (?,?)',[(1,23),(12,25),(22,27)])
    rows=c.execute('SELECT temperature FROM readings WHERE hour BETWEEN ? AND ?', (0,13)).fetchall()
    print(rows);assert rows==[(23.0,),(25.0,)]
Ask Dr. Mohammad about this cell
07Instructions · 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.exp11.database --mock --count 3 --interval 1 ``` ```bash python -m labs.exp11.database --query --start-hour 0 --end-hour 23 ``` ```python # ------------------------------------------------------------ # Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved. # PSUT IoT Engineering Learning Platform # ------------------------------------------------------------ # ==================================================================== # LAB PURPOSE / DATABASE # ==================================================================== """Experiment 11: insert and query sensor readings in MariaDB/MySQL.""" # ==================================================================== # 01 / IMPORT REQUIRED LIBRARIES # ==================================================================== import argparse import os from datetime import datetime from contextlib import closing from labs.common import parser, sensor, samples, require_env # ==================================================================== # 02 / ESTABLISH THE DATABASE CONNECTION # ==================================================================== def connect(): import mysql.connector # Read database settings from the environment; connect to sensorDB. return mysql.connector.connect(host=os.getenv('DB_HOST','127.0.0.1'), port=int(os.getenv('DB_PORT','3306')), user=os.getenv('DB_USER','iotlab'), password=require_env('DB_PASSWORD'), database='sensorDB') # ==================================================================== # 03 / INSERT ONE READING AS A TRANSACTION # ==================================================================== def insert(conn, reading): # Convert the UTC ISO timestamp to the SQL DATETIME representation. stamp = datetime.fromisoformat(reading.timestamp).replace(tzinfo=None) # UTC stored as DATETIME. # Ensure the SQL cursor is closed after use. with closing(conn.cursor()) as cur: try: # Create or update the sensor metadata with parameter binding. cur.execute('INSERT INTO sensors(sensor_id,sensor_name) VALUES (%s,%s) ON DUPLICATE KEY UPDATE sensor_name=VALUES(sensor_name)', (reading.sensor_id,'DHT22')) # Insert the measurement using bound values rather than SQL string concatenation. cur.execute('INSERT INTO sensor_readings(sensor_id,recorded_at,temperature,humidity,source) VALUES (%s,%s,%s,%s,%s)', (reading.sensor_id,stamp,reading.temperature,reading.humidity,reading.source)) # Commit both statements together. conn.commit() except Exception: # Undo the transaction on failure and propagate the error. conn.rollback(); raise # ==================================================================== # 04 / FILTER AND AGGREGATE MEASUREMENTS # ==================================================================== def query(conn, start_hour=9, end_hour=17): # Ensure the SQL cursor is closed after use. with closing(conn.cursor()) as cur: # Filter readings by UTC hour using parameterized bounds. cur.execute('SELECT reading_id,sensor_id,recorded_at,temperature,humidity,source FROM sensor_readings WHERE HOUR(recorded_at) BETWEEN %s AND %s ORDER BY recorded_at', (start_hour,end_hour)) # Retrieve the selected rows before executing the next query. rows = cur.fetchall() # Compute count and average measurements separately for each source. cur.execute('SELECT source,COUNT(*),AVG(temperature),AVG(humidity) FROM sensor_readings GROUP BY source') return rows, cur.fetchall() # ==================================================================== # 05 / CHOOSE LOGGING OR QUERY MODE # ==================================================================== def main(): p = parser(__doc__, count=24) p.add_argument('--query', action='store_true') p.add_argument('--start-hour', type=int, default=9); p.add_argument('--end-hour', type=int, default=17) a = p.parse_args() # Validate the requested hour range before querying. if not 0 <= a.start_hour <= a.end_hour <= 23: p.error('Hours must be ordered and in 0–23 UTC') with closing(connect()) as conn: # Read existing measurements and print aggregate statistics. if a.query: rows, aggregates = query(conn,a.start_hour,a.end_hour) for row in rows: print(row) print('Source, count, avg temperature, avg humidity:', aggregates) else: # Otherwise acquire samples and store each in the database. with sensor(a.mock) as dev: for r in samples(dev,a.interval,a.count): insert(conn,r); print(r.json(), flush=True) # ==================================================================== # PROGRAM ENTRY POINT / RUN THE EXPERIMENT # ==================================================================== if __name__ == '__main__': try: main() except KeyboardInterrupt: pass ```
08Instructions · 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:** Bounded notebook reference exercise; original device/service commands are reference-only. Notebook success does not certify external equipment or services.
09Instructions · 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. Change node to b and source to hardware; change temperature and insert. Calculate grouped means. 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.