Skip to content

markot-99/production-line-simulator-pl001

Repository files navigation

Production Line Simulator

Python 3.11+ OPC UA License

Industrial-grade, MES-ready production line simulation system for manufacturing environments. This simulator provides a complete Digital Twin of a real production line, enabling MES system development, testing, and integration without access to physical factory equipment.

🎯 Overview

This production line simulator replicates a real automotive manufacturing environment where Steering Gear Housing components are produced through a multi-stage process involving CNC machining, washing, and quality inspection. The simulator is designed to be indistinguishable from real factory equipment from the perspective of an MES (Manufacturing Execution System) system.

Why This Simulator?

  • No Physical Equipment Required: Develop and test MES systems without factory access
  • 1:1 Realism: Identical behavior to real industrial machines
  • OPC UA Standard: Full compliance with VDMA OPC UA Machine Tool Companion Specification
  • Configuration-Driven: Adjust machine parameters without code changes
  • MES-Ready: Drop-in replacement for real equipment during development

✨ Key Features

  • 🔄 Full OPC UA Compliance: VDMA OPC UA Machine Tool Companion specification (IEC 62541)
  • 🏭 Realistic Machine Behavior: State machines, cycle times, downtime patterns (MTBF/MTTR)
  • 📦 Material Flow Tracking: WIP tracking with unique PartID genealogy throughout production
  • ✅ Quality Management: CMM inspection simulation with configurable pass/fail rates
  • 📊 KPI Tracking: OEE, MTBF, MTTR, Throughput calculations
  • 🔒 Secure Communication: OPC UA with certificate-based security support
  • ⚙️ Configuration-Driven: Full machine parameterization via YAML files
  • 🔌 Multi-Machine Support: Simulate entire production lines with multiple machines
  • 📡 Event System: CycleStarted, CycleCompleted, AlarmRaised, AlarmCleared events
  • 🏷️ Material Inventory: Track raw material consumption and availability

🏭 Production Line

The simulator replicates a complete production line with the following machines:

Machine Type Function Cycle Time OPC UA Endpoint
CNC-01 Rough Machining Center Initial material removal 3 minutes opc.tcp://localhost:4840
CNC-02 Finish Machining Center Precision finishing 4 minutes opc.tcp://localhost:4841
WM-01 Industrial Parts Washer Parts cleaning (batch: 4 parts) 2 minutes opc.tcp://localhost:4842
CMM-01 Coordinate Measuring Machine Quality inspection 5 minutes opc.tcp://localhost:4843

Production Flow

[Raw Material] → CNC-01 (Rough) → WM-01 (Wash) → CNC-02 (Finish) → CMM-01 (Inspect) → [Completed]

Each machine is configured with realistic parameters:

  • Cycle times: Based on real industrial equipment specifications
  • Downtime patterns: MTBF (Mean Time Between Failures) and MTTR (Mean Time To Repair)
  • State machines: Idle, Setup, Running, Fault, Maintenance states
  • Tool management: Tool wear simulation and automatic tool change

🛠️ Technology Stack

  • Python 3.11+: Core programming language
  • asyncua: OPC UA server implementation
  • asyncio: Async/await for concurrent machine simulation
  • pydantic: Configuration and data validation
  • pyyaml: Configuration file parsing
  • structlog: Structured logging
  • sqlalchemy: Data persistence (optional)

Development Dependencies

  • pytest: Unit testing framework
  • mypy: Static type checking
  • black: Code formatting
  • ruff: Fast Python linter

📦 Installation

Prerequisites

  • Python 3.11 or higher
  • pip (Python package manager)

Step 1: Clone the Repository

git clone <repository-url>
cd production-line-simulator

Step 2: Create Virtual Environment

python3 -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

Step 3: Install Dependencies

# Install production dependencies
pip install -e .

# Or install with development dependencies
pip install -e ".[dev]"

🚀 Quick Start

Prerequisites

