Skip to content

Source Code Structure

Nikos Siatras edited this page Mar 1, 2026 · 2 revisions

This page describes the structure of the RabbitGRBL/src directory and explains the purpose of each module, folder, and key class.


🗂️ Top-Level Overview

src/
├── Commands/               # GRBL $ command parsing and execution
├── Connection/             # Communication layer (Serial, WiFi, BT)
├── Controller/             # Hardware controllers (Motors, Spindle, Coolant, Probe…)
├── Core/                   # Core enumerations shared across modules
├── CoordinatesManager/     # Work coordinate system management
├── Diagnostics/            # Error and Alarm management
├── Machines/               # Machine-specific configurations and pin assignments
├── NVS/                    # Non-Volatile Storage (ESP32 NVS)
├── Settings/               # Settings types and manager
├── Config.h                # Global compile-time configuration
├── Defaults.h              # Default values for all settings
├── Exec.h                  # Real-time execution flags
├── GCode.cpp/.h            # G-code parser
├── Grbl.cpp/.h             # Main GRBL entry point and includes
├── Jog.cpp/.h              # Jogging logic
├── Limits.cpp/.h           # Limit switch handling
├── Machine.h               # Active machine selection
├── MachineCommon.h         # Shared machine definitions
├── MotionControl.cpp/.h    # High-level motion commands
├── NutsBolts.cpp/.h        # Utility functions
├── Pins.cpp/.h             # GPIO pin abstraction
├── Planner.cpp/.h          # Motion planner (look-ahead buffer)
├── Protocol.cpp/.h         # Main communication protocol loop
├── Regex.cpp/.h            # Simple regex utilities
├── Report.cpp/.h           # Status and response reporting
├── Settings.cpp/.h         # Settings init entry point
├── SettingsDefinitions.cpp/.h  # All $ settings definitions
├── Stepper.cpp/.h          # Stepper motor ISR and timing
├── System.cpp/.h           # System state and variables

📦 Commands/

Handles all GRBL $ commands sent by the user.

File Class Description
Command.h/.cpp Command Abstract base class for all GRBL commands. Extends Word.
GrblCommand.h/.cpp GrblCommand Represents a single $ command with name and handler function pointer. Registers itself in GRBLCommandsManager upon construction.
GRBLCommandsManager.h/.cpp GRBLCommandsManager Registers all commands (e.g. $H, $X, $J, $I, $CMD…) and routes incoming $ strings to the correct handler.

📦 Connection/

Abstraction layer for all communication interfaces (Serial, WiFi, Bluetooth).

File Class Description
Connection.h Connection Abstract base class — defines the interface all connection types must implement (Init, Read, Write, WriteFormatted, Push, ResetReadBuffer, etc.)
ConnectionManager.h/.cpp ConnectionManager Static manager that holds the active connection. Routes realtime commands and provides Active() to access the current connection from anywhere in the codebase.
InputBuffer/
InputBuffer.h/.cpp InputBuffer Heap-allocated ring buffer that stores incoming bytes before they are processed by the protocol loop. Thread-safe via FreeRTOS critical sections.
MessageSender/
MessageSender.h/.cpp MessageSender Sends [MSG:...] style feedback messages with configurable severity filtering.
EMessageLevel.h EMessageLevel Enum: None, Error, Warning, Info, Debug, Verbose
EFeedbackMessage.h EFeedbackMessage Enum of standard GRBL feedback messages (e.g. AlarmLock, ProgramEnd, SleepMode)
SerialConnection/
SerialConnection.h/.cpp SerialConnection Concrete final implementation of Connection for UART/Serial. Runs a FreeRTOS background task (clientCheckTask) to read incoming bytes into InputBuffer. TX is protected by a FreeRTOS mutex.

📦 Controller/

Controls all physical hardware attached to the machine.

Controller.h/.cpp — Controller

Top-level static controller class. Initializes and provides access to all sub-controllers: MotorsManager, BacklashManager, CoolantManager, Spindle, Probe, UserOutputsManager.


📁 Backlash/

File Class Description
BacklashManager.h/.cpp BacklashManager Compensates for mechanical backlash on each axis by injecting extra steps when direction changes.

📁 Coolant/

File Class Description
Coolant.h/.cpp Coolant Represents a single coolant output (Flood or Mist) with configurable turn-on delay and optional pin inversion.
CoolantManager.h/.cpp CoolantManager Controls both coolant outputs; handles M7/M8/M9 G-code commands.

