スマートビルの照明 / カーテン / LED 制御システム
このページが扱うのは 120 の独立カーテン軸の位置決め制御(軸ごとに目標位置を一つ、Cue または手動で発行)であり、同期軸 / 電子ギアのユースケースではない。 「グループ」は同じ Cue の目標をまとめて発行するためのバッチ集合にすぎず、軸間にギア比や位相結合は無く、仮想マスタ軸も無い。 厳密な比例結合(1:1 のギア比、逆追従、ガントリ補正)は同期軸 / 電子ギアを参照。
ハードウェア構成
- マスタ:Windows 10 IoT x 1 + Intel 13900 x 1
- モーション制御:Panasonic MINAS A6B EtherCAT サーボドライバ x 120 + サーボモータ x 120
- ブレーキ制御:EL2808 デジタル出力 x 2(電磁ブレーキ 12 個。荷重支持の重要な軸をカバーする)
コスト分析
| 区分 | 型式 / 仕様 | 参考単価(¥) | 数量 | 小計(¥) |
|---|---|---|---|---|
| サーボドライバ | Panasonic MINAS A6B | 1,800 | 120 | 216,000 |
| サーボモータ | 200 W サーボモータ | 600 | 120 | 72,000 |
| デジタル出力 | EL2808 | 500 | 2 | 1,000 |
| 産業用 PC | Intel 13900 クラス | 10,000 | 1 | 10,000 |
主要部品の参考価格(人民元)。LED モジュール、ケーブル類は含まない。
性能指標
- グループ内同期誤差:≤1 ms(同じ Cue 内の全軸が同じ時刻基準で補間する)
- 軸数:120 の独立軸(6 グループ x 20 軸。グルーピングは一括目標発行のための集合であり、機械的な結合ではない)
- PDO サイクル:1 ms(1 kHz、
master.LoopCycle = 1_000_000、DC Sync0 と同じ値) - 位置決め精度:±0.1 mm
なぜ 125 µs ではなく 1 ms か:120 軸の一フレーム分のプロセスデータは長く、毎サイクルで 120 組の目標位置とブレーキ出力も書く必要がある。 1 ms は Windows のスケジューリングに余裕を残す。位置決め精度は Cue の補間とドライブの内側ループから得るものであり、バスサイクルを短くするものではない。 実際に 8 kHz で動かすには
LoopCycleと各スレーブのConfigureDCの両方を125000に設定し、フレーム長とサイクルジッタを測定しなければならない。 ドキュメントに 125 µs と書きながらコードが 1 ms でスケールすると、速度クランプとホーミングステップが 8 倍大きくなる。
アプリケーションシナリオ
大規模公演会場の成形投影カーテン制御。120 台のサーボがそれぞれ独立したカーテンユニット(5 m ストローク)を駆動し、位置決め目標は事前に組んだ Cue リストからグループ単位で発行される(グループは同じビートで目標を受け取り、軸間にギア比は無い)。DMX512 の照明と連携する。荷重支持の重要な 12 軸には電磁ブレーキがあり、停電時にロックして落下を防ぐ。
コードの説明
システム構成
グループ設計
グループ数とグループあたりの軸数は構成で定義し、固定の 6x20 に限られない。例では物理的な位置で軸を 6 グループに分けている:
| グループ | 名称 | 軸範囲 | ブレーキ付き軸 | 用途 |
|---|---|---|---|---|
| 0 | 前カーテン(Front) | 0~19 | 0, 10 | 舞台前の開口カーテン |
| 1 | 背面カーテン(Rear) | 20~39 | 20, 30 | 背景幕の巻き上げ |
| 2 | 左側カーテン(Left) | 40~59 | 40, 50 | 左袖のカーテン |
| 3 | 右側カーテン(Right) | 60~79 | 60, 70 | 右袖のカーテン |
| 4 | 天空カーテン(Ceiling) | 80~99 | 80, 90 | 上部の天空 / 投影カーテン |
| 5 | FX カーテン(FX) | 100~119 | 100, 110 | 成形 / ウェーブカーテン |
グループ定義は JSON 構成ファイルに保存し、任意のグループ数と任意の軸割り当てに対応する(連続である必要はない)。例:
- 市松グルーピング:奇数軸を一グループ、偶数軸をもう一グループにして、ずらして巻き上げる
- リンググルーピング:円形舞台の角度で 12 グループに分け、回転する波を作る
- 一時的グルーピング:上演中にグループを作成または統合する
{
"groups": [
{ "name": "前幕", "axisIds": [0,1,2,...,19], "brakeAxes": [0,10] },
{ "name": "环形-A区", "axisIds": [0,5,10,15,20,25], "brakeAxes": [0,20] }
]
}
動作モードと切り替え
| モード | 説明 | 操作 |
|---|---|---|
| AUTO | 自動モード | Cue リストを順に実行する。オペレータが GO を押して次の Cue をトリガする |
| MANUAL | 手動モード | グループを選び、ジョグ(Jog)または位置決め(GoTo)を行う。速度ノブ 0~120% |
| MAINTENANCE | 保守モード | 低速の単軸運転(100 mm/s に制限)。調整とキャリブレーション用 |
Cue システム
Cue とキーフレームの違い:CSP モードではアプリケーション層で補間する。同等の実装だが、より柔軟である(任意の曲線やウェーブ効果が可能)。
StageCue は AutoFollowDelay による自動連鎖に対応する:
AutoFollowDelay = -1— 既定。オペレータが GO を押すのを待つAutoFollowDelay = 0— 直前の Cue の完了直後に実行するAutoFollowDelay = 2.0— 直前の Cue の完了 2 秒後に自動実行するLoopCount > 1— 繰り返す(ループするウェーブ効果)
これにより、上演シーケンス全体を組める。GO を一度押すと、以降の Cue がタイムラインに沿って自動で進む。
ブレーキシーケンス
設計の要点:
- 電磁ブレーキ(停電時ロック) — 荷重支持の 12 軸は EL2808 の出力で制御する。停電や通信断では出力が零になり、ブレーキがロックする。非常停止はまずブレーキをロックして落下を防ぐ。通常停止はまず減速してからブレーキをロックし、衝撃を避ける
- Cue システム — オペレータが GO を押して場面転換をトリガする。自動連鎖(AutoFollowDelay)とループ(LoopCount)に対応
- 動的グルーピング — グループ数とグループあたりの軸割り当ては構成で定義する。任意の軸の組み合わせに対応(連続である必要はない)
- 成形動作 — PerAxisDelay で軸ごとに遅延を与え、チェイシング、進行波、ずらしの効果を作る
- 手動制御 — 両方向の押し込みジョグ(Jog)と位置決め(GoTo)。保守モードには速度制限がある
- 速度オーバーライド — 全体の速度ノブ 0~120%。リハーサルでは低速で確認し、本番ではフルスピードで使う
- ソフトリミット保護 — 位置がリミットを 10 mm 超過した時点で、安全監視スレッドが即時に非常停止をトリガする
- 位置フィードバック — 毎サイクル ActualPosition から同期し、指令値が実位置から離れないようにする
- 制御ワードは標準の CiA 402 意味論だけを使う — CSP では
0x6040を0x000Fのままにし、目標更新はすべて0x607A経由とする。 CSP で0x001Fを書いてはならない(bit4 の新規セットポイントは PP モードでのみ意味を持ち、一部のドライブは 0x7500 を報告する)。 非常停止は0x0002Quick Stop を使う(0x6085のランプで減速)。ステータスワードがQuickStopActive((sw & 0x6F) == 0x07)を確認したら、その状態から抜けるために0x0000(T12 = Disable Voltage)を送り、次に0x0006でイネーブルを外す。QuickStopActiveで0x0006は未定義であり、直接送ると軸はその状態に永久に固まる。0x0000はこの出口専用である。通常停止では使わない。吊られたカーテンは推力を一瞬にして失い、自由落下で滑り落ちるためである。 非常停止では、まずブレーキをロックし、速度がゼロになるのを待って軸の停止を確認してからQuickStopActiveを抜ける。
このケースの Cue シーケンスエンジン(補間曲線の設計、ウェーブとチェイシング効果、自動フォローのロジック)、 DMX512 の照明連携、ブレーキ安全シーケンス、 この規模での 120 軸の DC 同期調整は、追加のカスタム作業であり、 EtherCAT マスタソフトウェアのライセンスには含まれない。
コード例
データ構造
Servo_Input / Servo_Output は Panasonic MINAS A6B の ESI 既定マッピング(TxPDO 23 バイト、RxPDO 9 バイト)に従う。
A6B の既定 TxPDO には速度オブジェクトもトルクオブジェクトも無いため、この例では連続するサンプリング位置の差から速度を導出し、位置偏差からスタールを検出する。
型式を変えたり PDO 割り当てを変更したりする場合は、DENI がエクスポートした実際のマッピングから構造体を書き直す。オブジェクト番号順を前提にしないこと。
using System.Runtime.InteropServices;
using System.Collections.Generic;
// ============ PDO マッピング ============
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct Servo_Input // 23 バイト TxPDO 0x1A00(MINAS A6B の既定マッピング)
{
public ushort ErrorCode; // 0x603F エラーコード オフセット 0
public ushort StatusWord; // 0x6041 ステータスワード オフセット 2
public sbyte ModesOfOperationDisplay; // 0x6061 現在モード オフセット 4
public int ActualPosition; // 0x6064 実位置 オフセット 5
public ushort TouchProbeStatus; // 0x60B9 プローブ状態 オフセット 9
public int TouchProbe1PosValue; // 0x60BA プローブラッチ位置 オフセット 11
public int FollowingErrorActualValue; // 0x60F4 追随誤差 オフセット 15
public uint DigitalInputs; // 0x60FD デジタル入力 オフセット 19
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct Servo_Output // 9 バイト RxPDO 0x1600
{
public ushort ControlWord; // 0x6040 制御ワード オフセット 0
public sbyte ModeOfOperation; // 0x6060 動作モード オフセット 2(8=CSP)
public int TargetPosition; // 0x607A 目標位置 オフセット 3
public ushort TouchProbeFunction; // 0x60B8 プローブ機能 オフセット 7(本例では未使用、0 を維持)
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct EL2808_Output
{
public byte DigitalOutputs; // bit0~7、LOW=ブレーキ保持、HIGH=解放
public void SetBit(int ch, bool value)
{
if (value) DigitalOutputs |= (byte)(1 << ch);
else DigitalOutputs &= (byte)~(1 << ch);
}
}
// ============ 構成 ============
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; // 任意の軸割り当て(連続である必要はない)
public double MaxVelocity = 500; // mm/s
}
// ============ 操作 ============
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=全軸、0~指定グループ
public int AxisId = -1; // -1=グループ全体(メンテナンスモードでは単軸)
public double JogSpeed; // mm/s、正 = 上昇
public double GoToPosition; // 目標位置 mm
public double GoToVelocity; // 位置決め速度 mm/s
}
// ============ Cue システム ============
public class CueGroupMotion
{
public int GroupId;
public double[] Positions; // 各軸の目標位置 mm(長さ = グループ内の軸数)
public double MaxVelocity = 500; // mm/s
public InterpType Interp = InterpType.SmoothStep;
public double[] PerAxisDelay; // 各軸の遅延(秒)。null=同期。チェイス/ウェーブ効果に使う
}
/// <summary>
/// シーン(Cue)── 舞台オートメーションの基本単位
/// </summary>
public class StageCue
{
public int CueNumber; // 番号
public string Name; // 名称(「開幕」、「第一幕」、...)
public double Duration; // トランジション時間(秒)
public List<CueGroupMotion> Motions; // 各グループの動作パラメータ
public byte[] DmxData; // DMX512 照明。null=変更なし
public double AutoFollowDelay = -1; // -1=GO を待つ、>=0=前の Cue 完了後に指定時間待って自動実行
public int LoopCount = 1; // ループ回数(ウェーブ効果を持続させる)
}
public class CueList
{
public string ShowName;
public List<StageCue> Cues = new List<StageCue>();
}
ベースとなる Cue 動作に動的な変調エフェクトを重ね、持続的な演出動作を作る:
public enum EffectType { None, Wave, Breathing, Chase, Rainbow }
public class CueEffect
{
public int GroupId;
public EffectType Type;
public double Amplitude; // 変調振幅 mm
public double Frequency; // Hz
public double PhaseStep; // 隣接軸の位相差(ラジアン)。Wave では 2π/N が一般的
}
使い方:CueGroupMotion に CueEffect Effect フィールドを追加し、ProcessCue が基本の補間位置を計算した後でエフェクトを重ねる:
double offset = effect.Amplitude * Math.Sin(
2 * Math.PI * effect.Frequency * elapsed + effect.PhaseStep * axisIndex);
target += offset;
代表的なエフェクト:
- Wave:PhaseStep = 2π/20。グループ全体が進行波になる
- Breathing:PhaseStep = 0。グループ全体が同位相の正弦波で呼吸するように動く
- Chase:PhaseStep = π。隣接する軸が上下交互に動く
- Rainbow:PhaseStep を増やし、螺旋状の波を作る
InterpType 列挙型はカスタム式に拡張できる:
public enum InterpType { Linear, SmoothStep, EaseIn, EaseOut, Bezier, Custom }
public class CueGroupMotion
{
// ...既存のフィールド...
public double[] BezierControlPoints; // Bezier: [cx1, cy1, cx2, cy2]
public Func<double, double> CustomFunc; // カスタム:t -> 補間係数
}
Bezier 三次曲線に対応すれば、UI 上で制御点をドラッグして任意の加減速曲線を設計でき、照明デザイナの作業に合わせられる。
制御コード
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 周期 1ms(Windows 上で 120 軸を動かす場合の推奨値)
const int SLAVE_BRAKE_1 = 120, SLAVE_BRAKE_2 = 121;
const double MAINTENANCE_MAX_VEL = 100; // メンテナンスモードの速度上限 mm/s
const int BRAKE_RELEASE_SETTLE_MS = 200; // ブレーキ解放後に機械の応答を待つ(制御周期ではない)
const int STOP_POLL_MS = 1; // 停止待ちのポーリング間隔(CPU を譲るためのもの。制御周期ではない)
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>();
// ホーミングオフセット(生位置パルス):ホーミング後 現在位置 = (生位置 - HomeOffset) / PulsesPerMm
static readonly int[] HomeOffset = new int[AXIS_COUNT];
// 周期に関係するリアルタイム換算値:すべて実際の master.LoopCycle から導く。1ms を固定しない
static double cycleSeconds = CYCLE_NS / 1e9;
// 実行状態
static volatile OpMode mode = OpMode.Auto;
static volatile bool isRunning = true; // 正常終了フラグ
static volatile bool isEmergencyStop = false;
static volatile int speedPermille = 1000; // 速度つまみ 0~1200、0~120% に対応(volatile は double に付けられない)
static double SpeedOverride => speedPermille / 1000.0;
static int stopDone = 0;
// Cue エンジン
static CueList cueList;
static int cueIndex = -1;
static volatile bool cueGo = false;
static volatile bool cueActive = false; // 現在の Cue が実行中かどうか
static readonly Stopwatch cueTimer = new Stopwatch();
static double[] cueStartPos = new double[AXIS_COUNT];
// 手動制御
static ManualCommand manual = new ManualCommand();
static volatile long lastJogTick = 0; // Jog キーのタイムスタンプ(ホールド式)
// ======================== メインフロー ========================
static void Main(string[] args)
{
InitGroups();
InitUnits();
// Build() は BuildResult を返す(マスタそのものではない)。.Master をつないでマスタインスタンスを取り出す
// DENI = マスタ設定ツールが実スレーブをスキャンして書き出したネットワーク構成。手編集禁止
var master = new DarraEtherCAT()
.SetENI("config.deni")
.Build()
.Master;
if (master == null) { Console.WriteLine("主站初始化失败!"); return; } // マスタの初期化に失敗しました!
if (master.SlaveCount < AXIS_COUNT + 2)
{
Console.WriteLine($"从站不足: 需要 {AXIS_COUNT} 个轴 + 2 个 EL2808, 实际 {master.SlaveCount}"); // スレーブ不足: 軸 {AXIS_COUNT} 個 + EL2808 2 個が必要ですが, 実際は {master.SlaveCount} 個です
master.Dispose();
return;
}
try
{
// サイクル:120 軸は 1ms を使う。DC Sync0 と同値。決めたら LoopCycle を唯一の出所として周期関連の量を導く。
master.LoopCycle = CYCLE_NS;
if (master.LoopCycle != CYCLE_NS)
{
Console.WriteLine($"LoopCycle 设定失败: 请求 {CYCLE_NS}ns, 读回 {master.LoopCycle}ns"); // LoopCycle の設定に失敗しました: 要求 {CYCLE_NS}ns, 読み戻し {master.LoopCycle}ns
return;
}
cycleSeconds = master.LoopCycle / 1e9;
Console.WriteLine($"PDO 周期: {master.LoopCycle / 1000}µs"); // PDO サイクル: {master.LoopCycle / 1000}µs
// ステートマシンの順序:INIT → PreOp →(DC を構成)→ SafeOp → OP。DC は PreOp で構成しなければならず、
// INIT で直接 ConfigureDC しても受け付けられない。
if (!master.SetState(EcState.PreOp, out string preOpError))
{ Console.WriteLine($"无法进入 PreOp: {preOpError}"); return; } // PreOp に入れません: {preOpError}
// DC Sync0 と LoopCycle は同値。DC 非対応のスレーブは通常どおり走る
for (int i = 0; i < AXIS_COUNT; i++)
{
if (master.Slaves[i].HasDC && !master.Slaves[i].ConfigureDC(CYCLE_NS))
Console.WriteLine($"[警告] 轴{i} DC Sync0 配置失败"); // [警告] 軸{i} の DC Sync0 構成に失敗しました
}
if (!master.SetState(EcState.SafeOp, out string safeOpError))
{ Console.WriteLine($"无法进入 SafeOp: {safeOpError}"); return; } // SafeOp に入れません: {safeOpError}
if (!master.SetState(EcState.OP, out string opError)) { Console.WriteLine($"无法进入 OP: {opError}"); return; } // OP に入れません: {opError}
if (!EnableServos(master)) { Console.WriteLine("使能未通过, 不得起演"); return; } // イネーブルが確認できなかったため, 演出を開始できません
Console.WriteLine("回原点..."); // ホーミングしています
HomeAllAxes(master);
if (!PreShowCheck(master)) { Console.WriteLine("预演检查未通过!"); return; } // リハーサルチェックに合格しませんでした!
// 演出オーケストレーションを JSON から読み込むのは上位アプリの責務。本例では組み込みの Cue リストを直接使う
cueList = DefaultCueList();
Console.WriteLine($"演出 [{cueList.ShowName}] 共 {cueList.Cues.Count} Cue"); // 演出 [{cueList.ShowName}] Cue は全 {cueList.Cues.Count} 件です
Console.WriteLine("[G]=GO [A]=自动 [M]=手动 [E]=急停 [Q]=退出 [+/-]=速度"); // [G]=GO [A]=自動 [M]=手動 [E]=非常停止 [Q]=終了 [+/-]=速度 のキー操作
// バックグラウンドスレッド
StartThread(() => SafetyLoop(master));
StartThread(InputLoop);
// リアルタイム制御は SDK の PDO 周期コールバックに載せる ── バスサイクル(= LoopCycle、1ms)でハード同期駆動し、
// SDK の PDO スレッドのコンテキストで周期ごとに実行する。Thread.Sleep / while のビジーウェイトで刻みを作っては絶対にいけない。
// 引数 mi = マスタの連番。
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 周期異常] {ex.Message} が発生しました
}
}
master.Events.ProcessDataCyclicSync += OnPdoCycle;
// メインスレッドは終了/非常停止を待つだけ(非リアルタイム、PDO は書かない)。リアルタイム制御はすべて 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();
}
// ======================== 初期化 ========================
static void InitGroups()
{
// 既定は 6 グループ × 20 軸(設定ファイルから任意の分グループを読み込める)
string[] names = { "前幕", "后幕", "左侧幕", "右侧幕", "天幕", "特效幕" }; // 前幕・後幕・左袖幕・右袖幕・天幕・特効幕の各カーテン名
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>
/// イネーブル:軸ごとにステータスワードで CiA 402 を進める(0x06→0x07→0x0F)。各ステップで実際の状態確認を待つ(上限付きタイムアウト)。
/// false を返す = タイムアウトで確認できなかった軸、または Fault の軸がある。この場合は演出を開始してはならない。
/// </summary>
static bool EnableServos(DarraEtherCAT master)
{
// CSP モードと「目標 = 実位置」を事前設定する:未イネーブル時は目標が常に実位置に等しくなり、イネーブル時の瞬間的な飛びを防ぐ
for (int i = 0; i < AXIS_COUNT; i++)
{
ref var outp = ref master.Slaves[i].PDO.OutputsMapping<Servo_Output>();
outp.ModeOfOperation = 8; // CSP。実行中は毎周期これを維持する
outp.TargetPosition = master.Slaves[i].PDO.InputsMapping<Servo_Input>().ActualPosition;
outp.ControlWord = 0x0006;
}
// すでに Fault の軸には先にリセットパルス(bit7 立ち上がり)を与える。「少し待てば治る」に頼らない
ResetFaults(master);
// CiA 402: Shutdown -> Switch On -> Enable Operation
ushort[] sequence = { 0x0006, 0x0007, 0x000F };
ushort[] statusExpects = { 0x0021, 0x0023, 0x0027 }; // ステータスワードは常に 0x6F マスクで解釈する
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;
}
// 実際のステータスワードで確認を待つ。固定 Sleep で各ステップの所要時間を当て推量しない
if (!WaitAllStatus(master, statusExpects[s], 2000, out int badAxis, out ushort badSw))
{
Console.WriteLine($"使能失败: 轴{badAxis} 未进入 0x{statusExpects[s]:X4} " + // イネーブルに失敗しました: 軸{badAxis} が 0x{statusExpects[s]:X4} になりませんでした
$"(实际 0x{badSw:X4}, 控制字 0x{sequence[s]:X4})"); // (実際は 0x{badSw:X4}, 制御ワードは 0x{sequence[s]:X4})
return false;
}
}
// ブレーキ解放後に機械の応答を待つ(ハードウェアの動作時間であり、制御周期ではない)
SetBrakes(master, released: true);
Thread.Sleep(BRAKE_RELEASE_SETTLE_MS);
Console.WriteLine($"已使能 {AXIS_COUNT} 轴 (CSP), 释放 {BRAKE_AXES.Length} 个刹车"); // {AXIS_COUNT} 軸をイネーブルしました (CSP), ブレーキ {BRAKE_AXES.Length} 個を解放しました
return true;
}
/// <summary> 全軸のステータスワードが期待値に入るのを待つ(状態駆動、上限付きタイムアウト)。失敗時は最初に到達しなかった軸を返す </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>
/// フォルトリセット:6040 の bit7 は 0→1 の立ち上がりでなければならない。まず 0x0006(bit7=0)を 2 拍保持し、次に 0x0086
/// (bit7=1 + Shutdown ビット)を約 20ms 保持し、その後 0x0006 に戻してステータスワード駆動で再度ハンドシェイクする。
/// 保持時間は実際のサイクルで換算し、拍数を固定しない。
/// </summary>
static void ResetFaults(DarraEtherCAT master)
{
// QuickStopActive で止まっている軸があると 0x0006 / 0x0086 はどちらも効かない:まず 0x0000 で SwitchOnDisabled に戻す
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; // 状態駆動:全軸のリセットが成功したら早期に終了する
Thread.Sleep((int)Math.Ceiling(cycleSeconds * 1000));
}
SetAllControlWord(master, 0x0006);
}
/// <summary> フォルト判定:(sw & 0x4F) == 0x08(bit3 Fault)。フォルト軸が存在するかを返す </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}"); // 軸{i} ({grp?.Name}) はイネーブルされていません: 0x{sw:X4}
pass = false;
}
}
if (pass) Console.WriteLine("预演检查通过"); // リハーサルチェックに合格しました
return pass;
}
// ======================== Cue エンジン(自動モード) ========================
static int cueLoopRemain = 0; // 現在の Cue の残りループ回数
static readonly Stopwatch autoFollowTimer = new Stopwatch(); // 自動連結の計時
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)
{
// GO に応答する
if (cueGo)
{
cueGo = false;
autoFollowTimer.Reset();
if (cueIndex + 1 >= cueList.Cues.Count)
{
Console.WriteLine("所有 Cue 已完成, 按 [Q] 退出"); // すべての Cue が完了しました, [Q] で終了します
return;
}
StartCue(cueIndex + 1);
}
// 自動連結:前の Cue の完了後、遅延させて次をトリガする
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];
// 各軸独立の遅延(チェイス/ウェーブ効果)
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 完了
if (t >= 1.0 && cueActive)
{
// ループ
if (--cueLoopRemain > 0)
{
for (int i = 0; i < AXIS_COUNT; i++)
cueStartPos[i] = Units[i].CurrentPosition;
cueTimer.Restart();
Console.WriteLine($"[循环] Cue {cue.CueNumber} 剩余 {cueLoopRemain} 次"); // [ループ] Cue {cue.CueNumber} の残り {cueLoopRemain} 回
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}"); // [完了] Cue {cue.CueNumber}, {nc.AutoFollowDelay}s 後に Cue {nc.CueNumber} を自動実行します
}
else
Console.WriteLine($"[完成] Cue {cue.CueNumber}, 按 GO 执行 Cue {nc.CueNumber}: {nc.Name}"); // [完了] Cue {cue.CueNumber}, GO を押すと Cue {nc.CueNumber}: {nc.Name} を実行します
}
else
Console.WriteLine($"[完成] 所有 Cue 执行完毕"); // [完了] すべての Cue の実行が終わりました
}
}
// ======================== 手動モード ========================
static void ProcessManual(DarraEtherCAT master)
{
if (manual.Type == ManualCommand.CmdType.None) return;
if (manual.Type == ManualCommand.CmdType.Jog)
{
// ホールド式:200ms キー入力が無ければ自動停止(Console に key-up が無いためタイムアウトで代用)
if (Stopwatch.GetTimestamp() - Interlocked.Read(ref lastJogTick)
> Stopwatch.Frequency / 5)
{
manual.Type = ManualCommand.CmdType.None;
return;
}
double delta = manual.JogSpeed * SpeedOverride * cycleSeconds;
// メンテナンスモード:単軸
if (mode == OpMode.Maintenance && manual.AxisId >= 0)
{
WriteAxis(master, manual.AxisId,
Units[manual.AxisId].CurrentPosition + delta, MAINTENANCE_MAX_VEL);
}
// 手動モード:グループ全体
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"); // [位置到達] {g.Name} -> {manual.GoToPosition}mm に到達しました
manual.Type = ManualCommand.CmdType.None;
}
}
}
// ======================== 位置フィードバック同期 ========================
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;
}
// ======================== 動作出力(速度クランプ + ソフトリミット付き) ========================
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;
// 状態認識:OperationEnabled の場合にのみ動作目標を書く。未イネーブル/ハンドシェイク中/フォルト時は
// 目標は常に実位置に等しくし、制御ワードには停止コマンドを送る(QuickStopActive からは 0x0000 でしか抜けられない)──
// 未イネーブルの軸に動作目標を残しては絶対にいけない。
if ((sw & 0x006F) != 0x0027 || (sw & 0x004F) == 0x0008)
{
output.TargetPosition = actual;
output.ControlWord = StopControlWord(sw);
return;
}
// 速度クランプ:一サイクルの最大変位は実際のサイクルから導く(maxVel mm/s × cycleSeconds)。1ms を固定しない
double maxDelta = maxVel * cycleSeconds;
double delta = target - Units[id].CurrentPosition;
if (Math.Abs(delta) > maxDelta)
target = Units[id].CurrentPosition + Math.Sign(delta) * maxDelta;
// ソフトリミット
target = Math.Max(Units[id].MinPosition, Math.Min(Units[id].MaxPosition, target));
// CSP では 0x6040 は常に 0x000F:bit4(0x0010)は PP モードでのみ new set-point を表し、CSP では定義がない。
// 0x001F を書くとドライバによっては 0x7500 を返す。目標の更新は 0x607A の毎周期書き込みに完全に依拠する。
// mm → パルス に変換し、ホーミングオフセットを加える。目標と UpdatePositions が同じ座標原点を使うようにする
output.TargetPosition = (int)(target * Units[id].PulsesPerMm) + HomeOffset[id];
output.ControlWord = 0x000F;
}
// ======================== ホーミング ========================
static void HomeAllAxes(DarraEtherCAT master)
{
// 50mm/s の低速下降による底当てホーミング(50mm/s × cycleSeconds × 100pulse/mm、1ms のとき = 5 pulse/周期)
// リアルタイムのホーミングループは SDK の周期コールバック(ProcessDataCyclicSync)に載せる。ユーザ空間で Thread.Sleep のビジーウェイトを作ってはいけない。
// ステップ長は実際のサイクルから導かなければならない:サイクルが変わればホーミング速度も変わるべきであり、固定定数を 1ms とみなしてはいけない。
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);
// 各 PDO 周期はマスタのコールバックで駆動する:ホーミングを一段階進め、底当てを判定する。全軸到達時に finished.Set()
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>();
// 状態認識:未イネーブル/フォルトの軸は動かさない。目標 = 実位置 + 停止コマンドとし、上限付きタイムアウト後にまとめて報告する
if ((inp.StatusWord & 0x006F) != 0x0027)
{
outp.TargetPosition = inp.ActualPosition;
outp.ControlWord = StopControlWord(inp.StatusWord);
continue;
}
// MINAS A6B の既定 TxPDO にはトルクオブジェクトが無い:追随誤差で固着を判定する(しきい値は機構の剛性に合わせて標定、単位はパルス)
if (Math.Abs(inp.FollowingErrorActualValue) > 300)
{
outp.TargetPosition = inp.ActualPosition;
done[i] = true; count++;
HomeOffset[i] = inp.ActualPosition; // 底当て位置を 0 位置とする
Units[i].CurrentPosition = 0;
}
else
{
outp.TargetPosition = inp.ActualPosition - stepPerCycle;
}
outp.ControlWord = 0x000F;
}
// 全軸が底当てホーミングを完了、終了
if (count >= AXIS_COUNT) finished.Set();
}
catch (Exception ex)
{
Console.WriteLine($"[回零异常] {ex.Message}"); // [ホーミング異常] {ex.Message}
finished.Set(); // 上限付きで抜ける。起動フローを固まらせない
}
}
master.Events.ProcessDataCyclicSync += OnHomeCycle;
try
{
// 上限付き待ち:イネーブル喪失/フォルトの軸があっても、起動フロー全体を固まらせない
if (!finished.Wait(TimeSpan.FromSeconds(30)))
Console.WriteLine($"[警告] 回零超时, 只完成 {count}/{AXIS_COUNT} 轴"); // [警告] ホーミングがタイムアウトしました, {count}/{AXIS_COUNT} 軸のみ完了です
}
finally
{
try { master.Events.ProcessDataCyclicSync -= OnHomeCycle; } catch { }
}
Console.WriteLine($"回原点完成 {count}/{AXIS_COUNT} 轴"); // ホーミング完了 {count}/{AXIS_COUNT} 軸
}
// ======================== ブレーキ ========================
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);
}
}
// ======================== 安全監視 ========================
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}"); // [障害] 軸{i} ({grp}) のサーボ障害 0x{inp.StatusWord:X4}
// フラグを立てるだけ:停止はメインスレッドがまとめて実行する。バックグラウンドスレッドと Dispose が同時に 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"); // [障害] 軸{i} ({grp}) の位置がリミット超過です {pos:F1}mm
isEmergencyStop = true; return;
}
// 既定 PDO にトルクオブジェクトが無い:追随誤差が持続的に大きい場合は機械的な固着/過負荷の前兆とみなす(しきい値は機構に合わせて標定)
if (Math.Abs(inp.FollowingErrorActualValue) > 5000)
Console.WriteLine($"[警告] 轴{i} 跟随误差 {inp.FollowingErrorActualValue} 脉冲"); // [警告] 軸{i} の追随偏差は {inp.FollowingErrorActualValue} パルスです
}
Thread.Sleep(100);
}
}
// ======================== 停止する ========================
/// <summary>
/// 緊急停止:ブレーキをロック(落下防止)-> Quick Stop 0x0002(0x6085 のランプで減速)
/// -> QuickStopActive を確認 -> 0x0000 で QuickStopActive を抜ける -> 0x0006 でイネーブル解除。
/// 0x000B は書かない(標準の Quick Stop ではない)。0x0000 は QuickStopActive から抜けるときにのみ使う:
/// この状態の唯一の合法遷移先は Disable Voltage(T12)であり、0x0006 を直接送ると軸は QuickStopActive のまま固まる。
/// ブレーキは先にロックしてあるため、抜けるときにトルクを切っても吊り下げられた幕が自由落下しない。
/// </summary>
static void EmergencyStop(DarraEtherCAT master)
{
if (Interlocked.Exchange(ref stopDone, 1) == 1) return;
Console.WriteLine("[紧急停止]"); // [非常停止] に入ります
SetBrakes(master, released: false);
SetAllControlWord(master, 0x0002); // Quick Stop:0x6085 のランプで減速する
WaitQuickStopActive(master, 2000); // ステータスワードの確認を待つ((sw & 0x6F) == 0x07)
WaitStopped(master, 2000);
SetAllControlWord(master, 0x0000); // QuickStopActive を抜ける(T12 = Disable Voltage)
WaitSwitchOnDisabled(master, 2000);
SetAllControlWord(master, 0x0006); // Shutdown:イネーブル解除、電圧は保持
Console.WriteLine($"已停止, {BRAKE_AXES.Length} 个刹车锁止"); // 停止しました, ブレーキ {BRAKE_AXES.Length} 個をロックしました
}
/// <summary> 通常停止:位置を固定 -> 減速待ち -> ブレーキをロック -> 0x0006 でイネーブル解除 </summary>
static void GracefulStop(DarraEtherCAT master)
{
if (Interlocked.Exchange(ref stopDone, 1) == 1) return;
Console.WriteLine("[正常停止]"); // [正常停止] を実行します
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; // 位置固定:目標 = 現在
// イネーブル中の軸にだけ 0x000F を与える。それ以外は停止コマンドを送る(QuickStopActive のときは 0x0000)。未イネーブルの軸をついでに起動してはいけない
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); // 通常停止も Shutdown を経由する。トルクは切らない
Console.WriteLine($"已停止, {BRAKE_AXES.Length} 个刹车锁止"); // 停止しました, ブレーキ {BRAKE_AXES.Length} 個をロックしました
}
/// <summary> 停止制御ワード:QuickStopActive からは 0x0000 で抜ける(T12)。それ以外の状態には 0x0006(Shutdown)を送る </summary>
static ushort StopControlWord(ushort sw) => (sw & 0x006F) == 0x0007 ? (ushort)0x0000 : (ushort)0x0006;
/// <summary> 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> 全軸が QuickStopActive を離れ SwitchOnDisabled((sw & 0x4F) == 0x40)に入るのを待つ。フォルト軸は停止済みとみなす </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 确认超时, 继续后续停机步骤"); // [警告] SwitchOnDisabled の確認がタイムアウトしました, 後続の停止手順を続行します
}
/// <summary> ステータスワードが QuickStopActive((sw & 0x6F) == 0x07)に入るのを待つ。フォルト軸は停止済みとみなす </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 确认超时, 继续去使能"); // [警告] QuickStopActive の確認がタイムアウトしました, イネーブル解除を続行します
}
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>
/// 全軸が停止するのを待つ。MINAS A6B の既定 TxPDO には速度オブジェクトが無いため、二つのサンプリング点の位置差で判定する:
/// 20ms 以内の位置変化が 2 パルス(0.02mm)以下なら停止済みとみなす。
/// </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("[警告] 减速超时"); // [警告] 減速がタイムアウトしました
}
// ======================== オペレータ入力 ========================
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("[正常退出]"); // [正常終了] します
break;
case ConsoleKey.A:
mode = OpMode.Auto; manual.Type = ManualCommand.CmdType.None;
Console.WriteLine("[自动模式]"); // [自動モード] に切り替えます
break;
case ConsoleKey.M:
mode = OpMode.Manual;
Console.WriteLine("[手动模式] 数字键选组, 方向键点动"); // [手動モード] 数字キーでグループを選択し, 矢印キーでジョグします
break;
case ConsoleKey.T:
mode = OpMode.Maintenance;
Console.WriteLine("[维护模式] 限速 100mm/s"); // [メンテナンスモード] 速度制限 100mm/s
break;
case ConsoleKey.E:
isEmergencyStop = true; break;
// 速度の上書き
case ConsoleKey.OemPlus: case ConsoleKey.Add:
speedPermille = Math.Min(1200, speedPermille + 100);
Console.WriteLine($"[速度] {speedPermille / 10}%"); // [速度] {speedPermille / 10}% を表示
break;
case ConsoleKey.OemMinus: case ConsoleKey.Subtract:
speedPermille = Math.Max(0, speedPermille - 100);
Console.WriteLine($"[速度] {speedPermille / 10}%"); // [速度] {speedPermille / 10}% を表示
break;
// グループ選択(数字キー 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}"); // [グループ選択] {Groups[gid].Name}
}
}
break;
// ジョグ(キー押し続けでタイムスタンプを更新。200ms 入力が無ければ自動停止)
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;
}
}
}
// ======================== 既定 Cue リスト ========================
static CueList DefaultCueList()
{
var list = new CueList { ShowName = "默认演出" }; // デフォルトの演出名
int axesPerGroup = Groups[0].AxisIds.Length;
// Cue 1:開幕 ─ 前幕を最上部まで上げる(オペレータが GO でトリガ)
list.Cues.Add(new StageCue
{
CueNumber = 1, Name = "开幕", Duration = 5.0, // Cue の名前: 開幕
Motions = new List<CueGroupMotion>
{
new CueGroupMotion
{
GroupId = 0,
Positions = Enumerable.Repeat(5000.0, axesPerGroup).ToArray(),
MaxVelocity = 300, Interp = InterpType.EaseIn,
},
},
});
// Cue 2:第一幕 ─ 後幕下降 + 天幕展開(Cue 1 完了の 2s 後に自動実行)
list.Cues.Add(new StageCue
{
CueNumber = 2, Name = "第一幕", Duration = 8.0, // Cue の名前: 第一幕
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:チェイスウェーブ ─ 効果幕に正弦波 + 各軸遅延で進行波を作り、3 回ループ
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; // 軸ごとに 150ms の遅延を与え、進行波のチェイス効果を作る
}
list.Cues.Add(new StageCue
{
CueNumber = 3, Name = "追逐波浪", Duration = 4.0, // Cue の名前: 波を追う
AutoFollowDelay = 0, // Cue 2 完了後すぐに実行
LoopCount = 3,
Motions = new List<CueGroupMotion>
{
new CueGroupMotion { GroupId = 5,
Positions = wave, MaxVelocity = 500,
Interp = InterpType.SmoothStep,
PerAxisDelay = delays },
},
});
// Cue 4:終幕 ─ すべての幕をゼロ位置に戻す(GO でトリガ)
list.Cues.Add(new StageCue
{
CueNumber = 4, Name = "谢幕", Duration = 10.0, // Cue の名前: カーテンコール
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;
}
// ======================== ヘルパ ========================
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),
};
}
完全なサンプルコード
このページはシナリオの説明である。実行可能な参考として STF-EC_SyncAxis(多軸 CSP、サイクリックコールバック、軸ごとの目標発行、非常停止とフォルトリセットを備えた完全なプロジェクト。「ギア比追従」を「各 Cue が自分で位置決めする」に置き換えられる)を参照。純粋な多軸補間は Panasonic_CNC_Interpolation を参照。Cue シーケンス、DMX512、ブレーキシーケンスはこのページ固有のシナリオ向けのカスタマイズ部分であり、参考プロジェクトに対応する実装は無い。