- Implement health check endpoints for system monitoring including basic, detailed, readiness, liveness, and metrics. - Create process control endpoints to start, stop, pause, resume, and manage processes. - Add recipe management endpoints for listing, creating, retrieving, updating, deleting, duplicating, and validating recipes. - Introduce system management endpoints for retrieving system information, active alarms, and configuration. - Establish user management endpoints for listing and creating users with placeholder implementations. - Define Pydantic schemas for API request/response validation related to recipes, processes, and users.
Chocolate Tempering Machine Control System
A modern, modular Python implementation of an industrial chocolate tempering machine control system, built with FastAPI, asyncio, and SQLAlchemy.
Architecture Overview
This system replaces a legacy C# Avalonia application with a clean, microservices-based architecture designed for reliability, maintainability, and scalability.
Key Components
- FastAPI Web Service: RESTful API for user interface and system control
- Hardware Service: Asynchronous Modbus RTU communication with industrial hardware
- Recipe Service: State machine-based tempering process management
- Safety Service: Real-time monitoring and error handling
- Data Service: Logging, configuration management, and persistence
Technology Stack
- Web Framework: FastAPI with async/await patterns
- Hardware Communication: pymodbus for Modbus RTU over serial
- Database: SQLAlchemy with SQLite/PostgreSQL
- State Management: python-statemachine for recipe phases
- Configuration: Pydantic for type-safe settings
- Logging: structlog for structured logging
- Message Queue: Redis/Celery for inter-service communication
- Monitoring: Prometheus metrics integration
Project Structure
src/tempering_machine/
├── services/
│ ├── hardware/ # Modbus communication and hardware control
│ ├── recipe/ # Recipe state machine and process control
│ ├── safety/ # Safety monitoring and error handling
│ ├── web/ # FastAPI REST API service
│ └── data/ # Data logging and persistence
├── shared/
│ ├── config.py # Pydantic configuration settings
│ ├── database.py # SQLAlchemy database setup
│ ├── messaging.py # Message queue client
│ ├── models/ # Database ORM models
│ └── schemas/ # Pydantic data schemas
├── tests/ # Unit and integration tests
├── scripts/ # Utility and deployment scripts
└── docker/ # Docker configuration
Quick Start
Development Setup
- Clone and setup environment:
git clone <repository-url>
cd python_rewrite
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
pip install -r requirements-dev.txt
- Initialize database:
alembic upgrade head
- Start development server:
uvicorn tempering_machine.services.web.main:app --reload --host 0.0.0.0 --port 8000
- Access web interface:
- API Documentation: http://localhost:8000/docs
- Monitoring Dashboard: http://localhost:8000/metrics
Production Deployment
# Using Docker Compose
docker-compose up -d
# Or using systemd services
sudo systemctl enable tempering-machine
sudo systemctl start tempering-machine
Core Features
Chocolate Tempering Process
The system manages a three-phase chocolate tempering process:
- Heating Phase: Heat chocolate to target temperature (40-60°C)
- Cooling Phase: Cool to tempering temperature (20-40°C)
- Pouring Phase: Maintain pouring temperature with precise control
Hardware Control
- Temperature Monitoring: 4-zone temperature sensors with ±0.1°C accuracy
- Motor Control: Mixer, fountain, vibration, and heating elements
- Safety Systems: Emergency stop, overcurrent protection, temperature limits
- Communication: Modbus RTU over RS-485 with automatic retry
Safety & Monitoring
- Real-time Error Detection: Grid power, temperature, current monitoring
- Automatic Recovery: Self-healing from communication failures
- Audit Logging: Complete operational history and change tracking
- Prometheus Metrics: Performance monitoring and alerting
Configuration
The system uses environment variables and configuration files:
# Environment Configuration
TEMPERING_DATABASE_URL=sqlite:///tempering.db
TEMPERING_SERIAL_PORT=/dev/ttyUSB0
TEMPERING_SERIAL_BAUDRATE=9600
TEMPERING_LOG_LEVEL=INFO
# Hardware Configuration
TEMPERING_TANK_MAX_TEMP=60.0
TEMPERING_COOLING_GOAL=27.0
TEMPERING_HEATING_GOAL=46.0
API Endpoints
Recipe Management
GET /recipes/- List all recipesPOST /recipes/- Create new recipeGET /recipes/{id}- Get recipe detailsPUT /recipes/{id}- Update recipeDELETE /recipes/{id}- Delete recipe
Process Control
POST /process/start/{recipe_id}- Start tempering processPOST /process/stop- Stop current processGET /process/status- Get current process statusPOST /process/emergency-stop- Emergency shutdown
Hardware Status
GET /hardware/status- Get all hardware statusGET /hardware/temperatures- Get temperature readingsGET /hardware/motors- Get motor statesPOST /hardware/calibrate- Calibrate sensors
System Management
GET /system/health- System health checkGET /system/metrics- Prometheus metricsPOST /system/backup- Create configuration backupPOST /system/restore- Restore from backup
Testing
# Run all tests
pytest
# Run with coverage
pytest --cov=tempering_machine
# Run only unit tests
pytest -m unit
# Run integration tests (requires hardware)
pytest -m integration
Development Guidelines
Code Quality
- Type Hints: All functions must have complete type annotations
- Async/Await: Use async patterns for I/O operations
- Error Handling: Comprehensive exception handling with proper logging
- Testing: Minimum 80% code coverage required
Safety Standards
- No Blocking Operations: All I/O must be asynchronous
- Graceful Degradation: System continues operating during partial failures
- State Validation: All state transitions must be validated
- Hardware Simulation: All code testable without physical hardware
Performance Requirements
- Response Time: < 100ms for safety-critical operations
- Temperature Accuracy: ±0.1°C measurement precision
- Communication Latency: < 500ms for Modbus operations
- Uptime Target: 99.9% availability
Monitoring & Maintenance
Log Files
- Application Logs:
/var/log/tempering-machine/app.log - Access Logs:
/var/log/tempering-machine/access.log - Error Logs:
/var/log/tempering-machine/error.log
Metrics
- Process Metrics: Temperature accuracy, cycle times, error rates
- Hardware Metrics: Communication latency, sensor readings, motor status
- System Metrics: CPU usage, memory consumption, disk I/O
Backup Strategy
- Configuration: Automated daily backup of recipes and settings
- Data: Continuous replication of operational data
- System: Full system image backup weekly
Migration from Legacy System
The Python implementation maintains compatibility with existing:
- Recipe Formats: Existing recipes can be imported
- Hardware Configuration: Same Modbus addressing scheme
- Process Parameters: Identical tempering algorithms
- Safety Logic: Enhanced safety with backward compatibility
Support & Documentation
- API Documentation: Available at
/docsendpoint when running - Technical Documentation: See
docs/directory - Issue Tracking: GitHub Issues
- Support Email: support@tempering-machine.com
License
MIT License - see LICENSE file for details.