Skip to content

Sending Commands from a Raspberry Pi

gtls edited this page Nov 6, 2024 · 3 revisions

This guide will walk you through setting up a Raspberry Pi to communicate with the Monty Home BLE device, configuring necessary libraries, running Python scripts, and using BLE commands to retrieve and process data. We’ll also provide code explanations for core functions, along with tips for customization.


Setting Up BLE on Raspberry Pi

To start, ensure your Raspberry Pi is configured correctly to communicate with BLE devices. This section covers the initial Raspberry Pi setup, package installation, and BLE library configuration.

  1. Confirm BLE Support: Most modern Raspberry Pi models, including the Pi Zero 2, have built-in Bluetooth and BLE.
  2. Install Required Packages:
    • Update your system packages to ensure compatibility:
      sudo apt-get update
      sudo apt-get upgrade
    • Install Python 3 and Pip if they are not installed:
      sudo apt-get install python3 python3-pip

Installing Required Libraries

The following Python libraries are necessary for BLE communication, I2C display control, and handling HTTP requests. Install them with Pip:

  1. Bleak: A lightweight Python package for BLE communication.
    pip install bleak
  2. Requests: Required for HTTP requests in Project 3 (IFTTT integration).
    pip install requests
  3. Adafruit CircuitPython SSD1306: Required for controlling the OLED display in Project 2.
    pip install adafruit-circuitpython-ssd1306
  4. Pillow: A library for image manipulation, used to draw text and images on the OLED display.
    pip install pillow

Running Python Scripts on the Raspberry Pi

Each project in this guide comes with its own Python script. To execute a project, navigate to the folder containing the script and run it using Python:

python3 project_script.py

Replace project_script.py with the actual name of the script (e.g., project1_temperature_led.py).


Code Explanation for BLE Communication with Monty Home Device

This section provides a full breakdown of the Python code needed to communicate with the Monty Home BLE device, including scanning, connecting, sending commands, and handling notifications.

Scanning for the Monty Home Device

To begin, we need to scan for available BLE devices and locate the Monty Home device by its name.

import asyncio
from bleak import BleakScanner

DEVICE_NAME = "MontyHome"  # Replace with your actual device name

async def find_device_by_name():
    print(f"Scanning for BLE device named '{DEVICE_NAME}'...")
    devices = await BleakScanner.discover()

    for device in devices:
        if device.name == DEVICE_NAME:
            print(f"Device found: {device.name} - {device.address}")
            return device
    print("Device not found.")
    return None

Explanation:

  • DEVICE_NAME: This is the name of the Monty Home device. Update it to match your device’s actual name.
  • BleakScanner.discover(): Initiates a BLE scan for all nearby devices.
  • The function iterates over the discovered devices and returns the Monty Home device if it finds one matching DEVICE_NAME.

Connecting to the Monty Home Device and Sending Commands

Once the device is located, the next step is establishing a connection and sending BLE commands to retrieve data or control the device.

from bleak import BleakClient

async def connect_and_send_queries(device):
    async with BleakClient(device.address) as client:
        print(f"Connected to {device.name} - {device.address}")

        services = await client.get_services()  # Fetch available services
        write_characteristic = None
        notify_characteristic = None

        # Locate writable and notify characteristics
        for service in services:
            for characteristic in service.characteristics:
                if "write" in characteristic.properties:
                    write_characteristic = characteristic
                if "notify" in characteristic.properties:
                    notify_characteristic = characteristic

        # Example command to query temperature
        command = ";QT\r\n"  # Command to request temperature
        await client.write_gatt_char(write_characteristic.uuid, command.encode())

        # Notification handler for receiving responses
        def notification_handler(sender, data):
            print("Received data:", data.decode())

        await client.start_notify(notify_characteristic.uuid, notification_handler)
        await asyncio.sleep(30)
        await client.stop_notify(notify_characteristic.uuid)

