"""NC Error codes.

:author: Teemu Vartiainen <teemu@vartiainen.eu>
:license: MIT, see license file or https://opensource.org/licenses/MIT
:created on: 2025-12-16 15:39:24

"""

# https://github.com/stlehmann/pyads/issues/457
# General NC error codes (system-wide, internal, memory, parameter, etc.)
GENERAL_ERRORS = {
    16384: "Internal error - Internal system error in the NC on ring 0, no further details.",
    16385: "Memory error - The ring-0 memory management is not providing the required memory.",
    16386: "NC retain data error (persistent data) - Error loading NC Retain data; affected axes unreferenced (Homed=FALSE).",
    16387: "Parameter for monitoring the NC setpoint output is invalid - Cyclic monitoring enable/disable parameter invalid.",
    16388: "External error - Error code set by an external/third-party module or external module has an error.",
    16400: "Channel identifier not allowed - Value not 1..255 or channel does not exist.",
    16401: "Group identifier not allowed - Value not 1..255 or group does not exist.",
    16402: "Axis identifier not allowed - Value not 1..255 or axis does not exist.",
    16403: "Encoder identifier not allowed - Value not 1..255 or encoder does not exist.",
    16404: "Controller identifier not allowed - Value not 1..255 or controller does not exist.",
    16405: "Drive identifier not allowed - Value not 1..255 or drive does not exist.",
    16406: "Table identifier not allowed - Value not 1..255 or table does not exist.",
    16416: "Missing process image - No PLC-axis interface when creating an axis.",
    16417: "Missing process image - No axis-PLC interface when creating an axis.",
    16418: "Missing process image - No encoder-I/O interface when creating an axis.",
    16419: "Missing process image - No I/O-encoder interface when creating an axis.",
    16420: "Missing process image - No drive-I/O interface when creating an axis.",
    16421: "Missing process image - No I/O-drive interface when creating an axis.",
    16432: "Coupling type not allowed - Master/slave coupling type is not allowed.",
    16433: "Axis type not allowed - Type specification in axis generation is inadmissible.",
    16434: "Unknown channel type - NC channel type unknown (e.g. NCI, FIFO, etc.).",
    16448: "Axis is incompatible - Axis not suitable for intended purpose (e.g. rapid/slow traverse cannot be slave).",
    16464: "Channel not ready to operate - Channel incomplete; usually startup problems.",
    16465: "Group not ready to operate - Group incomplete; usually startup problems.",
    16466: "Axis not ready to operate - Axis incomplete; usually startup problems.",
    16480: "Channel exists - Channel to be created already exists.",
    16481: "Group exists - Group to be created already exists.",
    16482: "Axis exists - Axis to be created already exists.",
    16483: "Table exists - Table already exists / table id already in use internally.",
    16496: "Axis index not allowed - Invalid axis location within the channel.",
    16497: "Axis index not allowed - Invalid axis location within the group.",
}

# NC channel-related error codes
CHANNEL_ERRORS = {
    16641: "Group index not allowed - Location within the channel for a group is not allowed.",
    16642: "Null pointer - Pointer to the group is invalid (usually after startup error).",
    16643: "Missing process image - Data exchange with PLC not possible (no interface/interpreter or PLC connection faulty).",
    16644: "M-function index not allowed - Unacceptable M-function (not 0..159) at execution level.",
    16645: "No memory - No more system memory available (usually result of another error).",
    16646: "Not ready - Function not available because a similar function is being processed (access conflict).",
    16647: "Function/command not supported - Requested function/command not supported by the channel.",
    16648: "Invalid parameter while starting - TwinCAT-Start channel parameters invalid (e.g. memory size/channel type).",
    16649: "Channel function/command is not executable - Channel busy, no program loaded, or error state.",
    16650: "ItpGoAhead not executable - Interpreter is not executing a decoder stop.",
    16656: "Error opening a file - Specified file does not exist (e.g. NC program unknown).",
    16657: "Syntax error during loading - Syntax error found while loading NC program.",
    16658: "Syntax error during interpretation - Syntax error found while executing NC program.",
    16659: "Missing subroutine - Missing subroutine detected while loading.",
    16660: "Loading buffer of interpreter is too small - Interpreter loading buffer capacity exceeded.",
    16661: "Symbolism - Reserved, currently not used.",
    16662: "Symbolism - Reserved, currently not used.",
    16663: "Subroutine incomplete - Subroutine header is missing.",
    16664: "Error while loading the NC program - Maximum number of loadable NC programs reached.",
    16665: "Error while loading the NC program - Program name is too long.",
    16672: "Divide by Zero - Computation error during execution (division by 0).",
    16673: "Invalid circle parameterization - Specified circle is not calculable.",
    16674: "Invalid FPU-Operation - Invalid FPU operation (e.g. sqrt of negative number).",
    16688: "Stack overflow: Subroutines - Too many subroutine levels.",
    16689: "Stack underflow: Subroutines - Too many subroutine return commands (main must not end with return).",
    16690: "Stack overflow: Arithmetic unit - Calculation too complex or not written correctly.",
    16691: "Stack underflow: Arithmetic unit - Calculation too complex or not written correctly.",
    16704: "Register index not allowed - Invalid register index (not R0..R999) or pointer register invalid.",
    16705: "G-function index not allowed - Unacceptable G-function (not 0..159) during execution.",
    16706: "M-function index not allowed - Unacceptable M-function (not 0..159) during execution.",
    16707: "Extended address specification not allowed - Unacceptable extended address (not 1..9) during execution.",
    16708: "Index to the internal H-function not allowed - Unacceptable internal H-function (usually load error).",
    16709: "Machine data value not allowed - Impermissible MDB value (not 0..7).",
    16720: "Tool compensation parameters cannot be changed here - Unacceptable tool compensation parameter change during execution.",
    16721: "Cannot calculate tool compensation - Error calculating tool compensation.",
    16722: "Tool compensation - Plane for tool compensation cannot be changed here (while compensation active).",
    16723: "Tool compensation - D-word missing or invalid when turning on tool compensation.",
    16724: "Tool compensation - Tool radius invalid (<= 0).",
    16725: "Tool compensation - Tool radius cannot be changed here.",
    16726: "Tool compensation - Collision Detection Table is full.",
    16727: "Tool compensation - Internal error when switching on bottleneck detection.",
    16728: "Tool compensation - Bottleneck detection internal error (Update Reversed Geo failed).",
    16729: "Tool compensation - Unexpected geometry combination with bottleneck detection on.",
    16730: "Tool compensation - Inner circle smaller than cutter radius.",
    16731: "Tool compensation - Bottleneck detection recognized a contour violation.",
    16732: "No memory - Table for corrected entries is full.",
    16733: "No memory - Input table for tangential following is full.",
    16734: "No memory - Executing table for tangential following is full.",
    16735: "Geometry calculation - Geometric entry for tangential following cannot be calculated.",
    16736: "Reserved - Reserved, currently not used.",
    16737: "Reserved - Reserved, currently not used.",
    16738: "Interpolation rules can not be determined - Active interpolation rules/offset shifts/rotation cannot be detected.",
    16752: "Error loading: invalid parameter - Invalid parameter found while loading NC program.",
    16753: "Invalid contour start position - Contour not calculable because start position is not on contour.",
    16754: "Reverse: invalid table index - Invalid internal entry index during retrace execution.",
    16755: "Invalid G code - Invalid default G code (wrong expression/syntax).",
    16756: "Error opening the G code file - Error opening the default G code file.",
}