📁 Motors/

File Class Description
Motor.h/.cpp Motor Abstract base class for a single axis motor driver. Stores fAxisIndex and fDualAxisIndex.
MotorsManager.h/.cpp MotorsManager Manages all axis motors (up to MAX_AXES × MAX_GANGED). Handles step/direction/disable signals for each axis.
MotorsByType/ Concrete motor driver implementations:
NullMotor.h/.cpp NullMotor No-op motor — used when an axis has no physical motor.
Stepper_RMT.h/.cpp Stepper_RMT Hardware stepper using the ESP32 RMT peripheral for precise, jitter-free step pulses (up to 120 kHz).
Stepper_Software.h/.cpp Stepper_Software Software stepper using digitalWrite — for lower-speed axes or testing.

📁 Probe/

File Class Description
Probe.h/.cpp Probe Reads the probe pin state and manages probe touch detection for tool length and surface probing. Called from the Stepper ISR via StateMonitor().

📁 Spindles/

Polymorphic spindle system — the active spindle type is selected at runtime via $ setting (settings_spindle_type).

File Class Description
ESpindleType.h ESpindleType Enum of supported spindle types: PWM, RELAY, BESC, LASER, NONE
Spindle.h/.cpp Spindle Abstract base class for all spindle types. Contains common pin resolution and RPM/delay setup in Initialize(). Static Select() creates the correct instance.
Spindle_PWM.h/.cpp Spindle_PWM PWM-controlled spindle (e.g. VFD or ESC via analog signal).
Spindle_Relay.h/.cpp Spindle_Relay On/Off relay-controlled spindle with CW/CCW direction support and safe spin-down on direction change.
Spindle_BESC.h/.cpp Spindle_BESC Brushless ESC spindle (servo-style PWM).
Spindle_Laser.h/.cpp Spindle_Laser Laser module controlled via PWM power.
Spindle_Null.h/.cpp Spindle_Null No-op spindle — used when no spindle is configured.

📁 UserOutputs/

File Class Description
UserOutputBase.h UserOutputBase Abstract base class for user-defined outputs.
DigitalOutput.h/.cpp DigitalOutput A single digital (ON/OFF) GPIO output.
AnalogOutput.h/.cpp AnalogOutput A single analog (PWM) GPIO output.
UserOutputsManager.h/.cpp UserOutputsManager Manages up to 4 digital and 4 analog user outputs. Responds to M62/M63/M67 G-code commands.

📦 Core/

File Description
ERabbitGRBLItemType.h Enum that classifies item types within the RabbitGRBL system: SETTING (classic $100 style), EXTENDED_SETTING, COMMAND. Used for settings and command categorization.

📦 CoordinatesManager/

Management of work coordinate systems.

File Class Description
CoordinatesManager.h/.cpp CoordinatesManager Initializes and manages all work coordinate system offsets (G54–G59). Delegates persistence to NVSManager.

📦 Diagnostics/

Centralized error and alarm reporting.

📁 Alarms/

File Class Description
EAlarm.h EAlarm Enum of all GRBL alarm codes (e.g. HardLimit, SoftLimit, HomingFailApproach, SpindleControl).
AlarmsManager.h/.cpp AlarmsManager Sends ALARM:N messages to the client. Maintains a std::map of alarm descriptions. Provides $A alarm listing.

📁 Errors/

File Class Description
EError.h EError Enum of all GRBL error codes (e.g. BadNumberFormat, SoftLimitError, NvsSetFailed, InvalidValue).
ErrorsManager.h/.cpp ErrorsManager Sends error:N messages. Maintains a std::map of error descriptions. Provides $E error listing.

📦 Machines/

Machine profile definitions. Each .h file is a self-contained configuration for a specific machine. The active profile is selected in Machine.h.

📁 CNCMachines/SourceRabbit/

Pre-configured profiles for SourceRabbit CNC machines:

File Machine
Quantum.h Quantum 4-Axis CNC
MicroMill.h Micro Mill 4-Axis
VM1.h VM1 4-Axis
RabbitMill_Neo.h Rabbit Mill Neo
RabbitBeam.h Rabbit Beam (Laser)
RabbitMillMega_300x600x100.h Rabbit Mill Mega 300×600×100
RabbitMillMega_400x800x100.h Rabbit Mill Mega 400×800×100

📁 CNCMachines/Other/

File Machine
zx7045_4axis.h ZX7045 4-Axis Mill