Explanation:

  • BleakClient: Manages the BLE connection.
  • get_services(): Retrieves available services and characteristics for identifying writable and notify characteristics.
  • write_gatt_char: Sends the specified command (e.g., ;QT\r\n) to request temperature data.
  • notification_handler: Processes data sent back from the device in real-time.

Using BLE Commands and Queries

This table outlines all available BLE commands and their purposes. Use these commands in the code to request data or control the device.

Command Message ID Description
;QA\r\n MSG_QUERY_ALL_DATA_IND Returns the high and low index of all data in flash memory.
;QP\r\n MSG_QUERY_PENDING_DATA_IND Returns the high and low index of pending data in flash memory.
;QR\r\n MSG_QUERY_RECORD Retrieves a specific data record by index; responds with NACK if the index does not exist.
;QM\r\n MSG_QUERY_RECORD_MULTIPLE Returns multiple records within a specified index range.
;QS\r\n MSG_QUERY_STATUS Returns the device status, such as active or idle.
;QL\r\n MSG_QUERY_BATTLEVEL Requests the battery level as a percentage.
;QT\r\n MSG_QUERY_TEMP Requests the current temperature reading.
;QH\r\n MSG_QUERY_HUMIDITY Requests the relative humidity reading.
;QO\r\n MSG_QUERY_TVOC Retrieves the latest TVOC (Total Volatile Organic Compounds) reading.
;QC\r\n MSG_QUERY_CO2 Retrieves the latest CO2 reading.
;QU\r\n MSG_QUERY_UID Returns the unique ID of the device.
;QV\r\n MSG_QUERY_VERSION Requests the device firmware version.
;QZ\r\n MSG_QUERY_ZECLOCK Returns the internal seconds timer of the device.
;CR\r\n MSG_COMMAND_REBOOT Reboots the device and briefly flashes a white light.
;CF\r\n MSG_COMMAND_RESET Performs a factory reset and reboots the device.
;CS\r\n MSG_COMMAND_RECORD_SYNCED Marks a specific record as "synced" if the index exists.
;CM\r\n MSG_COMMAND_RECORD_SYNCED_MULTIPLE Marks a range of records as "synced."

Each command can be used in the write_gatt_char function to control or query specific device data.


Running the Full Code

Once you have the setup complete and the necessary BLE commands configured, run the Python script as follows:

python3 project_script.py

Replace project_script.py with the name of the specific project file (e.g., project1_temperature_led.py).


Tips for Customization and Modifications

  1. Using Different BLE Commands:

    • Replace the command variable with any command from the BLE table to query different data:
      command = ";QH\r\n"  # Change to query humidity instead of temperature
  2. Handling Multiple Commands:

    • Define a list of commands to query multiple data points (e.g., temperature, humidity) sequentially:
      commands = [";QT\r\n", ";QH\r\n"]
      for command in commands:
          await client.write_gatt_char(write_characteristic.uuid, command.encode())
  3. Expanding the Notification Handler:

    • You can process multiple types of data by adding conditions to notification_handler to handle specific responses, like temperature and humidity readings:
      def notification_handler(sender, data):
          response = data.decode().strip()
          if response.startswith(";RT"):
              temp_value = int(response.replace(";RT ", "")) / 100
              print(f"Temperature: {temp_value}°C")
          elif response.startswith(";RH"):
              hum_value = int(response.replace(";RH ", "")) / 100
              print(f"Humidity: {hum_value}%")
  4. Integrating with Other Applications:

    • You can extend this project by integrating the data into IoT platforms, creating visual dashboards, or triggering additional actions such as

sending notifications via IFTTT when specific conditions are met.

With this comprehensive guide, you should be well-prepared to configure your Raspberry Pi, connect it to the Monty Home device, run Python scripts, and make custom modifications. This approach allows you to experiment and expand on the core functionality, providing endless possibilities for monitoring and automation. Enjoy exploring BLE communication and IoT with your Monty Home device!