# NC group-related error codes
GROUP_ERRORS = {
    16896: "Group ID not allowed - Group ID already used, <=0, or >255.",
    16897: "Group type not allowed - Group type value undefined.",
    16898: "Master axis index not allowed - Invalid master axis index in interpolating 3D group.",
    16899: "Slave axis index not allowed - Invalid/occupied slave index or no slave present when removing.",
    16900: "Internal error - Unexpected internal error (often see Windows Event Viewer for details).",
    16901: "Cycle time for set execution task (SEC) not allowed - Outside valid range.",
    16902: "GROUPERR_RANGE_MAXELEMENTSINAXIS - Range parameter invalid (max elements in axis).",
    16903: "Cycle time for set preparation task (SPP) not allowed - Outside valid range.",
    16904: "Single step mode not allowed - Activation flag invalid.",
    16905: "Group (de)activation invalid - Activation flag invalid (internal error).",
    16906: "Set execution state not allowed - SEC state outside range / state machine error.",
    16907: "Channel address - Group has no channel or channel address not initialized.",
    16908: "Axis address (master axis) - No master axis or axis address not initialized.",
    16909: "Master axis address - No valid address for leading master axis (coupling insert).",
    16910: "Slave axis address - No valid address for slave axis (coupling insert).",
    16911: "Slave setpoint generator address - No valid address for slave setpoint generator.",
    16912: "Encoder address - Axis has no encoder or encoder address not initialized.",
    16913: "Controller address - Axis has no controller or controller address not initialized.",
    16914: "Drive address - Axis has no drive or drive address not initialized.",
    16915: "Master setpoint generator address - Missing/uninitialized (may be low memory).",
    16916: "Axis interface NC to PLC address - Missing/uninitialized NC->PLC axis interface.",
    16917: "Slave axis address - No valid slave axis address (coupling removal).",
    16918: "Table unknown - Table ID unknown (coupling/characteristic curve).",
    16919: "NcControl address - Not initialized.",
    16920: "Command lock - Persistent NC data waiting; axis blocked until valid I/O data.",
    16921: "MASTER-AUTOOFFSET invalid - No reference table found / reference not unique.",
    16922: "Master start position prevents synchronization - Cannot synchronize at given sync positions.",
    16923: "Slave coupling factor 0.0 not allowed - Gear ratio 0 causes invalid coupling/FPU exception.",
    16924: "Insert master axis not allowed - Slot occupied or reconfig blocked by existing slave coupling.",
    16925: "Delete master axis not allowed - No master axis at that location (internal error).",
    16926: "Not supported by setpoint generator - Feature not supported (general or situational).",
    16927: "Group initialization incomplete - Group created but init steps not completed.",
    16928: "Group not ready for new task - New task requested while previous task executing.",
    16929: "Requested target velocity not allowed - <=0, >max, or (servo) >reference velocity.",
    16930: "Requested target position not allowed (master) - Outside software end positions (if monitoring active).",
    16931: "No enable for controller/feed (master) - Required enables missing (controller/feed enable).",
    16932: "Travel path smaller than one encoder increment - Movement too small (internal/info).",
    16933: "Drive hardware not ready at axis start - Drive error/startup phase/enable missing.",
    16934: "Emergency stop parameters invalid - Decel/jerk <0 or weaker than start data.",
    16935: "Setpoint generator not active - Generator inactive; instructions not accepted.",
    16936: "Requested travel path/looping distance not allowed - Smaller than braking distance (rapid/slow axis).",
    16937: "Requested target position not allowed (slave) - Calculated slave target outside software end positions.",
    16938: "No enable for controller/feed (slave) - Required enables missing for one/more slave axes.",
    16939: "Activation position out of range - Threshold before actual pos or behind target pos.",
    16940: "External setpoint start/activation data invalid - Conflicting start type or incompatible generators.",
    16941: "Velocity not constant - Dynamics change requires constant velocity state.",
    16942: "Jerk <= 0.0 not allowed - Must be positive; 0 causes FPU exception.",
    16943: "Acceleration <= 0.0 not allowed - Must be positive; 0 yields no motion.",
    16944: "Abs deceleration <= 0.0 not allowed - Must be positive; 0 yields no motion.",
    16945: "Target velocity <= 0.0 not allowed - Must be >0 (and within valid numeric range).",
    16946: "Loss of precision for requested positioning - Very long motion causes resolution loss.",
    16947: "Cycle time <= 0.0 not allowed - Must be positive; 0 causes FPU exception.",
    16948: "PTP <intasdouble> range exceeded - Extreme params cause internal precision loss.",
    16949: "PTP LHL profile cannot be generated - Extreme params prevent LHL profile (internal error).",
    16950: "PTP HML profile cannot be generated - Extreme params prevent HML profile (internal error).",
    16951: "Start data address invalid - Start data pointer/address invalid.",
    16952: "Velocity override not allowed - <0% or >100% (0..1000000 in PlcToNc scaling).",
    16953: "Start type not allowed - Start type does not exist.",
    16954: "Velocity overshoot - Dynamics (jerk) too weak; overshoot imminent; command refused.",
    16955: "Start parameter invalid - Start structure params invalid (e.g. scaling/SEC/velocity <=0).",
    16956: "Override generator init parameter invalid - (Re)initialization parameter invalid.",
    16957: "Slave axis has no setpoint generator - Slave axis missing slave generator (internal error).",
    16958: "Table is empty - SPP or SEC table contains no entries.",
    16959: "Table is full - SPP or SEC table has no free lines.",
    16960: "No memory available - SEC dynamic entry allocation failed (SPP memory alloc).",
    16961: "Table already contains an entry - SEC entry canceled because entry already exists (internal error).",
    16962: "Stop already active - Stop instruction not forwarded (already active).",
    16963: "Compensation not over full section - Will compensate only over a smaller section.",
    16964: "Compensation parameters invalid - Invalid internal/start parameters (internal error).",
    16965: "Compensation active - Start refused (already active or axes not moving).",
    16966: "Compensation not active - Stop refused (not active).",
    16967: "Compensation type invalid - Only type 1 (trapezoidal profile) supported.",
    16968: "Axis address for compensation invalid - Master/slave address invalid (internal error).",
    16969: "Invalid slave address - Online coupling/uncoupling slave address invalid (internal error).",
    16970: "Coupling velocities not allowed - Master velocity is 0; online coupling impossible.",
    16971: "Coupling velocities not constant - Master/slave velocities not constant; online coupling impossible.",
    16972: "Cycle time <= 0.0 not allowed (slave) - Must be positive; 0 causes FPU exception.",
    16973: "Decoupling task not allowed - Slave type/state prevents online decoupling.",
    16974: "Function not allowed - Command logically not executable (e.g. slave restrictions).",
    16975: "No valid table weighting - All table weights 0; no table can be read.",
    16976: "Start/actual/end position type not allowed - Invalid start/position type(s) for command.",
    16977: "Function not supported - Function not released/implemented or not allowed for masters.",
    16978: "State machine invalid - Internal state machine state invalid (internal error).",
    16979: "PLC reference cam became free too soon - Cam must stay active until move-off sequence.",
    16980: "Distance monitoring latch->sync pulse - Increments too small; error when monitoring active.",
    16981: "No memory available - Dynamic allocation for generator/SPP/SEC failed.",
    16982: "Table slave has no active table - None of slave tables marked active; runtime stops group.",
    16983: "Function not allowed - Task/function not logically allowed (e.g. set pos for absolute encoder).",
    16984: "Stopping compensation not allowed - Already in stopping phase.",
    16985: "Slave table is being used - Cannot activate table because it is in use.",
    16986: "Coupling requested while job active - Certain coupling types require standstill; refused.",
    16987: "Slave start parameter incorrect - Invalid slave/coupling params (e.g. factor 0).",
    16988: "Slave type incorrect - Slave type does not match (SPP) start type.",
    16989: "Axis stop already active - Stop/Estop not initiated (already active).",
    16990: "Max number of tables per slave generator reached - Limit reached (e.g. MC_MultiCamIn=4).",
    16991: "Scaling mode not allowed - Mode undefined/unimplemented/invalid in this constellation.",
    16992: "Controller enable missing - Enable withdrawn during motion or start without enable.",
    16993: "Table not found - Table ID does not exist or not unique.",
    16994: "Incorrect table type - Referred table has wrong type.",
    16995: "Single step mode - New task requested while single-step task still processing.",
    16996: "Group task unknown - Task type/subtype unknown (asynchronous table entry).",
    16997: "Group function unknown - Function type unknown (synchronous function).",
    16998: "Group task for slave not allowed - Tasks generally only for masters (unless explicitly allowed).",
    16999: "Group function for slave not allowed - Functions only for masters (except section compensation).",
    17000: "NCI setpoint generator inactive - NCI command sent to inactive DXD group/override=0.",
    17001: "Start position equals target position - Invalid position parameters.",
    17002: "Delay-generator parameters invalid - Invalid delay time/cycle time/tics.",
    17003: "External compensation parameters invalid - Invalid dynamics/process params for superimposed function.",
    17004: "Invalid override type - Selected override type invalid.",
    17005: "Activation position under/overrun - Activation position lies in the past of the master.",
    17006: "Activation impossible: master at standstill - Master not moving; accurate sync not possible.",
    17007: "Activation mode not possible - Not possible while slave is moving (would force velocity jump).",
    17008: "Compensation start parameter invalid - One dynamic param invalid (acc/dec/process velo >0).",
    17009: "Compensation start parameter invalid - Velocity overshoot is negative.",
    17010: "Compensation start parameter invalid - Compensation section length not positive.",
    17011: "Target position under/overrun (internal) - Oriented stop end position already overrun.",
    17012: "Target position will be under/overrun (internal) - Oriented stop end position too close; will overrun.",
    17013: "Group parameter invalid - E.g. velo/acc/dec/jerk/cycle time <=0.",
    17014: "Group error at start of setpoint generation - Invalid dynamics/NC cycle/override at startup.",
    17015: "Dynamic parameters not permitted (internal) - Internally calculated dynamics invalid.",
    17017: "New target position invalid/unreachable - Already passed or will be passed during stop.",
    17018: "New travel/final velocity invalid - Travel velo >0; final velo >=0 required.",
    17019: "New final velocity or target position invalid - Final velo >=0 required; position invalid.",
    17020: "New travel velocity invalid - <=0 or otherwise not allowed.",
    17021: "Internal start mode invalid - Start mode invalid/not allowed (user cannot set directly).",
    17022: "Movement could not be realized (BISECTION) - Executed best possible; warning.",
    17023: "New target position overrun/will be overrun - Internal stop commanded.",
    17024: "Group not ready for new task (internal/info) - New task requested while executing.",
    17025: "Oriented stop parameters not allowed - Modulo target outside [0,period).",
    17026: "Modulo-start target invalid - Modulo target outside valid range.",
    17027: "Activation mode not allowed - Mode invalid/unimplemented or blocked by running job.",
    17028: "Jerk rate not allowed - Below minimum jerk rate (min 1.0).",
    17029: "Acceleration/deceleration not permitted - Below minimum based on jerk & cycle time.",
    17030: "Velocity not permitted - Below minimum based on jerk & cycle time (0 allowed).",
    17031: "Activation cannot execute due to pending activation - Only one activation can be pending.",
    17032: "Illegal combination of different cycle times in group - Detected different cycle times.",
    17033: "Invalid axis motion reversal - Would cause reversal; command refused and state restored.",
    17034: "Illegal command timing - Another command with future activation position still active.",
    17035: "Stop-calculation routine internal error - Command cannot be performed; state restored.",
    17036: "Activation-position command only partially possible - Remaining path too short to threshold.",
    17037: "Invalid decouple type - Invalid decouple/restart type.",
    17038: "Illegal target velocity when decoupling slave - Target velocity not in allowed range.",
    17039: "Activate new dynamics cannot be performed - Would require new travel velocity assignment.",
    17040: "Activation-position command not possible - Already braking; remaining path too short.",
    17041: "Decouple routine jerk scaling finds no valid solution - Would risk overshoot/reversal/overrun.",
    17042: "Command buffer full - Command rejected.",
    17043: "Look-ahead internal error - Command rejected.",
    17044: "New travel velocity cannot be implemented - Requested V not realizable; optimization impossible.",
    17045: "Successive commands have same end position - Travel path is zero.",
    17046: "Travel direction inconsistent with buffer command - Contradiction; command rejected.",
    17047: "Remaining distance too short in current segment - Command rejected (buffer/blending).",
    17050: "Restart failed - Restart modification of buffered motion command failed.",
    17051: "Invalid start parameters (group error) - User parameterization invalid (examples: dynamics, stepper params).",
    17052: "PLC referencing cam not found - Cam not detected; referencing aborted.",
    17053: "PLC referencing cam not released - Cam did not clear when moving off; referencing aborted.",
    17054: "I/O sync pulse not found (hardware latch) - Sync event missing; referencing aborted.",
    17055: "Buffer mode unknown/not supported - PTP buffer mode invalid in this context.",
    17056: "Group/axis consequential error - Follow-up error due to another axis error in group.",
    17057: "Velocity reduction factor for C0/C1 transition not allowed - Factor invalid.",
    17058: "Critical angle at segment transition not allowed - Angle outside valid range.",
    17059: "Tolerance sphere radius out of range - Radius outside permitted range.",
    17060: "Reserved - Currently not used.",
    17061: "Start type - Parameter (see docs; range shown as [0.1]).",
    17062: "Reserved - Currently not used.",
    17063: "Blending - Blending not possible with given parameters.",
    17064: "Reserved - Currently not used.",
    17065: "Curve velocity reduction method not allowed - Method does not exist (internal error).",
    17066: "Minimum velocity not allowed - Entered minimum velocity < 0.0.",
    17067: "Power function input not allowed - power_() params cause FPU exception (internal error).",
    17068: "Dynamic change parameter not allowed - Invalid dynamics-change parameterization.",
    17069: "Memory allocation error - Error during memory allocation (internal error).",
    17070: "End position internal error - Calculated end position differs from NC block end position.",
    17071: "Calculate remaining path length - Invalid value (expected 0/1).",
    17072: "Setpoint generator SPP active - Start refused because SPP task already active.",
    17073: "SPP parameter not allowed - Internal SPP params cause logical/FPU issues (internal error).",
    17074: "Velocity reduction factor not allowed - Invalid reduction params for segment transitions.",
    17075: "Helix is a circle - Helix degenerates; enter as circle.",
    17076: "Helix is a straight line - Helix degenerates; enter as line.",
    17077: "Guider parameter not allowed - Guider params cause logical/FPU issues.",
    17078: "Invalid segment address - Geometry/dynamic structure address invalid (internal error).",
    17079: "Not parameterized generator - SPP generator not parameterized (internal error).",
    17080: "Not parameterized table - Table missing address of corresponding dynamic generator (internal error).",
    17082: "Arc length of smoothed path internal error - Error calculating arc length.",
    17083: "Tolerance sphere radius too small - Smaller than 0.1 mm.",
    17084: "DXD software end positions internal error - Error calculating DXD software end positions.",
    17085: "NC block violates group software end positions - Geo entry denied due to limit switch violation.",
    17086: "Path axis violates end position - Active limit monitoring violated.",
    17087: "Invalid reference velocity type - Invalid reference velocity type.",
    17088: "Interpolating group has incorrect axis type - 3D group may only contain axis type 1 (SERVO).",
    17089: "Scalar product cannot be calculated - One vector length is 0.0.",
    17090: "Inverse cosine cannot be calculated - One vector length is 0.0.",
    17091: "Invalid table entry type - Table entry type unknown.",
    17092: "Invalid DIN66025 info type - Unknown DIN66025 type (internal error).",
    17093: "Invalid dimension - CNC dimension unknown/invalid for geometry (internal error).",
    17094: "Geometrical object is not a straight line - Length is 0.0.",
    17095: "Geometrical object is not a circle - Arc length/angle/radius is 0.0.",
    17096: "Geometrical object is not a helix - Arc length/angle/radius/height is 0.0.",
    17097: "Target velocity <= 0.0 invalid (CNC) - Must be >0; 0 cannot generate motion.",
    17098: "Look-ahead address invalid - Look-ahead address invalid (internal error).",
    17099: "Setpoint generator SEC active - Start refused because SEC task already active.",
    17100: "CNC setpoint generation not active - Stop/override denied; generation inactive.",
    17101: "CNC setpoint generation in stop phase - Stop/override denied; stop phase active.",
    17102: "Override not allowed - Override <0% or >100% invalid.",
    17103: "Invalid table address - Table init address invalid or logger connection missing (internal error).",
    17104: "Invalid table entry type - Table entry type unknown.",
    17105: "Memory allocation failed - Memory allocation for a table failed.",
    17106: "Memory allocation failed - Memory allocation for a filter failed.",
    17107: "Invalid parameter - Filter parameter not allowed.",
    17108: "Residual distance deletion not possible - Delete Distance to Go failed (only interpolation).",
    17109: "Flying saw generator incompatible values - Internal error.",
    17110: "Axis stopped to avoid target overrun (old PTP) - Internal stop to guarantee no overrun.",
    17111: "Internal error transforming slave to master - Internal error.",
    17112: "Wrong direction in slave-to-master transformation - Direction invalid.",
    17114: "Motion Function (MF) parameters incorrect - MF parameters invalid (initial or online change).",
    17115: "Motion Function (MF) parameters incorrect - MF parameters invalid (e.g. active point -> IGNORE point).",
    17116: "Internal error using Motion Function (MF) - Contact TwinCAT Support.",
    17117: "Sync generator coupling declined - Slave dynamic values invalid or sync velo > max.",
    17118: "Sync generator coupling conditions not allowed - Master sync position not in travel direction future.",
    17119: "Sync generator profile violates limits - Slave dynamic limits exceeded or profile property invalid.",
    17120: "Invalid parameter - Encoder generator parameter not allowed.",
    17121: "Invalid parameter - External (FIFO) generator parameter not allowed.",
    17122: "External generator active - Cannot start; already active.",
    17123: "External generator not active - Cannot stop; not active.",
    17124: "NC block (aux axis) violates software limits - Geo entry denied due to aux axis limit violation.",
    17125: "Bezier curve block contains singularity - Split with Casteljau algorithm to remove singularity.",
    17127: "Dead time compensation value not allowed - Slave coupling to encoder axis; outside range.",
    17128: "GROUPERR_RANGE_NOMOTIONWINDOW - Internal range error.",
    17129: "GROUPERR_RANGE_NOMOTIONFILTERTIME - Internal range error.",
    17130: "GROUPERR_RANGE_TIMEUNITFIFO - Internal range error.",
    17131: "GROUPERR_RANGE_OVERRIDETYPE - Internal range error.",
    17132: "GROUPERR_RANGE_OVERRIDECHANGETIME - Internal range error.",
    17133: "GROUPERR_FIFO_INVALIDDIMENSIO - FIFO dimension invalid (axes count).",
    17134: "GROUPERR_ADDR_FIFOTABLE - FIFO table address internal error.",
    17135: "Axis locked because stop still active - Release stop (Execute=FALSE) or reset axis.",
    17136: "Invalid number of auxiliary axes - Local count differs from global count.",
    17137: "Invalid reduction parameter for auxiliary axes - Reduction params inconsistent.",
    17138: "Invalid dynamic parameter for auxiliary axes - Dynamic params inconsistent.",
    17139: "Invalid coupling parameter for auxiliary axes - Coupling params inconsistent.",
    17140: "Invalid auxiliary axis entry - Entry empty (no axis motion).",
    17142: "Invalid parameter - Aux velocity reduction limit invalid (must be 0..1.0).",
    17144: "BlockSearch: segment not found - nBlockId not found until program end.",
    17145: "BlockSearch: invalid remaining segment length - fLength incorrectly parameterized.",
    17147: "Internal error with coupled axes (slave axes) - Inconsistent internal state; contact Support.",
    17148: "Max jobs to transfer invalid - Invalid max entries per NC cycle from SPP to SEC (range 1..20).",
    17151: "Customer-specific error - Customer-specific monitoring function.",
}

