19 KiB
IoT Equipment Integration - Implementation Guide
Overview
This guide documents the implementation of real-time IoT equipment tracking for bakery production equipment, specifically targeting smart industrial ovens with IoT connectivity capabilities.
Table of Contents
- Architecture
- Database Schema
- IoT Connectors
- Supported Equipment
- Implementation Status
- Next Steps
- Usage Examples
Architecture
Component Overview
┌─────────────────────────────────────────────────────────────┐
│ Frontend Dashboard │
│ (Real-time Equipment Monitoring UI) │
└────────────────┬────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ Production Service API │
│ /api/v1/equipment/{id}/iot-config │
│ /api/v1/equipment/{id}/realtime-data │
│ /api/v1/equipment/{id}/sensor-history │
│ /api/v1/equipment/{id}/test-connection │
└────────────────┬────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ IoT Integration Service │
│ - Connection management │
│ - Data transformation │
│ - Protocol abstraction │
└────────────────┬────────────────────────────────────────────┘
│
┌──────────┴──────────┬──────────────────┐
▼ ▼ ▼
┌────────────┐ ┌──────────────┐ ┌─────────────┐
│ REST API │ │ OPC UA │ │ MQTT │
│ Connector │ │ Connector │ │ Connector │
└─────┬──────┘ └──────┬───────┘ └──────┬──────┘
│ │ │
▼ ▼ ▼
┌─────────────────────────────────────────────────────────────┐
│ Smart IoT-Enabled Equipment │
│ - Rational iCombi (ConnectedCooking) │
│ - Wachtel REMOTE │
│ - SALVA Smart Ovens │
│ - Generic REST API Equipment │
└─────────────────────────────────────────────────────────────┘
Database Schema
New Tables
1. equipment (Extended)
Added IoT connectivity fields:
iot_enabled- Enable/disable IoT connectivityiot_protocol- Protocol type (rest_api, opc_ua, mqtt, modbus, custom)iot_endpoint- Connection endpoint URL/IPiot_port- Connection portiot_credentials- JSON encrypted credentialsiot_connection_status- Current connection statusiot_last_connected- Timestamp of last successful connectioniot_config- Additional protocol-specific configurationmanufacturer- Equipment manufacturerfirmware_version- Firmware versionsupports_realtime- Supports real-time monitoringpoll_interval_seconds- Data polling intervaltemperature_zones- Number of temperature zonessupports_humidity- Humidity monitoring capabilitysupports_energy_monitoring- Energy monitoring capabilitysupports_remote_control- Remote control capability
2. equipment_sensor_readings
Time-series sensor data storage:
- Core readings: temperature, humidity, energy consumption
- Status: operational_status, cycle_stage, progress
- Process parameters: motor_speed, door_status, steam_level
- Quality indicators: product_weight, moisture_content
- Flexible JSON field for manufacturer-specific sensors
3. equipment_connection_logs
Connection event tracking:
- event_type, event_time, connection_status
- Error tracking: error_message, error_code
- Performance metrics: response_time_ms, data_points_received
4. equipment_iot_alerts
Real-time equipment alerts:
- Alert types: temperature_deviation, connection_lost, equipment_error
- Severity levels: info, warning, critical
- Status tracking: active, acknowledged, resolved
- Automated response tracking
Migration
Run migration to add IoT support:
cd services/production
alembic upgrade head
Migration file: migrations/versions/002_add_iot_equipment_support.py
IoT Connectors
Connector Architecture
All connectors implement the BaseIoTConnector abstract interface:
from app.services.iot import BaseIoTConnector, ConnectorFactory
# Create connector instance
connector = ConnectorFactory.create_connector(
protocol='rest_api',
equipment_id='equipment-uuid',
config={
'endpoint': 'https://api.example.com',
'port': 443,
'credentials': {'api_key': 'xxx'},
'additional_config': {}
}
)
# Test connection
status = await connector.test_connection()
# Get current readings
reading = await connector.get_current_reading()
# Get equipment capabilities
capabilities = await connector.get_capabilities()
Available Connectors
1. Generic REST API Connector
Protocol: rest_api
File: app/services/iot/rest_api_connector.py
Configuration Example:
{
"protocol": "rest_api",
"endpoint": "https://api.equipment.com",
"port": 443,
"credentials": {
"api_key": "your-api-key",
"token": "bearer-token"
},
"additional_config": {
"data_endpoint": "/api/v1/equipment/{equipment_id}/data",
"status_endpoint": "/api/v1/equipment/{equipment_id}/status",
"timeout": 10,
"verify_ssl": true
}
}
Features:
- Standard REST API support
- Bearer token & API key authentication
- Basic authentication
- Configurable endpoints
- SSL verification control
- Timeout configuration
2. Rational ConnectedCooking Connector
Protocol: rational or rational_connected_cooking
File: app/services/iot/rational_connector.py
Configuration Example:
{
"protocol": "rational",
"endpoint": "https://www.connectedcooking.com/api/v1",
"port": 443,
"credentials": {
"username": "your-email@example.com",
"password": "your-password"
},
"additional_config": {
"unit_id": "12345",
"timeout": 15
}
}
Features:
- Multi-zone temperature (cabinet + core)
- Humidity monitoring
- Energy consumption tracking
- Remote control support
- HACCP documentation
- Recipe management
- Automatic cleaning status
Contact: cc-support@rational-online.com
3. Wachtel REMOTE Connector
Protocol: wachtel or wachtel_remote
File: app/services/iot/wachtel_connector.py
Configuration Example:
{
"protocol": "wachtel",
"endpoint": "https://remote.wachtel.de/api",
"port": 443,
"credentials": {
"username": "bakery-username",
"password": "bakery-password"
},
"additional_config": {
"oven_id": "oven-serial-number",
"deck_count": 3
}
}
Features:
- Multi-deck temperature monitoring
- Energy consumption tracking
- Maintenance alerts
- Operation hours tracking
- Deck-specific control
Contact: support@wachtel.de
4. OPC UA Connector (Template)
Protocol: opc_ua
Status: Template only (requires implementation)
For bakery equipment supporting OPC UA or Weihenstephan Standards (WS Bake).
Dependencies:
pip install asyncua==1.1.5
Template Location: To be created at app/services/iot/opcua_connector.py
Supported Equipment
Equipment Research Summary
Spanish Manufacturers (Madrid Region)
-
SALVA Industrial (Lezo, Guipuzcoa)
- Smart touch control panels
- Energy monitoring
- Digital integration
- Status: API details pending
-
Farjas (Madrid, Móstoles)
- Rotary ovens
- Status: IoT capabilities unknown
-
COLBAKE (Valencia)
- Complete bakery lines
- Status: IoT capabilities to be confirmed
International Manufacturers with Madrid Presence
-
Rational (Germany) - ✅ Implemented
- Product: iCombi ovens
- Platform: ConnectedCooking
- API: Available (REST)
- Showroom: Madrid (15 min from airport)
-
Wachtel (Germany) - ✅ Template Created
- Product: Deck ovens
- Platform: REMOTE monitoring
- API: REST (details pending confirmation)
-
Sveba Dahlen (Sweden)
- Showroom in Madrid
- Status: IoT capabilities to be researched
Industry Standards
- OPC UA: Standard protocol for industrial automation
- Weihenstephan Standards (WS Bake): Bakery-specific communication standard
- MQTT: Common IoT message protocol
- Modbus: Industrial communication protocol
Implementation Status
✅ Completed
-
Database Schema
- Migration created and tested
- All IoT tables defined
- Indexes optimized for time-series queries
-
Models
- Equipment model extended with IoT fields
- Sensor reading model
- Connection log model
- IoT alert model
- Enums: IoTProtocol, IoTConnectionStatus
-
Schemas (Pydantic)
- IoTConnectionConfig
- Equipment schemas updated with IoT fields
- EquipmentSensorReadingResponse
- EquipmentConnectionTestResponse
- RealTimeDataResponse
- EquipmentIoTAlertResponse
- EquipmentSensorHistoryResponse
-
IoT Connectors
- Base connector interface (
BaseIoTConnector) - Connector factory pattern
- Generic REST API connector (fully implemented)
- Rational ConnectedCooking connector (implemented)
- Wachtel REMOTE connector (template created)
- Base connector interface (
-
Dependencies
- requirements.txt updated
- httpx for REST APIs
- Commented dependencies for OPC UA and MQTT
🚧 In Progress / To Do
-
IoT Integration Service ⏳
- High-level service layer
- Connection pool management
- Automatic retry logic
- Health monitoring
-
Repository Layer ⏳
- Equipment IoT configuration CRUD
- Sensor data storage and retrieval
- Connection log management
- Alert management
-
API Endpoints ⏳
- POST
/api/v1/equipment/{id}/iot-config- Configure IoT - POST
/api/v1/equipment/{id}/test-connection- Test connectivity - GET
/api/v1/equipment/{id}/realtime-data- Get current data - GET
/api/v1/equipment/{id}/sensor-history- Historical data - GET
/api/v1/batches/{id}/realtime-tracking- Batch tracking - GET
/api/v1/equipment/iot-alerts- Get active alerts
- POST
-
Background Workers ⏳
- Periodic data collection worker
- Connection health monitor
- Alert generation and notification
- Data cleanup (old sensor readings)
-
Frontend Components ⏳
- Equipment IoT configuration wizard
- Real-time monitoring dashboard
- Sensor data visualization charts
- Alert notification system
- Connection status indicators
-
Additional Connectors 📋
- OPC UA connector implementation
- MQTT connector implementation
- SALVA-specific connector (pending API details)
Next Steps
Priority 1: Core Service Layer
-
Create IoT Integration Service
# app/services/iot_integration_service.py class IoTIntegrationService: async def configure_equipment_iot(equipment_id, config) async def test_connection(equipment_id) async def get_realtime_data(equipment_id) async def get_sensor_history(equipment_id, start, end) async def store_sensor_reading(equipment_id, reading) -
Create Repository Methods
# app/repositories/equipment_repository.py async def update_iot_config(equipment_id, config) async def get_iot_config(equipment_id) async def update_connection_status(equipment_id, status) # app/repositories/sensor_reading_repository.py async def create_reading(reading) async def get_readings(equipment_id, start_time, end_time) async def get_latest_reading(equipment_id) -
Create API Endpoints
# app/api/equipment_iot.py router = APIRouter(prefix="/equipment", tags=["equipment-iot"]) @router.post("/{equipment_id}/iot-config") @router.post("/{equipment_id}/test-connection") @router.get("/{equipment_id}/realtime-data") @router.get("/{equipment_id}/sensor-history")
Priority 2: Background Processing
-
Data Collection Worker
- Poll IoT-enabled equipment at configured intervals
- Store sensor readings in database
- Handle connection errors gracefully
-
Alert Generation
- Monitor temperature deviations
- Detect connection losses
- Generate alerts for critical conditions
Priority 3: Frontend Integration
-
Equipment Configuration UI
- IoT setup wizard
- Protocol selection
- Connection testing
- Credential management
-
Real-time Dashboard
- Live equipment status cards
- Temperature/humidity gauges
- Energy consumption charts
- Alert notifications
Usage Examples
Example 1: Configure Equipment for IoT
from app.services.iot_integration_service import IoTIntegrationService
service = IoTIntegrationService()
# Configure Rational iCombi oven
config = {
"protocol": "rational",
"endpoint": "https://www.connectedcooking.com/api/v1",
"port": 443,
"credentials": {
"username": "bakery@example.com",
"password": "secure-password"
},
"additional_config": {
"unit_id": "12345"
}
}
await service.configure_equipment_iot(equipment_id="uuid-here", config=config)
Example 2: Test Connection
# Test connection before saving configuration
result = await service.test_connection(equipment_id="uuid-here")
if result.success:
print(f"Connected in {result.response_time_ms}ms")
print(f"Supported features: {result.supported_features}")
else:
print(f"Connection failed: {result.error_details}")
Example 3: Get Real-time Data
# Get current equipment data
data = await service.get_realtime_data(equipment_id="uuid-here")
print(f"Temperature: {data.temperature}°C")
print(f"Status: {data.operational_status}")
print(f"Progress: {data.cycle_progress_percentage}%")
print(f"Time remaining: {data.time_remaining_minutes} min")
Example 4: Retrieve Sensor History
from datetime import datetime, timedelta
# Get last 24 hours of data
end_time = datetime.now()
start_time = end_time - timedelta(hours=24)
history = await service.get_sensor_history(
equipment_id="uuid-here",
start_time=start_time,
end_time=end_time
)
# Plot temperature over time
for reading in history.readings:
print(f"{reading.reading_time}: {reading.temperature}°C")
API Endpoint Specifications
POST /api/v1/equipment/{equipment_id}/iot-config
Configure IoT connectivity for equipment.
Request Body:
{
"protocol": "rational",
"endpoint": "https://www.connectedcooking.com/api/v1",
"port": 443,
"credentials": {
"username": "user@example.com",
"password": "password"
},
"additional_config": {
"unit_id": "12345"
},
"supports_realtime": true,
"poll_interval_seconds": 30
}
Response:
{
"success": true,
"message": "IoT configuration saved successfully",
"equipment_id": "uuid",
"connection_test_result": {
"success": true,
"status": "connected",
"response_time_ms": 145
}
}
GET /api/v1/equipment/{equipment_id}/realtime-data
Get current real-time sensor data.
Response:
{
"equipment_id": "uuid",
"equipment_name": "Horno Principal #1",
"timestamp": "2025-01-12T10:30:00Z",
"connection_status": "connected",
"temperature": 185.5,
"temperature_zones": {
"cabinet": 180,
"core": 72
},
"humidity": 65.0,
"operational_status": "running",
"cycle_stage": "baking",
"cycle_progress_percentage": 45.0,
"time_remaining_minutes": 12,
"energy_consumption_kwh": 12.5,
"active_batch_id": "batch-uuid",
"active_batch_name": "Baguettes - Batch #123"
}
Security Considerations
-
Credential Storage
- Store API keys/passwords encrypted in database
- Use environment variables for sensitive configuration
- Rotate credentials periodically
-
SSL/TLS
- Always use HTTPS for REST API connections
- Verify SSL certificates in production
- Support self-signed certificates for local equipment
-
Authentication
- Require user authentication for IoT configuration
- Log all configuration changes
- Implement role-based access control
-
Network Security
- Support firewall-friendly protocols
- Document required network ports
- Consider VPN for equipment access
Troubleshooting
Connection Issues
-
Timeout errors
- Increase timeout in additional_config
- Check network connectivity
- Verify firewall rules
-
Authentication failures
- Verify credentials are correct
- Check API key expiration
- Confirm endpoint URL is correct
-
SSL certificate errors
- Set
verify_ssl: falsefor testing (not recommended for production) - Install proper SSL certificates
- Use certificate bundles for corporate networks
- Set
Data Quality Issues
-
Missing sensor readings
- Check equipment supports requested sensors
- Verify polling interval is appropriate
- Review connection logs for errors
-
Anomalous data
- Implement data validation
- Set reasonable min/max thresholds
- Flag outliers for manual review
Resources
Manufacturer Contacts
- Rational: cc-support@rational-online.com
- Wachtel: support@wachtel.de / https://www.wachtel.de
- SALVA: https://www.salva.es/en
Standards and Protocols
- OPC Foundation: https://opcfoundation.org/
- Weihenstephan Standards: https://www.weihenstephan-standards.com
- MQTT: https://mqtt.org/
Libraries
- httpx: https://www.python-httpx.org/
- asyncua: https://github.com/FreeOpcUa/opcua-asyncio
- paho-mqtt: https://pypi.org/project/paho-mqtt/
Last Updated: 2025-01-12 Status: Phase 1 Complete - Foundation & Connectors Next Milestone: Service Layer & API Endpoints