> ## Documentation Index
> Fetch the complete documentation index at: https://docs.coreflux.org/llms.txt
> Use this file to discover all available pages before exploring further.

# Model Examples

> Practical examples of LoT models for common IoT data structuring scenarios.

## Examples Index

Find the right pattern for your use case:

| Example                                                   | Pattern          | Best For                           |
| --------------------------------------------------------- | ---------------- | ---------------------------------- |
| [Simple Sensor Reading](#simple-sensor-reading)           | Basic            | Single source, static metadata     |
| [Multi-Source Equipment](#multi-source-equipment-status)  | Basic            | Combining multiple topics          |
| [Production Record](#production-record-with-calculations) | Calculated       | Derived metrics                    |
| [Multi-Instance Sensor](#multi-instance-sensor-model)     | Wildcard         | Multiple similar devices           |
| [Factory Hierarchy](#factory-hierarchy-model)             | Wildcard         | Multi-level topic structures       |
| [Alarm Record](#alarm-record-from-json)                   | Action-Published | JSON processing, conditional logic |
| [Production Event](#production-event-with-calculations)   | Action-Published | Complex calculations               |
| [Quality Check](#quality-check-with-validation)           | Action-Published | Pass/fail determination            |
| [Alert Family](#alert-model-family)                       | Inheritance      | Related data types                 |
| [Sensor with Metadata](#sensor-with-metadata)             | Nested Objects   | Grouped configuration              |

***

## Basic Model Examples

### Simple Sensor Reading

A straightforward model that formats raw sensor data with static metadata.

```mermaid actions={false} theme={null}
flowchart LR
    subgraph Input
        A[sensors/raw/temperature]
    end
    subgraph Model
        B[SensorReading]
    end
    subgraph Output
        C[sensors/formatted/temperature]
    end
    A -->|triggers| B
    B -->|publishes| C
```

This model adds context (sensor ID, unit, status) to a raw temperature value:

```lot theme={null}
DEFINE MODEL SensorReading WITH TOPIC "sensors/formatted/temperature"
    ADD STRING "sensor_id" WITH "TEMP001"
    ADD DOUBLE "value" WITH TOPIC "sensors/raw/temperature" AS TRIGGER
    ADD STRING "unit" WITH "celsius"
    ADD STRING "timestamp" WITH TIMESTAMP "UTC"
    ADD STRING "status" WITH "ACTIVE"
```

When a value arrives at `sensors/raw/temperature`, the model publishes:

```json theme={null}
{
  "sensor_id": "TEMP001",
  "value": 25.5,
  "unit": "celsius",
  "timestamp": "2025-10-25T14:30:15Z",
  "status": "ACTIVE"
}
```

***

### Multi-Source Equipment Status

Combine data from multiple topics into a unified equipment status report.

```mermaid actions={false} theme={null}
flowchart LR
    subgraph Inputs
        A[equipment/current/id]
        B[equipment/current/status]
        C[equipment/current/runtime]
        D[equipment/current/efficiency]
    end
    subgraph Model
        E[EquipmentStatus]
    end
    subgraph Output
        F[equipment/status/formatted]
    end
    A --> E
    B -->|triggers| E
    C --> E
    D --> E
    E -->|publishes| F
```

Each field pulls from a different source topic. The status topic acts as the trigger:

```lot theme={null}
DEFINE MODEL EquipmentStatus WITH TOPIC "equipment/status/formatted"
    ADD STRING "equipment_id" WITH TOPIC "equipment/current/id"
    ADD STRING "status" WITH TOPIC "equipment/current/status" AS TRIGGER
    ADD INT "runtime_hours" WITH TOPIC "equipment/current/runtime"
    ADD DOUBLE "efficiency" WITH TOPIC "equipment/current/efficiency"
    ADD BOOL "maintenance_required" WITH TOPIC "equipment/current/maintenance_flag"
    ADD STRING "last_update" WITH TIMESTAMP "UTC"
    ADD STRING "location" WITH "Factory Floor A"
```

When the status topic updates, the model publishes a combined report to `equipment/status/formatted`:

```json theme={null}
{
  "equipment_id": "CNC-4500",
  "status": "RUNNING",
  "runtime_hours": 1823,
  "efficiency": 92.4,
  "maintenance_required": false,
  "last_update": "2025-10-25T14:30:15Z",
  "location": "Factory Floor A"
}
```

***

### Production Record with Calculations

Automatically calculate derived values like efficiency percentages.

```mermaid actions={false} theme={null}
flowchart LR
    subgraph Inputs
        A[quantity]
        B[target]
    end
    subgraph Calculation
        C["efficiency = quantity / target × 100"]
    end
    subgraph Output
        D[ProductionRecord]
    end
    A --> C
    B --> C
    C --> D
```

The `efficiency_percent` field is calculated inline from other topic values:

```lot theme={null}
DEFINE MODEL ProductionRecord WITH TOPIC "production/records/completed"
    ADD STRING "batch_id" WITH TOPIC "production/current/batch_id"
    ADD STRING "product_code" WITH TOPIC "production/current/product_code"
    ADD INT "quantity_produced" WITH TOPIC "production/current/quantity" AS TRIGGER
    ADD INT "quantity_target" WITH TOPIC "production/current/target"
    ADD DOUBLE "efficiency_percent" WITH (GET TOPIC "production/current/quantity" AS DOUBLE / GET TOPIC "production/current/target" AS DOUBLE * 100)
    ADD STRING "operator" WITH TOPIC "production/current/operator"
    ADD STRING "completion_time" WITH TIMESTAMP "UTC"
```

Example output when 95 of 100 units are produced:

```json theme={null}
{
  "batch_id": "BATCH_2025_001",
  "product_code": "WIDGET_A",
  "quantity_produced": 95,
  "quantity_target": 100,
  "efficiency_percent": 95.0,
  "operator": "John Smith",
  "completion_time": "2025-10-25T14:30:15Z"
}
```

***

## Wildcard Model Examples

### Multi-Instance Sensor Model

Handle multiple sensors with a single model definition using the `+` wildcard.

```mermaid actions={false} theme={null}
flowchart TB
    subgraph Inputs
        A[sensors/temp001/value]
        B[sensors/pressure002/value]
        C[sensors/humidity003/value]
    end
    subgraph SingleModel
        D["GenericSensorData<br/>sensors/+/formatted"]
    end
    subgraph Outputs
        E[sensors/temp001/formatted]
        F[sensors/pressure002/formatted]
        G[sensors/humidity003/formatted]
    end
    A -->|triggers| D
    B -->|triggers| D
    C -->|triggers| D
    D --> E
    D --> F
    D --> G
```

The `+` wildcard matches any single level in the topic hierarchy:

```lot theme={null}
DEFINE MODEL GenericSensorData WITH TOPIC "sensors/+/formatted"
    ADD STRING "sensor_id" WITH TOPIC "sensors/+/id"
    ADD DOUBLE "value" WITH TOPIC "sensors/+/value" AS TRIGGER
    ADD STRING "unit" WITH TOPIC "sensors/+/unit"
    ADD STRING "location" WITH TOPIC "sensors/+/location"
    ADD STRING "timestamp" WITH TIMESTAMP "UTC"
```

When `sensors/temp001/value` receives data, the model publishes to `sensors/temp001/formatted`:

```json theme={null}
{
  "sensor_id": "TEMP001",
  "value": 23.7,
  "unit": "celsius",
  "location": "Building A - Room 101",
  "timestamp": "2025-10-25T14:30:15Z"
}
```

<Note>
  Each sensor instance (temp001, pressure002, etc.) gets its own output topic automatically. The wildcard maintains topic context through the model.
</Note>

***

### Factory Hierarchy Model

Handle multi-level topic hierarchies with multiple wildcards.

```mermaid actions={false} theme={null}
flowchart TB
    subgraph Factory
        A["factory/line1/machine1/status"]
        B["factory/line1/machine2/status"]
        C["factory/line2/machine1/status"]
    end
    subgraph Model
        D["MachineData<br/>factory/+/+/data/formatted"]
    end
    subgraph Outputs
        E["factory/line1/machine1/data/formatted"]
        F["factory/line1/machine2/data/formatted"]
        G["factory/line2/machine1/data/formatted"]
    end
    A -->|triggers| D
    B -->|triggers| D
    C -->|triggers| D
    D --> E
    D --> F
    D --> G
```

Multiple `+` wildcards capture different levels of the hierarchy:

```lot theme={null}
DEFINE MODEL MachineData WITH TOPIC "factory/+/+/data/formatted"
    ADD STRING "line_id" WITH TOPIC "factory/+/id"
    ADD STRING "machine_id" WITH TOPIC "factory/+/+/id"
    ADD STRING "status" WITH TOPIC "factory/+/+/status" AS TRIGGER
    ADD DOUBLE "output_rate" WITH TOPIC "factory/+/+/output_rate"
    ADD STRING "timestamp" WITH TIMESTAMP "UTC"
```

When `factory/line1/machine1/status` updates, the model publishes to `factory/line1/machine1/data/formatted`:

```json theme={null}
{
  "line_id": "LINE_01",
  "machine_id": "MACH_01",
  "status": "RUNNING",
  "output_rate": 145.8,
  "timestamp": "2025-10-25T14:30:15Z"
}
```

***

## Models Published by Actions Examples

<Tip>
  Use this pattern when you need **full control** over publishing logic—conditional decisions, complex calculations, JSON extraction, or custom routing. The action determines when and where to publish.
</Tip>

### Alarm Record from JSON

Process incoming JSON payloads into structured alarm records.

```mermaid actions={false} theme={null}
flowchart LR
    subgraph Input
        A["alarms/+/json_input<br/>{type, value, threshold, ...}"]
    end
    subgraph Action
        B[ProcessAlarmJSON]
    end
    subgraph Output
        C["alarms/structured/{equipment_id}<br/>AlarmRecord model"]
    end
    A -->|triggers| B
    B -->|PUBLISH MODEL| C
```

First, define the model schema with `COLLAPSED` (no automatic trigger):

```lot theme={null}
DEFINE MODEL AlarmRecord COLLAPSED
    ADD STRING "alarm_id"
    ADD STRING "equipment_id"
    ADD STRING "alarm_type"
    ADD DOUBLE "trigger_value"
    ADD DOUBLE "threshold"
    ADD STRING "severity"
    ADD STRING "message"
    ADD STRING "timestamp"
    ADD BOOL "auto_generated"
```

Then create an action that extracts JSON fields and publishes the model:

```lot theme={null}
DEFINE ACTION ProcessAlarmJSON
ON TOPIC "alarms/+/json_input" DO
    SET "equipment_id" WITH TOPIC POSITION 2
    
    PUBLISH MODEL AlarmRecord TO "alarms/structured/" + {equipment_id} WITH
        alarm_id = (RANDOM UUID)
        equipment_id = {equipment_id}
        alarm_type = (GET JSON "type" IN PAYLOAD AS STRING)
        trigger_value = (GET JSON "value" IN PAYLOAD AS DOUBLE)
        threshold = (GET JSON "threshold" IN PAYLOAD AS DOUBLE)
        severity = (GET JSON "severity" IN PAYLOAD AS STRING)
        message = (GET JSON "message" IN PAYLOAD AS STRING)
        timestamp = TIMESTAMP "UTC"
        auto_generated = TRUE
```

When a JSON payload arrives at `alarms/pump003/json_input`, the action publishes to `alarms/structured/pump003`:

```json theme={null}
{
  "alarm_id": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
  "equipment_id": "pump003",
  "alarm_type": "OVERHEAT",
  "trigger_value": 95.3,
  "threshold": 85.0,
  "severity": "CRITICAL",
  "message": "Motor temperature exceeded safe limit",
  "timestamp": "2025-10-25T14:30:15Z",
  "auto_generated": true
}
```

***

### Production Event with Calculations

Create production records with computed metrics like efficiency.

```mermaid actions={false} theme={null}
flowchart LR
    subgraph Input
        A["production/+/events<br/>{parts, cycle_time, target, ...}"]
    end
    subgraph Action
        B["ProcessProductionEvent<br/>Calculate efficiency"]
    end
    subgraph Output
        C["production/events/structured/{line}<br/>ProductionEvent model"]
    end
    A -->|triggers| B
    B -->|PUBLISH MODEL| C
```

Define the schema for production events:

```lot theme={null}
DEFINE MODEL ProductionEvent COLLAPSED
    ADD STRING "event_id"
    ADD STRING "line_id"
    ADD STRING "event_type"
    ADD INT "parts_count"
    ADD DOUBLE "cycle_time"
    ADD DOUBLE "efficiency_percent"
    ADD STRING "operator"
    ADD STRING "timestamp"
```

The action performs calculations before publishing:

```lot theme={null}
DEFINE ACTION ProcessProductionEvent
ON TOPIC "production/+/events" DO
    SET "line_id" WITH TOPIC POSITION 2
    SET "parts" WITH (GET JSON "parts_produced" IN PAYLOAD AS INT)
    SET "cycle" WITH (GET JSON "cycle_time" IN PAYLOAD AS DOUBLE)
    SET "target" WITH (GET JSON "target_cycle_time" IN PAYLOAD AS DOUBLE)
    SET "eff" WITH ({target} / {cycle} * 100)
    
    PUBLISH MODEL ProductionEvent TO "production/events/structured/" + {line_id} WITH
        event_id = (RANDOM UUID)
        line_id = {line_id}
        event_type = (GET JSON "event_type" IN PAYLOAD AS STRING)
        parts_count = {parts}
        cycle_time = {cycle}
        efficiency_percent = {eff}
        operator = (GET JSON "operator" IN PAYLOAD AS STRING)
        timestamp = TIMESTAMP "UTC"
```

When a production event arrives at `production/line2/events` with a target cycle time of 10s and an actual cycle time of 8.5s, the action publishes to `production/events/structured/line2`:

```json theme={null}
{
  "event_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  "line_id": "line2",
  "event_type": "BATCH_COMPLETE",
  "parts_count": 250,
  "cycle_time": 8.5,
  "efficiency_percent": 117.6,
  "operator": "Maria Garcia",
  "timestamp": "2025-10-25T14:30:15Z"
}
```

***

### Quality Check with Validation

Determine pass/fail status based on measurement tolerances.

```mermaid actions={false} theme={null}
flowchart LR
    subgraph Input
        A["quality/+/measurement<br/>{value, target, tolerance}"]
    end
    subgraph Action
        B["ValidateQuality<br/>Check tolerance range"]
    end
    subgraph Outputs
        C["quality/passed/{id}"]
        D["quality/failed/{id}"]
    end
    A -->|triggers| B
    B -->|if within tolerance| C
    B -->|if outside tolerance| D
```

<Note>
  Complex conditional logic (like tolerance checking) is cleaner in an action than inline in a model. The action can also route to different topics based on the result.
</Note>

Define the quality reading schema:

```lot theme={null}
DEFINE MODEL QualityReading COLLAPSED
    ADD STRING "inspection_id"
    ADD STRING "part_id"
    ADD DOUBLE "measurement"
    ADD DOUBLE "target"
    ADD DOUBLE "tolerance"
    ADD STRING "result"
    ADD STRING "timestamp"
```

The action checks if the measurement is within tolerance and routes accordingly:

```lot theme={null}
DEFINE ACTION ValidateQuality
ON TOPIC "quality/+/measurement" DO
    SET "part_id" WITH TOPIC POSITION 2
    SET "value" WITH (GET JSON "value" IN PAYLOAD AS DOUBLE)
    SET "target" WITH (GET JSON "target" IN PAYLOAD AS DOUBLE)
    SET "tolerance" WITH (GET JSON "tolerance" IN PAYLOAD AS DOUBLE)
    SET "min_allowed" WITH ({target} - {tolerance})
    SET "max_allowed" WITH ({target} + {tolerance})
    
    IF {value} >= {min_allowed} AND {value} <= {max_allowed} THEN
        PUBLISH MODEL QualityReading TO "quality/passed/" + {part_id} WITH
            inspection_id = (RANDOM UUID)
            part_id = {part_id}
            measurement = {value}
            target = {target}
            tolerance = {tolerance}
            result = "PASS"
            timestamp = TIMESTAMP "UTC"
    ELSE
        PUBLISH MODEL QualityReading TO "quality/failed/" + {part_id} WITH
            inspection_id = (RANDOM UUID)
            part_id = {part_id}
            measurement = {value}
            target = {target}
            tolerance = {tolerance}
            result = "FAIL"
            timestamp = TIMESTAMP "UTC"
```

When a measurement of 10.02 mm arrives for a part with a target of 10.00 mm and tolerance of 0.05 mm, it passes and publishes to `quality/passed/PART_A1`:

```json theme={null}
{
  "inspection_id": "b7e8f9a0-1234-5678-90ab-cdef01234567",
  "part_id": "PART_A1",
  "measurement": 10.02,
  "target": 10.0,
  "tolerance": 0.05,
  "result": "PASS",
  "timestamp": "2025-10-25T14:30:15Z"
}
```

***

## Model Inheritance Examples

<Info>
  For complete inheritance patterns and syntax, see [Model Inheritance](./model-inheritance).
</Info>

### Alert Model Family

Create specialized alert types from a common base model.

```mermaid actions={false} theme={null}
flowchart TB
    subgraph BaseModel
        A["BaseAlert<br/>alert_id, source, timestamp,<br/>severity, message, acknowledged"]
    end
    subgraph SpecializedModels
        B["TemperatureAlert<br/>+ temperature_value<br/>+ threshold_exceeded<br/>+ sensor_location"]
        C["PressureAlert<br/>+ pressure_value<br/>+ max_safe_pressure<br/>+ system_affected"]
        D["MaintenanceAlert<br/>+ equipment_id<br/>+ hours_since_service<br/>+ maintenance_type"]
    end
    A --> B
    A --> C
    A --> D
```

First, define the base model with common fields:

```lot theme={null}
DEFINE MODEL BaseAlert COLLAPSED
    ADD STRING "alert_id"
    ADD STRING "source_system"
    ADD STRING "timestamp"
    ADD STRING "severity"
    ADD STRING "message"
    ADD BOOL "acknowledged"
```

Then create specialized models that inherit and extend it:

```lot theme={null}
DEFINE MODEL TemperatureAlert FROM BaseAlert
    ADD DOUBLE "temperature_value"
    ADD DOUBLE "threshold_exceeded"
    ADD STRING "sensor_location"
    ADD STRING "unit"
```

```lot theme={null}
DEFINE MODEL PressureAlert FROM BaseAlert
    ADD DOUBLE "pressure_value"
    ADD DOUBLE "max_safe_pressure"
    ADD STRING "pressure_unit"
    ADD STRING "system_affected"
```

```lot theme={null}
DEFINE MODEL MaintenanceAlert FROM BaseAlert
    ADD STRING "equipment_id"
    ADD STRING "maintenance_type"
    ADD INT "hours_since_service"
    ADD INT "recommended_interval"
```

Use the specialized model in an action:

```lot theme={null}
DEFINE ACTION GenerateTemperatureAlert
ON TOPIC "sensors/temperature/+/alert" DO
    SET "sensor_id" WITH TOPIC POSITION 3
    
    PUBLISH MODEL TemperatureAlert TO "alerts/temperature/" + {sensor_id} WITH
        alert_id = (RANDOM UUID)
        source_system = "TemperatureMonitor"
        timestamp = TIMESTAMP "UTC"
        severity = "HIGH"
        message = "Temperature threshold exceeded"
        acknowledged = FALSE
        temperature_value = (GET JSON "value" IN PAYLOAD AS DOUBLE)
        threshold_exceeded = (GET JSON "threshold" IN PAYLOAD AS DOUBLE)
        sensor_location = (GET JSON "location" IN PAYLOAD AS STRING)
        unit = "celsius"
```

When an alert triggers for sensor `TH_042`, the action publishes to `alerts/temperature/TH_042` with both inherited and specialized fields:

```json theme={null}
{
  "alert_id": "c3d4e5f6-7890-1234-abcd-ef5678901234",
  "source_system": "TemperatureMonitor",
  "timestamp": "2025-10-25T14:30:15Z",
  "severity": "HIGH",
  "message": "Temperature threshold exceeded",
  "acknowledged": false,
  "temperature_value": 92.7,
  "threshold_exceeded": 85.0,
  "sensor_location": "Boiler Room B",
  "unit": "celsius"
}
```

***

## Nested Object Examples

### Sensor with Metadata

Group related configuration and context fields into nested sub-objects using the `OBJECT` type and indentation.

```mermaid actions={false} theme={null}
flowchart LR
    subgraph Inputs
        A[sensors/+/value]
        B[sensors/+/id]
        C[sensors/+/location]
        D[sensors/+/floor]
        E[sensors/+/building]
        F[sensors/+/unit]
    end
    subgraph Model
        G["SensorWithMetadata<br/>sensors/+/formatted"]
    end
    subgraph Output
        H["sensors/{id}/formatted<br/>{value, metadata: {location, ...}}"]
    end
    A -->|triggers| G
    B --> G
    C --> G
    D --> G
    E --> G
    F --> G
    G -->|publishes| H
```

The `metadata` field uses `OBJECT` to group location details into a nested object. Fields indented under `ADD OBJECT` become its properties. When indentation returns to the parent level, fields belong to the top-level model again:

```lot theme={null}
DEFINE MODEL SensorWithMetadata WITH TOPIC "sensors/+/formatted"
    ADD STRING "sensor_id" WITH TOPIC "sensors/+/id"
    ADD DOUBLE "value" WITH TOPIC "sensors/+/value" AS TRIGGER
    ADD OBJECT "metadata"
        ADD STRING "unit" WITH TOPIC "sensors/+/unit"
        ADD STRING "location" WITH TOPIC "sensors/+/location"
        ADD INT "floor" WITH TOPIC "sensors/+/floor"
        ADD STRING "building" WITH TOPIC "sensors/+/building"
    ADD STRING "timestamp" WITH TIMESTAMP "UTC"
```

When `sensors/temp001/value` receives data, the model publishes to `sensors/temp001/formatted`:

```json theme={null}
{
  "sensor_id": "TEMP001",
  "value": 25.5,
  "metadata": {
    "unit": "celsius",
    "location": "Room 101",
    "floor": 3,
    "building": "Building A"
  },
  "timestamp": "2025-10-25T14:30:15Z"
}
```

<Note>
  The indentation rule applies everywhere `OBJECT` is used — in basic models, wildcard models, and `COLLAPSED` templates published from actions.
</Note>

***

## Choosing the Right Pattern

<AccordionGroup>
  <Accordion title="Basic Models (WITH TOPIC + AS TRIGGER)">
    **Use when:** Data flows continuously and formatting is straightforward.

    **Best for:** Sensor readings, status updates, simple aggregation.

    **Trigger:** Automatic when source topic updates.
  </Accordion>

  <Accordion title="Calculated Fields">
    **Use when:** You need derived metrics computed from source values.

    **Best for:** Percentages, totals, averages, unit conversions.

    **Note:** Keep calculations simple; use actions for complex logic.
  </Accordion>

  <Accordion title="Wildcard Models (+)">
    **Use when:** You have multiple instances of the same data structure.

    **Best for:** Fleets of sensors, multi-line factories, device groups.

    **Benefit:** One model definition handles all instances.
  </Accordion>

  <Accordion title="Action-Published Models (COLLAPSED)">
    **Use when:** You need control over timing, routing, or complex logic.

    **Best for:** JSON extraction, conditional publishing, pass/fail routing, complex calculations.

    **Benefit:** Full action power with structured output.
  </Accordion>

  <Accordion title="Inherited Models (FROM)">
    **Use when:** You have related data types sharing common fields.

    **Best for:** Alert families, equipment types, event categories.

    **Benefit:** DRY principle—define common fields once.
  </Accordion>

  <Accordion title="Nested Objects (OBJECT)">
    **Use when:** Your JSON output needs grouped or hierarchical data.

    **Best for:** Metadata grouping, configuration objects, multi-level status reports.

    **Benefit:** Clean nested JSON without external formatting. Indentation controls structure.
  </Accordion>
</AccordionGroup>

***

## Next Steps

<CardGroup cols={2}>
  <Card title="Routes Overview" icon="route" href="/lot-language/routes/overview">
    Connect your broker to external systems and databases.
  </Card>

  <Card title="Actions Syntax" icon="bolt" href="/lot-language/actions/syntax">
    Master the action syntax for publishing models.
  </Card>
</CardGroup>