Before starting, ensure you have:

  • Python 3.11+ installed
  • Virtual environment activated (if using one)
  • All dependencies installed (pip install -e .)

Step 1: Activate Virtual Environment (if using one)

# On Linux/macOS
source venv/bin/activate

# On Windows
venv\Scripts\activate

Step 2: Start the Simulator

python -m simulator.main

What happens:

  • All machines are initialized and OPC UA servers start
  • Production begins automatically
  • All machines are set to Automatic mode
  • Parts are created and flow through the production line

You should see log output indicating:

  • Configuration loaded
  • Machines initialized
  • OPC UA servers started on their respective ports
  • Production loop started

Step 3: Connect to OPC UA Servers

Use an OPC UA client to connect to the simulator. Recommended clients:

  • UaExpert (Windows, free)
  • Prosys OPC UA Client (Cross-platform, free)
  • OPC UA Expert (Various platforms)

Connection Endpoints:

Machine OPC UA Endpoint
CNC-01 opc.tcp://localhost:4840
CNC-02 opc.tcp://localhost:4841
WM-01 opc.tcp://localhost:4842
CMM-01 opc.tcp://localhost:4843

Connection Steps (UaExpert):

  1. Open UaExpert
  2. Right-click on "Servers" → "Add Server"
  3. Enter endpoint URL (e.g., opc.tcp://localhost:4840)
  4. Click "OK" → Server appears in the list
  5. Double-click server to connect
  6. Browse the address space to see machine nodes

Step 4: Monitor Production

Key OPC UA Variables to Track

For each machine:

  • Production.PartCounter - Number of parts processed
  • Production.ScrapCounter - Number of scrap parts
  • Status.MachineState - Current state (Idle, Running, Fault, etc.)
  • Status.Mode - Operating mode (Manual=0, SemiAutomatic=1, Automatic=2)
  • Alarm.AlarmActive - Active alarm status (Boolean)
  • Alarm.AlarmID - Current alarm identifier (String)

For CNC-01 (material tracking):

  • Production.MaterialAvailable - Material availability status (Boolean)
  • Production.MaterialQuantity - Current material quantity (Double, -1.0 = unlimited)

Subscribing to Variables (Real-time Updates)

To see real-time updates in UaExpert:

  1. Browse to the variable (e.g., Production.PartCounter)
  2. Right-click → "Create Monitored Item" (or "Subscribe")
  3. Variable will now update automatically in the Data Access View

Note: Simple "Read" operations show current values but don't auto-refresh. Use Monitored Items (subscriptions) for real-time updates.

OPC UA Events

Subscribe to events to receive notifications:

  • CycleStarted - Emitted when a production cycle begins
  • CycleCompleted - Emitted when a cycle finishes (includes PartCounter and CycleTime)
  • AlarmRaised - Emitted when a fault occurs (includes AlarmID, Message, Severity)
  • AlarmCleared - Emitted when an alarm is cleared (includes AlarmID)

In UaExpert:

  1. Right-click on the machine node (e.g., MachineTool_CNC-01)
  2. Select "Create Event Subscription"
  3. Events will appear in the Event View when they occur

Step 5: Verify Production is Running

Check these indicators:

  1. Console Logs: Should show parts being created and processed
  2. OPC UA Variables: PartCounter should increment over time
  3. Machine State: Should alternate between Idle and Running
  4. Material Tracking (CNC-01): MaterialQuantity should decrease if material tracking is enabled

Expected Timeline:

  • T=0s: First part created, CNC-01 starts processing (3 minutes)
  • T=3min: CNC-01 completes, part moves to WM-01
  • T=5min: WM-01 completes, part moves to CNC-02
  • T=9min: CNC-02 completes, part moves to CMM-01
  • T=14min: CMM-01 completes inspection, part marked as completed or scrap

Step 6: Stop the Simulator

Press Ctrl+C in the terminal. The simulator will:

  • Gracefully shut down all OPC UA servers
  • Stop production loops
  • Clean up resources
  • Exit cleanly

📊 What to Monitor

Production Metrics

Successful Production:

  • CMM-01 PartCounter = Total parts that passed inspection
  • CMM-01 ScrapCounter = Total parts that failed inspection
  • Successful parts = PartCounter - ScrapCounter

Material Status (CNC-01):

  • MaterialAvailable = false → Production paused (material shortage)
  • MaterialQuantity = 0.0 → No material remaining
  • MaterialQuantity = -1.0 → Unlimited material (tracking disabled)

Machine Health

Normal Operation:

  • MachineState alternates between Idle and Running
  • Mode = Automatic (value: 2)
  • AlarmActive = false

Fault Condition:

  • MachineState = Fault
  • AlarmActive = true
  • AlarmID contains fault code
  • Production stops until Reset() method is called

Troubleshooting

If production doesn't start:

  • Check console logs for errors
  • Verify all machines are in Automatic mode
  • Ensure material is available (if material tracking enabled)
  • Check that buffers are not full

If OPC UA connection fails:

  • Verify simulator is running
  • Check that port is not already in use
  • Ensure firewall allows connections on ports 4840-4843
  • Try connecting to opc.tcp://127.0.0.1:4840 instead of localhost

⚙️ Configuration

All machine parameters are configured via YAML files in the config/ directory. This allows adjusting machine behavior without code changes - just like configuring real factory equipment.

Configuration File: config/machines.yaml

production_line:
  name: "Steering Gear Housing Production Line"
  description: "Complete production line simulation for Steering Gear Housing"

machines:
  CNC-01:
    machine_id: "CNC-01"
    machine_type: "CNC_Rough"
    manufacturer: "HELLER"
    model: "H2000"
    controller: "Siemens 840D"
    
    cycle_times:
      normal_cycle: 180.0      # 3 minutes per part
      setup_time: 600.0        # 10 minutes setup
    
    downtime:
      mtbf_hours: 240.0        # Mean Time Between Failures: 240 hours
      mttr_minutes: 45.0       # Mean Time To Repair: 45 minutes
    
    opcua:
      port: 4840
      update_rate_ms: 100
      namespace: "http://example.com/CNC-01"

Material Inventory Configuration

Material tracking can be enabled/disabled in the configuration:

production:
  material_inventory:
    initial_quantity: 100.0      # Initial material quantity
    material_per_part: 1.0       # Material consumed per part
    # Set to None or 0 to disable material tracking (unlimited material)

When material runs out, production automatically pauses and MaterialAvailable becomes false.

See docs/CONFIGURATION.md for detailed configuration documentation.


🔌 OPC UA Integration

Information Model

Each machine exposes a standard OPC UA information model following the VDMA OPC UA Machine Tool Companion Specification:

MachineTool_<MachineID>/
├── Status/
│   ├── MachineState (Idle, Running, Setup, Fault, Maintenance, etc.)
│   ├── Mode (Manual, SemiAutomatic, Automatic, Setup)
│   └── ActiveProgram
├── Production/
│   ├── PartCounter
│   ├── ScrapCounter
│   ├── CycleTime
│   ├── MaterialAvailable (CNC-01 only)
│   └── MaterialQuantity (CNC-01 only)
└── Alarm/
    ├── AlarmActive
    └── AlarmID

Methods (Operator Actions)

  • StartCycle() - Start production cycle
  • StopCycle() - Stop current cycle
  • Setup() - Enter setup mode
  • Reset() - Reset machine from fault state

Events

All machines emit OPC UA events that MES systems can subscribe to:

  • CycleStarted: Cycle begins
  • CycleCompleted: Cycle finishes (includes PartCounter, CycleTime)
  • AlarmRaised: Fault detected (includes AlarmID, Message, Severity)
  • AlarmCleared: Alarm resolved (includes AlarmID)

MES System Integration

The simulator is designed to be a drop-in replacement for real factory equipment:

  1. Connect via OPC UA: Use standard OPC UA client libraries
  2. Subscribe to Events: Monitor production cycles and alarms
  3. Read Variables: Get real-time machine status and production metrics
  4. Call Methods: Control machines (StartCycle, StopCycle, Reset)
  5. Track Genealogy: Each part has a unique PartID and complete processing history

📁 Project Structure

production-line-simulator/
├── src/
│   └── simulator/
│       ├── __init__.py
│       ├── main.py                  # Main entry point
│       ├── machines/                # Machine implementations
│       │   ├── base.py              # BaseMachine abstract class
│       │   ├── cnc.py               # CNC machine implementations
│       │   ├── washer.py            # Washer machine
│       │   ├── cmm.py               # CMM machine
│       │   └── factory.py           # Machine factory
│       ├── opcua/                   # OPC UA server implementation
│       │   ├── server.py            # OPC UA server for each machine
│       │   ├── events.py            # Event definitions
│       │   ├── integration.py       # OPC UA bridge
│       │   └── kpi.py               # KPI calculations
│       ├── simulation/              # Simulation engine
│       │   ├── engine.py            # ProductionLineEngine
│       │   └── buffer.py            # Material buffer management
│       ├── config/                  # Configuration management
│       │   ├── loader.py            # Configuration loader
│       │   └── models.py            # Pydantic configuration models
│       ├── models/                  # Data models
│       │   └── part.py              # Part model with genealogy
│       └── utils/                   # Utilities
│           └── logging.py           # Structured logging
├── config/                          # Configuration files
│   └── machines.yaml                # Machine configuration
├── docs/                            # Documentation
│   ├── ARCHITECTURE.md              # System architecture
│   ├── CONFIGURATION.md             # Configuration guide
│   └── PROJECT_SETUP.md             # Setup documentation
├── tests/                           # Test suite
├── HOW_TO_RUN.md                    # Quick start guide
├── pyproject.toml                   # Project configuration
├── requirements.txt                 # Dependencies
└── README.md                        # This file

📊 Production Tracking

Part Genealogy

Every part in the system has a unique PartID and complete genealogy tracking:

{
    "part_id": "PART-0001",
    "created_at": "2026-01-12T10:00:00",
    "material": "Aluminum alloy AlSi10Mg",
    "processing_history": [
        {
            "machine_id": "CNC-01",
            "started_at": "2026-01-12T10:05:00",
            "completed_at": "2026-01-12T10:08:00",
            "cycle_time": 180.0
        },
        # ... more processing steps
    ],
    "quality_results": {
        "passed": true,
        "inspection_time": "2026-01-12T10:25:00"
    }
}

Quality Control

The CMM-01 machine performs quality inspection with a configurable pass rate (default: 95%). Parts that fail inspection are marked as scrap and tracked via ScrapCounter.


🎓 Standards Compliance

This simulator adheres to industrial standards:

  • VDMA OPC UA Machine Tool Companion Specification
  • IEC 62541 OPC UA Standard
  • Real industrial machine specifications (Siemens SINUMERIK, HELLER, Zeiss CMM)

🧪 Development

Running Tests

pytest

Type Checking

mypy src/

Code Formatting

black src/
ruff check src/

Adding New Machines

  1. Create a new machine class inheriting from BaseMachine
  2. Implement required abstract methods
  3. Add machine configuration to config/machines.yaml
  4. Register the machine type in MachineFactory

See docs/ARCHITECTURE.md for detailed architecture documentation.


📝 License

Proprietary - All rights reserved


🤝 Contributing

This project is designed for internal use. For questions or support, please contact the development team.


📚 Additional Documentation

Note: For quick start instructions, see the Quick Start section above.


🎯 Use Cases

  • MES Development: Develop MES systems without factory access
  • Integration Testing: Test MES integrations in a controlled environment
  • Training: Train MES engineers on OPC UA integration
  • Proof of Concept: Validate MES concepts before factory deployment
  • Production Planning: Simulate production scenarios and optimize workflows

Built with ❤️ for the manufacturing industry

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors