Creating Controllers

Controllers in RouteMQ handle the business logic for processing MQTT messages. They extend the base Controller class and contain static async methods that process incoming messages.

Basic Controller Structure

All controllers should extend the Controller base class:

from core.controller import Controller

class DeviceController(Controller):
    @staticmethod
    async def handle_message(device_id: str, payload, client):
        """Handle incoming MQTT messages for devices"""
        # Your business logic here
        return {"status": "success"}

Controller Requirements

1. Extend Controller Base Class

from core.controller import Controller

class MyController(Controller):
    # Your controller methods here

2. Use Static Async Methods

All handler methods must be:

  • Static methods (decorated with @staticmethod)

  • Async functions (use async def)

  • Accept the correct parameters based on your route

3. Method Parameters

Controller methods receive parameters in this order:

  1. Route parameters - Extracted from the MQTT topic pattern

  2. payload - The parsed message payload (dict if JSON, raw if not)

  3. client - The MQTT client instance for publishing responses

Example Controllers

Simple Message Handler

Device Control Controller

Controller Organization

File Naming

  • Use descriptive names: device_controller.py, sensor_controller.py

  • Place controllers in the app/controllers/ directory

  • Use snake_case for file names

Class Naming

  • Use PascalCase for class names

  • End with "Controller": DeviceController, SensorController

  • Keep names descriptive and specific

Method Naming

  • Use descriptive method names: handle_control, process_data

  • Use snake_case for method names

  • Start with action verbs: handle_, process_, validate_

Error Handling

Always include proper error handling in your controllers:

Next Steps

Last updated