Controller Methods

Controller methods are the handler functions that process MQTT messages. This guide covers different patterns and best practices for writing effective controller methods.

Method Signatures

Basic Handler Pattern

@staticmethod
async def handler_name(payload, client):
    """Handle messages without route parameters"""
    # Process payload
    return result

Single Parameter Handler

@staticmethod
async def handler_name(param: str, payload, client):
    """Handle messages with one route parameter"""
    # Process with parameter
    return result

Multiple Parameters Handler

@staticmethod
async def handler_name(param1: str, param2: str, payload, client):
    """Handle messages with multiple route parameters"""
    # Process with multiple parameters
    return result

Parameter Types

Route Parameters

Route parameters are automatically extracted from the MQTT topic and passed to your handler:

Payload Parameter

The payload parameter contains the parsed message data:

Client Parameter

The client parameter is the MQTT client instance for publishing responses:

Handler Patterns

Fire and Forget

Simple handlers that process messages without sending responses:

Request-Response

Handlers that process requests and send responses:

Publish-Subscribe

Handlers that receive messages and broadcast to multiple topics:

State Management

Handlers that maintain state across messages:

Advanced Patterns

Batch Processing

Handle multiple items in a single message:

Pipeline Processing

Chain multiple processing steps:

Error Recovery

Handle errors and implement retry logic:

Method Organization

Organize related functionality in the same controller:

Separation of Concerns

Keep controllers focused on specific domains:

Testing Controller Methods

Example test structure for controller methods:

Next Steps

Last updated