Skip to main content

Smart building lighting / curtain / LED control system

Control type: positioning control of 120 independent curtain axes

This page covers positioning control of 120 independent curtain axes (one target position per axis, issued by a Cue or manually); it is not a synchronized-axis / electronic-gearing use case. A "group" is only a batch set that issues targets for the same Cue at once; there is no gear ratio or phase coupling between axes, and there is no virtual master axis. For strict proportional coupling (1:1 gear ratio, reverse following, gantry correction), see Synchronized axes / electronic gearing.

Hardware configuration​

  • Master: Windows 10 IoT x 1 + Intel 13900 x 1
  • Motion control: Panasonic MINAS A6B EtherCAT servo drives x 120 + servo motors x 120
  • Brake control: EL2808 digital outputs x 2 (12 electromagnetic brakes, covering the critical load-bearing axes)

Cost analysis​

CategoryModel/specReference unit price (¥)QtySubtotal (¥)
Servo drivePanasonic MINAS A6B1,800120216,000
Servo motor200 W servo motor60012072,000
Digital outputEL280850021,000
Industrial PCIntel 13900 class10,000110,000

Reference prices (RMB) for the core components; LED modules, cabling and similar are not included.

Performance figures​

  • Synchronization error within a group: ≤1 ms (all axes in the same Cue interpolate against the same time base)
  • Axes: 120 independent axes (6 groups x 20 axes; grouping is only a set for batch target issue, not mechanical coupling)
  • PDO cycle: 1 ms (1 kHz, master.LoopCycle = 1_000_000, the same value as DC Sync0)
  • Position accuracy: ±0.1 mm

Why 1 ms instead of 125 µs: the single-frame process data for 120 axes is long, and every cycle also has to write 120 sets of target positions plus the brake outputs. 1 ms leaves headroom for Windows scheduling; positioning accuracy comes from the Cue interpolation plus the drive's inner loop, not from shortening the bus cycle. To actually run at 8 kHz you must set both LoopCycle and each slave's ConfigureDC to 125000, and measure the frame length and cycle jitter; writing 125 µs in the documentation while the code scales by 1 ms makes the velocity clamp and the homing step 8 times too large.

Application scenario​

Shaped projection-curtain control for a large performance venue. 120 servos each drive an independent curtain unit (5 m travel); positioning targets are issued per group from a pre-programmed Cue list (a group receives its targets on the same beat, and there is no gear ratio between axes), coordinated with DMX512 lighting. 12 critical load-bearing axes have electromagnetic brakes that lock on power loss to prevent falling.

Code description​

System architecture​

Group design​

The number of groups and the number of axes per group are defined by configuration and are not limited to a fixed 6x20. The example splits the axes into 6 groups by physical position:

GroupNameAxis rangeBrake axesPurpose
0Front curtain (Front)0~190, 10Front-of-stage opening curtain
1Back curtain (Rear)20~3920, 30Backdrop curtain lift
2Left side curtain (Left)40~5940, 50Left wing curtain
3Right side curtain (Right)60~7960, 70Right wing curtain
4Sky curtain (Ceiling)80~9980, 90Overhead sky / projection curtain
5FX curtain (FX)100~119100, 110Shaped / wave curtain
Extension: dynamic grouping

Group definitions are stored in a JSON configuration file and support any number of groups and any axis assignment (contiguity not required). For example:

  • Checkerboard grouping: odd axes in one group and even axes in another, for staggered lifting
  • Ring grouping: 12 groups by angle around a circular stage, for a rotating wave
  • Temporary grouping: create or merge groups during a show
{
"groups": [
{ "name": "前幕", "axisIds": [0,1,2,...,19], "brakeAxes": [0,10] },
{ "name": "环形-A区", "axisIds": [0,5,10,15,20,25], "brakeAxes": [0,20] }
]
}

Operating modes and switching​

ModeDescriptionOperation
AUTOAutomatic modeRuns the Cue list in order; the operator presses GO to trigger the next Cue
MANUALManual modeSelect a group, then jog (Jog) or position (GoTo); speed knob 0~120%
MAINTENANCEMaintenance modeLow-speed single-axis operation (limited to 100 mm/s) for commissioning and calibration

Cue system​

Cue vs keyframes: we interpolate at the application layer in CSP mode — an equivalent implementation, but more flexible (arbitrary curves and wave effects are possible).

Extension: Cue chaining and looping

StageCue supports automatic chaining through AutoFollowDelay:

  • AutoFollowDelay = -1 — default, wait for the operator to press GO
  • AutoFollowDelay = 0 — run immediately after the previous Cue completes
  • AutoFollowDelay = 2.0 — run automatically 2 seconds after the previous Cue completes
  • LoopCount > 1 — repeat (looping wave effects)

This lets you program a complete show sequence: press GO once, and the following Cues advance automatically along the timeline.

Brake sequence​

Key design:

  1. Electromagnetic brakes (lock on power loss) — the 12 load-bearing axes are controlled through EL2808 outputs; on power loss or loss of communication the outputs drop to zero and the brakes lock. An emergency stop locks the brakes first to prevent falling; a normal stop decelerates first and then locks the brakes to avoid shock
  2. Cue system — the operator presses GO to trigger a scene change; automatic chaining (AutoFollowDelay) and looping (LoopCount) are supported
  3. Dynamic grouping — the number of groups and the axis assignment per group are defined by configuration; any combination of axes is supported (contiguity not required)
  4. Shaped motion — PerAxisDelay gives each axis its own delay, producing chase, travelling-wave and staggered effects
  5. Manual control — hold-to-jog (Jog) in both directions and positioning (GoTo); maintenance mode has a speed limit
  6. Speed override — a global speed knob of 0~120%: slow-speed verification during rehearsal, full speed for the show itself
  7. Soft limit protection — the safety monitoring thread triggers an emergency stop immediately when a position exceeds its limit by 10 mm
  8. Position feedback — synchronized from ActualPosition every cycle, so the commanded value does not drift away from the actual position
  9. The control word uses standard CiA 402 semantics only — in CSP, 0x6040 stays at 0x000F and every target update comes from 0x607A. Do not write 0x001F in CSP (bit4 means new set-point only in PP mode; some drives report 0x7500). Emergency stop uses 0x0002 Quick Stop (decelerating on the 0x6085 ramp); once the status word confirms QuickStopActive ((sw & 0x6F) == 0x07), you must send 0x0000 to leave that state (T12 = Disable Voltage), then 0x0006 to remove enable; 0x0006 is undefined in QuickStopActive, and sending it directly leaves the axis stuck there permanently. 0x0000 is used only for this exit point: a normal stop does not use it, because a suspended curtain loses force instantly and slides down freely; on an emergency stop, lock the brakes first, wait for the velocity to reach zero and confirm the axis has stopped, then leave QuickStopActive.
