Skip to content

Source Code Structure

Nikos Siatras edited this page Mar 15, 2026 · 4 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, Bluetooth)
├── 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. Stores type, name, description and an optional checker function pointer.
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, $EA, $EE…) and routes incoming $ strings to the correct handler. Maintains a std::vector<GrblCommand*> list.

📦 Connection/

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

File Class Description
Connection.h Connection Abstract base class — defines the interface all connection types must implement (Init, Read, Write, WriteFormatted, Push, ResetReadBuffer, GetRxBufferAvailable, 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. Selects Serial or Bluetooth at init time based on ENABLE_BLUETOOTH define.
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.
BluetoothConnection/
BluetoothConnection.h/.cpp BluetoothConnection Concrete final implementation of Connection for Bluetooth SPP (Serial Port Profile). Enabled via #define ENABLE_BLUETOOTH. Device name is set via BT_DEVICE_NAME in the machine config. Runs a FreeRTOS background task (btClientCheckTask). TX is protected by a FreeRTOS mutex. Experimental.

📦 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. The concrete stepper implementation (Stepper_RMT, Stepper_Software, or Stepper_I2S) is selected at compile time.
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. Default implementation.
Stepper_Software.h/.cpp Stepper_Software Software stepper using digitalWrite — for lower-speed axes or testing. Enabled via USE_SOFTWARE_STEPS.
Stepper_I2S.h/.cpp Stepper_I2S I2S-based stepper — uses the ESP32 I2S peripheral as a 32-bit shift register to drive virtual step/dir/disable pins. Enabled via USE_I2S_STEPS.

📁 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: NONE, PWM, RELAY, LASER, BESC
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, 50 Hz). Extends Spindle_PWM.
Spindle_Laser.h/.cpp Spindle_Laser Laser module controlled via PWM power. Extends Spindle_PWM. No spin-up/spin-down delays.
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. Stores logical output number and MCU GPIO pin.
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 Static manager responsible for all Work Coordinate Systems (G54–G59) and reference positions (G28/G30). Provides getCoordinates(ECoordinatesIndex index) for typed access. Delegates persistence to NVSManager.
ECoordinatesIndex.h ECoordinatesIndex Enum indexing all coordinate entries (G54–G59, G28, G30).

📦 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::vector<Diagnostic> of alarm descriptions. Provides $EA 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::vector<Diagnostic> of error descriptions. Provides $EE 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

📁 CNCMachines/Genmitsu/

File Machine
3030_prover_rabbit_board_4axis_1_2.h Genmitsu 3030 ProVer (Serial)
3030_prover_rabbit_board_4axis_1_2_bluetooth.h Genmitsu 3030 ProVer (Bluetooth SPP)

📁 MotionControllers/SourceRabbit/

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

File Board
4axis_cnc_motherboard_1_3.h SourceRabbit 4-Axis CNC Motherboard v1.3 (active default)
rabbit_board_4axis_1_2.h SourceRabbit Rabbit Board 4-Axis v1.2

📁 MotionControllers/SourceRabbit/Deprecated/

Older board profiles kept for reference only — not actively used:

File Board
4axis_cnc_motherboard_1_2.h SourceRabbit 4-Axis CNC Motherboard v1.2
4axis_cnc_motherboard_compact_1_1.h SourceRabbit 4-Axis CNC Motherboard Compact v1.1
4axis_cnc_motherboard_compact_1_1_cloned_y.h SourceRabbit 4-Axis CNC Motherboard Compact v1.1 (Cloned Y)

📁 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, WriteInt8, 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. Extends Word. Maintains a linked list of all registered settings (Setting::List). Derives NVS key names using Knuth's hash for names > 15 chars.
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.
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 (SPI pins, ESP32 timer clock, step mask).
Exec.h Bit-field flags for realtime execution state (ExecStateBits, ExecAccessoryBits unions).
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, float reading, delay, bit manipulation).
SettingsDefinitions.h/.cpp Instantiates all $ settings objects and registers them with SettingsManager.
Settings.h/.cpp Settings subsystem entry point. All setting class implementations live in Settings/.
Pins.h/.cpp GPIO abstraction helpers.
Regex.h/.cpp Minimal regex matching used in settings key parsing (via cmp_str).

Clone this wiki locally