Documentation

State

MudPi represents all data as state, managed by a thread-safe state manager with Redis backups.

Overview

Every component in MudPi maintains a state object that represents its current data. State is managed by a thread-safe state manager and automatically backed up to Redis for persistence across restarts.

State Structure

A state object contains the component's identifier, current value, timestamp, and optional metadata:

JSON
{
  "component_id": "soil_sensor_1",
  "state": 65.2,
  "updated_at": "2024-03-15T10:30:00Z",
  "metadata": {
    "unit": "percent",
    "icon": "droplet",
    "label": "Soil Moisture"
  }
}

State Changes

When a component's state changes, a StateUpdated event is emitted. This event is the primary mechanism for inter-component communication. Triggers, displays, and other components can subscribe to state changes and react accordingly.

Metadata

The metadata field provides additional context about the state value. This is useful for dashboards and UIs that need to display data with proper formatting:

  • unit — The measurement unit (e.g., percent, celsius, lux)
  • icon — An icon identifier for UI display
  • label — A human-readable label for the state value

Fetching State

There are three ways to access component state in MudPi:

1. State Manager

Access state directly through the state manager's get() method:

Python
state = mudpi.states.get('soil_sensor_1')
print(state)  # 65.2

2. Event System Subscription

Subscribe to StateUpdated events to react to state changes in real time:

Python
def on_state_update(event):
    print(f"{event['component_id']}: {event['state']}")

mudpi.events.subscribe('StateUpdated', on_state_update)

3. Redis Backups

State is persisted in Redis using the key format {key}.state. You can query state directly from Redis:

Python
import redis

r = redis.Redis(host='localhost', port=6379)
state = r.get('soil_sensor_1.state')
print(state)

Note

The state manager is thread-safe, so you can read and write state from any worker or component without worrying about race conditions.