Custom services

The Cue sequencing engine in this case (interpolation curve design, wave and chase effects, auto-follow logic), the DMX512 lighting integration, the brake safety sequencing, and the DC synchronization tuning for 120 axes at this scale are additional custom work and are not included in the EtherCAT master software license.

Code example​

Data structures​

PDO mapping

Servo_Input / Servo_Output follow the default mapping of the Panasonic MINAS A6B ESI (TxPDO 23 bytes, RxPDO 9 bytes). The A6B default TxPDO has no velocity or torque object, so this example derives velocity from the difference between consecutive sampled positions and detects a stall from the following error. If you change the model or modify the PDO assignment, rewrite the structs from the actual mapping exported by DENI; do not assume the order follows object numbers.

using System.Runtime.InteropServices;
using System.Collections.Generic;

// ============ PDO mapping ============

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct Servo_Input // 23-byte TxPDO 0x1A00 (MINAS A6B default mapping)
{
public ushort ErrorCode; // 0x603F error code offset 0
public ushort StatusWord; // 0x6041 status word offset 2
public sbyte ModesOfOperationDisplay; // 0x6061 actual mode offset 4
public int ActualPosition; // 0x6064 actual position offset 5
public ushort TouchProbeStatus; // 0x60B9 probe status offset 9
public int TouchProbe1PosValue; // 0x60BA probe latched position offset 11
public int FollowingErrorActualValue; // 0x60F4 following error offset 15
public uint DigitalInputs; // 0x60FD digital inputs offset 19
}

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct Servo_Output // 9-byte RxPDO 0x1600
{
public ushort ControlWord; // 0x6040 control word offset 0
public sbyte ModeOfOperation; // 0x6060 mode of operation offset 2 (8=CSP)
public int TargetPosition; // 0x607A target position offset 3
public ushort TouchProbeFunction; // 0x60B8 probe function offset 7 (not used in this example, keep 0)
}

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct EL2808_Output
{
public byte DigitalOutputs; // bit0~7, LOW=brake locked, HIGH=released

public void SetBit(int ch, bool value)
{
if (value) DigitalOutputs |= (byte)(1 << ch);
else DigitalOutputs &= (byte)~(1 << ch);
}
}

// ============ Configuration ============

public class CurtainUnit
{
public int AxisId, GroupId;
public double MinPosition, MaxPosition; // mm
public int PulsesPerMm;
public double CurrentPosition;
public bool HasBrake;
public int BrakeSlaveIdx, BrakeChannel;
}

public class CurtainGroup
{
public int GroupId;
public string Name;
public int[] AxisIds; // Any axis assignment (they need not be consecutive)
public double MaxVelocity = 500; // mm/s
}

// ============ Operations ============

public enum OpMode { Auto, Manual, Maintenance }
public enum InterpType { Linear, SmoothStep, EaseIn, EaseOut }

public class ManualCommand
{
public enum CmdType { None, Jog, GoTo }
public CmdType Type = CmdType.None;
public int GroupId = -1; // -1=all, 0..N=the specified group
public int AxisId = -1; // -1=whole group (single axis in maintenance mode)
public double JogSpeed; // mm/s, positive = upward
public double GoToPosition; // Target position in mm
public double GoToVelocity; // Positioning velocity in mm/s
}

// ============ Cue system ============

public class CueGroupMotion
{
public int GroupId;
public double[] Positions; // Target position of each axis in mm (length = number of axes in the group)
public double MaxVelocity = 500; // mm/s
public InterpType Interp = InterpType.SmoothStep;
public double[] PerAxisDelay; // Per-axis delay (seconds), null=synchronous, used for chase/wave effects
}

/// <summary>
/// Scene (Cue) - the basic unit of stage automation
/// </summary>
public class StageCue
{
public int CueNumber; // Number
public string Name; // Name ("opening", "first act", ...)
public double Duration; // Transition time (seconds)
public List<CueGroupMotion> Motions; // Motion parameters for each group
public byte[] DmxData; // DMX512 lighting, null=leave unchanged
public double AutoFollowDelay = -1; // -1=waiting for GO, >=0=auto-delayed execution after the previous Cue completes
public int LoopCount = 1; // Loop count (for a continuous wave effect)
}

public class CueList
{
public string ShowName;
public List<StageCue> Cues = new List<StageCue>();
}
Extension: effect overlay layer

Superimpose a dynamic modulation effect on the base Cue motion, for sustained artistic movement:

public enum EffectType { None, Wave, Breathing, Chase, Rainbow }

public class CueEffect
{
public int GroupId;
public EffectType Type;
public double Amplitude; // Modulation amplitude in mm
public double Frequency; // Hz
public double PhaseStep; // Phase difference between adjacent axes (radians), commonly 2pi/N for Wave
}

Usage: add a CueEffect Effect field to CueGroupMotion, and after ProcessCue computes the base interpolated position, add the effect on top:

double offset = effect.Amplitude * Math.Sin(
2 * Math.PI * effect.Frequency * elapsed + effect.PhaseStep * axisIndex);
target += offset;

Typical effects:

  • Wave: PhaseStep = 2π/20, the whole group forms a travelling wave
  • Breathing: PhaseStep = 0, the whole group breathes as an in-phase sine
  • Chase: PhaseStep = π, adjacent axes alternate up and down
  • Rainbow: PhaseStep increases, forming a spiral wave
Extension: custom interpolation function

The InterpType enum can be extended into a custom expression:

public enum InterpType { Linear, SmoothStep, EaseIn, EaseOut, Bezier, Custom }

public class CueGroupMotion
{
// ...existing fields...
public double[] BezierControlPoints; // Bezier: [cx1, cy1, cx2, cy2]
public Func<double, double> CustomFunc; // Custom: t -> interpolation coefficient
}

With Bezier cubic curves supported, control points can be dragged in the UI to design arbitrary acceleration and deceleration curves, matching the way lighting designers work.

Control code​

using System;
using System.Diagnostics;
using System.Threading;
using System.Collections.Generic;
using System.Linq;
using DarraEtherCAT_Master;

