Separating CiA402 Logic from EtherCAT (lcec): Modular Adapter + Drive Stub Valid

More
7 months 4 weeks ago #343830 by Marcos DC
I'm preparing a small repository for this. The current README draft describes the structure I'm experimenting with.
# linuxcnc-cia402-layer

Vendor-agnostic CiA402 (DS402) semantic layer for LinuxCNC.

Status: experimental reference implementation
Target: LinuxCNC HAL architecture
Focus: deterministic CiA402 semantic separation
License: MIT

This project provides a clean separation between drive semantics,
machine policy and fieldbus transport for CiA402 devices in LinuxCNC.


---

# Overview

This project implements a deterministic HAL architecture that separates:

- Power Drive System (PDS) state machine (6040 / 6041)
- Procedure layer (homing / operation handshake)
- Deterministic controlword composition
- Machine-level safety policy
- Fieldbus adapters (EtherCAT / CANopen / etc.)

The goal is to validate CiA402 semantics in a clean and deterministic way
before involving real fieldbus hardware.

The semantic layer is designed to remain:

- drive-agnostic
- fieldbus-agnostic
- reusable across different servo drives


---

# Motivation

Many CiA402 integrations inside LinuxCNC mix together:

- fieldbus communication
- drive state logic
- machine safety policy
- procedure logic

inside a single component.

This makes systems harder to:

- debug
- validate
- reuse
- maintain

This project separates these responsibilities into clear HAL layers.


---

# Safety Notice

This project provides software-level safety behavior such as:

- controlword gating
- quick stop policy
- fault handling
- machine enable supervision

However, it **does NOT replace hardware safety systems** such as:

- physical E-stop circuits
- STO (Safe Torque Off)
- safety PLC
- certified safety devices

Always implement proper hardware safety according to applicable safety standards.


---

# Architecture Overview

The architecture ensures that machine-level safety always has authority
over drive-level state machines.


Machine Safety Policy
│
▼
safety_gate.comp
│
▼
pds_manager.comp
│
▼
procedure layer (c402hu)
│
▼
cw_compose.comp
│
▼
Fieldbus Adapter (LCEC / CANopen)
│
▼
Drive


LinuxCNC motion interacts with the drive through the semantic layer.


---

# Core Components (Drive-Agnostic)

## safety_gate.comp

Machine-level safety policy.

Responsibilities:

- integrates with halui
- supervises machine enable state
- supervises E-stop state
- blocks procedures when unsafe
- overrides controlword when required

Typical policies:

- Machine OFF → Disable Voltage
- E-stop → Quick Stop
- Fault → block enable until reset

The safety gate sits **above the PDS layer** to guarantee machine authority.


---

## pds_manager.comp

Implements the CiA402 Power Drive System state machine.

Responsibilities:

- decode statusword (6041)
- generate base controlword (6040)
- track DS402 states
- expose HAL signals

Outputs include:

- op_enabled
- fault
- decoded state
- debug mask patterns
- cw_pds


---

## c402hu.comp (Procedure Layer)

Procedure management for CiA402 operations.

Handles:

- mode request (6060)
- mode confirmation (6061)
- homing start generation
- completion detection
- error detection

Responsibilities:

- manage operation sequences
- latch completion states
- detect abnormal conditions

All procedures are gated by:


ut.enable


which is typically controlled by the safety gate.


---

## cw_compose.comp

Single source of truth for the final controlword (6040).

Responsibilities:

- combine PDS controlword
- combine procedure bits
- apply safety overrides

Typical composition:


cw_final = cw_pds | procedure_bits


Safety overrides may replace this value when required.


---

# Coupler (Decouple / Recouple)

Planned component:


coupler.comp


Purpose:

Allow drives to perform internal motion (such as homing)
without creating position jumps in LinuxCNC.

Responsibilities:

- temporarily decouple motion feedback
- follow drive position during internal motion
- recouple after completion

Typical use cases:

- drive-based homing
- drive internal motion procedures
- avoiding position discontinuities


---

# Gantry Support

Future component:


gantry_manager.comp


Possible responsibilities:

- synchronized homing of multiple drives
- gantry squaring
- position difference monitoring
- safe recoupling after homing

This allows coordination of multiple CiA402 drives
in gantry machines.


---

# Fieldbus Adapters

Adapters are intentionally simple.

Example:


adapters/adapter_TEMPLATE.hal