📁 MotionControllers/SourceRabbit/

Generic motion controller board profiles (not tied to a specific CNC machine):

File Board
rabbit_board_4axis_1_2.h SourceRabbit 4-Axis Board v1.2

📁 MotionControllers/Other/

File Board
espduino_cnc_shieldv3.h ESPDuino-32 + Protoneer CNC Shield v3

📦 NVS/

ESP32 Non-Volatile Storage — persistent settings saved to flash.

File Class Description
NVSManager.h/.cpp NVSManager Wraps the ESP-IDF NVS API under the "Ra_GRBL" namespace. Provides typed read/write/erase methods (WriteInt, WriteFloat, WriteString, WriteBlob, ReadInt, etc.). All NVS access in the system must go through this class.

📦 Settings/

A typed settings system. Each setting has a key, type, default value, min/max, and is stored in NVS.

File Class Description
Word.h/.cpp Word Base class for all named items (settings and commands). Stores GRBL name, full name, description, and ERabbitGRBLItemType.
Setting.h/.cpp Setting Abstract base class for all setting types. Maintains a linked list of all registered settings (Setting::List).
IntSetting.h/.cpp IntSetting Integer setting (e.g. $0 step pulse).
FloatSetting.h/.cpp FloatSetting Float setting (e.g. $110 max rate).
FlagSetting.h/.cpp FlagSetting Boolean on/off setting. Stored as int8 in NVS.
EnumSetting.h/.cpp EnumSetting Setting with a fixed set of named values (enum_opt_t map). Accepts both string name and numeric value.
AxisMaskSetting.h/.cpp AxisMaskSetting Bitmask setting for axis combinations.
StringSetting.h/.cpp StringSetting Text string setting.
FakeSetting.h FakeSetting Placeholder setting — accepts writes but does nothing (for backward compatibility).
AxisSettings.h/.cpp AxisSettings Groups per-axis settings: steps_per_mm, max_rate, acceleration, max_travel, backlash, etc.
Coordinates.h/.cpp Coordinates Stores work coordinate system offsets (G54–G59) as blobs in NVS.
Word.h/.cpp Word Wraps a single settings keyword string.
Settings.h/.cpp Settings Entry point — all setting class implementations have been moved to their respective individual source files.
SettingsManager.h/.cpp SettingsManager Handles $ read/write commands, iterates all registered settings, saves/loads from NVS. Includes MakeSettings(), LoadSettings(), ShowSetting(), NormalizeKey(), and all Report* / List* methods.

📄 Root-Level Files

File Description
Config.h Global compile-time constants (buffer sizes, baud rate, axis count, etc.).
Defaults.h Default values for all $ settings — overridden by machine profiles.
Machine.h Selects the active machine profile by #include-ing the correct .h from Machines/.
MachineCommon.h Shared macro definitions used across all machine profiles.
Exec.h Bit-field flags for realtime execution state (cycle start, feed hold, reset, etc.).
Grbl.h/.cpp Master include file and system initialization. grbl_init() bootstraps all subsystems. run_once() resets state and starts the main loop.
GCode.h/.cpp Full G-code parser — interprets G/M/F/S/T words and dispatches to motion/spindle/coolant. Includes canned cycles (G73, G81, G83).
MotionControl.h/.cpp High-level motion API (mc_line, mc_arc, mc_homing_cycle, mc_reset, etc.).
Planner.h/.cpp Look-ahead motion planner — calculates junction velocities and manages the block buffer.
Stepper.h/.cpp Low-level stepper ISR — generates step pulses with precise timing using ESP32 hardware timers.
Protocol.h/.cpp Main loop — reads characters from the active connection, dispatches G-code lines and realtime commands via protocol_main_loop().
Limits.h/.cpp Limit switch ISR and homing cycle logic.
Jog.h/.cpp Handles $J= jog commands.
Report.h/.cpp Formats and sends status reports (<Idle|MPos:…>), ok, error:N, and [MSG:…].
System.h/.cpp System state struct (sys), state machine transitions, and global system variables.
NutsBolts.h/.cpp General-purpose utility functions (string parsing, delay, bit manipulation).
SettingsDefinitions.h/.cpp Instantiates all $ settings objects and registers them with SettingsManager.
Settings.h/.cpp Settings subsystem entry point.
Pins.h/.cpp GPIO abstraction helpers.
Regex.h/.cpp Minimal regex matching used in settings key parsing (via cmp_str).

Clone this wiki locally