# Printer Communication ## Summary The printer communication system handles serial port connections to 3D printers, sending G-code commands, receiving responses, and managing print state. It uses a stream-based architecture for G-code processing with modular transformers for features like print leveling, pause handling, and temperature monitoring. ## Technical Description ### PrinterConnection Class `PrinterConnection` is the main class managing printer communication: **Communication States:** | State | Description | |-------|-------------| | `Disconnected` | No active connection | | `AttemptingToConnect` | Connection in progress | | `FailedToConnect` | Connection attempt failed | | `Connected` | Ready to receive commands | | `PreparingToPrint` | Setting up for print | | `Printing` | Active print from host | | `PrintingFromSd` | Printing from SD card | | `Paused` | Print paused | | `FinishedPrint` | Print completed | | `Disconnecting` | Closing connection | | `ConnectionLost` | Unexpected disconnect | **Supported Firmware:** - Marlin - Repetier - Sprinter - Smoothie ### Serial Communication Connection parameters: - `BaudRate` - Typically 115200 or 250000 - `SerialPort` - Platform-specific via `IFrostedSerialPort` - Checksum support for error detection - Line-by-line send/receive with buffering **Response Parsing:** ```csharp // Register callbacks for specific responses readLineStartCallBacks.Register("ok", PrintingCanContinue); readLineStartCallBacks.Register("T:", ReadTemperatures); readLineStartCallBacks.Register("Error:", PrinterReportsError); ``` **Write Callbacks:** ```csharp writeLineStartCallBacks.Register("M104", HotendTemperatureWasWritenToPrinter); writeLineStartCallBacks.Register("M140", BedTemperatureWasWritenToPrinter); ``` ### G-Code Stream Pipeline G-code is processed through a chain of `GCodeStream` transformers: ``` GCodeFileStream (source) └── GCodeSwitcher (file switching) └── QueuedCommandsStream (injected commands) └── PauseHandlingStream (pause/resume) └── RelativeToAbsoluteStream (coordinate conversion) └── PrintLevelingStream (bed leveling adjustments) └── BabyStepsStream (live Z offset) └── MaxLengthStream (segment splitting) └── ToolChangeStream (extruder switching) └── ExtrusionMultiplierStream └── FeedRateMultiplierStream └── WaitForTempStream └── RequestTemperaturesStream └── to Serial Port ``` Each stream can: - Modify G-code lines passing through - Inject additional commands - Block/delay commands - Monitor state ### Key G-Code Streams | Stream | Purpose | |--------|---------| | `GCodeFileStream` | Reads G-code from file | | `GCodeSwitcher` | Switches between print files | | `QueuedCommandsStream` | Injects immediate commands | | `PauseHandlingStream` | Manages pause/resume logic | | `PrintLevelingStream` | Applies bed leveling corrections | | `MaxLengthStream` | Splits long moves into segments | | `ToolChangeStream` | Handles multi-extruder switching | | `WaitForTempStream` | Waits for temperature targets | | `PrintRecoveryStream` | Enables print recovery after failure | | `ValidatePrintLevelingStream` | Validates leveling data | | `SoftwareEndstopsStream` | Enforces software limits | | `BabyStepsStream` | Applies live Z offset adjustments | ### Temperature Management Temperature tracking for: - Heated bed (`ActualBedTemperature`, `TargetBedTemperature`) - Up to 16 hotends (`actualHotendTemperature[]`, `targetHotendTemperature[]`) **Temperature Reading:** ```csharp // Parses responses like "T:205.3 /210.0 B:60.0 /60.0" readLineContainsCallBacks.Register("T:", ReadTemperatures); ``` **Automatic Heater Shutdown:** - `TimeToHoldTemperature` - Configurable delay - `SecondsToHoldTemperature` - Countdown timer - `TurnOffBedAndExtruders(TurnOff.AfterDelay)` - Scheduled shutdown ### Print State Management **Detailed Printing States:** | State | Description | |-------|-------------| | `HomingAxis` | Executing homing sequence | | `HeatingBed` | Waiting for bed temperature | | `HeatingT0` | Waiting for extruder 0 temp | | `HeatingT1` | Waiting for extruder 1 temp | | `Printing` | Active G-code execution | **Events:** | Event | Description | |-------|-------------| | `PrintStarted` | Print begins | | `PrintFinished` | Print completes | | `CancelRequested` | Cancel initiated | | `CancelCompleted` | Cancel finished | | `PauseOnLayer` | Pause at specific layer | | `FilamentRunout` | Filament sensor triggered | ### Error Handling Error detection via response parsing: ```csharp readLineContainsCallBacks.Register("MINTEMP", PrinterReportsError); readLineContainsCallBacks.Register("MAXTEMP", PrinterReportsError); readLineContainsCallBacks.Register("Thermal Runaway", PrinterReportsError); ``` Errors trigger: 1. `ErrorReported` event 2. Print pause (if printing) 3. User notification dialog ### Alternative Drivers The system supports alternative communication protocols: | Driver | Location | Purpose | |--------|----------|---------| | Emulator | Drivers/Emulator | Virtual printer for testing | | TCPIP | Drivers/TCPIP | Network-connected printers | | X3G | Drivers/X3G | MakerBot X3G protocol | ### TerminalLog All communication is logged via `TerminalLog`: - Send/receive history - Exportable for debugging - Real-time display in UI terminal ### Design Rationale **Stream Pipeline**: The chain-of-responsibility pattern allows: - Modular feature implementation - Easy addition/removal of processing stages - Clear data flow through transformations - Independent testing of each stage **Callback-Based Parsing**: Using `StartsWith` and `Contains` callbacks: - Efficient string matching - Handles firmware variations - Easy to extend for new responses **State Machine**: The `CommunicationStates` enum ensures: - Clear state transitions - Appropriate UI updates - Safe operation sequencing ## Reference ### Core Classes | Class | Location | Description | |-------|----------|-------------| | `PrinterConnection` | [PrinterCommunication/PrinterConnection.cs](MatterControlLib/PrinterCommunication/PrinterConnection.cs) | Main communication class | | `TerminalLog` | [PrinterCommunication/TerminalLog.cs](MatterControlLib/PrinterCommunication/TerminalLog.cs) | Communication log | | `PrinterConfig` | [SlicerConfiguration/PrinterConfig.cs](MatterControlLib/SlicerConfiguration/Settings/PrinterConfig.cs) | Printer configuration | ### G-Code Streams | Class | Location | Description | |-------|----------|-------------| | `GCodeStream` | [PrinterCommunication/Io/GCodeStream.cs](MatterControlLib/PrinterCommunication/Io/GCodeStream.cs) | Base stream class | | `GCodeSwitcher` | [PrinterCommunication/Io/GCodeSwitcher.cs](MatterControlLib/PrinterCommunication/Io/GCodeSwitcher.cs) | File switching | | `PauseHandlingStream` | [PrinterCommunication/Io/PauseHandlingStream.cs](MatterControlLib/PrinterCommunication/Io/PauseHandlingStream.cs) | Pause/resume | | `PrintLevelingStream` | [PrinterCommunication/Io/PrintLevelingStream.cs](MatterControlLib/PrinterCommunication/Io/PrintLevelingStream.cs) | Bed leveling | | `ToolChangeStream` | [PrinterCommunication/Io/ToolChangeStream.cs](MatterControlLib/PrinterCommunication/Io/ToolChangeStream.cs) | Tool changes | | `WaitForTempStream` | [PrinterCommunication/Io/WaitForTempStream.cs](MatterControlLib/PrinterCommunication/Io/WaitForTempStream.cs) | Temperature wait | ### Events | Event | Source | Description | |-------|--------|-------------| | `CommunicationStateChanged` | `PrinterConnection` | State transition | | `TemperatureRead` | `PrinterConnection` | Temp update | | `LineReceived` | `PrinterConnection` | Serial input | | `LineSent` | `PrinterConnection` | Serial output | | `PrintFinished` | `PrinterConnection` | Print complete | | `ErrorReported` | `PrinterConnection` | Printer error | ### Enums | Enum | Values | |------|--------| | `CommunicationStates` | Disconnected, Connected, Printing, Paused, etc. | | `DetailedPrintingState` | HomingAxis, HeatingBed, HeatingT0, Printing | | `FirmwareTypes` | Unknown, Repetier, Marlin, Sprinter, Smoothie | | `TurnOff` | Now, AfterDelay | | `Axis` | X, Y, Z, E, XYZ, C |