Responsibilities:

- map fieldbus objects to semantic layer pins

Typical mapping:

- 6040 → drive controlword
- 6041 → statusword
- 6060 → mode of operation
- 6061 → mode display
- 6064 → position actual
- 607A → position command

Adapters should contain **no logic**.

They only wire fieldbus data to the semantic layer.


---

# Repository Layout


src/
safety/
safety_gate.comp

pds/
pds_manager.comp

procedure/
c402hu.comp

controlword/
cw_compose.comp

coupler/
coupler.comp

gantry/
gantry_manager.comp

adapters/
adapter_TEMPLATE.hal

sim/
cia402_stub.comp
opc_validation.hal

docs/
architecture.md



---

# Validation Approach

The semantic layer was initially validated using LinuxCNC AXIS simulation.

Simulation includes:

- CiA402 stub drive
- statusword generation
- homing procedure testing
- fault injection

This allows deterministic validation before connecting real hardware.


---

# Current Project Status

Validated:

- PDS state decoding
- deterministic controlword composition
- mode handshake (6060 / 6061)
- homing start/done detection
- fault handling behavior
- operation enabled gating

In progress:

- safety gate implementation
- drive motion decouple / recouple
- gantry synchronization logic
- EtherCAT adapter validation


---

# License

MIT License

Copyright (c) 2026
Marcos Duque Cesar


---

# Project Goal

Provide a clean reference implementation of CiA402 semantics for LinuxCNC HAL that is:

- deterministic
- reusable
- independent of fieldbus drivers
- suitable for different servo drives

Please Log in or Create an account to join the conversation.

More
7 months 4 weeks ago - 7 months 4 weeks ago #343843 by hmnijp
1) It may not be a good idea to divide the architecture of a single module too much. This can cause unnecessary complications in the connections between them and race conditions between components...  For example, the state machine of the “homemode” module in some situations cyclically processes several states in one cycle, thanks to its flat structure, which would be difficult to do if it were broken down into modules.


2)

gantry_manager.comp
Possible responsibilities:
- synchronized homing of multiple drives
- gantry squaring


I think this should be handled by the built-in homing and kinematic module, regardless of the communication bus.

I recently encountered this using ethercat drives with absolute encoders - it is already partially successful. 
Alignment occurs during the homing procedure when jointY1 and joint Y2 move independently and synchronously (home sequence) by calling free_tp,
but requires a revision of the procedure for HOME_ABSOLUTE_ENCODER, which is used by cia402/ethercat ( github.com/LinuxCNC/linuxcnc/pull/3774/c...be947439e20fc5da9825 ), to prepare it for correct communication with the cia402 state machine

as a result, squaring control should take place in the trivkins module where, when declaring KINS=XYYZ, the connection is established 
joints[1] = pos->tran.y
joints[2] = pos->tran.y

I don't see the need for another layer  “motion -> trivkins -> gantry.comp -> pid -> cia402 ->lcec”   since we already have independent joints, each of which is connected to feedback for tracking following error.
Last edit: 7 months 4 weeks ago by hmnijp.

Please Log in or Create an account to join the conversation.

More
7 months 4 weeks ago - 7 months 4 weeks ago #343873 by Marcos DC
Thanks for the feedback. Just to clarify an important point that I may not have emphasized clearly:

All components in the current tests run in the same servo-thread at 1 kHz, with a fixed execution order using addf. For example:

safety → pds_manager → procedure (UT) → controlword composer → driver interface

Because of this, execution is deterministic. In HAL this effectively becomes a sequential call chain within the same realtime cycle.

Also, there is only one writer for the final 6040 controlword, produced by the controlword composer, which avoids the typical “multiple writers” problem that often causes ambiguous state transitions.

In HAL, race conditions are caused by multiple threads or multiple writers, not by the number of components.

Regarding gantry and coupling: I agree that final squaring and coordinated homing logic belongs in the motion/kinematics layer. If a coupler is introduced on the HAL side it would only serve a limited purpose — handling safe decouple/recouple situations when the drive performs internal motion (for example CiA402 homing) to avoid command/feedback jumps. It would not replace motion’s gantry or homing logic.

