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
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 cell07Instructions · 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.