# NC axis-related error codes
AXIS_ERRORS = {
    17152: "Axis ID not allowed - Axis ID already used, <=0, >255, or not in current configuration.",
    17153: "Axis type not allowed - Axis type undefined (e.g. servo/fast-creep/stepper).",
    17158: "Slow manual velocity not allowed - Slow jog velocity outside allowed range.",
    17159: "Fast manual velocity not allowed - Fast jog velocity outside allowed range.",
    17160: "Rapid traverse velocity not allowed - Rapid traverse velocity outside allowed range.",
    17161: "Acceleration not allowed - Axis acceleration outside allowed range.",
    17162: "Deceleration not allowed - Axis deceleration outside allowed range.",
    17163: "Jerk not allowed - Axis jerk outside allowed range.",
    17164: "Dead time compensation delay not allowed - Delay time between position and velocity invalid.",
    17165: "Override type not allowed - Velocity override type invalid.",
    17166: "NCI Velo-Jump-Factor not allowed - VeloJumpFactor invalid (TwinCAT NCI).",
    17167: "NCI tolerance sphere radius invalid (aux axis) - Invalid tolerance sphere size for auxiliary axes.",
    17168: "NCI max deviation invalid (aux axis) - Invalid maximum allowed deviation for auxiliary axes.",
    17170: "Referencing velocity (cam direction) not allowed - Invalid referencing speed towards cam.",
    17171: "Referencing velocity (sync direction) not allowed - Invalid referencing speed towards sync pulse.",
    17172: "Pulse width + not allowed - Pulsed operation positive pulse width invalid.",
    17173: "Pulse width - not allowed - Pulsed operation negative pulse width invalid.",
    17174: "Pulse time + not allowed - Pulsed operation positive pulse time invalid.",
    17175: "Pulse time - not allowed - Pulsed operation negative pulse time invalid.",
    17176: "Creep distance + not allowed - Positive creep distance invalid.",
    17177: "Creep distance - not allowed - Negative creep distance invalid.",
    17178: "Braking distance + not allowed - Positive braking distance invalid.",
    17179: "Braking distance - not allowed - Negative braking distance invalid.",
    17180: "Deceleration time + not allowed - Positive deceleration time invalid.",
    17181: "Deceleration time - not allowed - Negative deceleration time invalid.",
    17182: "Switching time rapid->slow not allowed - Time to switch from rapid to slow traverse invalid.",
    17183: "Creep distance for stop not allowed - Creep distance for explicit stop invalid.",
    17184: "Motion monitoring not allowed - Motion monitoring enable flag invalid.",
    17185: "Position window monitoring not allowed - Position window monitoring enable flag invalid.",
    17186: "Target window monitoring not allowed - Target window monitoring enable flag invalid.",
    17187: "Loop not allowed - Loop movement enable flag invalid.",
    17188: "Motion monitoring time not allowed - Motion monitoring time invalid.",
    17189: "Target window range not allowed - Target window size invalid.",
    17190: "Position window range not allowed - Position window size invalid.",
    17191: "Position window monitoring time not allowed - Position window monitoring time invalid.",
    17192: "Looping distance not allowed - Looping distance invalid.",
    17193: "Axis cycle time not allowed - Axis cycle time outside allowed range.",
    17194: "Stepper operation mode not allowed - Stepper motor operating mode invalid.",
    17195: "Displacement per step not allowed - Step scaling (mm/step) invalid.",
    17196: "Stepper minimum velocity not allowed - Min velocity for stepper profile invalid.",
    17197: "Stepper stages per velocity level not allowed - Steps per velocity level invalid.",
    17198: "Axis units interpretation DWORD not allowed - Unit/flags DWORD invalid.",
    17199: "Maximum velocity not allowed - Max permitted velocity invalid.",
    17200: "Motion monitoring window not allowed - Motion monitoring window size invalid.",
    17201: "PEH time monitoring not allowed - PEH monitoring enable flag invalid.",
    17202: "PEH monitoring time not allowed - PEH timeout invalid.",
    17203: "Brake Release Delay invalid - Brake release delay parameter invalid.",
    17204: "NC Data Persistence invalid - Axis NC Data Persistence boolean invalid.",
    17205: "Error reaction mode invalid - Error reaction mode parameter invalid.",
    17206: "Error reaction delay invalid - Error reaction delay parameter invalid.",
    17207: "Use actual values in deactivated state invalid - Boolean parameter invalid.",
    17208: "Allow motion commands for slave axes invalid - Boolean parameter invalid.",
    17209: "Allow motion commands in external setpoint generation invalid - Boolean parameter invalid.",
    17210: "Fading Acceleration invalid - Fading acceleration parameter invalid.",
    17211: "Fast Axis Stop signal type not allowed - Signal type for Fast Axis Stop invalid (0..5).",
    17212: "ADS index offset not allowed - ADS offset (axis state) for UserData in AxisRef invalid.",
    17216: "Axis not initialized - Axis created but initialization steps not completed.",
    17217: "Group address missing - Axis has no group or group address not initialized.",
    17218: "Encoder address missing - Axis has no encoder or encoder address not initialized.",
    17219: "Controller address missing - Axis has no controller or controller address not initialized.",
    17220: "Drive address missing - Axis has no drive or drive address not initialized.",
    17221: "PLC->NC axis interface address missing - PlcToNc interface missing or not initialized.",
    17222: "NC->PLC axis interface address missing - NcToPlc interface missing or not initialized.",
    17223: "NC->PLC interface size not allowed - NcToPlc size invalid (internal error).",
    17224: "PLC->NC interface size not allowed - PlcToNc size invalid (internal error).",
    17238: "Controller enable missing - Controller enable not available (required for motion).",
    17239: "Feed enable minus missing - Negative direction feed enable not available.",
    17240: "Feed enable plus missing - Positive direction feed enable not available.",
    17241: "Target velocity not allowed - Requested target velocity invalid (<=0, >max, or >ref velo).",
    17242: "Movement < 1 encoder increment - Movement too small (handled internally; no user error).",
    17243: "Set acceleration monitoring - Set acceleration exceeded permitted acc/dec limits (internal error).",
    17244: "PEH time monitoring - Target position window not reached within PEH time.",
    17245: "Motion Monitoring - Actual position changed too little within monitoring time (blocked axis/encoder fault).",
    17246: "Looping distance <= braking distance - Looping distance not allowed (<= braking distance).",
    17247: "Starting velocity not allowed - Start velocity invalid (<=0, >max, or >ref velo).",
    17248: "Final velocity not allowed - Final velocity invalid (<=0, >max, or >ref velo).",
    17249: "Time range exceeded (future) - Calculated position too far in the future.",
    17250: "Time range exceeded (past) - Calculated position too far in the past.",
    17251: "Position cannot be determined - Position never reached in past or will never be reached in future.",
    17252: "Position indeterminable (conflicting direction of travel) - Expected travel direction conflicts with actual.",
    17253: "Monitoring - Position not convertible; converting to incremental position would exceed encoder range.",
    17264: "No slave coupling possible (velocity violation) - Coupling rejected to avoid exceeding slave max velocity.",
    17265: "No slave coupling possible (acceleration violation) - Coupling rejected to avoid exceeding slave max acceleration.",
    17312: "Axis consequential error - Consequential error due to another causative error on another axis.",
}

# TF5055 NC Flying Saw specific error codes
TF5055_ERRORS = {
    17266: "Sync profile would violate the lower end position of the slave (GearInSync_CheckMask_MinPos).",
    17267: "Sync profile would violate the upper end position of the slave (GearInSync_CheckMask_MaxPos).",
    17268: "Sync profile would violate the user limit Options.PositionLimitMin (GearInSync_CheckMask_OptionalMinPos).",
    17269: "Sync profile would violate the user limit Options.PositionLimitMax (GearInSync_CheckMask_OptionalMaxPos).",
    17270: "Sync point lies under start position; profile undershoots start and sync position (GearInSync_CheckMask_UndershootPos).",
    17271: "Sync profile would swing under the slave start position of the flying saw (GearInSync_CheckMask_UndershootPos).",
    17272: "Sync point lies under start position; profile overshoots slave start position (GearInSync_CheckMask_OvershootPos).",
    17273: "Sync profile would overshoot the slave synchronous position (GearInSync_CheckMask_OvershootPos).",
    17274: "Max velocity of sync profile exceeds max velocity of slave axis (GearInSync_CheckMask_MaxVelo, case A).",
    17275: "Max velocity of sync profile exceeds max velocity of slave axis (GearInSync_CheckMask_MaxVelo, case B).",
    17276: "Max sync profile velocity exceeds synchronous velocity (pos dir, start velo < sync velo) (GearInSync_CheckMask_OvershootVelo).",
    17277: "Max sync profile velocity exceeds start and sync velocity (pos dir, start velo > sync velo) (GearInSync_CheckMask_OvershootVelo).",
    17278: "Max sync profile velocity exceeds synchronous velocity (neg dir, start velo < sync velo) (GearInSync_CheckMask_OvershootVelo).",
    17279: "Max sync profile velocity exceeds start and sync velocity (neg dir, start velo > sync velo) (GearInSync_CheckMask_OvershootVelo).",
    17280: "Min sync profile velocity below synchronous velocity (pos dir, start velo > sync velo) (GearInSync_CheckMask_UndershootVelo).",
    17281: "Min sync profile velocity below start velocity (pos dir, start velo < sync velo) (GearInSync_CheckMask_UndershootVelo).",
    17282: "Min sync profile velocity below synchronous velocity (neg dir, start velo > sync velo) (GearInSync_CheckMask_UndershootVelo).",
    17283: "Min sync profile velocity below start velocity (neg dir, start velo < sync velo) (GearInSync_CheckMask_UndershootVelo).",
    17286: "Flying saw velocity drops below zero; motion reverses (master positive direction) (GearInSync_CheckMask_UndershootVeloZero).",
    17287: "Flying saw velocity drops below zero; motion reverses (master negative direction) (GearInSync_CheckMask_UndershootVeloZero).",
    17288: "Max acceleration of sync profile exceeds max acceleration of slave axis (GearInSync_CheckMask_MaxAcc).",
    17289: "Max deceleration of sync profile exceeds max deceleration of slave axis (GearInSync_CheckMask_MaxDec).",
    17290: "Max jerk of sync profile exceeds max jerk of slave axis (GearInSync_CheckMask_MaxJerk; check SlaveJerkMax).",
    17291: "Max jerk of sync profile exceeds max jerk of slave axis (GearInSync_CheckMask_MaxJerk; check SlaveJerkMin).",
}

# NC encoder-related error codes
ENCODER_ERRORS = {
    17408: "Encoder ID not allowed - Encoder ID already used, <=0, or >255.",
    17409: "Encoder type not allowed - Encoder type undefined.",
    17410: "Encoder mode invalid - Operation mode invalid (pos / pos+velo).",
    17411: "Encoder count direction invalid - Counting direction flag invalid.",
    17412: "Calibration state invalid - Referenced/unreferenced flag invalid.",
    17413: "Encoder increments per rotation not allowed - INC per physical rotation invalid.",
    17414: "Scaling factor not allowed - INC to physical unit scaling invalid.",
    17415: "Position offset not allowed - Zero-point offset invalid.",
    17416: "Modulo factor not allowed - Modulo factor invalid.",
    17417: "Position filter time not allowed - Actual position PT1 filter time invalid.",
    17418: "Velocity filter time not allowed - Actual velocity PT1 filter time invalid.",
    17419: "Acceleration filter time not allowed - Actual acceleration PT1 filter time invalid.",
    17420: "Cycle time not allowed - SEC cycle time for actual value calc invalid (internal error).",
    17421: "Selected units setting invalid - Modulo/velocity/etc unit settings invalid.",
    17422: "Actual position correction not allowed - Measuring system error correction enable flag invalid.",
    17423: "Filter time for actual position correction not allowed - Correction PT1 filter time invalid.",
    17424: "Search direction for referencing cam inverted invalid - Cam search direction flag invalid.",
    17425: "Search direction for sync pulse inverted invalid - Zero pulse search direction flag invalid.",
    17426: "Reference position not allowed - Reference position value invalid.",
    17427: "Distance monitoring latch->sync pulse invalid (obsolete) - Enable flag invalid.",
    17428: "Min gap latch->sync pulse invalid (obsolete) - Minimum increment gap invalid.",
    17429: "External sync pulse invalid (obsolete) - External sync pulse enable flag invalid.",
    17430: "Noise rate scaling not allowed - Simulation encoder noise scaling invalid.",
    17431: "Tolerance window for modulo-start invalid - Must be >=0 and < half modulo period.",
    17432: "Encoder referencing mode not allowed - Reference mode invalid/unsupported for encoder type.",
    17433: "Encoder evaluation direction not allowed - Logical counting direction invalid.",
    17434: "Encoder reference system invalid - 0 incremental / 1 absolute / 2 absolute+modulo.",
    17435: "Encoder position initialization mode invalid - Startup init mode invalid.",
    17436: "Encoder sign interpretation invalid - Data type UNSIGNED/SIGNED setting invalid.",
    17437: "Homing Sensor Source invalid - Homing sensor source invalid/unsupported for encoder type.",
    17440: "Software end position monitoring min not allowed - Enable flag invalid.",
    17441: "Software end position monitoring max not allowed - Enable flag invalid.",
    17442: "Set actual value out of range - New actual position outside expected range.",
    17443: "Software end position minimum not allowed - Min software limit invalid.",
    17444: "Software end position maximum not allowed - Max software limit invalid.",
    17445: "Filter mask for encoder raw value not allowed - Raw INC filter mask invalid.",
    17446: "Reference mask for encoder raw value not allowed - Raw INC reference/resolution mask invalid.",
    17447: "Dead time compensation mode invalid (encoder) - Mode invalid (OFF/velo/velo+acc).",
    17448: "Dead time compensation control bits invalid (encoder) - Control bits invalid.",
    17449: "Dead time compensation time shift invalid (encoder) - Time shift (ns) invalid.",
    17456: "Hardware latch activation - Latch already active and not yet valid; call refused.",
    17457: "External latch / touch probe activation - Already active/not yet valid or blocked by other function.",
    17458: "External hardware latch activation - Must not be called while latch valid from previous referencing.",
    17459: "External latch / touch probe activation - Previous activation not finished; renewed activation rejected.",
    17460: "Encoder function not supported - Function not released or not implemented.",
    17461: "Encoder function already active - Cannot activate because already active.",
    17472: "Encoder not initialized - Created but initialization steps not completed.",
    17473: "Axis address missing - Encoder has no axis or axis address not initialized.",
    17474: "I/O input structure address missing - No valid I/O input address in process image.",
    17475: "I/O output structure address missing - No valid I/O output address in process image.",
    17488: "Encoder counter underflow - Incremental counter underflow detected.",
    17489: "Encoder counter overflow - Incremental counter overflow detected.",
    17504: "Min software position limit (axis start) - Axis started below minimum software limit (monitoring active).",
    17505: "Max software position limit (axis start) - Axis started above maximum software limit (monitoring active).",
    17506: "Min software position limit (positioning) - Actual position fell below min software limit (monitoring active).",
    17507: "Max software position limit (positioning) - Actual position exceeded max software limit (monitoring active).",
    17508: "Encoder hardware error - Drive/encoder reports hardware error (see event log).",
    17509: "Position initialization error at startup - Initial actual position outside min/max in all init trials.",
    17510: "Invalid I/O data for >n NC cycles (encoder) - Invalid encoder I/O data over n SEC cycles (e.g. WcState).",
    17511: "Invalid actual position (encoder) - I/O device reports invalid actual position (e.g. TxPDO invalid).",
    17512: "Invalid I/O input data type 1 - Cyclic I/O input counter not updated for >=3 SEC cycles.",
    17513: "Invalid I/O input data type 2 - Cyclic I/O input counter quality insufficient (statistical threshold).",
    17520: "SSI transformation faulty/not finished - FOX 50 SSI transformation faulty for some NC cycles.",
    17570: "Internal error - ENCERR_ADDR_CONTROLLER.",
    17571: "Internal error - ENCERR_INVALID_CONTROLLERTYPE.",
}

