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 8 · Bluetooth telemetry & LED control
IoTPSUT IoT Engineering StudioPrincess Sumaya University for Technology · Dr. Mohammad Alja’afreh
Pi practical / X8
Networking and Communication

Lab 8 · Bluetooth telemetry & LED control

Ask Dr. Mohammad · X8 →

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.

Design experiment & verify evidence →
X8 · Laboratory mentorAsk about the current experiment, its algorithms or Python notebook.
Ask Dr. MohammadAdaptive practice
Learning workflow · Core IoT & programmingX8 · Bluetooth telemetry & LED control
Readiness checksRevision deckEngineering workspaceRecord evidence

Related course access: IoT Programming and Applications — same laboratory, notebook and completion record.

X8 · Academic orientation

Scope and objectives

Scope of the experiment

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.

Environment and experimental methodology

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.

Ubuntu WSL setup →
Before you run / verification gate

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

Command-driven telemetry session — Client; TCP service; LED state; READ / 0>1; Return measurement / 1>0; ON / 0>1; LED on / 1>2; STOP / 0>1; Cleanup / 1>2
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.

  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.

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.

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: 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.

Lab 8 · Bluetooth telemetry & LED control: independent state notebook123456Calculated state 1Step1CommandREADResponse{"temperature":23,"humidity":63,"source":"…LEDOFFSessionOpen

Step 1 of 6 · Calculated state 1

Calculated state 1

Step
1
Command
READ
Response
{"temperature":23,"humidity":63,"source":"mock"}
LED
OFF
Session
Open

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

Recall the concept before revealing its explanation.

0 / 3 revealed
X8 · 01 / 08Why use TCP instead of Bluetooth?Reveal explanation
Engineering explanation

It demonstrates application command semantics without claiming radio pairing.

X8 · 02 / 08What does READ return?Reveal explanation
Engineering explanation

A synthetic sensor reading in JSON.

X8 · 03 / 08What transport/session prerequisites precede virtual Bluetooth telemetry?Reveal explanation
Engineering explanation

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.
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 events
    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

    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.

    ComponentSignal / pinConnection notesSource
    LEDBCM GPIO24 · physical 18LED with resistor to GNDexp08/bluetooth_server.py
    DHT22 DATABCM GPIO17 · physical 113.3 V, GND; pull-up on bare sensorlabs/pi-practical/labs/common.py
    X8 · 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

    X8 · 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 8 · Bluetooth telemetry & LED control

    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.

    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

    Trace READ;ON;READ;OFF;BAD;STOP from LED OFF in both-mode service, recording expected reply type and LED state.

    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.

    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?

    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

    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.

    3 · Compare controlled trials

    TrialIndependent changeExpected checkObservation
    Mixed referenceUse reference inputs aboveTemperature records: 2; LED commands: 2; Final LED: OFFRecord actual result
    Sensor onlyService mode = sensorLED commands: 0Record actual result
    DisconnectedTCP substitute connected = NoLED commands: 0Record actual result
    Malformed commandCommands separated by ; = LED:BADRejected frames: 1Record actual result
    Stop then ONCommands separated by ; = ON;STOP;ONFinal LED: OFF; LED commands: 1Record 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.

    TrialIndependent changeDependent observation
    Mixed referenceUse reference inputs aboveRecord actual outcome and units
    Sensor onlyService mode = sensorRecord actual outcome and units
    DisconnectedTCP substitute connected = NoRecord actual outcome and units
    Malformed commandCommands separated by ; = LED:BADRecord 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.

    Download NotebookOpen Google ColabAll Python notebooks

    Independent implementation sequence

    1. Terminal A — start Bluetooth protocol substitute
    2. Terminal B — connect the phone substitute
    3. Send protocol commands
    4. Stop the server
    02 / Implement

    Step-by-step instructions

    Before you run / verification gate

    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)
    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. 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)
    1. READThe service returns a JSON reading.
    2. ONThe service acknowledges LED on.
    3. OFFThe service acknowledges LED off.
    4. 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.

    03 / Inspect

    Source code and method

    labs/pi-practical/labs/exp08/bluetooth_server.pyDownload source
    PY · source file
    # ------------------------------------------------------------
    # Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
    # PSUT IoT Engineering Learning Platform
    # ------------------------------------------------------------
    # ====================================================================
    # LAB PURPOSE / BLUETOOTH SERVER
    # ====================================================================
    """Experiment 8a/b: authenticated Bluetooth Classic SPP using BlueZ Profile1."""
    
    # ====================================================================
    # 01 / IMPORT REQUIRED LIBRARIES
    # ====================================================================
    import argparse
    import socket
    import threading
    from contextlib import ExitStack
    from labs.common import sensor
    from labs.exp08.protocol import serve_connection
    
    # The standard Serial Port Profile UUID identifies the Bluetooth service.
    UUID = '00001101-0000-1000-8000-00805f9b34fb'  # Standard SPP UUID.
    # D-Bus object path exported for BlueZ callbacks.
    PATH = '/org/iotstudio/iot/spp'
    
    # ====================================================================
    # 02 / CONFIGURE SERVICE MODE AND HARDWARE
    # ====================================================================
    def main():
        p = argparse.ArgumentParser(description=__doc__)
        # Select telemetry, actuator control or both.
        p.add_argument('--mode', choices=['sensor','led','both'], default='both')
        # Simulate the sensor and LED, but retain real Bluetooth communication.
        p.add_argument('--mock', action='store_true', help='Mock sensor and LED; real Bluetooth still required')
        a = p.parse_args()
        import dbus, dbus.service
        from dbus.mainloop.glib import DBusGMainLoop
        from gi.repository import GLib
        if a.mock:
            class MockLED:
                value = False
                def off(self): self.value = False
        # ====================================================================
        # 03 / CONNECT TO BLUEZ AND GLIB
        # ====================================================================
        DBusGMainLoop(set_as_default=True)
        # Connect to the system D-Bus used by the Bluetooth daemon.
        bus = dbus.SystemBus()
        # Access the BlueZ profile registration interface.
        manager = dbus.Interface(bus.get_object('org.bluez','/org/bluez'),'org.bluez.ProfileManager1')
        # Create the event loop that dispatches profile callbacks.
        loop = GLib.MainLoop()
        # Manage sensor and LED resources according to the selected mode.
        with ExitStack() as stack:
            dev = stack.enter_context(sensor(a.mock)) if a.mode != 'led' else None
            led = None
            if a.mode != 'sensor':
                if a.mock: led = MockLED()
                else:
                    from gpiozero import LED
                    led = stack.enter_context(LED(24, initial_value=False))
            # ====================================================================
            # 04 / IMPLEMENT BLUEZ PROFILE CALLBACKS
            # ====================================================================
            class Profile(dbus.service.Object):
                def __init__(self):
                    super().__init__(bus, PATH); self.sessions = {}; self.lock = threading.Lock()
                @dbus.service.method('org.bluez.Profile1', in_signature='', out_signature='')
                # BlueZ calls this when the profile is released.
                def Release(self):
                    self.close_sessions(); loop.quit()
                @dbus.service.method('org.bluez.Profile1', in_signature='oha{sv}', out_signature='')
                # Receive an authenticated connection and its file descriptor.
                def NewConnection(self, device, fd, properties):
                    # Wrap the provided descriptor as a Python socket.
                    conn = socket.socket(fileno=fd.take())
                    with self.lock:
                        # Allow only one connected client to protect shared resources.
                        if self.sessions:  # One client at a time protects the sensor/LED.
                            conn.close(); return
                        # Track the connection by BlueZ device path.
                        self.sessions[str(device)] = conn
                    # Handle requests in a background thread so the D-Bus loop stays responsive.
                    def worker():
                        try: serve_connection(conn, a.mode, dev, led)
                        except OSError as exc: print('Bluetooth session closed:', exc)
                        finally:
                            with self.lock: self.sessions.pop(str(device), None)
                    # Start the session worker without blocking the event loop.
                    threading.Thread(target=worker, daemon=True).start()
                @dbus.service.method('org.bluez.Profile1', in_signature='o', out_signature='')
                # Close the active connection requested by BlueZ.
                def RequestDisconnection(self, device):
                    with self.lock: conn = self.sessions.get(str(device))
                    if conn:
                        # Wake any blocking socket read or write during disconnect.
                        try: conn.shutdown(socket.SHUT_RDWR)
                        except OSError: pass
                def close_sessions(self):
                    with self.lock: connections = list(self.sessions.values())
                    for conn in connections:
                        # Wake any blocking socket read or write during disconnect.
                        try: conn.shutdown(socket.SHUT_RDWR)
                        except OSError: pass
            # ====================================================================
            # 05 / REGISTER THE AUTHENTICATED SPP SERVICE
            # ====================================================================
            profile = Profile()
            # Publish RFCOMM channel 7 and require authentication and authorization.
            manager.RegisterProfile(PATH, UUID, {'Name':'IoT Serial', 'Role':'server', 'Channel':dbus.UInt16(7), 'RequireAuthentication':dbus.Boolean(True), 'RequireAuthorization':dbus.Boolean(True)})
            print('SPP service registered. Connect a paired Android serial terminal; send READ, ON, OFF, STOP with LF.')
            # Keep the Bluetooth service available until stopped.
            try: loop.run()
            finally:
                # ====================================================================
                # 06 / UNREGISTER AND SWITCH OFF THE LED
                # ====================================================================
                # Shut down open client sessions before releasing resources.
                profile.close_sessions()
                try: manager.UnregisterProfile(PATH)
                except dbus.DBusException: pass
                if led is not None: led.off()
    
    # ====================================================================
    # PROGRAM ENTRY POINT / RUN THE EXPERIMENT
    # ====================================================================
    if __name__ == '__main__':
        try: main()
        except KeyboardInterrupt: pass
    
    labs/pi-practical/labs/exp08/protocol.pyDownload source
    PY · source file
    # ------------------------------------------------------------
    # Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
    # PSUT IoT Engineering Learning Platform
    # ------------------------------------------------------------
    # ====================================================================
    # LAB PURPOSE / PROTOCOL
    # ====================================================================
    """Newline-delimited commands for Bluetooth SPP. Shared with socket-pair tests."""
    
    # ====================================================================
    # 01 / IMPORT REQUIRED LIBRARIES
    # ====================================================================
    import json
    
    # ====================================================================
    # 02 / INTERPRET COMMANDS
    # ====================================================================
    def respond(command, mode, device, led):
        # Normalize whitespace and capitalization before matching commands.
        cmd = command.strip().upper()
        # Stop the current session and switch off the LED.
        if cmd == 'STOP':
            if led is not None: led.off()
            return {'status':'stopped'}, True
        # Read the sensor only if the service allows telemetry.
        if cmd == 'READ' and mode in ('sensor','both'):
            try: return json.loads(device.read().json()), False
            except RuntimeError: return {'error':'sensor read failed'}, False
        # Permit LED control only in the appropriate service modes.
        if cmd in ('ON','OFF') and mode in ('led','both'):
            # Translate ON/OFF into a logical GPIO state.
            led.value = cmd == 'ON'
            return {'led':cmd}, False
        # Reject unknown commands without changing device state.
        return {'error':'unsupported command'}, False
    
    # ====================================================================
    # 03 / PROCESS NEWLINE-DELIMITED MESSAGES
    # ====================================================================
    def serve_connection(sock, mode, device, led):
        # Bound command length, and turn the LED off on disconnect.
        try:
            with sock.makefile('rwb') as stream:
                while True:
                    # Limit the size of each incoming command.
                    line = stream.readline(129)
                    # End the session when the peer closes the stream.
                    if not line: break
                    # Reject oversized or incomplete commands.
                    if len(line) > 128 or not line.endswith(b'\n'): break
                    # Decode ASCII commands and route them to the handler.
                    try: result, stop = respond(line.decode('ascii'), mode, device, led)
                    except UnicodeError: result, stop = {'error':'ASCII command required'}, False
                    # Return a JSON response followed by a newline; flush the buffer.
                    stream.write((json.dumps(result)+'\n').encode()); stream.flush()
                    # End the session after a STOP command.
                    if stop: break
        # ====================================================================
        # 04 / DISCONNECT AND RESET OUTPUT
        # ====================================================================
        finally:
            if led is not None: led.off()
            sock.close()
    
    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

    X8 · 13 notebook cells · 4 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
    # 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)
    
    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
    # =====================================================================
    # 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()
    
    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
    # =====================================================================
    # X8 | Code cell 03 | Lab 8 · Bluetooth telemetry & LED control
    # 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.
    # =====================================================================
    # ------------------------------------------------------------
    # Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
    # PSUT IoT Engineering Learning Platform
    # ------------------------------------------------------------
    # ====================================================================
    # LAB PURPOSE / PROTOCOL
    # ====================================================================
    """Newline-delimited commands for Bluetooth SPP. Shared with socket-pair tests."""
    
    # ====================================================================
    # 01 / IMPORT REQUIRED LIBRARIES
    # ====================================================================
    import json
    
    # ====================================================================
    # 02 / INTERPRET COMMANDS
    # ====================================================================
    def respond(command, mode, device, led):
        # Normalize whitespace and capitalization before matching commands.
        cmd = command.strip().upper()
        # Stop the current session and switch off the LED.
        if cmd == 'STOP':
            if led is not None: led.off()
            return {'status':'stopped'}, True
        # Read the sensor only if the service allows telemetry.
        if cmd == 'READ' and mode in ('sensor','both'):
            try: return json.loads(device.read().json()), False
            except RuntimeError: return {'error':'sensor read failed'}, False
        # Permit LED control only in the appropriate service modes.
        if cmd in ('ON','OFF') and mode in ('led','both'):
            # Translate ON/OFF into a logical GPIO state.
            led.value = cmd == 'ON'
            return {'led':cmd}, False
        # Reject unknown commands without changing device state.
        return {'error':'unsupported command'}, False
    
    # ====================================================================
    # 03 / PROCESS NEWLINE-DELIMITED MESSAGES
    # ====================================================================
    def serve_connection(sock, mode, device, led):
        # Bound command length, and turn the LED off on disconnect.
        try:
            with sock.makefile('rwb') as stream:
                while True:
                    # Limit the size of each incoming command.
                    line = stream.readline(129)
                    # End the session when the peer closes the stream.
                    if not line: break
                    # Reject oversized or incomplete commands.
                    if len(line) > 128 or not line.endswith(b'\n'): break
                    # Decode ASCII commands and route them to the handler.
                    try: result, stop = respond(line.decode('ascii'), mode, device, led)
                    except UnicodeError: result, stop = {'error':'ASCII command required'}, False
                    # Return a JSON response followed by a newline; flush the buffer.
                    stream.write((json.dumps(result)+'\n').encode()); stream.flush()
                    # End the session after a STOP command.
                    if stop: break
        # ====================================================================
        # 04 / DISCONNECT AND RESET OUTPUT
        # ====================================================================
        finally:
            if led is not None: led.off()
            sock.close()
    
    Ask Dr. Mohammad about this cell
    09Instructions · Markdown
    ### 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')
    
    Ask Dr. Mohammad about this cell
    11Instructions · 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 source ~/psut-wsl/activate.sh cd ~/psut-wsl/labs/pi-practical python ~/psut-wsl/tools/bt_over_tcp.py --mode both --mock ``` ```python # ------------------------------------------------------------ # Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved. # PSUT IoT Engineering Learning Platform # ------------------------------------------------------------ # ==================================================================== # LAB PURPOSE / BLUETOOTH SERVER # ==================================================================== """Experiment 8a/b: authenticated Bluetooth Classic SPP using BlueZ Profile1.""" # ==================================================================== # 01 / IMPORT REQUIRED LIBRARIES # ==================================================================== import argparse import socket import threading from contextlib import ExitStack from labs.common import sensor from labs.exp08.protocol import serve_connection # The standard Serial Port Profile UUID identifies the Bluetooth service. UUID = '00001101-0000-1000-8000-00805f9b34fb' # Standard SPP UUID. # D-Bus object path exported for BlueZ callbacks. PATH = '/org/iotstudio/iot/spp' # ==================================================================== # 02 / CONFIGURE SERVICE MODE AND HARDWARE # ==================================================================== def main(): p = argparse.ArgumentParser(description=__doc__) # Select telemetry, actuator control or both. p.add_argument('--mode', choices=['sensor','led','both'], default='both') # Simulate the sensor and LED, but retain real Bluetooth communication. p.add_argument('--mock', action='store_true', help='Mock sensor and LED; real Bluetooth still required') a = p.parse_args() import dbus, dbus.service from dbus.mainloop.glib import DBusGMainLoop from gi.repository import GLib if a.mock: class MockLED: value = False def off(self): self.value = False # ==================================================================== # 03 / CONNECT TO BLUEZ AND GLIB # ==================================================================== DBusGMainLoop(set_as_default=True) # Connect to the system D-Bus used by the Bluetooth daemon. bus = dbus.SystemBus() # Access the BlueZ profile registration interface. manager = dbus.Interface(bus.get_object('org.bluez','/org/bluez'),'org.bluez.ProfileManager1') # Create the event loop that dispatches profile callbacks. loop = GLib.MainLoop() # Manage sensor and LED resources according to the selected mode. with ExitStack() as stack: dev = stack.enter_context(sensor(a.mock)) if a.mode != 'led' else None led = None if a.mode != 'sensor': if a.mock: led = MockLED() else: from gpiozero import LED led = stack.enter_context(LED(24, initial_value=False)) # ==================================================================== # 04 / IMPLEMENT BLUEZ PROFILE CALLBACKS # ==================================================================== class Profile(dbus.service.Object): def __init__(self): super().__init__(bus, PATH); self.sessions = {}; self.lock = threading.Lock() @dbus.service.method('org.bluez.Profile1', in_signature='', out_signature='') # BlueZ calls this when the profile is released. def Release(self): self.close_sessions(); loop.quit() @dbus.service.method('org.bluez.Profile1', in_signature='oha{sv}', out_signature='') # Receive an authenticated connection and its file descriptor. def NewConnection(self, device, fd, properties): # Wrap the provided descriptor as a Python socket. conn = socket.socket(fileno=fd.take()) with self.lock: # Allow only one connected client to protect shared resources. if self.sessions: # One client at a time protects the sensor/LED. conn.close(); return # Track the connection by BlueZ device path. self.sessions[str(device)] = conn # Handle requests in a background thread so the D-Bus loop stays responsive. def worker(): try: serve_connection(conn, a.mode, dev, led) except OSError as exc: print('Bluetooth session closed:', exc) finally: with self.lock: self.sessions.pop(str(device), None) # Start the session worker without blocking the event loop. threading.Thread(target=worker, daemon=True).start() @dbus.service.method('org.bluez.Profile1', in_signature='o', out_signature='') # Close the active connection requested by BlueZ. def RequestDisconnection(self, device): with self.lock: conn = self.sessions.get(str(device)) if conn: # Wake any blocking socket read or write during disconnect. try: conn.shutdown(socket.SHUT_RDWR) except OSError: pass def close_sessions(self): with self.lock: connections = list(self.sessions.values()) for conn in connections: # Wake any blocking socket read or write during disconnect. try: conn.shutdown(socket.SHUT_RDWR) except OSError: pass # ==================================================================== # 05 / REGISTER THE AUTHENTICATED SPP SERVICE # ==================================================================== profile = Profile() # Publish RFCOMM channel 7 and require authentication and authorization. manager.RegisterProfile(PATH, UUID, {'Name':'IoT Serial', 'Role':'server', 'Channel':dbus.UInt16(7), 'RequireAuthentication':dbus.Boolean(True), 'RequireAuthorization':dbus.Boolean(True)}) print('SPP service registered. Connect a paired Android serial terminal; send READ, ON, OFF, STOP with LF.') # Keep the Bluetooth service available until stopped. try: loop.run() finally: # ==================================================================== # 06 / UNREGISTER AND SWITCH OFF THE LED # ==================================================================== # Shut down open client sessions before releasing resources. profile.close_sessions() try: manager.UnregisterProfile(PATH) except dbus.DBusException: pass if led is not None: led.off() # ==================================================================== # PROGRAM ENTRY POINT / RUN THE EXPERIMENT # ==================================================================== if __name__ == '__main__': try: main() except KeyboardInterrupt: pass ``` ```python # ------------------------------------------------------------ # Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved. # PSUT IoT Engineering Learning Platform # ------------------------------------------------------------ # ==================================================================== # LAB PURPOSE / PROTOCOL # ==================================================================== """Newline-delimited commands for Bluetooth SPP. Shared with socket-pair tests.""" # ==================================================================== # 01 / IMPORT REQUIRED LIBRARIES # ==================================================================== import json # ==================================================================== # 02 / INTERPRET COMMANDS # ==================================================================== def respond(command, mode, device, led): # Normalize whitespace and capitalization before matching commands. cmd = command.strip().upper() # Stop the current session and switch off the LED. if cmd == 'STOP': if led is not None: led.off() return {'status':'stopped'}, True # Read the sensor only if the service allows telemetry. if cmd == 'READ' and mode in ('sensor','both'): try: return json.loads(device.read().json()), False except RuntimeError: return {'error':'sensor read failed'}, False # Permit LED control only in the appropriate service modes. if cmd in ('ON','OFF') and mode in ('led','both'): # Translate ON/OFF into a logical GPIO state. led.value = cmd == 'ON' return {'led':cmd}, False # Reject unknown commands without changing device state. return {'error':'unsupported command'}, False # ==================================================================== # 03 / PROCESS NEWLINE-DELIMITED MESSAGES # ==================================================================== def serve_connection(sock, mode, device, led): # Bound command length, and turn the LED off on disconnect. try: with sock.makefile('rwb') as stream: while True: # Limit the size of each incoming command. line = stream.readline(129) # End the session when the peer closes the stream. if not line: break # Reject oversized or incomplete commands. if len(line) > 128 or not line.endswith(b'\n'): break # Decode ASCII commands and route them to the handler. try: result, stop = respond(line.decode('ascii'), mode, device, led) except UnicodeError: result, stop = {'error':'ASCII command required'}, False # Return a JSON response followed by a newline; flush the buffer. stream.write((json.dumps(result)+'\n').encode()); stream.flush() # End the session after a STOP command. if stop: break # ==================================================================== # 04 / DISCONNECT AND RESET OUTPUT # ==================================================================== finally: if led is not None: led.off() sock.close() ```
    12Instructions · 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 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.