The Bluetooth link cannot run on WSL, but the lab’s command protocol ( labs/exp08/protocol.py ), the DHT22 and the LED on GPIO24 can: tools/bt_over_tcp.py serves the same serve_connection() over TCP, and a terminal plays the phone.
Run the exact READ / ON / OFF / STOP newline command grammar and JSON responses of exp08.protocol.
The focus of this experiment is to trace Bluetooth telemetry and LED control messages. Students then validate command parsing and separate sensor units from actuator state, and verify expected responses under controlled valid and invalid messages. The Concepts view explains the operation before the practical work; the Simulation view is used to examine reference and changed inputs, not to substitute for actual measurements.
Learning objectives
Trace Bluetooth telemetry and LED control messages.
Validate command parsing and separate sensor units from actuator state.
Verify expected responses under controlled valid and invalid messages.
Identify the configured inputs (Commands separated by ;; Service mode; TCP substitute connected; Initial LED) 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 trace Bluetooth telemetry and LED control messages, validate command parsing and separate sensor units from actuator state, and verify expected responses under controlled valid and invalid messages.
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 expected responses under controlled valid and invalid messages. Separate predicted values from observations.
Prerequisite knowledge and related learning
Review the following catalogue prerequisites before starting. After completion, continue to Lab 14 · TCP humidity server & client.
The browser instrument and the specified local software or network environment. Use the experiment’s documented topology and distinguish modeled values from actual packet observations.
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.
X8 / 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.
Keep server running; enter READ, ON, OFF, STOP in the nc session, not Bash. Exit nc if still open and stop the server with Ctrl+C.
CONCEPTS / ACTIVE RECALL
Understand the experiment
Scientific architecture · Bluetooth-style telemetry and LED control over TCP
Scientific concept map: Client session — READ / ON / OFF / STOP; TCP stream — Bluetooth-style substitute; Command handler — Parse request; GPIO LED — State change; Reply and cleanup — Telemetry / disconnect.
Scientific foundations and analytical reasoning
The telemetry service interprets application commands independently of the transport. Session state determines whether subsequent commands are processed.
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 · Application protocol over Bluetooth
The transport carries bytes while the application defines commands and responses. Session lifecycle and parser state determine whether a command is valid. The LED state and telemetry state must be distinguished from connection status. Authorization matters even when pairing succeeds.
Worked example and engineering interpretation
Within the laboratory session, READ requests telemetry, ON/OFF change the LED and STOP terminates the relevant session. After disconnection, a stale command should not be interpreted as a new authorized request. Compare command, response and observed state independently.
Engineering principles · additional worked teaching example
A stream command protocol needs framing and explicit acknowledgments. READ should not change LED state; ON/OFF mutate it; STOP terminates according to protocol. A TCP substitute models message semantics, not Bluetooth radio pairing or latency.
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 8 · Bluetooth telemetry & LED control
Use the documented TCP substitute to exchange Bluetooth-style messages.
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: Use the documented TCP substitute to exchange Bluetooth-style messages.
Use READ;ON;READ;OFF;BAD;STOP. The actual source normalizes case and whitespace, returns JSON for each complete newline command, and closes the connection on STOP.
Set mode=sensor and then led. Inspect the unsupported-command error and unchanged actuator state for forbidden operations.
Run ON;STOP;ON: STOP de-energizes the LED and closes the session; the following command is not processed.
In WSL, run python ~/psut-wsl/tools/bt_over_tcp.py --mode both --mock, open nc 127.0.0.1 7008 in another terminal, and enter one command per line. This is TCP substitution, not a physical Bluetooth radio link.
Reference check:
Model boundary:
Independent task and submission evidence
2. Set mode=sensor and then led. Inspect the unsupported-command error and unchanged actuator state for forbidden operations. 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.
Trial
Changed setting
Fixed settings
Predicted result
Actual observation / units
Evidence / uncertainty
A: baseline
Reference
Record
Predict
Record
Record
B: one change
Record
Same as A
Predict
Record
Record
A: repeat
Restore
Same as A
Predict
Record
Record
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: Commands separated by ; = READ;ON;READ;OFF;BAD;STOP; Service mode = both; TCP substitute connected = true; Initial LED = OFF. In the classroom model, Temperature records = 2; LED commands = 2; Rejected frames = 1; Final LED = OFF. A simplified single-session command replay; actual READ includes full Reading metadata. 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.
Keep server running; enter READ, ON, OFF, STOP in the nc session, not Bash. Exit nc if still open and stop the server with Ctrl+C.
X8 · 04 / 08Why distinguish the TCP substitute from Bluetooth telemetry?Reveal explanation
Engineering reasoning
Both may exchange application text, but the substitute does not exercise radio discovery, pairing or Bluetooth transport.
X8 · 05 / 08How should READ and LED commands be verified?Reveal explanation
Engineering reasoning
Check the application response and expected modeled output state; do not infer physical behavior from a socket exchange alone.
X8 · 06 / 08A TCP substitute carries Bluetooth-style telemetry. Select every technically valid statement.
A. The substitute can test application message logic.
B. It does not establish physical Bluetooth performance.
C. TCP measurements are necessarily BLE radio measurements.
D. Successful LED commands prove pairing security.Reveal explanation
Applied scenario
Correct: A. The substitute can test application message logic.; B. It does not establish physical Bluetooth performance.
X8 · 07 / 08In Bluetooth telemetry & LED control, which command or code executes Send protocol commands?Reveal explanation
Implementation recall
READ
ON
OFF
STOP
X8 · 08 / 08For Bluetooth telemetry & LED control, which actual output or state confirms the prescribed practical run succeeded, and what does it not establish?Reveal explanation
Evidence & acceptance
Activate toolkit and use updated bt_over_tcp.py. Terminal A starts the --mode both --mock server; it needs gpiozero. Without gpiozero, --mode sensor --mock is an explicit partial alternative: READ and STOP work; ON/OFF return unsupported command. B opens nc and types commands one per line. For both mode expected JSON led ON/OFF; STOP ends client session, not the listening server. Ctrl+C in A ends it.
Execution boundary · Real protocol over TCP. 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.
Bluetooth telemetry. Session and application commands.
Independent conceptual protocol trace
Animated Lab 8 · Bluetooth telemetry & LED control
Use the scenario selector to explore reference, failure and recovery. The animation is explanatory, separate from the actual terminal exercise. Animation timing is for learning, not measured protocol latency.
Recent trace eventsShared research workbenches · network designer & advanced studiesConcurrent-device simulation & Monte Carlo research
Distributed digital twin · topology, protocol & battery researchLoading experiment-specific apparatus…Previous model / additional reference tools
Simulation task
Use the documented TCP substitute to exchange Bluetooth-style messages.
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 workbenchX8 · 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.
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.
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.
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 sensor-only TCP server and READ/unsupported/STOP passed; combined GPIO mode pending.
Activate toolkit and use updated bt_over_tcp.py. Terminal A starts the --mode both --mock server; it needs gpiozero. Without gpiozero, --mode sensor --mock is an explicit partial alternative: READ and STOP work; ON/OFF return unsupported command. B opens nc and types commands one per line. For both mode expected JSON led ON/OFF; STOP ends client session, not the listening server. Ctrl+C in A ends it.
Record the actual output, source (mock/model or physical), and any error. A missing tool, timeout or untested external service is not a pass.
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
Trace READ;ON;READ;OFF;BAD;STOP from LED OFF in both-mode service, recording expected reply type and LED state.
Engineering method — A stream command protocol needs framing and explicit acknowledgments. READ should not change LED state; ON/OFF mutate it; STOP terminates according to protocol. A TCP substitute models message semantics, not Bluetooth radio pairing or latency. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
02 · Compare or justify using evidence
Repeat the reasoning for a telemetry-only service and a disconnected session; explain why an acknowledged command is not a radio measurement.
Engineering method — A stream command protocol needs framing and explicit acknowledgments. READ should not change LED state; ON/OFF mutate it; STOP terminates according to protocol. A TCP substitute models message semantics, not Bluetooth radio pairing or latency. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
03 · State tracing
State tracing · Independent work
From LED ON, process OFF;READ;BAD;ON;READ. Record state and action classes; why must BAD not mutate state?
State tracing — A stream command protocol needs framing and explicit acknowledgments. READ should not change LED state; ON/OFF mutate it; STOP terminates according to protocol. A TCP substitute models message semantics, not Bluetooth radio pairing or latency. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
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 · X8-01
Use the reference configuration (Commands separated by ; = READ;ON;READ;OFF;BAD;STOP; Service mode = both; TCP substitute connected = true; Initial LED = OFF), but change Service mode = led. The model reports Temperature records = 0. Explain the governing rule and assumptions that make this output plausible; identify an independent verification method.
Intermediate · Quantitative comparison
Independent theoretical exercise · X8-02
Two model observations of Temperature records are 2 (reference) and 0 (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 · X8-03
For Service mode = sensor, the model supplies this excerpt from Command / JSON response:
Step · Command · Response · LED · Session
1 · READ · {"temperature":23,"humidity":63,"source":"mock"} · OFF · Open
2 · ON · {"error":"unsupported command"} · OFF · Open
3 · READ · {"temperature":23.6,"humidity":62.8,"source":"mock"} · OFF · Open
4 · OFF · {"error":"unsupported command"} · OFF · Open
5 · BAD · {"error":"unsupported command"} · OFF · Open
Count rows whose Command value is exactly “READ”, and identify the displayed row numbers. Explain what the count describes.
Advanced · Reverse reasoning
Independent theoretical exercise · X8-04
An observation is LED commands = 0. Candidate A uses Commands separated by ; = READ;ON;READ;OFF;BAD;STOP; Service mode = both; TCP substitute connected = true; Initial LED = OFF. Candidate B changes the listed settings (Service mode = sensor) 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 · X8-05
A student configures TCP substitute connected = false while preserving all other reference settings, but copies the reference report of Temperature records = 2. Evaluate whether the report is justified. Identify the first configuration/output check to perform.
Challenging · Design a controlled verification
Independent theoretical exercise · X8-06
Design a controlled comparison for Lab 8 · Bluetooth telemetry & LED control using reference Commands separated by ; = READ;ON;READ;OFF;BAD;STOP; Service mode = both; TCP substitute connected = true; Initial LED = OFF and test Service mode = led. Specify the changed setting(s), measured metric Temperature records, controls, repetitions, an acceptance check and what evidence can distinguish an actual implementation from the model.
Step-by-step experimental procedure
Run the exact READ / ON / OFF / STOP newline command grammar and JSON responses of exp08.protocol.
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.
Commands separated by ;READ;ON;READ;OFF;BAD;STOP
Service modeboth
TCP substitute connectedYes
Initial LEDOFF
2 · Perform the investigation in order
Use READ;ON;READ;OFF;BAD;STOP. The actual source normalizes case and whitespace, returns JSON for each complete newline command, and closes the connection on STOP.
Set mode=sensor and then led. Inspect the unsupported-command error and unchanged actuator state for forbidden operations.
Run ON;STOP;ON: STOP de-energizes the LED and closes the session; the following command is not processed.
In WSL, run python ~/psut-wsl/tools/bt_over_tcp.py --mode both --mock, open nc 127.0.0.1 7008 in another terminal, and enter one command per line. This is TCP substitution, not a physical Bluetooth radio link.
3 · Compare controlled trials
Trial
Independent change
Expected check
Observation
Mixed reference
Use reference inputs above
Temperature records: 2; LED commands: 2; Final LED: OFF
Record actual result
Sensor only
Service mode = sensor
LED commands: 0
Record actual result
Disconnected
TCP substitute connected = No
LED commands: 0
Record actual result
Malformed command
Commands separated by ; = LED:BAD
Rejected frames: 1
Record actual result
Stop then ON
Commands separated by ; = ON;STOP;ON
Final LED: OFF; LED commands: 1
Record actual result
4 · Analyze and report
Compare application framing and service permissions independently of physical Bluetooth pairing.
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.
Trial
Independent change
Dependent observation
Mixed reference
Use reference inputs above
Record actual outcome and units
Sensor only
Service mode = sensor
Record actual outcome and units
Disconnected
TCP substitute connected = No
Record actual outcome and units
Malformed command
Commands separated by ; = LED:BAD
Record 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 Bluetooth application protocol with mock sensor and LED; no Bluetooth radio. Validated locally in a fresh Jupyter kernel. Download, then upload to Google Colab.
Keep server running; enter READ, ON, OFF, STOP in the nc session, not Bash. Exit nc if still open and stop the server with Ctrl+C.
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
Terminal A — start Bluetooth protocol substitute
This is TCP on loopback, not actual Bluetooth.
WSL · Bash
source ~/psut-wsl/activate.sh
cd ~/psut-wsl/labs/pi-practical
python ~/psut-wsl/tools/bt_over_tcp.py --mode both --mock
✓ Expected: The TCP-based Bluetooth teaching substitute listens on port 7008. Keep running for the client connection.Expected result for each action (3)
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.
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.
python ~/psut-wsl/tools/bt_over_tcp.py --mode both --mockThe TCP-based Bluetooth teaching substitute listens on port 7008. Keep running for the client connection.
Checkpoint Listening on port 7008; keep running.
02
Terminal B — connect the phone substitute
Open a new WSL terminal.
WSL · Bash
nc 127.0.0.1 7008
✓ Expected: The connection opens and waits for application text. Enter READ, ON, OFF or STOP as directed.
Checkpoint Connected or waiting for input.
03
Send protocol commands
Type one command per line and press Enter. These are nc input, not Bash.
Netcat session
READ
ON
OFF
STOP
✓ Expected: The service reports stopped status.Expected result for each action (4)
READThe service returns a JSON reading.
ONThe service acknowledges LED on.
OFFThe service acknowledges LED off.
STOPThe service reports stopped status.
Checkpoint JSON readings, LED acknowledgement and stopped status.
04
Stop the server
Ctrl+C in Terminal A. No Bluetooth pairing took place.
Checkpoint Complete the action before continuing.
Experimental notebook
Record your own results. Values are not prefilled or independently verified.
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.
Download this notebook and open Google Colab. Select File → Upload notebook and choose the downloaded .ipynb.
Read the Markdown instructions before each executable cell. Use a Python runtime, run cells from top to bottom, and resolve imports if necessary.
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
# x8 · Lab 8 · Bluetooth telemetry & LED control
**PSUT IoT Engineering Studio — Dr. Mohammad Alja’afreh**
## Introduction
Use the documented TCP substitute to exchange Bluetooth-style messages.
## 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 Bluetooth application protocol with mock sensor and LED; no Bluetooth radio. 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
Use the documented TCP substitute to exchange Bluetooth-style messages.
**Reference procedure (use the matching simulator/WSL tool where named, not an unrelated service):**
1. Use READ;ON;READ;OFF;BAD;STOP. The actual source normalizes case and whitespace, returns JSON for each complete newline command, and closes the connection on STOP.
2. Set mode=sensor and then led. Inspect the unsupported-command error and unchanged actuator state for forbidden operations.
3. Run ON;STOP;ON: STOP de-energizes the LED and closes the session; the following command is not processed.
4. In WSL, run python ~/psut-wsl/tools/bt_over_tcp.py --mode both --mock, open nc 127.0.0.1 7008 in another terminal, and enter one command per line. This is TCP substitution, not a physical Bluetooth radio link.
**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
# =====================================================================
# X8 | Code cell 01 | Lab 8 · Bluetooth telemetry & LED control
# 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)
## 3. Implementation
Read the comments and variable definitions before execution. Assertions must pass; inspect values, not just completion.
06Python · executable cell
PYTHON · Code cell
# =====================================================================
# X8 | Code cell 02 | Lab 8 · Bluetooth telemetry & LED control
# 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()
### Step 2 · Run the reference calculation
Read the comments and variable definitions before execution. Assertions must pass; inspect values, not just completion.
### Step 3 · Run the reference calculation
Read the comments and variable definitions before execution. Assertions must pass; inspect values, not just completion.
10Python · executable cell
PYTHON · Code cell
# =====================================================================
# X8 | Code cell 04 | Lab 8 · Bluetooth telemetry & LED control
# Purpose: Step 3 · 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)
# Encapsulate state and operations for MockLED; keep its logic separate from the trial.
class MockLED:
value=False
def off(self):self.value=False
# Set led for the next computation or reference condition.
led=MockLED()
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert respond('ON','both',sensor,led)[0]=={'led':'ON'} and led.value
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert respond('READ','both',sensor,led)[0]['source']=='mock'
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert 'error' in respond('BAD','both',sensor,led)[0]
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert respond('STOP','both',sensor,led)[1] and not led.value
sensor.close()
print('Mock READ, ON, invalid and STOP checks passed')
## 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 Bluetooth application protocol with mock sensor and LED; no Bluetooth radio. Notebook success does not certify external equipment or services.
13Instructions · 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. Set mode=sensor and then led. Inspect the unsupported-command error and unchanged actuator state for forbidden operations. 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.