# Controller-related NC errors
CONTROLLER_ERRORS = {
    17664: "Controller ID not allowed - ID already used, <=0, or >255.",
    17665: "Controller type not allowed - Undefined controller type.",
    17666: "Controller operation mode not allowed - Operating mode invalid.",
    17667: "Velocity pre-control weighting not allowed - Percentage weighting invalid.",
    17668: "Lag error monitor (position) not allowed - Enable flag invalid.",
    17669: "Lag error monitoring (velocity) not allowed - Enable flag invalid.",
    17670: "Lag error window (position) not allowed - Max permissible position lag invalid.",
    17671: "Lag error filter time (position) not allowed - Position lag filter time invalid.",
    17672: "Lag error window (velocity) not allowed - Max permissible velocity lag invalid.",
    17673: "Lag error filter time (velocity) not allowed - Velocity lag filter time invalid.",
    17674: "Controller output limitation not allowed - Total output limitation invalid.",

    17680: "Proportional gain Kv/Kp (position) not allowed - P gain invalid.",
    17681: "Integral action time Tn (position) not allowed - I time invalid.",
    17682: "Rate time Tv (position) not allowed - D time invalid.",
    17683: "Damping time Td (position) not allowed - D damping time invalid.",
    17684: "Automatic offset calibration not allowed - Only supported for controllers without I-part.",
    17685: "Additional proportional gain Kv/Kp not allowed - Secondary P gain invalid.",
    17686: "Reference velocity for additional proportional gain not allowed - Reference velocity percentage invalid.",
    17687: "Proportional gain Pa (acceleration) not allowed - Acceleration P gain invalid.",
    17688: "Proportional gain Kv (velocity) not allowed - Velocity P gain invalid.",
    17689: "Integral action time Tn (velocity) not allowed - Velocity I time invalid.",

    17690: "Reserved - Currently not used.",
    17691: "Reserved - Currently not used.",

    17692: "Velocity filter time not allowed - PT1 filter time invalid.",
    17693: "Dead range not allowed - Neutral zone for control deviation invalid.",
    17695: "Proportional gain Kcp not allowed - Slave coupling difference control gain invalid.",
    17696: "Rate time Tv (velocity) not allowed - Velocity D time invalid.",
    17697: "Damping time Td (velocity) not allowed - Velocity damping time invalid.",
    17698: "Limitation of I-part not allowed - I-part limitation percentage invalid.",
    17699: "Limitation of D-part not allowed - D-part limitation percentage invalid.",
    17700: "Deactivation of I-part during travel not allowed - Boolean parameter invalid.",
    17701: "Filter time for P-T2 filter not allowed - Filter time exceeds allowed relation to cycle time.",

    17702: "Velocity observer mode not allowed - Mode must be OFF or LUENBERGER.",
    17703: "Velocity observer motor torque constant invalid - Kt/Kf parameter invalid.",
    17704: "Velocity observer motor inertia invalid - JM parameter invalid.",
    17705: "Velocity observer bandwidth f0 invalid - Must satisfy f0 < 1/(6*T).",
    17706: "Velocity observer correction factor kc invalid.",
    17707: "Velocity observer time constant T invalid - 1st order filter parameter invalid.",
    17708: "Velocity observer amplitude damping invalid - 2nd order filter damping invalid.",
    17709: "Velocity observer frequency invalid - 2nd order filter frequency invalid.",

    17728: "Controller not initialized - Created but initialization/reset not completed.",
    17729: "Axis address missing - Controller does not know its axis or address not initialized.",
    17730: "Drive address missing - Controller does not know its drive or address not initialized.",

    17744: "Lag error (position) exceeded - Position lag exceeded window longer than filter time.",
    17745: "Lag error (velocity) exceeded - Velocity lag exceeded window longer than filter time.",

    17824: "Internal controller error - CONTROLERR_RANGE_AREA_ASIDE.",
    17825: "Internal controller error - CONTROLERR_RANGE_AREA_BSIDE.",
    17826: "Internal controller error - CONTROLERR_RANGE_QNENN.",
    17827: "Internal controller error - CONTROLERR_RANGE_PNENN.",
    17828: "Internal controller error - CONTROLERR_RANGE_AXISIDPRESP0.",
}

# Drive-related NC errors
DRIVE_ERRORS = {
    17920: "Drive ID not allowed - ID already used, <=0, or >255.",
    17921: "Drive type not allowed - Undefined drive type.",
    17922: "Drive operation mode not allowed - Operating mode invalid.",
    17923: "Motor polarity flag invalid - Polarity must be 0 (positive) or 1 (negative).",
    17924: "Drift compensation / DAC offset not allowed - Velocity offset out of range.",
    17925: "Reference velocity not allowed - Velocity pre-control value invalid.",
    17926: "Reference output percentage not allowed - Output scaling invalid.",
    17927: "Quadrant compensation factor not allowed.",
    17928: "Velocity reference point percentage not allowed.",
    17929: "Output reference point percentage not allowed.",
    17930: "Min/max output limits not allowed - Limits invalid or inconsistent.",
    17931: "Maximum output value not allowed - Drive output digit range invalid.",
    17932: "Internal Drive Control Word not allowed - Internal NC drive control value invalid.",
    17933: "Internal RESET timer for drive not allowed - Timing parameter invalid.",
    17934: "Master Motion Controller ID not allowed - Invalid for additional slave NC motion controller.",
    17935: "Drive torque/force output scaling not allowed.",
    17936: "Drive velocity output scaling not allowed.",
    17937: "ProfiDrive DSC proportional gain Kpc not allowed.",
    17938: "Table ID not allowed - Invalid table identifier.",
    17939: "Table interpolation type not allowed - Must be LINEAR or SPLINE.",
    17940: "Output offset percentage not allowed.",
    17941: "ProfiDrive DSC scaling for Xerr calculation not allowed.",
    17942: "Drive acceleration/deceleration output scaling not allowed.",
    17943: "Drive position output scaling not allowed.",
    17944: "Dead time compensation mode (Motion Controller) invalid.",
    17945: "Dead time compensation control bits (Motion Controller) invalid.",
    17946: "Dead time compensation time shift (Motion Controller) invalid.",
    17947: "Output delay for velocity interface (Motion Controller) invalid.",
    17948: "Drive filter type for output position not allowed.",
    17949: "Drive filter time for output position not allowed.",
    17950: "Drive filter order for output position not allowed.",

    17952: "Stepper motor cycle bit mask not allowed.",
    17953: "Stepper motor holding current bit mask not allowed.",
    17954: "Scaling factor for actual torque/current not allowed.",
    17955: "Filter time for actual torque/current not allowed.",
    17956: "Filter time for derivative of actual torque/current not allowed.",
    17957: "Drive operation mode parameter invalid - Unsupported or invalid NC/drive mode.",
    17958: "Motion Controller function not supported or temporarily unavailable.",
    17959: "Drive operation mode busy - Interface already in use by another object.",
    17960: "Drive operation mode changeover not configured or mode not found.",
    17961: "Drive operation mode changeover feedback timeout.",

    # Reserved range for external drive errors
    17968: "Overtemperature detected in drive or terminal.",
    17969: "Undervoltage detected in drive or terminal.",
    17970: "Wire break detected in phase A.",
    17971: "Wire break detected in phase B.",
    17972: "Overcurrent detected in phase A.",
    17973: "Overcurrent detected in phase B.",
    17974: "Torque overload / stall detected in drive or terminal.",

    17984: "Drive not initialized - Created but initialization/reset not completed.",
    17985: "Axis address missing - Drive does not know its axis.",
    17986: "I/O input address missing - No valid drive input process image.",
    17987: "I/O output address missing - No valid drive output process image.",

    18000: "Drive hardware not ready - Error state, startup phase, or controller enable missing.",
    18001: "Cyclic communication error with drive - Life Counter / fieldbus error.",
    18002: "Changing table ID not allowed while controller enable is active.",
    18005: "Invalid I/O data detected for more than n NC cycles (encoder or drive).",
}

# Table-related NC errors
TABLE_ERRORS = {
    18944: "Table ID not allowed - ID already used, <=0, or >255.",
    18945: "Table type not permitted - Undefined table type.",
    18946: "Number of lines in table not allowed - Too few lines for selected interpolation type.",
    18947: "Number of columns in table not allowed - Columns must be >0 (depends on table/slave type).",
    18948: "Step size (position delta) not allowed - Delta must be >0.",
    18949: "Period not allowed - Period must be >0.",
    18950: "Table is not monotonic - Table values/step size inconsistent (monotonicity violated).",
    18951: "Table sub type not allowed - Undefined or mismatching sub-type for table class/slave type.",
    18952: "Table interpolation type not allowed - Undefined interpolation type (linear/4-point/spline).",
    18953: "Incorrect table main type - Undefined or mismatching main type for table class/slave type.",

    18960: "Table not initialized - Created but initialization not completed (e.g. lines/cols <=0).",
    18961: "Not enough memory - Table could not be created.",
    18962: "Function not executed/not available - Not implemented or not executable for this table type.",
    18963: "Line index not allowed - Read/write line index out of range.",
    18964: "Column index not allowed - Read/write column index out of range.",
    18965: "Number of lines not allowed - Must match n * number_of_columns.",
    18966: "Number of columns not allowed - Must match n * number_of_lines.",
    18967: "Error in scaling or range entry - Inconsistent table header entries (may stop group at runtime).",
    18968: "Multi table slave out of range - Master position outside table range (runtime error, stops group).",
    18969: "Solo table underflow - Master value below first table value (runtime error, stops group).",
    18970: "Solo table overflow - Master value above table range (runtime error, stops group).",

    18971: "Incorrect execution mode - Cyclic execution mode must be TRUE/FALSE.",
    18972: "Invalid parameter - FIFO parameter not allowed.",
    18973: "FIFO is empty - External generator FIFO empty (end of track or runtime error).",
    18974: "FIFO is full - External generator FIFO full; retry writing rejected values.",
    18975: "Motion function point index invalid - Must be >0 and consecutive per column; must not change online.",

    18976: "No diagonalization of matrix - Spline cannot be calculated; master positions invalid.",
    18977: "Number of spline points too small - Cubic spline needs at least 3 points/lines.",
    18978: "FIFO must not be overwritten - Must not overwrite active processing line.",
    18979: "Motion Function has too few points - <2 valid points (too few or too many Ignore points).",
    18981: "Master start position of table invalid - Periodic position table must start at 0; periodic MF first master pos must be >0 and <= period.",
}