Interestingly, the recent HOME_ABSOLUTE_ENCODER fix in motion (PR #3774) also highlights a similar concern about maintaining internal consistency when offsets are applied during homing. In that patch the motion code re-normalizes pos_cmd, pos_fb, free_tp.curr_pos, and motor_offset to avoid accumulated offsets during re-homing. Conceptually this looks similar to a recoupling step inside the motion layer to keep controller and physical states aligned.

The goal here is not to duplicate motion functionality, but simply to keep CiA402 semantics independent from the transport layer (LCEC/EtherCAT) while maintaining a deterministic controlword path.
Last edit: 7 months 4 weeks ago by Marcos DC.

Please Log in or Create an account to join the conversation.

More
7 months 4 weeks ago #343874 by Marcos DC
Small clarification regarding the README

After reading the feedback I realized that one part of the README may have been ambiguous, especially the section mentioning “Gantry Support” and gantry_manager.comp.

To clarify the intent of the project:

The goal of this repository is not to introduce a new motion or gantry control layer in HAL. Final gantry squaring, coordinated homing and axis relationships are expected to remain in the motion / kinematics layer (e.g. trivkins) as usual.

The purpose of the HAL components in this project is limited to:

separating CiA402 semantics from the transport layer (LCEC / EtherCAT)

providing a deterministic controlword composition path

adding safety gating

optionally handling decouple/recouple situations when a drive performs internal motion (for example CiA402 homing), to avoid command/feedback discontinuities

So any future “coupler” component would only handle safe transition and coupling of drive states, not replace motion-level gantry logic.

I will update the README to make this clearer.

Please Log in or Create an account to join the conversation.

More
7 months 3 weeks ago #343880 by NWE

To prepare proper adapter templates for your two drives (the Lichuan OL57E-4A and the Stepperonline A6-750EC), I just need a few details from your setup so I can map the HAL pins correctly.

If possible, could you share:
1. Your LCEC configuration
• lcec.conf (or equivalent configuration file)
• The EtherCAT XML/ENI if you have it
• Or a snippet of the HAL where the lcec.* pins for the drives appear
2. PDO mapping
I mainly need to confirm the HAL pins for the standard CiA402 objects:
• 6040 Controlword
• 6041 Statusword
• 6060 Modes of Operation (command)
• 6061 Modes of Operation Display
If available in PDO as well:
• 6064 Position Actual Value
• 607A Target Position
3. Homing
• Which homing method (object 6098) you plan to use
• Whether the homing/limit switches are connected to the drive inputs
• The HAL pin names for those inputs (for example lcec.*.din-*)
4. Quick Stop
• Is Quick Stop (Controlword 0x0002) configured and usable on these drives?
• Or do they require a different shutdown sequence?
5. Anything unusual
• Any known quirks with enable, fault reset, or homing behavior.

 
Later tomorrow I should be able to gather some of the info you requested. I know I will have hal pins, lcec.conf, PDO/SDO, and a terminal log from test driving these servos.

I have not looked at CiA402 homing at all yet, I will take a quick look at the manual to check whether I have a preference which homing method I'd use.

One potential quirk I noticed with the Lichuan OL57E-4A was if I test drive it in velocity mode (I was typing hal commands at the terminal) I then can momentarily disconnect the servo amplifier power, shutting down the servo amplifier and resulting in a flood of ethercat error logs in dmesg, in a second or two the drive recovers and ethercat reconnects, and the motors resume rotating at the velocity I had previously set in lcec.

This is hardly a problem, as we will be running in position control mode. I expect a servo drop-out like that would at least trigger a following error in a standard linuxcnc config. It did not do that here as I was just running simple hal commands in the terminal directly to lcec without using CiA402.

Please Log in or Create an account to join the conversation.

More
7 months 3 weeks ago #343985 by Marcos DC
Hi @NWE,

Sorry for the late reply — I was a bit busy the last days.

The CiA402 semantic layer is now running in simulation using a HAL drive stub and the core parts are behaving as expected (PDS state machine, controlword ownership, homing supervision, etc.).

The next step is integrating it with real hardware via lcec.

I don't currently have EtherCAT hardware locally, so the plan is to prepare a configuration for your two drives and let you try it when convenient.

I also made the repository public so you can see the current architecture. It is still experimental and not finished yet, but the simulation layer is already working.

Repo:
github.com/MarcosDuqueCesar/linuxcnc-cia402-layer
The following user(s) said Thank You: NWE

Please Log in or Create an account to join the conversation.

Time to create page: 0.114 seconds
Powered by Kunena Forum