class CurtainController
{
const int AXIS_COUNT = 120;
const uint CYCLE_NS = 1_000_000; // PDO cycle 1 ms (recommended for 120 axes on Windows)
const int SLAVE_BRAKE_1 = 120, SLAVE_BRAKE_2 = 121;
const double MAINTENANCE_MAX_VEL = 100; // Maintenance mode speed limit in mm/s
const int BRAKE_RELEASE_SETTLE_MS = 200; // Wait for the mechanical response after releasing the brake (not a control cycle)
const int STOP_POLL_MS = 1; // Polling interval while waiting to stop (a courtesy back-off, not the control cycle)
static readonly int[] BRAKE_AXES = { 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110 };

static CurtainUnit[] Units = new CurtainUnit[AXIS_COUNT];
static List<CurtainGroup> Groups = new List<CurtainGroup>();

// Homing offset (raw position pulses): after homing, current position = (raw position - HomeOffset) / PulsesPerMm
static readonly int[] HomeOffset = new int[AXIS_COUNT];

// Cycle-derived real-time quantities: always derive them from the actual master.LoopCycle, never hard-code 1 ms
static double cycleSeconds = CYCLE_NS / 1e9;

// Running state
static volatile OpMode mode = OpMode.Auto;
static volatile bool isRunning = true; // Normal exit flag
static volatile bool isEmergencyStop = false;
static volatile int speedPermille = 1000; // Velocity knob 0~1200 maps to 0~120% (volatile cannot be applied to double)
static double SpeedOverride => speedPermille / 1000.0;
static int stopDone = 0;

// Cue engine
static CueList cueList;
static int cueIndex = -1;
static volatile bool cueGo = false;
static volatile bool cueActive = false; // Whether the current Cue is running
static readonly Stopwatch cueTimer = new Stopwatch();
static double[] cueStartPos = new double[AXIS_COUNT];

// Manual control
static ManualCommand manual = new ManualCommand();
static volatile long lastJogTick = 0; // Jog key timestamp (latched)

// ======================== Main flow ========================

static void Main(string[] args)
{
InitGroups();
InitUnits();

// Build() returns a BuildResult (not the master itself); you must call .Master to get the master instance
// DENI = the network configuration the master configuration tool exports after scanning the real slaves; do not edit it by hand
var master = new DarraEtherCAT()
.SetENI("config.deni")
.Build()
.Master;

if (master == null) { Console.WriteLine("主站初始化失败!"); return; } // Master initialization failed!
if (master.SlaveCount < AXIS_COUNT + 2)
{
Console.WriteLine($"从站不足: 需要 {AXIS_COUNT} 个轴 + 2 个 EL2808, 实际 {master.SlaveCount}"); // Not enough slaves: {AXIS_COUNT} axes + 2 EL2808 needed, {master.SlaveCount} found
master.Dispose();
return;
}

try
{
// Cycle time: 1 ms for 120 axes, equal to DC Sync0. Once set, LoopCycle is the single source for every cycle-derived quantity.
master.LoopCycle = CYCLE_NS;
if (master.LoopCycle != CYCLE_NS)
{
Console.WriteLine($"LoopCycle 设定失败: 请求 {CYCLE_NS}ns, 读回 {master.LoopCycle}ns"); // LoopCycle setup failed: {CYCLE_NS}ns requested, {master.LoopCycle}ns read back
return;
}
cycleSeconds = master.LoopCycle / 1e9;
Console.WriteLine($"PDO 周期: {master.LoopCycle / 1000}µs"); // PDO cycle time: {master.LoopCycle / 1000}µs

// State machine order: INIT → PreOp -> (configure DC) -> SafeOp → OP. DC must be configured in PreOp,
// ConfigureDC directly in INIT will not be accepted.
if (!master.SetState(EcState.PreOp, out string preOpError))
{ Console.WriteLine($"无法进入 PreOp: {preOpError}"); return; } // Failed to enter PreOp: {preOpError}

// DC Sync0 equals LoopCycle; slaves without DC run as usual
for (int i = 0; i < AXIS_COUNT; i++)
{
if (master.Slaves[i].HasDC && !master.Slaves[i].ConfigureDC(CYCLE_NS))
Console.WriteLine($"[警告] 轴{i} DC Sync0 配置失败"); // [Warning] Axis{i} DC Sync0 configuration failed
}

if (!master.SetState(EcState.SafeOp, out string safeOpError))
{ Console.WriteLine($"无法进入 SafeOp: {safeOpError}"); return; } // Failed to enter SafeOp: {safeOpError}

if (!master.SetState(EcState.OP, out string opError)) { Console.WriteLine($"无法进入 OP: {opError}"); return; } // Failed to enter OP: {opError}

if (!EnableServos(master)) { Console.WriteLine("使能未通过, 不得起演"); return; } // Enable check not passed, the show must not start

Console.WriteLine("回原点..."); // Homing...
HomeAllAxes(master);

if (!PreShowCheck(master)) { Console.WriteLine("预演检查未通过!"); return; } // Pre-show check failed!

// Loading show choreography from JSON is an upper-layer concern; this example uses the built-in Cue list directly
cueList = DefaultCueList();
Console.WriteLine($"演出 [{cueList.ShowName}] 共 {cueList.Cues.Count} Cue"); // Show [{cueList.ShowName}], {cueList.Cues.Count} cues in total
Console.WriteLine("[G]=GO [A]=自动 [M]=手动 [E]=急停 [Q]=退出 [+/-]=速度"); // [G]=GO [A]=auto [M]=manual [E]=emergency stop [Q]=quit [+/-]=speed

// Background thread
StartThread(() => SafetyLoop(master));
StartThread(InputLoop);

// Real-time control is attached to the SDK's PDO cycle callback - hard-synchronised by the bus cycle (= LoopCycle, 1 ms),
// Runs per cycle in the SDK's PDO thread context. Never set the pace with Thread.Sleep / a while spin.
// Parameter mi = master index.
void OnPdoCycle(ushort mi)
{
try
{
var m = master;
if (m == null || !isRunning || isEmergencyStop) return;
UpdatePositions(m);
if (mode == OpMode.Auto) ProcessCue(m);
else ProcessManual(m);
}
catch (Exception ex)
{
Console.WriteLine($"[PDO周期异常] {ex.Message}"); // [PDO cycle exception] {ex.Message}
}
}
master.Events.ProcessDataCyclicSync += OnPdoCycle;

// The main thread only waits for exit / emergency stop (not real time, does not write the PDO); all real-time control runs inside OnPdoCycle
while (isRunning && !isEmergencyStop)
Thread.Sleep(50);

try { master.Events.ProcessDataCyclicSync -= OnPdoCycle; } catch { }
}
finally
{
if (isEmergencyStop) EmergencyStop(master);
else GracefulStop(master);
master.Dispose();
}
}

static void StartThread(ThreadStart action)
{
new Thread(action) { IsBackground = true }.Start();
}

// ======================== Initialisation ========================

static void InitGroups()
{
// Default 6 groups x 20 axes (any grouping can be loaded from a configuration file)
string[] names = { "前幕", "后幕", "左侧幕", "右侧幕", "天幕", "特效幕" }; // Front curtain, rear curtain, left curtain, right curtain, sky backdrop, effects curtain
for (int g = 0; g < names.Length; g++)
{
int start = g * 20;
Groups.Add(new CurtainGroup
{
GroupId = g, Name = names[g],
AxisIds = Enumerable.Range(start, 20).ToArray(),
});
}
}

static void InitUnits()
{
for (int i = 0; i < AXIS_COUNT; i++)
{
int bi = Array.IndexOf(BRAKE_AXES, i);
int gid = Groups.FindIndex(g => g.AxisIds.Contains(i));
Units[i] = new CurtainUnit
{
AxisId = i, GroupId = gid >= 0 ? gid : 0,
MinPosition = 0, MaxPosition = 5000, PulsesPerMm = 100,
HasBrake = bi >= 0,
BrakeSlaveIdx = bi >= 0 ? (bi < 8 ? SLAVE_BRAKE_1 : SLAVE_BRAKE_2) : -1,
BrakeChannel = bi >= 0 ? (bi < 8 ? bi : bi - 8) : -1,
};
}
}

/// <summary>
/// Enable: advance CiA 402 per axis from the status word (0x06->0x07->0x0F), waiting for real state confirmation at every step (bounded timeout).
/// Returning false means an axis timed out unconfirmed or is in Fault; the show must not start.
/// </summary>
static bool EnableServos(DarraEtherCAT master)
{
// Preload CSP mode and "target=actual": while disabled the target always equals the actual position, so nothing jumps at enable
for (int i = 0; i < AXIS_COUNT; i++)
{
ref var outp = ref master.Slaves[i].PDO.OutputsMapping<Servo_Output>();
outp.ModeOfOperation = 8; // CSP, held every cycle at runtime
outp.TargetPosition = master.Slaves[i].PDO.InputsMapping<Servo_Input>().ActualPosition;
outp.ControlWord = 0x0006;
}

// Give axes already in the fault state a reset pulse (bit7 rising edge) first; do not expect them to recover by "waiting a bit longer"
ResetFaults(master);

// CiA 402: Shutdown -> Switch On -> Enable Operation
ushort[] sequence = { 0x0006, 0x0007, 0x000F };
ushort[] statusExpects = { 0x0021, 0x0023, 0x0027 }; // Always parse the status word with the 0x6F mask

for (int s = 0; s < sequence.Length; s++)
{
for (int i = 0; i < AXIS_COUNT; i++)
{
ref var outp = ref master.Slaves[i].PDO.OutputsMapping<Servo_Output>();
outp.ControlWord = sequence[s];
outp.TargetPosition = master.Slaves[i].PDO.InputsMapping<Servo_Input>().ActualPosition;
}

// Wait for confirmation from the real status word; never guess each step's duration with a fixed Sleep
if (!WaitAllStatus(master, statusExpects[s], 2000, out int badAxis, out ushort badSw))
{
Console.WriteLine($"使能失败: 轴{badAxis} 未进入 0x{statusExpects[s]:X4} " + // Enable failed: axis{badAxis} did not reach 0x{statusExpects[s]:X4}
$"(实际 0x{badSw:X4}, 控制字 0x{sequence[s]:X4})"); // (actual 0x{badSw:X4}, control word 0x{sequence[s]:X4})
return false;
}
}

// Wait for the mechanical response after releasing the brake (hardware action time, not a control cycle)
SetBrakes(master, released: true);
Thread.Sleep(BRAKE_RELEASE_SETTLE_MS);
Console.WriteLine($"已使能 {AXIS_COUNT} 轴 (CSP), 释放 {BRAKE_AXES.Length} 个刹车"); // {AXIS_COUNT} axes enabled (CSP), {BRAKE_AXES.Length} brakes released
return true;
}

/// <summary> Wait until every axis status word reaches the expected value (state driven, bounded timeout); on failure reports the first axis that did not arrive </summary>
static bool WaitAllStatus(DarraEtherCAT master, ushort expect, int timeoutMs,
out int badAxis, out ushort badSw)
{
var deadline = DateTime.UtcNow.AddMilliseconds(timeoutMs);
while (true)
{
badAxis = -1; badSw = 0;
for (int i = 0; i < AXIS_COUNT; i++)
{
ushort sw = master.Slaves[i].PDO.InputsMapping<Servo_Input>().StatusWord;
if ((sw & 0x006F) != expect) { badAxis = i; badSw = sw; break; }
}
if (badAxis < 0) return true;
if (DateTime.UtcNow >= deadline) return false;
Thread.Sleep(STOP_POLL_MS);
}
}

/// <summary>
/// Fault reset: 6040 bit7 must be a 0->1 rising edge. Hold 0x0006 (bit7=0) for 2 ticks first, then 0x0086
/// (bit7=1 + Shutdown bits) held for about 20 ms, then back to 0x0006 and the status word drives the handshake again.
/// Hold times are computed from the actual cycle time instead of a hard-coded tick count.
/// </summary>
static void ResetFaults(DarraEtherCAT master)
{
// When an axis is stuck in QuickStopActive neither 0x0006 nor 0x0086 takes effect: go back to SwitchOnDisabled with 0x0000 first
if (AnyQuickStopActive(master))
{
SetAllControlWord(master, 0x0000);
WaitSwitchOnDisabled(master, 1000);
}

SetAllControlWord(master, 0x0006);
Thread.Sleep((int)Math.Ceiling(2 * cycleSeconds * 1000));

int highCycles = Math.Max(2, (int)(0.020 / cycleSeconds));
SetAllControlWord(master, 0x0086);
while (highCycles-- > 0)
{
if (!AnyFault(master)) break; // State driven: ends early once every reset succeeds
Thread.Sleep((int)Math.Ceiling(cycleSeconds * 1000));
}

SetAllControlWord(master, 0x0006);
}

/// <summary> Fault detection: (sw & 0x4F) == 0x08 (bit3 Fault); returns whether a faulted axis exists </summary>
static bool AnyFault(DarraEtherCAT master)
{
for (int i = 0; i < AXIS_COUNT; i++)
if ((master.Slaves[i].PDO.InputsMapping<Servo_Input>().StatusWord & 0x004F) == 0x0008)
return true;
return false;
}

static bool PreShowCheck(DarraEtherCAT master)
{
bool pass = true;
for (int i = 0; i < AXIS_COUNT; i++)
{
var sw = master.Slaves[i].PDO.InputsMapping<Servo_Input>().StatusWord;
if ((sw & 0x006F) != 0x0027)
{
var grp = Groups.FirstOrDefault(g => g.AxisIds.Contains(i));
Console.WriteLine($" 轴{i} ({grp?.Name}) 未使能: 0x{sw:X4}"); // Axis{i} ({grp?.Name}) not enabled: 0x{sw:X4}
pass = false;
}
}
if (pass) Console.WriteLine("预演检查通过"); // Pre-show check passed
return pass;
}

// ======================== Cue engine (automatic mode) ========================

static int cueLoopRemain = 0; // Remaining loop count of the current Cue
static readonly Stopwatch autoFollowTimer = new Stopwatch(); // Automatic chaining timer

static void StartCue(int index)
{
cueIndex = index;
var c = cueList.Cues[cueIndex];
cueLoopRemain = c.LoopCount;

for (int i = 0; i < AXIS_COUNT; i++)
cueStartPos[i] = Units[i].CurrentPosition;
cueTimer.Restart();
cueActive = true;
Console.WriteLine($"[GO] Cue {c.CueNumber}: {c.Name} ({c.Duration}s x{c.LoopCount})");
}

static void ProcessCue(DarraEtherCAT master)
{
// Respond to GO
if (cueGo)
{
cueGo = false;
autoFollowTimer.Reset();
if (cueIndex + 1 >= cueList.Cues.Count)
{
Console.WriteLine("所有 Cue 已完成, 按 [Q] 退出"); // All cues completed, press [Q] to exit
return;
}
StartCue(cueIndex + 1);
}

// Automatic chaining: the next Cue is triggered after a delay once the previous one completes
if (!cueActive && autoFollowTimer.IsRunning && cueIndex + 1 < cueList.Cues.Count)
{
var next = cueList.Cues[cueIndex + 1];
if (next.AutoFollowDelay >= 0 && autoFollowTimer.Elapsed.TotalSeconds >= next.AutoFollowDelay)
{
autoFollowTimer.Reset();
StartCue(cueIndex + 1);
}
}

if (!cueActive || cueIndex < 0) return;

var cue = cueList.Cues[cueIndex];
double elapsed = cueTimer.Elapsed.TotalSeconds;
double t = Math.Min(1.0, elapsed / cue.Duration);

foreach (var m in cue.Motions)
{
var g = Groups[m.GroupId];

for (int a = 0; a < g.AxisIds.Length; a++)
{
int id = g.AxisIds[a];

// Independent per-axis delay (chase/wave effects)
double axisT = t;
if (m.PerAxisDelay != null && a < m.PerAxisDelay.Length)
{
double axisElapsed = elapsed - m.PerAxisDelay[a];
axisT = axisElapsed <= 0 ? 0 : Math.Min(1.0, axisElapsed / cue.Duration);
}

double it = Interp(axisT, m.Interp);
double target = Lerp(cueStartPos[id], m.Positions[a], it);
WriteAxis(master, id, target, m.MaxVelocity * SpeedOverride);
}
}

// Cue complete
if (t >= 1.0 && cueActive)
{
// Loop
if (--cueLoopRemain > 0)
{
for (int i = 0; i < AXIS_COUNT; i++)
cueStartPos[i] = Units[i].CurrentPosition;
cueTimer.Restart();
Console.WriteLine($"[循环] Cue {cue.CueNumber} 剩余 {cueLoopRemain} 次"); // [Loop] Cue {cue.CueNumber}, {cueLoopRemain} runs left
return;
}

cueActive = false;
cueTimer.Stop();

int next = cueIndex + 1;
if (next < cueList.Cues.Count)
{
var nc = cueList.Cues[next];
if (nc.AutoFollowDelay >= 0)
{
autoFollowTimer.Restart();
Console.WriteLine($"[完成] Cue {cue.CueNumber}, {nc.AutoFollowDelay}s 后自动执行 Cue {nc.CueNumber}"); // [Done] Cue {cue.CueNumber}, Cue {nc.CueNumber} runs automatically in {nc.AutoFollowDelay}s
}
else
Console.WriteLine($"[完成] Cue {cue.CueNumber}, 按 GO 执行 Cue {nc.CueNumber}: {nc.Name}"); // [Done] Cue {cue.CueNumber}, press GO to run Cue {nc.CueNumber}: {nc.Name}
}
else
Console.WriteLine($"[完成] 所有 Cue 执行完毕"); // [Done] All cues finished
}
}

// ======================== Manual mode ========================

static void ProcessManual(DarraEtherCAT master)
{
if (manual.Type == ManualCommand.CmdType.None) return;

if (manual.Type == ManualCommand.CmdType.Jog)
{
// Latching: auto-stop after 200 ms without a key press (Console has no key-up, so this simulates it with a timeout)
if (Stopwatch.GetTimestamp() - Interlocked.Read(ref lastJogTick)
> Stopwatch.Frequency / 5)
{
manual.Type = ManualCommand.CmdType.None;
return;
}

double delta = manual.JogSpeed * SpeedOverride * cycleSeconds;

// Maintenance mode: single axis
if (mode == OpMode.Maintenance && manual.AxisId >= 0)
{
WriteAxis(master, manual.AxisId,
Units[manual.AxisId].CurrentPosition + delta, MAINTENANCE_MAX_VEL);
}
// Manual mode: whole group
else if (manual.GroupId >= 0 && manual.GroupId < Groups.Count)
{
var g = Groups[manual.GroupId];
foreach (int id in g.AxisIds)
WriteAxis(master, id, Units[id].CurrentPosition + delta, g.MaxVelocity);
}
}
else if (manual.Type == ManualCommand.CmdType.GoTo
&& manual.GroupId >= 0 && manual.GroupId < Groups.Count)
{
var g = Groups[manual.GroupId];
bool done = true;
foreach (int id in g.AxisIds)
{
WriteAxis(master, id, manual.GoToPosition, manual.GoToVelocity * SpeedOverride);
if (Math.Abs(Units[id].CurrentPosition - manual.GoToPosition) > 0.5)
done = false;
}
if (done)
{
Console.WriteLine($"[到位] {g.Name} -> {manual.GoToPosition}mm"); // [In position] {g.Name} -> {manual.GoToPosition}mm
manual.Type = ManualCommand.CmdType.None;
}
}
}

// ======================== Position feedback sync ========================

static void UpdatePositions(DarraEtherCAT master)
{
for (int i = 0; i < AXIS_COUNT; i++)
Units[i].CurrentPosition =
(master.Slaves[i].PDO.InputsMapping<Servo_Input>().ActualPosition - HomeOffset[i])
/ (double)Units[i].PulsesPerMm;
}

// ======================== Motion output (with velocity clamp + soft limits) ========================

static void WriteAxis(DarraEtherCAT master, int id, double target, double maxVel)
{
ref readonly var input = ref master.Slaves[id].PDO.InputsMapping<Servo_Input>();
ref var output = ref master.Slaves[id].PDO.OutputsMapping<Servo_Output>();

ushort sw = input.StatusWord;
int actual = input.ActualPosition;

// State-aware: only OperationEnabled writes motion targets. When disabled / handshaking / faulted
// The target always equals the actual position and the control word sends the stop command (QuickStopActive can only be left with 0x0000 first) -
// Never leave a motion target on a disabled axis.
if ((sw & 0x006F) != 0x0027 || (sw & 0x004F) == 0x0008)
{
output.TargetPosition = actual;
output.ControlWord = StopControlWord(sw);
return;
}

// Velocity clamp: the maximum displacement per cycle is derived from the actual cycle (maxVel mm/s x cycleSeconds), never hard-coded to 1 ms
double maxDelta = maxVel * cycleSeconds;
double delta = target - Units[id].CurrentPosition;
if (Math.Abs(delta) > maxDelta)
target = Units[id].CurrentPosition + Math.Sign(delta) * maxDelta;

// Soft limit
target = Math.Max(Units[id].MinPosition, Math.Min(Units[id].MaxPosition, target));

// In CSP, 0x6040 is always 0x000F: bit4 (0x0010) only means new set-point in PP mode; it is undefined in CSP,
// Writing 0x001F makes some drives report 0x7500; target updates rely entirely on writing 0x607A every cycle.
// mm -> pulses, plus the homing offset, so the target uses the same origin as UpdatePositions
output.TargetPosition = (int)(target * Units[id].PulsesPerMm) + HomeOffset[id];
output.ControlWord = 0x000F;
}

// ======================== Homing ========================

static void HomeAllAxes(DarraEtherCAT master)
{
// 50 mm/s slow descent onto the stop for homing (50 mm/s x cycleSeconds x 100 pulses/mm, at 1 ms = 5 pulses/cycle)
// The real-time homing loop hangs off the SDK cycle callback (ProcessDataCyclicSync), not a user-space Thread.Sleep spin.
// The step must be derived from the actual cycle: when the cycle changes the homing velocity must change with it; a fixed constant must not be taken as 1 ms.
const double HOME_VEL = 50; // mm/s
int stepPerCycle = Math.Max(1, (int)(HOME_VEL * cycleSeconds * Units[0].PulsesPerMm));
bool[] done = new bool[AXIS_COUNT];
int count = 0;
var finished = new ManualResetEventSlim(false);

// Driven by the master callback every PDO cycle: advance one homing step + test for bottoming out, and finished.Set() when all are in position
void OnHomeCycle(ushort mi)
{
try
{
var m = master;
if (m == null || finished.IsSet) return;

for (int i = 0; i < AXIS_COUNT; i++)
{
if (done[i]) continue;
ref readonly var inp = ref m.Slaves[i].PDO.InputsMapping<Servo_Input>();
ref var outp = ref m.Slaves[i].PDO.OutputsMapping<Servo_Output>();

// State-aware: a disabled / faulted axis must not move; target=actual + the stop command, reported uniformly after a bounded timeout
if ((inp.StatusWord & 0x006F) != 0x0027)
{
outp.TargetPosition = inp.ActualPosition;
outp.ControlWord = StopControlWord(inp.StatusWord);
continue;
}

// The MINAS A6B default TxPDO has no torque object: use the following error to detect a stall (threshold calibrated to the mechanics, in pulses)
if (Math.Abs(inp.FollowingErrorActualValue) > 300)
{
outp.TargetPosition = inp.ActualPosition;
done[i] = true; count++;
HomeOffset[i] = inp.ActualPosition; // Treat the bottom-out position as position 0
Units[i].CurrentPosition = 0;
}
else
{
outp.TargetPosition = inp.ActualPosition - stepPerCycle;
}
outp.ControlWord = 0x000F;
}

// All axes bottom out and home, done
if (count >= AXIS_COUNT) finished.Set();
}
catch (Exception ex)
{
Console.WriteLine($"[回零异常] {ex.Message}"); // [Homing exception] {ex.Message}
finished.Set(); // Bounded exit, so the startup flow cannot hang
}
}

master.Events.ProcessDataCyclicSync += OnHomeCycle;
try
{
// Bounded wait: when an axis loses enable or faults, do not hang the whole startup flow
if (!finished.Wait(TimeSpan.FromSeconds(30)))
Console.WriteLine($"[警告] 回零超时, 只完成 {count}/{AXIS_COUNT} 轴"); // [Warning] Homing timed out, only {count}/{AXIS_COUNT} axes completed
}
finally
{
try { master.Events.ProcessDataCyclicSync -= OnHomeCycle; } catch { }
}
Console.WriteLine($"回原点完成 {count}/{AXIS_COUNT} 轴"); // Homing complete on {count}/{AXIS_COUNT} axes
}

// ======================== Brake ========================

static void SetBrakes(DarraEtherCAT master, bool released)
{
foreach (int axis in BRAKE_AXES)
{
var u = Units[axis];
ref var b = ref master.Slaves[u.BrakeSlaveIdx].PDO.OutputsMapping<EL2808_Output>();
b.SetBit(u.BrakeChannel, released);
}
}

// ======================== Safety monitoring ========================

static void SafetyLoop(DarraEtherCAT master)
{
while (isRunning && !isEmergencyStop)
{
for (int i = 0; i < AXIS_COUNT; i++)
{
ref readonly var inp = ref master.Slaves[i].PDO.InputsMapping<Servo_Input>();
string grp = Groups.FirstOrDefault(g => g.AxisIds.Contains(i))?.Name ?? "?";

if ((inp.StatusWord & 0x0008) != 0)
{
Console.WriteLine($"[故障] 轴{i} ({grp}) 伺服故障 0x{inp.StatusWord:X4}"); // [Fault] Axis{i} ({grp}) servo fault 0x{inp.StatusWord:X4}
// Set the flag only: stopping is executed centrally by the main thread, so a background thread cannot race Dispose writing the PDO
isEmergencyStop = true; return;
}

double pos = (inp.ActualPosition - HomeOffset[i]) / (double)Units[i].PulsesPerMm;
if (pos < Units[i].MinPosition - 10 || pos > Units[i].MaxPosition + 10)
{
Console.WriteLine($"[故障] 轴{i} ({grp}) 位置超限 {pos:F1}mm"); // [Fault] Axis{i} ({grp}) position over limit {pos:F1}mm
isEmergencyStop = true; return;
}

// The default PDO has no torque object: a persistently large following error counts as a sign of mechanical jamming / overload (threshold calibrated to the mechanics)
if (Math.Abs(inp.FollowingErrorActualValue) > 5000)
Console.WriteLine($"[警告] 轴{i} 跟随误差 {inp.FollowingErrorActualValue} 脉冲"); // [Warning] Axis{i} following error {inp.FollowingErrorActualValue} pulses
}
Thread.Sleep(100);
}
}

// ======================== Stop ========================

/// <summary>
/// Emergency stop: lock the brake (to prevent a fall) -> Quick Stop 0x0002 (decelerate on the 0x6085 ramp)
/// -> confirm QuickStopActive -> 0x0000 leaves QuickStopActive -> 0x0006 disables.
/// 0x000B is not written (it is not a standard Quick Stop). 0x0000 is only used to leave QuickStopActive:
/// The only legal exit from this state is Disable Voltage (T12); sending 0x0006 directly leaves the axis stuck in QuickStopActive for good.
/// The brake is already locked, so cutting torque on exit will not let the suspended curtain free-fall.
/// </summary>
static void EmergencyStop(DarraEtherCAT master)
{
if (Interlocked.Exchange(ref stopDone, 1) == 1) return;
Console.WriteLine("[紧急停止]"); // [Emergency stop]
SetBrakes(master, released: false);
SetAllControlWord(master, 0x0002); // Quick Stop: decelerate on the 0x6085 ramp
WaitQuickStopActive(master, 2000); // Wait for status word confirmation ((sw & 0x6F) == 0x07)
WaitStopped(master, 2000);
SetAllControlWord(master, 0x0000); // Leave QuickStopActive (T12 = Disable Voltage)
WaitSwitchOnDisabled(master, 2000);
SetAllControlWord(master, 0x0006); // Shutdown: disable, keep the voltage
Console.WriteLine($"已停止, {BRAKE_AXES.Length} 个刹车锁止"); // Stopped, {BRAKE_AXES.Length} brakes engaged
}

/// <summary> Normal stop: lock position -> wait for deceleration -> lock brake -> 0x0006 to disable </summary>
static void GracefulStop(DarraEtherCAT master)
{
if (Interlocked.Exchange(ref stopDone, 1) == 1) return;
Console.WriteLine("[正常停止]"); // [Normal stop]
for (int i = 0; i < AXIS_COUNT; i++)
{
ref readonly var input = ref master.Slaves[i].PDO.InputsMapping<Servo_Input>();
ref var outp = ref master.Slaves[i].PDO.OutputsMapping<Servo_Output>();
outp.TargetPosition = input.ActualPosition; // Lock position: target=current
// Give 0x000F only to axes that are being enabled; otherwise send the stop command (0x0000 in QuickStopActive), never drag a disabled axis up along the way
outp.ControlWord = (input.StatusWord & 0x006F) == 0x0027 ? (ushort)0x000F : StopControlWord(input.StatusWord);
}
WaitStopped(master, 5000);
SetBrakes(master, released: false);
Thread.Sleep(BRAKE_RELEASE_SETTLE_MS);
SetAllControlWord(master, 0x0006); // A normal stop also goes through Shutdown, without cutting torque
Console.WriteLine($"已停止, {BRAKE_AXES.Length} 个刹车锁止"); // Stopped, {BRAKE_AXES.Length} brakes engaged
}

/// <summary> Stop control word: QuickStopActive can only be left with 0x0000 (T12); every other state sends 0x0006 (Shutdown) </summary>
static ushort StopControlWord(ushort sw) => (sw & 0x006F) == 0x0007 ? (ushort)0x0000 : (ushort)0x0006;

/// <summary> Whether any axis is stopped in QuickStopActive </summary>
static bool AnyQuickStopActive(DarraEtherCAT master)
{
for (int i = 0; i < AXIS_COUNT; i++)
if ((master.Slaves[i].PDO.InputsMapping<Servo_Input>().StatusWord & 0x006F) == 0x0007)
return true;
return false;
}

/// <summary> Wait until all axes leave QuickStopActive and reach SwitchOnDisabled ((sw & 0x4F) == 0x40); faulty axes count as stopped </summary>
static void WaitSwitchOnDisabled(DarraEtherCAT master, int timeoutMs)
{
var deadline = DateTime.UtcNow.AddMilliseconds(timeoutMs);
while (DateTime.UtcNow < deadline)
{
bool settled = true;
for (int i = 0; i < AXIS_COUNT; i++)
{
ushort sw = master.Slaves[i].PDO.InputsMapping<Servo_Input>().StatusWord;
if ((sw & 0x004F) != 0x0040 && (sw & 0x004F) != 0x0008) { settled = false; break; }
}
if (settled) return;
Thread.Sleep(STOP_POLL_MS);
}
Console.WriteLine("[警告] SwitchOnDisabled 确认超时, 继续后续停机步骤"); // [Warning] SwitchOnDisabled confirmation timed out, continuing with the remaining shutdown steps
}

/// <summary> Wait until the status word reaches QuickStopActive ((sw & 0x6F) == 0x07); faulty axes count as safely stopped </summary>
static void WaitQuickStopActive(DarraEtherCAT master, int timeoutMs)
{
var deadline = DateTime.UtcNow.AddMilliseconds(timeoutMs);
while (DateTime.UtcNow < deadline)
{
bool settled = true;
for (int i = 0; i < AXIS_COUNT; i++)
{
ushort sw = master.Slaves[i].PDO.InputsMapping<Servo_Input>().StatusWord;
if ((sw & 0x006F) != 0x0007 && (sw & 0x004F) != 0x0008) { settled = false; break; }
}
if (settled) return;
Thread.Sleep(STOP_POLL_MS);
}
Console.WriteLine("[警告] QuickStopActive 确认超时, 继续去使能"); // [Warning] QuickStopActive confirmation timed out, continuing with the disable
}

static void SetAllControlWord(DarraEtherCAT master, ushort cw)
{
for (int i = 0; i < AXIS_COUNT; i++)
master.Slaves[i].PDO.OutputsMapping<Servo_Output>().ControlWord = cw;
}

/// <summary>
/// Wait for all axes to come to a full stop. The MINAS A6B default TxPDO has no velocity object, so use the position difference between two samples:
/// a position change of no more than 2 pulses (0.02 mm) within 20 ms counts as stopped.
/// </summary>
static void WaitStopped(DarraEtherCAT master, int timeoutMs)
{
int[] last = new int[AXIS_COUNT];
for (int i = 0; i < AXIS_COUNT; i++)
last[i] = master.Slaves[i].PDO.InputsMapping<Servo_Input>().ActualPosition;

var deadline = DateTime.UtcNow.AddMilliseconds(timeoutMs);
while (DateTime.UtcNow < deadline)
{
Thread.Sleep(20);
bool stopped = true;
for (int i = 0; i < AXIS_COUNT; i++)
{
int pos = master.Slaves[i].PDO.InputsMapping<Servo_Input>().ActualPosition;
if (Math.Abs(pos - last[i]) > 2) stopped = false;
last[i] = pos;
}
if (stopped) return;
}
Console.WriteLine("[警告] 减速超时"); // [Warning] Deceleration timed out
}

// ======================== Operator input ========================

static void InputLoop()
{
while (isRunning && !isEmergencyStop)
{
if (!Console.KeyAvailable) { Thread.Sleep(50); continue; }
var key = Console.ReadKey(true).Key;

switch (key)
{
case ConsoleKey.G:
if (mode == OpMode.Auto) cueGo = true;
break;
case ConsoleKey.Q:
isRunning = false;
Console.WriteLine("[正常退出]"); // [Normal exit]
break;
case ConsoleKey.A:
mode = OpMode.Auto; manual.Type = ManualCommand.CmdType.None;
Console.WriteLine("[自动模式]"); // [Auto mode]
break;
case ConsoleKey.M:
mode = OpMode.Manual;
Console.WriteLine("[手动模式] 数字键选组, 方向键点动"); // [Manual mode] number keys select the group, arrow keys jog
break;
case ConsoleKey.T:
mode = OpMode.Maintenance;
Console.WriteLine("[维护模式] 限速 100mm/s"); // [Maintenance mode] speed limited to 100mm/s
break;
case ConsoleKey.E:
isEmergencyStop = true; break;

// Velocity override
case ConsoleKey.OemPlus: case ConsoleKey.Add:
speedPermille = Math.Min(1200, speedPermille + 100);
Console.WriteLine($"[速度] {speedPermille / 10}%"); // [Speed] {speedPermille / 10}%
break;
case ConsoleKey.OemMinus: case ConsoleKey.Subtract:
speedPermille = Math.Max(0, speedPermille - 100);
Console.WriteLine($"[速度] {speedPermille / 10}%"); // [Speed] {speedPermille / 10}%
break;

// Select a group (number keys 0~9)
case ConsoleKey.D0: case ConsoleKey.D1: case ConsoleKey.D2:
case ConsoleKey.D3: case ConsoleKey.D4: case ConsoleKey.D5:
case ConsoleKey.D6: case ConsoleKey.D7: case ConsoleKey.D8:
case ConsoleKey.D9:
if (mode != OpMode.Auto)
{
int gid = (int)key - (int)ConsoleKey.D0;
if (gid < Groups.Count)
{
manual.GroupId = gid;
Console.WriteLine($"[选组] {Groups[gid].Name}"); // [Group selected] {Groups[gid].Name}
}
}
break;

// Jog (keep pressing to refresh the timestamp; auto-stop after 200 ms without a key press)
case ConsoleKey.UpArrow:
if (mode != OpMode.Auto)
{
Interlocked.Exchange(ref lastJogTick, Stopwatch.GetTimestamp());
manual.Type = ManualCommand.CmdType.Jog;
manual.JogSpeed = mode == OpMode.Maintenance ? MAINTENANCE_MAX_VEL : 300;
}
break;
case ConsoleKey.DownArrow:
if (mode != OpMode.Auto)
{
Interlocked.Exchange(ref lastJogTick, Stopwatch.GetTimestamp());
manual.Type = ManualCommand.CmdType.Jog;
manual.JogSpeed = -(mode == OpMode.Maintenance ? MAINTENANCE_MAX_VEL : 300);
}
break;
}
}
}

// ======================== Default Cue list ========================

static CueList DefaultCueList()
{
var list = new CueList { ShowName = "默认演出" }; // Default show
int axesPerGroup = Groups[0].AxisIds.Length;

// Cue 1: opening - the front curtain rises to the top (operator presses GO)
list.Cues.Add(new StageCue
{
CueNumber = 1, Name = "开幕", Duration = 5.0, // Opening
Motions = new List<CueGroupMotion>
{
new CueGroupMotion
{
GroupId = 0,
Positions = Enumerable.Repeat(5000.0, axesPerGroup).ToArray(),
MaxVelocity = 300, Interp = InterpType.EaseIn,
},
},
});

// Cue 2: first act - the back curtain descends + the sky curtain unfolds (runs automatically 2 s after Cue 1 completes)
list.Cues.Add(new StageCue
{
CueNumber = 2, Name = "第一幕", Duration = 8.0, // Act 1
AutoFollowDelay = 2.0,
Motions = new List<CueGroupMotion>
{
new CueGroupMotion { GroupId = 1,
Positions = Enumerable.Repeat(1000.0, axesPerGroup).ToArray(),
MaxVelocity = 200, Interp = InterpType.SmoothStep },
new CueGroupMotion { GroupId = 4,
Positions = Enumerable.Repeat(3000.0, axesPerGroup).ToArray(),
MaxVelocity = 400, Interp = InterpType.SmoothStep },
},
});

// Cue 3: chasing wave - sine wave on the effect curtain + per-axis delay forms a travelling wave, looped 3 times
var wave = new double[axesPerGroup];
var delays = new double[axesPerGroup];
for (int i = 0; i < axesPerGroup; i++)
{
wave[i] = 2500 + 2000 * Math.Sin(2 * Math.PI * i / axesPerGroup);
delays[i] = i * 0.15; // 150 ms delay per axis, producing a travelling-wave chase effect
}

list.Cues.Add(new StageCue
{
CueNumber = 3, Name = "追逐波浪", Duration = 4.0, // Chasing waves
AutoFollowDelay = 0, // Runs immediately after Cue 2 completes
LoopCount = 3,
Motions = new List<CueGroupMotion>
{
new CueGroupMotion { GroupId = 5,
Positions = wave, MaxVelocity = 500,
Interp = InterpType.SmoothStep,
PerAxisDelay = delays },
},
});

// Cue 4: curtain call - all curtains return to zero (operator presses GO)
list.Cues.Add(new StageCue
{
CueNumber = 4, Name = "谢幕", Duration = 10.0, // Curtain call
Motions = Groups.Select(g => new CueGroupMotion
{
GroupId = g.GroupId,
Positions = Enumerable.Repeat(0.0, g.AxisIds.Length).ToArray(),
MaxVelocity = 200, Interp = InterpType.EaseOut,
}).ToList(),
});

return list;
}

// ======================== Auxiliary ========================

static double Lerp(double a, double b, double t) => a + (b - a) * t;

static double Interp(double t, InterpType type) => type switch
{
InterpType.Linear => t,
InterpType.SmoothStep => t * t * (3 - 2 * t),
InterpType.EaseIn => t * t,
InterpType.EaseOut => 1 - (1 - t) * (1 - t),
_ => t * t * (3 - 2 * t),
};
}

Complete example code​

This page describes a scenario. For a runnable reference, see STF-EC_SyncAxis (a complete project with multi-axis CSP, a cyclic callback, per-axis target issue, emergency stop and fault reset, where "gear-ratio following" can be replaced with "each Cue positions on its own"). For pure multi-axis interpolation, see Panasonic_CNC_Interpolation. Cue sequencing, DMX512 and the brake sequence are the parts customized for the scenario on this page; the reference projects have no corresponding implementation.