# NC ↔ PLC communication errors
NC_PLC_ERRORS = {
    19200: "Axis was stopped - Stopped during travel (PLC via ADS/AXFNC/System Manager).",
    19201: "Axis cannot be started - Axis in error, busy, protected mode, or not ready.",
    19202: "Control mode not permitted - No target position control and no position area control.",
    19203: "Axis is not moving - Position/velocity can only be restarted while axis is physically moving.",
    19204: "Invalid mode - e.g. invalid Direction at MC_MoveModulo; Position correction inactive with MC_BacklashCompensation.",
    19205: "Command not permitted - e.g. continuous motion with unspecified direction; read/write parameter unsuitable type.",
    19206: "Parameter is not correct - e.g. override >100% or <0%; gear ratio denominator = 0.",
    19207: "Timeout axis function block - NC feedback monitoring (position/target window) not reached; aborts after 6 s.",
    19208: "Axis is in protected mode - e.g. coupled; cannot be moved.",
    19209: "Axis is not ready - Cannot be moved.",
    19210: "Error during referencing - Homing could not be started or was not successful.",
    19211: "Incorrect trigger input definition - MC_TouchProbe trigger definition invalid (encoder ID/signal/edge).",
    19212: "Position latch was disabled - MC_TouchProbe cycle was disabled (e.g. by axis reset).",
    19213: "NC state feedback timeout - PLC->NC function sent but expected status feedback did not arrive.",
    19214: "Additional product not installed - Function is a supplement but not installed.",
    19215: "No NC Cycle Counter Update - NcToPlc interface / NC cycle counter not updated.",

    19216: "M-function query missing - M-function confirmed but request bit was not set.",
    19217: "Zero shift index outside range - Zero offset shift index invalid.",
    19218: "R parameter index/size invalid - R parameter read/write index or size out of range.",
    19219: "Tool description index invalid - Tool description index invalid.",
    19220: "Cyclic channel interface version mismatch - Older TwinCAT calling newer TcNci.lib functions.",
    19221: "Channel not ready for requested function - Wrong channel state (e.g. reverse travel without ItpEStop).",
    19222: "Requested function not activated - Function requires explicit activation.",
    19223: "Axis already in another group - Axis already added to another group.",
    19224: "Block search failed - Block search could not be executed successfully (e.g. invalid block number).",
    19225: "Invalid block search parameter - ItpBlocksearch called with invalid parameters.",
    19232: "Cannot add all axes - Adding auxiliary axis to interpolation group failed (likely prior aux instruction skipped).",

    19248: "Pointer is invalid - Null/invalid pointer; MC_CAM_REF not initialized.",
    19249: "Memory size invalid - SIZE is 0/too small/mismatch with points/rows/cols or requested data.",
    19250: "Cam plate ID invalid - Cam plate ID not in 1..255.",
    19251: "Point ID invalid - Motion function point ID < 1.",
    19252: "Number of points invalid - Points to read/write < 1.",
    19253: "MC table type invalid - Cam plate type does not match MC_TableType.",
    19254: "Number of rows invalid - Rows (interpolation points) < 1.",
    19255: "Number of columns invalid - Columns invalid or mismatch (motion function !=1, standard cam plate !=2, mismatch with ValueSelectMask).",
    19256: "Step size invalid - Interpolation step size <= 0.",

    19264: "Terminal type not supported - Terminal not supported by this function block.",
    19265: "Register read/write error - Validity error.",
    19266: "Axis is enabled - Axis is enabled but must not be enabled for this process.",
    19267: "Incorrect compensation table size - Specified table size (bytes) does not match actual size.",
    19268: "Positional deviation - Min/max position in compensation table does not match ST_CompensationDesc.",
    19269: "Not implemented - Function not implemented in this combination.",
    19270: "Window not in specified modulo range - Min/max position not in specified modulo range.",
    19271: "Buffer overflow - Too many events overflowed buffer; not all events acquired.",

    19296: "Motion command did not become active - Buffered/confirmed but never became active (termination condition/internal NC error).",
    19297: "Motion command could not be monitored by PLC - NC executed newer command; execution state unclear.",
    19298: "Buffered command terminated with error - Error number not available because new command already executing.",
    19299: "Buffered command completed without feedback - Completed but no success/failure feedback.",
    19300: "'BufferMode' not supported - BufferMode not supported by this command.",
    19301: "Command number is zero - Queued command number unexpectedly 0.",
    19302: "Function block not called cyclically - PLC couldn't monitor; NC already executing subsequent command.",

    19313: "Invalid NCI entry type - FB_NciFeedTablePreparation called with unknown nEntryType.",
    19314: "NCI feed table full - Entry not accepted; transfer to NC with FB_NciFeedTable, then reset and refill.",
    19315: "Internal error - (no further details).",
    19316: "Tangential following: tangential axis not auxiliary axis - ST_NciTangentialFollowingDesc invalid tangential axis.",
    19317: "Tangential following: invalid path axis - nPathAxis1 or nPathAxis2 not a path axis; plane cannot be determined.",
    19318: "Tangential following: identical path axes - nPathAxis1 and nPathAxis2 same; plane cannot be determined.",
    19319: "Circle incorrectly parameterized - ST_NciGeoCirclePlane invalid.",
    19320: "Internal error - Tangential following calculation internal error.",
    19321: "Tangential following monitoring - Deviation angle too large (E_TfErrorOnCritical1).",
    19322: "Reserved - Reserved, currently not used.",
    19323: "Tangential following - Radius of current arc is too small.",
    19324: "FB_NciFeedTablePreparation - pEntry is NULL.",
    19325: "FB_NciFeedTablePreparation - nEntryType does not match structure type.",
    19326: "ST_NciMFuncFast/ST_NciMFuncHsk - M-function not between 0 and 159.",
    19327: "ST_NciDynOvr - Dynamic override not between 0.01 and 1.",
    19328: "ST_NciVertexSmoothing - Invalid parameter (negative radius or unknown smoothing type).",
    19329: "FB_NciFeedTablePreparation - Requested velocity not in valid range.",
    19330: "ST_Nci* - Invalid parameter.",
    
    19344: "Drive type not supported - Determined drive type not supported.",
    19345: "Direction impermissible - Invalid direction.",
    19346: "SwitchMode impermissible - Invalid SwitchMode.",
    19347: "Mode impermissible - Invalid parameter-handling mode.",
    19348: "Torque limits inconsistent - Torque limit parameterization inconsistent.",
    19349: "Lag error limit impermissible - Position lag limit <= 0.",
    19350: "Distance limit impermissible - Distance limit < 0.",
    19351: "Saving parameters invalid - Parameters already backed up.",
    19352: "Restoring parameters invalid - No backup present.",
    19359: "Cancellation of homing failed - Abortion of homing failed.",
    
    19360: "KinGroup error - Kinematic group in error/unexpected state (e.g. simultaneous calls).",
    19361: "KinGroup timeout - Timeout during call of a kinematic block.",
    
    19376: "Invalid axis position - Current/new-offset position exceeds valid range.",
    19377: "Invalid position offset - New offset exceeds valid range (AX5000: 2^31).",
    19378: "Invalid axis position - Current/new-offset position below valid range.",
    19379: "Invalid position offset - New offset below valid range (AX5000: -2^31).",
    19380: "Feedback/storage location deviation - Activated feedback/storage (AX5000: P-0-0275) differs from FB parameterization.",
    19381: "Reinit NC actual position failed - e.g. ABSOLUTE(single overflow) & software end position monitoring disabled.",
    19382: "Set/delete position offset rejected - Rejected without feedback data (firmware may not support).",
    19383: "Set/delete position offset rejected - Rejected with feedback data (details may hint cause).",
    19384: "Invalid firmware version - Servo terminal requires firmware >= 19.",
    19385: "Deviating modulo settings - Drive controller and NC modulo settings differ.",
    19386: "Brake test failed - Brake test failed.",
    19387: "Not supported drive type - Determined drive/axis type not supported.",
    19388: "Command was aborted - Aborted by another command.",
    19389: "Timeout - Command aborted due to timeout.",
    
    19394: "Invalid position offset - New position offset exceeds valid range.",
    19395: "Invalid I/O data - I/O data invalid or terminal in error state.",
    19396: "ADS port not linked - ADS port variable not linked in PLC interface while changing terminal parameters.",
}

# Kinematic transformation errors
KINEMATIC_TRANSFORMATION_ERRORS = {
    19456: "Transformation failed - Calculation of the kinematic transformation failed.",
    19457: "Ambiguous solution - Transformation solution is not unique.",
    19458: "Invalid axis position - Transformation cannot be calculated with current position data (e.g. position outside kinematics working area).",
    19459: "Invalid dimension - Parameterized input dimension does not match kinematic object (too many position values / check number of parameterized axes).",
    19460: "Internal error - NCERR_KINTRAFO_REGISTRATION.",
    19461: "Newton iteration failed - Newton iteration does not converge.",
    19462: "Jacobi matrix cannot be inverted - Jacobian matrix is singular / not invertible.",
    19463: "Invalid cascade - Kinematic configuration is not permitted.",
    19464: "Singularity - Machine configuration results in singular axis velocities.",
    19467: "No metainfo - Metainfo pointer is null.",
    19475: "NCERR_RBTFRAME_INVALIDWCSTOMCS - WcsToMcs component yields positions kinematics cannot assume; adjust WcsToMcs parameters.",
    19488: "Transformation failed (extended model) - Call of extended kinematic model failed.",
    19504: "Invalid input frame - Programmed Cartesian position cannot be reached in the ACS configuration.",
    19536: "Invalid offset - Access violation detected in the observer.",
}

