# 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

1. **Clone and setup environment:**
```bash
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
```

2. **Initialize database:**
```bash
alembic upgrade head
```

3. **Start development server:**
```bash
uvicorn tempering_machine.services.web.main:app --reload --host 0.0.0.0 --port 8000
```

4. **Access web interface:**
   - API Documentation: http://localhost:8000/docs
   - Monitoring Dashboard: http://localhost:8000/metrics

### Production Deployment

```bash
# 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:

1. **Heating Phase**: Heat chocolate to target temperature (40-60°C)
2. **Cooling Phase**: Cool to tempering temperature (20-40°C) 
3. **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:

```bash
# 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 recipes
- `POST /recipes/` - Create new recipe
- `GET /recipes/{id}` - Get recipe details
- `PUT /recipes/{id}` - Update recipe
- `DELETE /recipes/{id}` - Delete recipe

### Process Control
- `POST /process/start/{recipe_id}` - Start tempering process
- `POST /process/stop` - Stop current process
- `GET /process/status` - Get current process status
- `POST /process/emergency-stop` - Emergency shutdown

### Hardware Status
- `GET /hardware/status` - Get all hardware status
- `GET /hardware/temperatures` - Get temperature readings
- `GET /hardware/motors` - Get motor states
- `POST /hardware/calibrate` - Calibrate sensors

### System Management
- `GET /system/health` - System health check
- `GET /system/metrics` - Prometheus metrics
- `POST /system/backup` - Create configuration backup
- `POST /system/restore` - Restore from backup

## Testing

```bash
# 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 `/docs` endpoint 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.