# Bode return codes
BODE_RETURN_CODES = {
    33024: "INTERNAL - Internal error.",
    33025: "NOTINITIALIZED - Not initialized (e.g. no NC axis).",
    33026: "INVALIDPARAM - Invalid parameter.",
    33027: "INVALIDOFFSET - Invalid index offset.",
    33028: "INVALIDSIZE - Invalid parameter size.",
    33029: "INVALIDSTARTPARAM - Invalid start parameter (setpoint generator).",
    33030: "NOTSUPPORTED - Not supported.",
    33031: "AXISNOTENABLED - NC axis not enabled.",
    33032: "AXISINERRORSTATE - NC axis in error state.",
    33033: "DRIVEINERRORSTATE - IO drive in error state.",
    33034: "AXISANDDRIVEINERRORSTATE - NC axis AND IO drive in error state.",
    33035: "INVALIDDRIVEOPMODE - Invalid drive operation mode active or requested (no bode plot mode).",
    33036: "INVALIDCONTEXT - Invalid context for this command (mandatory task or Windows context needed).",
    33037: "NOAXISINTERFACE - Missing TCom axis interface (axis null pointer); no connection to NC axis / axis not parameterized or does not exist.",
    33038: "INPUTCYCLECOUNTER - Invalid input cycle counter from IO drive (e.g. frozen); cyclic drive data consistency/communication loss detected (see also AX5000 F440).",
    33039: "POSITION_MONITORING - Axis position outside maximum allowed moving range; recording aborted and NC axis set to runtime error state.",
    33040: "DRIVELIMITATIONDETECTED - Drive limitations detected (current/velocity limit) causing nonlinear behavior; recording aborted (check amplitude/scaling).",
    33041: "LIFECOUNTERMONITORING - GUI heartbeat/life counter timeout; communication to GUI lost; recording terminated and NC axis set to runtime error state.",
    33042: "NCERR_BODEPLOT_WCSTATE - WC state error (I/O working counter); e.g. EtherCAT CRC/telegram failures, device not OP, real-time errors.",
    
    # Reserved range 0x8113..0x811F (33043..33055)
    33043: "Reserved (0x8113).",
    33044: "Reserved (0x8114).",
    33045: "Reserved (0x8115).",
    33046: "Reserved (0x8116).",
    33047: "Reserved (0x8117).",
    33048: "Reserved (0x8118).",
    33049: "Reserved (0x8119).",
    33050: "Reserved (0x811A).",
    33051: "Reserved (0x811B).",
    33052: "Reserved (0x811C).",
    33053: "Reserved (0x811D).",
    33054: "Reserved (0x811E).",
    33055: "Reserved (0x811F).",
}

# Further / miscellaneous NC error codes
FURTHER_ERROR_CODES = {
    33056: "Environment - Invalid configuration for Object (e.g. in System Manager).",
    33057: "Environment - Invalid environment for Object (e.g. TcCom-Object hierarchy or missing/faulty objects).",
    33058: "Environment - Incompatible driver or object.",
    33060: "Function Block - Command execution does not terminate (e.g. MC_Reset does not signal DONE).",
    33072: "Communication - Invalid ObjectID of communication target.",
    33073: "Communication - Communication target expects call in different context.",
    33074: "Communication - Invalid state of communication target.",
    33076: "Communication - Communication with communication target cannot be established.",
    33083: "Parameter - TransitionMode is invalid.",
    33084: "Parameter - BufferMode is invalid.",
    33085: "Function Block - Only one active instance of function block per group is allowed.",
    33086: "State - Command is not allowed in current group state.",
    33087: "Function Block - Slave cannot synchronize; cannot reach SlaveSyncPosition with given dynamics.",
    33088: "Parameter - Invalid value for one or more dynamic parameters (acc/dec/jerk).",
    33089: "Parameter - IdentInGroup is invalid.",
    33090: "Parameter - Number of axes in group incompatible with axes convention.",
    33091: "Communication - Function block / command not supported by target.",
    33092: "State - Command queue full; cannot accept more until some are processed.",
    33093: "Function Block - Mapping of cyclic NC↔PLC interface missing (e.g. AXIS_REF, AXES_GROUP_REF, ...).",
    33094: "Function Block - Invalid velocity value (not set or invalid).",
    33095: "Parameter - Invalid coordinate dimension; set coordinate interpretation dimension mismatch.",
    33096: "Function Block - Invalid input value.",
    33097: "Parameter - Unsupported dynamics for selected group kernel.",
    33098: "Parameter - Programmed position dimension incompatible with axes convention.",
    33099: "Function Block - Path buffer is invalid (invalid address or too small).",
    33100: "Function Block - Path does not contain any element.",
    33101: "Function Block - Provided path buffer too small to store more path elements.",
    33102: "Parameter - Dimension or at least one value of transition parameters is invalid.",
    33103: "Function Block - Invalid or incomplete input array.",
    33104: "Function Block - Path length is zero.",
    33105: "State - Command is not allowed in current axis state.",
    33106: "State - TwinCAT system is shutting down and cannot complete request.",
    33107: "Parameter - Configured axes convention and configured axes do not match.",
    33108: "Initialization - Invalid number of ACS axes; does not match kinematic transformation expectation.",
    33109: "Initialization - Invalid number of MCS data; does not match kinematic transformation expectation.",
    33110: "Initialization - Invalid value set for kinematic parameters; outside definition range.",
    33112: "NC Programming - Given ACS values cannot be reached; invalid machine configuration.",
    33113: "NC Programming - Set target positions cannot be reached; outside admissible working space.",
    33117: "NC Programming - Discontinuity in ACS axes detected.",
    33120: "NC Programming - Circle specification in path is invalid/ambiguous (center cannot be determined reliably).",
    33121: "NC Programming - Maximum stream lines reached (see FB documentation).",
    33123: "Function Block - Invalid first segment; needs well-defined start point.",
    33124: "Function Block - Invalid auxiliary point; not well-defined.",
    33126: "Function Block - Invalid parameter for GapControlMode (likely with GapControlDirection).",
    33127: "External - Group got unsupported axis event (e.g. state change triggered by single axis reset).",
    33128: "Parameter - Unsupported compensation type (not set or not supported by addressed object).",
    33129: "Function Block - Master axis does not exist or cannot be used.",
    33130: "External - Invalid/missing tracking transformation (MC_TrackConveyorBelt: invalid CoordTransform ObjectID or unsupported transform).",
    33131: "Function Block - Position is not on track (actual not on track or target not on active track/track part).",
    33132: "Function Block - Axis does not have an activated track.",
    33133: "NC Programming - Invalid compensation ObjectId (does not exist or wrong type; must be compensation).",
    33134: "Monitoring - Axis in error because it was not in target when InTargetAlarm timer expired.",
    33135: "State - Coupling would cause cyclic dependency of axis (e.g. via MC_GearInPos).",
    33136: "Function Block - Axis not added to an axes group; command not valid.",
    33151: "State - Drive has invalid state.",
    33153: "Function Block - Gap control parameters invalid for current configuration (gap-control FB issued to axis not in CA group).",
    33154: "Monitoring - Software position limit violation (would have been or has been violated).",
    33155: "NC Programming - Target position not reachable (no path available or unreachable in general).",
    33157: "NC Programming - Mover / relevant coordinate busy.",
    33158: "NC Programming - Collision has occurred or would occur.",
    33159: "NC Programming - Invalid track specification; geometry incompatible with existing track geometry.",
    33160: "NC Programming - Command not allowed in track state.",
    33161: "Function Block - Invalid reference passed (reference/pointer used before initialization).",
    33162: "NC Programming - Path locked against modifications (might be resettable).",
    33164: "Parameter - Position out of modulo range (0..modulo factor; AdditionalTurns considered).",
    33165: "Parameter - AdditionalTurns not allowed; must be zero for specified Direction.",
    33166: "Function Block - Master/slave sync position incompatible with sync direction.",
    36664: "Internal - Internal error.",
    36688: "Internal - (No description given).",
    36694: "Internal - Internal error.",
    36697: "Internal - Internal error.",
    36700: "Internal - Internal error.",
    36706: "Internal - (No description given).",
    36709: "Internal - Internal error.",
    36712: "Internal - Internal error.",
    36862: "Internal - (No description given).",
}

NC_ERROR_CODES = {
    **GENERAL_ERRORS,
    **CHANNEL_ERRORS,
    **GROUP_ERRORS,
    **AXIS_ERRORS,
    **TF5055_ERRORS,
    **ENCODER_ERRORS,
    **CONTROLLER_ERRORS,
    **DRIVE_ERRORS,
    **TABLE_ERRORS,
    **NC_PLC_ERRORS,
    **KINEMATIC_TRANSFORMATION_ERRORS,
    **BODE_RETURN_CODES,
    **FURTHER_ERROR_CODES
}